text
stringlengths
54
60.6k
<commit_before>10af6968-2e4f-11e5-ac49-28cfe91dbc4b<commit_msg>10b64557-2e4f-11e5-8d12-28cfe91dbc4b<commit_after>10b64557-2e4f-11e5-8d12-28cfe91dbc4b<|endoftext|>
<commit_before>a3e47438-2e4f-11e5-b10d-28cfe91dbc4b<commit_msg>a3eb5e45-2e4f-11e5-ad0b-28cfe91dbc4b<commit_after>a3eb5e45-2e4f-11e5-ad0b-28cfe91dbc4b<|endoftext|>
<commit_before>4a5f6d08-2e3a-11e5-b349-c03896053bdd<commit_msg>4a6d0410-2e3a-11e5-98ac-c03896053bdd<commit_after>4a6d0410-2e3a-11e5-98ac-c03896053bdd<|endoftext|>
<commit_before>62ca5dd1-2e4f-11e5-be4b-28cfe91dbc4b<commit_msg>62d0b5d9-2e4f-11e5-9651-28cfe91dbc4b<commit_after>62d0b5d9-2e4f-11e5-9651-28cfe91dbc4b<|endoftext|>
<commit_before>7e7919ba-2d15-11e5-af21-0401358ea401<commit_msg>7e7919bb-2d15-11e5-af21-0401358ea401<commit_after>7e7919bb-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>c5e6c31c-35ca-11e5-9e2f-6c40088e03e4<commit_msg>c5ede518-35ca-11e5-a168-6c40088e03e4<commit_after>c5ede518-35ca-11e5-a168-6c40088e03e4<|endoftext|>
<commit_before>cb0ac500-35ca-11e5-b576-6c40088e03e4<commit_msg>cb11477e-35ca-11e5-aac3-6c40088e03e4<commit_after>cb11477e-35ca-11e5-aac3-6c40088e03e4<|endoftext|>
<commit_before>70de14a4-2fa5-11e5-97a6-00012e3d3f12<commit_msg>70dfe964-2fa5-11e5-9854-00012e3d3f12<commit_after>70dfe964-2fa5-11e5-9854-00012e3d3f12<|endoftext|>
<commit_before>776cbb62-2d53-11e5-baeb-247703a38240<commit_msg>776d3b3c-2d53-11e5-baeb-247703a38240<commit_after>776d3b3c-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>#include <vector> #include <tuple> #include <fstream> #include "Windows.h" #include <psapi.h> #include <vector> using namespace std; namespace { typedef void(*callable)(void*); typedef tuple<void*, size_t> MyTuple; constexpr DWORD invocation_interval_ms = 15 * 1000; constexpr size_t stack_size = 0x10000; struct VersionToOffset { WORD file_version[4]; uint32_t relative_offset; }; /* * See https://changewindows.org/ for a detailed Windows 10 release history, * including updates to milestone releases. A new build of the "mshtml.dll" * file has not been included with every update. */ vector<VersionToOffset> mshtml_gadget_offset_map = { // Windows 10 Creators Update (Build v10.0.15063.0 as of Mar 20, 2017) { 11, 0, 15063, 0, 0x00585098 }, // Windows 10 Anniversary Update (Build v10.0.14393.953 as of Mar 14, 2017) { 11, 0, 14393, 953, 0x003CBD4D }, // The default ROP gadget offset (for Windows v8.1?) { 0, 0, 0, 0, 0x006D55DD } }; struct SetupConfiguration { uint32_t initialized; void* setup_address; uint32_t setup_length; void* VirtualProtectEx; void* WaitForSingleObjectEx; void* CreateWaitableTimer; void* SetWaitableTimer; void* MessageBox; void* tramp_addr; void* sleep_handle; uint32_t interval; void* target; uint8_t shadow[8]; }; struct StackTrampoline { void* VirtualProtectEx; void* return_address; void* current_process; void* address; uint32_t size; uint32_t protections; void* old_protections_ptr; uint32_t old_protections; void* setup_config; }; struct Workspace { SetupConfiguration config; uint8_t stack[stack_size]; StackTrampoline tramp; }; } Workspace& allocate_workspace() { auto result = VirtualAllocEx(GetCurrentProcess(), nullptr, sizeof(Workspace), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!result) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); RtlSecureZeroMemory(result, sizeof(Workspace)); return *static_cast<Workspace*>(result); } MyTuple allocate_pic(const string& filename) { fstream file_stream{ filename, fstream::in | fstream::ate | fstream::binary }; if (!file_stream) throw runtime_error("[-] Couldn't open " + filename); auto pic_size = static_cast<size_t>(file_stream.tellg()); file_stream.seekg(0, fstream::beg); auto pic = VirtualAllocEx(GetCurrentProcess(), nullptr, pic_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!pic) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); file_stream.read(static_cast<char*>(pic), pic_size); file_stream.close(); DWORD old_protection; auto prot_result = VirtualProtectEx(GetCurrentProcess(), pic, pic_size, PAGE_EXECUTE_READ, &old_protection); if (!prot_result) throw runtime_error("[-] Couldn't VirtualProtectEx: " + GetLastError()); return MyTuple(pic, pic_size); } uint32_t get_mshtml_gadget_relative_offset(const char *mshtml_filename) { DWORD version_handle; auto version_info_size = GetFileVersionInfoSizeA(mshtml_filename, &version_handle); if (version_info_size == 0) throw runtime_error("[-] Couldn't GetFileVersionInfoSize: " + GetLastError()); vector<char> version_data(version_info_size); auto result = GetFileVersionInfoA(mshtml_filename, version_handle, version_info_size, &version_data[0]); if (!result) { throw runtime_error("[-] Couldn't GetFileVersionInfo: " + GetLastError()); } LPBYTE version_info_buffer; UINT version_info_buffer_size; result = VerQueryValueA(&version_data[0], "\\", reinterpret_cast<VOID FAR* FAR*>(&version_info_buffer), &version_info_buffer_size); if (!result) { throw runtime_error("[-] Couldn't VerQueryValue: " + GetLastError()); } auto *version_info = reinterpret_cast<VS_FIXEDFILEINFO *>(version_info_buffer); WORD unpacked_file_version_words[4] = { (version_info->dwFileVersionMS >> 16) & 0xffff, (version_info->dwFileVersionMS >> 0) & 0xffff, (version_info->dwFileVersionLS >> 16) & 0xffff, (version_info->dwFileVersionLS >> 0) & 0xffff }; auto unpacked_file_version = *reinterpret_cast<DWORDLONG *>(unpacked_file_version_words); printf("[ ] Found %s version %d.%d.%d.%d.\n", mshtml_filename, unpacked_file_version_words[0], unpacked_file_version_words[1], unpacked_file_version_words[2], unpacked_file_version_words[3]); uint32_t relative_offset = 0; auto using_default = false; auto entry_num = 0; while (relative_offset == 0) { auto* version_entry = &mshtml_gadget_offset_map[entry_num]; if (*reinterpret_cast<DWORDLONG *>(version_entry->file_version) == unpacked_file_version || *reinterpret_cast<DWORDLONG *>(version_entry->file_version) == 0) relative_offset = version_entry->relative_offset; using_default = *reinterpret_cast<DWORDLONG *>(version_entry->file_version) == 0; ++entry_num; } if (using_default) { printf("[*] WARNING: Unrecognized version, so using default relative offset.\n"); } printf("[ ] %s ROP gadget is at relative offset 0x%p.\n", mshtml_filename, reinterpret_cast<void *>(relative_offset)); return relative_offset; } void* get_mshtml_gadget() { auto mshtml_filename = "mshtml.dll"; printf("[ ] Loading %s.\n", mshtml_filename); auto mshtml_gadget_offset = get_mshtml_gadget_relative_offset(mshtml_filename); auto mshtml_base = reinterpret_cast<uint8_t*>(LoadLibraryA(mshtml_filename)); if (!mshtml_base) throw runtime_error("[-] Couldn't LoadLibrary: " + GetLastError()); printf("[+] Loaded %s into memory at 0x%p.\n", mshtml_filename, mshtml_base); return mshtml_base + mshtml_gadget_offset; } void* get_gadget(bool use_mshtml, const string& gadget_pic_path) { void* memory; if (use_mshtml) { memory = get_mshtml_gadget(); } else { printf("[ ] Allocating memory for %s.\n", gadget_pic_path.c_str()); size_t size; tie(memory, size) = allocate_pic(gadget_pic_path); printf("[ ] Allocated %u bytes for gadget PIC.\n", size); } return memory; } void launch(const string& setup_pic_path, const string& gadget_pic_path) { printf("[ ] Allocating executable memory for %s.\n", setup_pic_path.c_str()); void* setup_memory; size_t setup_size; tie(setup_memory, setup_size) = allocate_pic(setup_pic_path); printf("[+] Allocated %d bytes for PIC.\n", setup_size); auto use_mshtml{ true }; printf("[ ] Configuring ROP gadget.\n"); auto gadget_memory = get_gadget(use_mshtml, gadget_pic_path); printf("[+] ROP gadget configured.\n"); printf("[ ] Allocating read/write memory for config, stack, and trampoline.\n"); auto& scratch_memory = allocate_workspace(); auto& config = scratch_memory.config; auto& tramp = scratch_memory.tramp; printf("[+] Allocated %u bytes for scratch memory.\n", sizeof(scratch_memory)); printf("[ ] Building stack trampoline.\n"); tramp.old_protections_ptr = &tramp.old_protections; tramp.protections = PAGE_EXECUTE_READ; tramp.current_process = GetCurrentProcess(); tramp.VirtualProtectEx = VirtualProtectEx; tramp.size = static_cast<uint32_t>(setup_size); tramp.address = setup_memory; tramp.return_address = setup_memory; tramp.setup_config = &config; printf("[+] Stack trampoline built.\n"); printf("[ ] Building configuration.\n"); config.setup_address = setup_memory; config.setup_length = static_cast<uint32_t>(setup_size); config.VirtualProtectEx = VirtualProtectEx; config.WaitForSingleObjectEx = WaitForSingleObjectEx; config.CreateWaitableTimer = CreateWaitableTimerW; config.SetWaitableTimer = SetWaitableTimer; config.MessageBox = MessageBoxA; config.tramp_addr = &tramp; config.interval = invocation_interval_ms; config.target = gadget_memory; printf("[+] Configuration built.\n"); printf("[+] Success!\n"); printf(" ================================\n"); printf(" Gargoyle PIC @ -----> 0x%p\n", setup_memory); printf(" ROP gadget @ -------> 0x%p\n", gadget_memory); printf(" Configuration @ ----> 0x%p\n", &scratch_memory.config); printf(" Top of stack @ -----> 0x%p\n", &scratch_memory.stack); printf(" Bottom of stack @ --> 0x%p\n", &scratch_memory.stack[stack_size-1]); printf(" Stack trampoline @ -> 0x%p\n", &scratch_memory.tramp); reinterpret_cast<callable>(setup_memory)(&config); } int main() { try { launch("setup.pic", "gadget.pic"); } catch (exception& e) { printf("%s\n", e.what()); } } <commit_msg>Added the ROP gadget offset for the "mshtml.dll" file included with Windows 10 build v10.0.15063.138.<commit_after>#include <vector> #include <tuple> #include <fstream> #include "Windows.h" #include <psapi.h> #include <vector> using namespace std; namespace { typedef void(*callable)(void*); typedef tuple<void*, size_t> MyTuple; constexpr DWORD invocation_interval_ms = 15 * 1000; constexpr size_t stack_size = 0x10000; struct VersionToOffset { WORD file_version[4]; uint32_t relative_offset; }; /* * See https://changewindows.org/ for a detailed Windows 10 release history, * including updates to milestone releases. A new build of the "mshtml.dll" * file has not been included with every update. */ vector<VersionToOffset> mshtml_gadget_offset_map = { // Windows 10 Creators Update (Build v10.0.15063.138 as of Apr 11, 2017) { 11, 0, 15063, 138, 0x00585068 }, // Windows 10 Creators Update (Build v10.0.15063.0 as of Mar 20, 2017) { 11, 0, 15063, 0, 0x00585098 }, // Windows 10 Anniversary Update (Build v10.0.14393.953 as of Mar 14, 2017) { 11, 0, 14393, 953, 0x003CBD4D }, // The default ROP gadget offset (for Windows v8.1?) { 0, 0, 0, 0, 0x006D55DD } }; struct SetupConfiguration { uint32_t initialized; void* setup_address; uint32_t setup_length; void* VirtualProtectEx; void* WaitForSingleObjectEx; void* CreateWaitableTimer; void* SetWaitableTimer; void* MessageBox; void* tramp_addr; void* sleep_handle; uint32_t interval; void* target; uint8_t shadow[8]; }; struct StackTrampoline { void* VirtualProtectEx; void* return_address; void* current_process; void* address; uint32_t size; uint32_t protections; void* old_protections_ptr; uint32_t old_protections; void* setup_config; }; struct Workspace { SetupConfiguration config; uint8_t stack[stack_size]; StackTrampoline tramp; }; } Workspace& allocate_workspace() { auto result = VirtualAllocEx(GetCurrentProcess(), nullptr, sizeof(Workspace), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!result) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); RtlSecureZeroMemory(result, sizeof(Workspace)); return *static_cast<Workspace*>(result); } MyTuple allocate_pic(const string& filename) { fstream file_stream{ filename, fstream::in | fstream::ate | fstream::binary }; if (!file_stream) throw runtime_error("[-] Couldn't open " + filename); auto pic_size = static_cast<size_t>(file_stream.tellg()); file_stream.seekg(0, fstream::beg); auto pic = VirtualAllocEx(GetCurrentProcess(), nullptr, pic_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!pic) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); file_stream.read(static_cast<char*>(pic), pic_size); file_stream.close(); DWORD old_protection; auto prot_result = VirtualProtectEx(GetCurrentProcess(), pic, pic_size, PAGE_EXECUTE_READ, &old_protection); if (!prot_result) throw runtime_error("[-] Couldn't VirtualProtectEx: " + GetLastError()); return MyTuple(pic, pic_size); } uint32_t get_mshtml_gadget_relative_offset(const char *mshtml_filename) { DWORD version_handle; auto version_info_size = GetFileVersionInfoSizeA(mshtml_filename, &version_handle); if (version_info_size == 0) throw runtime_error("[-] Couldn't GetFileVersionInfoSize: " + GetLastError()); vector<char> version_data(version_info_size); auto result = GetFileVersionInfoA(mshtml_filename, version_handle, version_info_size, &version_data[0]); if (!result) { throw runtime_error("[-] Couldn't GetFileVersionInfo: " + GetLastError()); } LPBYTE version_info_buffer; UINT version_info_buffer_size; result = VerQueryValueA(&version_data[0], "\\", reinterpret_cast<VOID FAR* FAR*>(&version_info_buffer), &version_info_buffer_size); if (!result) { throw runtime_error("[-] Couldn't VerQueryValue: " + GetLastError()); } auto *version_info = reinterpret_cast<VS_FIXEDFILEINFO *>(version_info_buffer); WORD unpacked_file_version_words[4] = { (version_info->dwFileVersionMS >> 16) & 0xffff, (version_info->dwFileVersionMS >> 0) & 0xffff, (version_info->dwFileVersionLS >> 16) & 0xffff, (version_info->dwFileVersionLS >> 0) & 0xffff }; auto unpacked_file_version = *reinterpret_cast<DWORDLONG *>(unpacked_file_version_words); printf("[ ] Found %s version %d.%d.%d.%d.\n", mshtml_filename, unpacked_file_version_words[0], unpacked_file_version_words[1], unpacked_file_version_words[2], unpacked_file_version_words[3]); uint32_t relative_offset = 0; auto using_default = false; auto entry_num = 0; while (relative_offset == 0) { auto* version_entry = &mshtml_gadget_offset_map[entry_num]; if (*reinterpret_cast<DWORDLONG *>(version_entry->file_version) == unpacked_file_version || *reinterpret_cast<DWORDLONG *>(version_entry->file_version) == 0) relative_offset = version_entry->relative_offset; using_default = *reinterpret_cast<DWORDLONG *>(version_entry->file_version) == 0; ++entry_num; } if (using_default) { printf("[*] WARNING: Unrecognized version, so using default relative offset.\n"); } printf("[ ] %s ROP gadget is at relative offset 0x%p.\n", mshtml_filename, reinterpret_cast<void *>(relative_offset)); return relative_offset; } void* get_mshtml_gadget() { auto mshtml_filename = "mshtml.dll"; printf("[ ] Loading %s.\n", mshtml_filename); auto mshtml_gadget_offset = get_mshtml_gadget_relative_offset(mshtml_filename); auto mshtml_base = reinterpret_cast<uint8_t*>(LoadLibraryA(mshtml_filename)); if (!mshtml_base) throw runtime_error("[-] Couldn't LoadLibrary: " + GetLastError()); printf("[+] Loaded %s into memory at 0x%p.\n", mshtml_filename, mshtml_base); return mshtml_base + mshtml_gadget_offset; } void* get_gadget(bool use_mshtml, const string& gadget_pic_path) { void* memory; if (use_mshtml) { memory = get_mshtml_gadget(); } else { printf("[ ] Allocating memory for %s.\n", gadget_pic_path.c_str()); size_t size; tie(memory, size) = allocate_pic(gadget_pic_path); printf("[ ] Allocated %u bytes for gadget PIC.\n", size); } return memory; } void launch(const string& setup_pic_path, const string& gadget_pic_path) { printf("[ ] Allocating executable memory for %s.\n", setup_pic_path.c_str()); void* setup_memory; size_t setup_size; tie(setup_memory, setup_size) = allocate_pic(setup_pic_path); printf("[+] Allocated %d bytes for PIC.\n", setup_size); auto use_mshtml{ true }; printf("[ ] Configuring ROP gadget.\n"); auto gadget_memory = get_gadget(use_mshtml, gadget_pic_path); printf("[+] ROP gadget configured.\n"); printf("[ ] Allocating read/write memory for config, stack, and trampoline.\n"); auto& scratch_memory = allocate_workspace(); auto& config = scratch_memory.config; auto& tramp = scratch_memory.tramp; printf("[+] Allocated %u bytes for scratch memory.\n", sizeof(scratch_memory)); printf("[ ] Building stack trampoline.\n"); tramp.old_protections_ptr = &tramp.old_protections; tramp.protections = PAGE_EXECUTE_READ; tramp.current_process = GetCurrentProcess(); tramp.VirtualProtectEx = VirtualProtectEx; tramp.size = static_cast<uint32_t>(setup_size); tramp.address = setup_memory; tramp.return_address = setup_memory; tramp.setup_config = &config; printf("[+] Stack trampoline built.\n"); printf("[ ] Building configuration.\n"); config.setup_address = setup_memory; config.setup_length = static_cast<uint32_t>(setup_size); config.VirtualProtectEx = VirtualProtectEx; config.WaitForSingleObjectEx = WaitForSingleObjectEx; config.CreateWaitableTimer = CreateWaitableTimerW; config.SetWaitableTimer = SetWaitableTimer; config.MessageBox = MessageBoxA; config.tramp_addr = &tramp; config.interval = invocation_interval_ms; config.target = gadget_memory; printf("[+] Configuration built.\n"); printf("[+] Success!\n"); printf(" ================================\n"); printf(" Gargoyle PIC @ -----> 0x%p\n", setup_memory); printf(" ROP gadget @ -------> 0x%p\n", gadget_memory); printf(" Configuration @ ----> 0x%p\n", &scratch_memory.config); printf(" Top of stack @ -----> 0x%p\n", &scratch_memory.stack); printf(" Bottom of stack @ --> 0x%p\n", &scratch_memory.stack[stack_size-1]); printf(" Stack trampoline @ -> 0x%p\n", &scratch_memory.tramp); reinterpret_cast<callable>(setup_memory)(&config); } int main() { try { launch("setup.pic", "gadget.pic"); } catch (exception& e) { printf("%s\n", e.what()); } } <|endoftext|>
<commit_before>9101ad66-2d14-11e5-af21-0401358ea401<commit_msg>9101ad67-2d14-11e5-af21-0401358ea401<commit_after>9101ad67-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>25d23e52-2e3a-11e5-bd65-c03896053bdd<commit_msg>25e94cf0-2e3a-11e5-9650-c03896053bdd<commit_after>25e94cf0-2e3a-11e5-9650-c03896053bdd<|endoftext|>
<commit_before>a2d719f0-2d3f-11e5-9965-c82a142b6f9b<commit_msg>a332112b-2d3f-11e5-be45-c82a142b6f9b<commit_after>a332112b-2d3f-11e5-be45-c82a142b6f9b<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMeshSpatialObjectTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <itkDefaultDynamicMeshTraits.h> #include <itkMesh.h> #include <itkMeshSpatialObject.h> #include <itkTetrahedronCell.h> int itkMeshSpatialObjectTest(int, char * [] ) { typedef itk::DefaultDynamicMeshTraits< float , 3, 3 > MeshTrait; typedef itk::Mesh<float,3,MeshTrait> MeshType; typedef MeshType::CellTraits CellTraits; typedef itk::CellInterface< float, CellTraits > CellInterfaceType; typedef itk::TetrahedronCell<CellInterfaceType> TetraCellType; typedef itk::MeshSpatialObject<MeshType> MeshSpatialObjectType; typedef MeshType::PointType PointType; typedef MeshType::CellType CellType; typedef CellType::CellAutoPointer CellAutoPointer; // Create an itkMesh MeshType::Pointer mesh = MeshType::New(); MeshType::CoordRepType testPointCoords[4][3] = { {0,0,0}, {9,0,0}, {9,9,0}, {0,0,9} }; unsigned long tetraPoints[4] = {0,1,2,4}; int i; for(i=0; i < 4 ; ++i) { mesh->SetPoint(i, PointType(testPointCoords[i])); } mesh->SetCellsAllocationMethod( MeshType::CellsAllocatedDynamicallyCellByCell ); CellAutoPointer testCell1; testCell1.TakeOwnership( new TetraCellType ); testCell1->SetPointIds(tetraPoints); mesh->SetCell(0, testCell1 ); // Create the mesh Spatial Object MeshSpatialObjectType::Pointer meshSO = MeshSpatialObjectType::New(); meshSO->SetMesh(mesh); std::cout << "Testing GetMesh(): "; if(mesh != meshSO->GetMesh()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Bounding Box: "; if( (meshSO->GetBoundingBox()->GetBounds()[0] != 0) || (meshSO->GetBoundingBox()->GetBounds()[1] != 9) || (meshSO->GetBoundingBox()->GetBounds()[2] != 0) || (meshSO->GetBoundingBox()->GetBounds()[3] != 9) || (meshSO->GetBoundingBox()->GetBounds()[4] != 0) || (meshSO->GetBoundingBox()->GetBounds()[5] != 9) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing is inside std::cout << "Testing IsInside: "; MeshSpatialObjectType::PointType inside; inside[0] = 1; inside[1] = 1; inside[2] = 1; MeshSpatialObjectType::PointType outside; outside[0] = 0; outside[1] = 3; outside[2] = 0; if(!meshSO->IsInside(inside) || meshSO->IsInside(outside)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing is valueAt std::cout << "Testing ValueAt: "; double value; meshSO->ValueAt(inside,value); if(!value) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } meshSO->ValueAt(outside,value); if(value) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing IsInside() for triangle mesh std::cout << "Testing IsInside() Triangle: "; typedef itk::TriangleCell<CellInterfaceType> TriangleCellType; // Create an itkMesh MeshType::Pointer meshTriangle = MeshType::New(); MeshType::CoordRepType testTrianglePointCoords[4][3] = { {50,50,64}, {50,100,64}, {100,50,64} , {100,100,64}}; unsigned long trianglePoint1[3] = {0,1,2}; for(i=0; i < 4 ; ++i) { meshTriangle->SetPoint(i, PointType(testTrianglePointCoords[i])); } unsigned long trianglePoint2[] = {1,2,3}; meshTriangle->SetCellsAllocationMethod( MeshType::CellsAllocatedDynamicallyCellByCell ); CellAutoPointer testCell3; testCell3.TakeOwnership( new TriangleCellType ); testCell3->SetPointIds(trianglePoint1); meshTriangle->SetCell(0, testCell3 ); CellAutoPointer testCell4; testCell4.TakeOwnership( new TriangleCellType ); testCell4->SetPointIds(trianglePoint2); meshTriangle->SetCell(1, testCell4 ); // Create the mesh Spatial Object MeshSpatialObjectType::Pointer meshTriangleSO = MeshSpatialObjectType::New(); meshTriangleSO->SetMesh(meshTriangle); itk::Point<double,3> pIn; pIn[0] = 60; pIn[1] = 60; pIn[2] = 64; itk::Point<double,3> pOut; pOut[0] = 60; pOut[1] = 102; pOut[2] = 64; if(!meshTriangleSO->IsInside(pIn) || meshTriangleSO->IsInside(pOut)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: bad index for tetraPoints.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMeshSpatialObjectTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <itkDefaultDynamicMeshTraits.h> #include <itkMesh.h> #include <itkMeshSpatialObject.h> #include <itkTetrahedronCell.h> int itkMeshSpatialObjectTest(int, char * [] ) { typedef itk::DefaultDynamicMeshTraits< float , 3, 3 > MeshTrait; typedef itk::Mesh<float,3,MeshTrait> MeshType; typedef MeshType::CellTraits CellTraits; typedef itk::CellInterface< float, CellTraits > CellInterfaceType; typedef itk::TetrahedronCell<CellInterfaceType> TetraCellType; typedef itk::MeshSpatialObject<MeshType> MeshSpatialObjectType; typedef MeshType::PointType PointType; typedef MeshType::CellType CellType; typedef CellType::CellAutoPointer CellAutoPointer; // Create an itkMesh MeshType::Pointer mesh = MeshType::New(); MeshType::CoordRepType testPointCoords[4][3] = { {0,0,0}, {9,0,0}, {9,9,0}, {0,0,9} }; unsigned long tetraPoints[4] = {0,1,2,3}; int i; for(i=0; i < 4 ; ++i) { mesh->SetPoint(i, PointType(testPointCoords[i])); } mesh->SetCellsAllocationMethod( MeshType::CellsAllocatedDynamicallyCellByCell ); CellAutoPointer testCell1; testCell1.TakeOwnership( new TetraCellType ); testCell1->SetPointIds(tetraPoints); mesh->SetCell(0, testCell1 ); // Create the mesh Spatial Object MeshSpatialObjectType::Pointer meshSO = MeshSpatialObjectType::New(); meshSO->SetMesh(mesh); std::cout << "Testing GetMesh(): "; if(mesh != meshSO->GetMesh()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Bounding Box: "; if( (meshSO->GetBoundingBox()->GetBounds()[0] != 0) || (meshSO->GetBoundingBox()->GetBounds()[1] != 9) || (meshSO->GetBoundingBox()->GetBounds()[2] != 0) || (meshSO->GetBoundingBox()->GetBounds()[3] != 9) || (meshSO->GetBoundingBox()->GetBounds()[4] != 0) || (meshSO->GetBoundingBox()->GetBounds()[5] != 9) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing is inside std::cout << "Testing IsInside: "; MeshSpatialObjectType::PointType inside; inside[0] = 1; inside[1] = 1; inside[2] = 1; MeshSpatialObjectType::PointType outside; outside[0] = 0; outside[1] = 3; outside[2] = 0; if(!meshSO->IsInside(inside) || meshSO->IsInside(outside)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing is valueAt std::cout << "Testing ValueAt: "; double value; meshSO->ValueAt(inside,value); if(!value) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } meshSO->ValueAt(outside,value); if(value) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing IsInside() for triangle mesh std::cout << "Testing IsInside() Triangle: "; typedef itk::TriangleCell<CellInterfaceType> TriangleCellType; // Create an itkMesh MeshType::Pointer meshTriangle = MeshType::New(); MeshType::CoordRepType testTrianglePointCoords[4][3] = { {50,50,64}, {50,100,64}, {100,50,64} , {100,100,64}}; unsigned long trianglePoint1[3] = {0,1,2}; for(i=0; i < 4 ; ++i) { meshTriangle->SetPoint(i, PointType(testTrianglePointCoords[i])); } unsigned long trianglePoint2[] = {1,2,3}; meshTriangle->SetCellsAllocationMethod( MeshType::CellsAllocatedDynamicallyCellByCell ); CellAutoPointer testCell3; testCell3.TakeOwnership( new TriangleCellType ); testCell3->SetPointIds(trianglePoint1); meshTriangle->SetCell(0, testCell3 ); CellAutoPointer testCell4; testCell4.TakeOwnership( new TriangleCellType ); testCell4->SetPointIds(trianglePoint2); meshTriangle->SetCell(1, testCell4 ); // Create the mesh Spatial Object MeshSpatialObjectType::Pointer meshTriangleSO = MeshSpatialObjectType::New(); meshTriangleSO->SetMesh(meshTriangle); itk::Point<double,3> pIn; pIn[0] = 60; pIn[1] = 60; pIn[2] = 64; itk::Point<double,3> pOut; pOut[0] = 60; pOut[1] = 102; pOut[2] = 64; if(!meshTriangleSO->IsInside(pIn) || meshTriangleSO->IsInside(pOut)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/profiler/utils/kernel_stats_utils.h" #include <algorithm> #include <string> #include <tuple> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/protobuf/kernel_stats.pb.h" namespace tensorflow { namespace profiler { namespace { // The maximum number of Kernels displayed on Kernel Stats page. const int kMaxNumOfKernels = 1000; } // namespace void ParseKernelLaunchParams(absl::string_view xstat_kernel_details, KernelReport* kernel) { const std::vector<absl::string_view> params = absl::StrSplit(xstat_kernel_details, absl::ByAnyChar(" \n")); constexpr uint32 kNumDimensions = 3; for (uint32 dim = 0; dim < kNumDimensions; ++dim) { kernel->add_block_dim(1); kernel->add_grid_dim(1); } // Process tokens. for (const auto& param : params) { const std::vector<absl::string_view> key_value = absl::StrSplit(param, ':'); if (key_value.size() != 2) { // Unrecognized token. continue; } absl::string_view key = key_value[0]; absl::string_view value_str = key_value[1]; uint32 value = 0; double pct = 0.0; // Cases that consume a pair of tokens "key:value". if (key == "regs" && absl::SimpleAtoi(value_str, &value)) { kernel->set_registers_per_thread(value); } else if (key == "static_shared" && absl::SimpleAtoi(value_str, &value)) { kernel->set_static_shmem_bytes(value); } else if (key == "dynamic_shared" && absl::SimpleAtoi(value_str, &value)) { kernel->set_dynamic_shmem_bytes(value); } else if (key == "block") { const std::vector<absl::string_view>& block = absl::StrSplit(value_str, ','); uint32 tmp[3]; if (block.size() == 3 && absl::SimpleAtoi(block[0], &tmp[0]) && absl::SimpleAtoi(block[1], &tmp[1]) && absl::SimpleAtoi(block[2], &tmp[2])) { std::copy_n(tmp, 3, kernel->mutable_block_dim()->begin()); } } else if (key == "grid") { const std::vector<absl::string_view>& grid = absl::StrSplit(value_str, ','); uint32 tmp[3]; if (grid.size() == 3 && absl::SimpleAtoi(grid[0], &tmp[0]) && absl::SimpleAtoi(grid[1], &tmp[1]) && absl::SimpleAtoi(grid[2], &tmp[2])) { std::copy_n(tmp, 3, kernel->mutable_grid_dim()->begin()); } } else if (key == "occ_pct" && absl::SimpleAtod(value_str, &pct)) { kernel->set_occupancy_pct(pct); } } } bool IsKernelUsingTensorCore(absl::string_view kernel_name) { // Some examples: volta_h884gemm, volta_fp16_s884gemm, // turing_fp16_s1688cudnn_fp16 bool possible_tensor_kernel = absl::StrContains(kernel_name, "884") || absl::StrContains(kernel_name, "1688") || absl::StrContains(kernel_name, "hmma") || absl::StrContains(kernel_name, "xmma"); if (possible_tensor_kernel) { VLOG(3) << "Possible tensor kernel: " << kernel_name; } return (absl::StartsWith(kernel_name, "volta_i884") || absl::StartsWith(kernel_name, "volta_h884") || absl::StartsWith(kernel_name, "volta_s884") || absl::StartsWith(kernel_name, "volta_fp16_i884") || absl::StartsWith(kernel_name, "volta_fp16_h884") || absl::StartsWith(kernel_name, "volta_fp16_s884") || absl::StartsWith(kernel_name, "turing_i1688") || absl::StartsWith(kernel_name, "turing_h1688") || absl::StartsWith(kernel_name, "turing_s1688") || absl::StartsWith(kernel_name, "turing_fp16_i1688") || absl::StartsWith(kernel_name, "turing_fp16_h1688") || absl::StartsWith(kernel_name, "turing_fp16_s1688") || absl::StrContains(kernel_name, "hmma") || absl::StrContains(kernel_name, "xmma")); } // This list is not exhaustive. bool IsOpTensorCoreEligible(absl::string_view tf_op_name) { // Disable formatting to keep inline comments vertically aligned. // clang-format off return false // Using EndsWith to match Fused operations. || absl::EndsWith(tf_op_name, "Conv2D") || absl::EndsWith(tf_op_name, "Conv2DBackpropFilter") || absl::EndsWith(tf_op_name, "Conv2DBackpropInput") || absl::EndsWith(tf_op_name, "Conv3D") || absl::EndsWith(tf_op_name, "DepthwiseConv2dNative") || absl::EndsWith(tf_op_name, "DepthwiseConv2dNativeBackpropFilter") || absl::EndsWith(tf_op_name, "DepthwiseConv2dNativeBackpropInput") // Using Contains to match V2/V3 suffixes. || absl::StrContains(tf_op_name, "BatchMatMul") // MatMul requires exact matching. || absl::EndsWith(tf_op_name, "/MatMul") || absl::EndsWith(tf_op_name, "FusedMatMul") // cuDNN operations. || absl::EndsWith(tf_op_name, "/CudnnRNN") || absl::StrContains(tf_op_name, "CudnnRNNV") || absl::StrContains(tf_op_name, "CudnnRNNForward") || absl::StrContains(tf_op_name, "CudnnRNNBackprop") // Special cases. || absl::EndsWith(tf_op_name, "XlaDot") || absl::EndsWith(tf_op_name, "XlaDotV2"); // clang-format on } bool IsEinsumTensorCoreEligible(absl::string_view equation) { if (equation.empty()) { return false; } const std::vector<absl::string_view> input_output = absl::StrSplit(equation, "->"); if (input_output.size() != 2) { return false; } const std::vector<absl::string_view> lhs_rhs = absl::StrSplit(input_output[0], ','); return lhs_rhs.size() == 2; } bool KernelReportLessThanComparator::operator()(const KernelReport& lhs, const KernelReport& rhs) const { // Disable formatting to keep vertical alignment for better readability, // and make it easier to reorder columns. // clang-format off auto lhs_tuple = std::make_tuple( lhs.name(), lhs.grid_dim(0), lhs.grid_dim(1), lhs.grid_dim(2), lhs.block_dim(0), lhs.block_dim(1), lhs.block_dim(2), lhs.registers_per_thread(), lhs.static_shmem_bytes(), lhs.dynamic_shmem_bytes(), lhs.is_kernel_using_tensor_core(), lhs.is_op_tensor_core_eligible(), lhs.op_name()); auto rhs_tuple = std::make_tuple( rhs.name(), rhs.grid_dim(0), rhs.grid_dim(1), rhs.grid_dim(2), rhs.block_dim(0), rhs.block_dim(1), rhs.block_dim(2), rhs.registers_per_thread(), rhs.static_shmem_bytes(), rhs.dynamic_shmem_bytes(), rhs.is_kernel_using_tensor_core(), rhs.is_op_tensor_core_eligible(), rhs.op_name()); // clang-format on return lhs_tuple < rhs_tuple; } bool KernelReportEqualToComparator::operator()(const KernelReport& lhs, const KernelReport& rhs) const { // Disable formatting to keep vertical alignment for better readability, // and make it easier to reorder columns. // clang-format off // Put the most expensive string comparisons last. return ( lhs.is_kernel_using_tensor_core() == rhs.is_kernel_using_tensor_core() && lhs.is_op_tensor_core_eligible() == rhs.is_op_tensor_core_eligible() && lhs.block_dim(0) == rhs.block_dim(0) && lhs.block_dim(1) == rhs.block_dim(1) && lhs.block_dim(2) == rhs.block_dim(2) && lhs.grid_dim(0) == rhs.grid_dim(0) && lhs.grid_dim(1) == rhs.grid_dim(1) && lhs.grid_dim(2) == rhs.grid_dim(2) && lhs.registers_per_thread() == rhs.registers_per_thread() && lhs.static_shmem_bytes() == rhs.static_shmem_bytes() && lhs.dynamic_shmem_bytes() == rhs.dynamic_shmem_bytes() && lhs.name() == rhs.name() && lhs.op_name() == rhs.op_name()); // clang-format on } void SortAndKeepTopKDurationKernelReportsInDb(KernelStatsDb* kernel_stats_db) { auto comp = [](const KernelReport& lhs, const KernelReport& rhs) { return lhs.total_duration_ns() > rhs.total_duration_ns() || (lhs.total_duration_ns() == rhs.total_duration_ns() && KernelReportLessThanComparator()(lhs, rhs)); }; // Sort and keep at most <kMaxNumOfKernels> kernel reports. if (kernel_stats_db->reports_size() > kMaxNumOfKernels) { std::partial_sort( kernel_stats_db->mutable_reports()->begin(), kernel_stats_db->mutable_reports()->begin() + kMaxNumOfKernels, kernel_stats_db->mutable_reports()->end(), comp); kernel_stats_db->mutable_reports()->erase( kernel_stats_db->mutable_reports()->begin() + kMaxNumOfKernels, kernel_stats_db->mutable_reports()->end()); } else { std::sort(kernel_stats_db->mutable_reports()->begin(), kernel_stats_db->mutable_reports()->end(), comp); } } void CopyTopKDurationKernelReportsToDb(const KernelReportMap& reports, KernelStatsDb* dst) { std::vector<std::pair<const KernelReport*, const KernelReportValue*>> kernels_to_sort; kernels_to_sort.reserve(reports.size()); for (const auto& report_value : reports) { kernels_to_sort.push_back( std::make_pair(&report_value.first, &report_value.second)); } auto comp = [](const std::pair<const KernelReport*, const KernelReportValue*>& lhs, const std::pair<const KernelReport*, const KernelReportValue*>& rhs) { return lhs.second->total_duration_ns > rhs.second->total_duration_ns || (lhs.second->total_duration_ns == rhs.second->total_duration_ns && KernelReportLessThanComparator()(*lhs.first, *rhs.first)); }; // Sort and copy at most <kMaxNumOfKernels> kernels to <dst>. if (kernels_to_sort.size() > kMaxNumOfKernels) { absl::c_partial_sort(kernels_to_sort, kernels_to_sort.begin() + kMaxNumOfKernels, comp); } else { absl::c_sort(kernels_to_sort, comp); } int copy_size = std::min(kMaxNumOfKernels, static_cast<int>(kernels_to_sort.size())); for (int i = 0; i < copy_size; i++) { KernelReport* report = dst->add_reports(); *report = *kernels_to_sort[i].first; const KernelReportValue& kernel_value = *kernels_to_sort[i].second; // Set value using KernelReportValue. report->set_occurrences(kernel_value.occurrences); report->set_min_duration_ns(kernel_value.min_duration_ns); report->set_max_duration_ns(kernel_value.max_duration_ns); report->set_total_duration_ns(kernel_value.total_duration_ns); } } void InsertOrUpdateKernelReport(const KernelReport& kernel, const KernelReportValue& value, KernelReportMap* dst) { KernelReportValue& element = (*dst)[kernel]; if (element.occurrences == 0) { element = value; } else { element.total_duration_ns += value.total_duration_ns; element.min_duration_ns = std::min(element.min_duration_ns, value.min_duration_ns); element.max_duration_ns = std::max(element.max_duration_ns, value.max_duration_ns); element.occurrences += 1; } } void MergeKernelReports(const KernelReportMap& reports, KernelReportMap* dst) { for (auto& kernel_value : reports) { InsertOrUpdateKernelReport(kernel_value.first, kernel_value.second, dst); } } KernelStatsByOpName GroupKernelReportsByOpName( const KernelStatsDb& kernel_stats_db) { KernelStatsByOpName op_level_kernel_stats; for (const KernelReport& kernel_report : kernel_stats_db.reports()) { auto ret = op_level_kernel_stats.emplace(kernel_report.op_name(), OpLevelKernelStats()); if (ret.second) { // Inserted. Add a new op in <op_level_kernel_stats>. OpLevelKernelStats& stats = ret.first->second; stats.is_op_tensor_core_eligible = kernel_report.is_op_tensor_core_eligible(); stats.total_duration_ns += kernel_report.total_duration_ns(); if (kernel_report.is_kernel_using_tensor_core()) { stats.tensor_core_duration_ns += kernel_report.total_duration_ns(); } } else { // Not inserted. Aggregate kernel stats to op level. OpLevelKernelStats& stats = ret.first->second; // Verifies operations with the same name have the same TensorCore // eligibility. DCHECK_EQ(stats.is_op_tensor_core_eligible, kernel_report.is_op_tensor_core_eligible()); stats.total_duration_ns += kernel_report.total_duration_ns(); if (kernel_report.is_kernel_using_tensor_core()) { stats.tensor_core_duration_ns += kernel_report.total_duration_ns(); } } } return op_level_kernel_stats; } } // namespace profiler } // namespace tensorflow <commit_msg>Update the rules to determine if a kernel uses Tensor Core.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/profiler/utils/kernel_stats_utils.h" #include <algorithm> #include <string> #include <tuple> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/protobuf/kernel_stats.pb.h" namespace tensorflow { namespace profiler { namespace { // The maximum number of Kernels displayed on Kernel Stats page. const int kMaxNumOfKernels = 1000; // A list of patterns to help determine if a kernel uses Tensor Core. // A kernel uses Tensor Core if its kernel name contains any of these patterns. // Some examples of kernel names: volta_h884gemm, turing_fp16_s1688cudnn_fp16 constexpr absl::string_view kTensorCoreKernelNamePatterns[] = { "16816", "c1688", "conv1x1", "conv2d_c1_k1", "dgrad_1x1_stride_2x2", "direct_group", "first_layer_wgrad_kernel", "h1688", "h884", "hmma", "i16832", "i8816", "s884", "s1688", "xmma_gemm", "xmma_implicit_gemm", "xmma_sparse_conv", "xmma_sparse_gemm", "xmma_warp_specialized_implicit_gemm"}; } // namespace void ParseKernelLaunchParams(absl::string_view xstat_kernel_details, KernelReport* kernel) { const std::vector<absl::string_view> params = absl::StrSplit(xstat_kernel_details, absl::ByAnyChar(" \n")); constexpr uint32 kNumDimensions = 3; for (uint32 dim = 0; dim < kNumDimensions; ++dim) { kernel->add_block_dim(1); kernel->add_grid_dim(1); } // Process tokens. for (const auto& param : params) { const std::vector<absl::string_view> key_value = absl::StrSplit(param, ':'); if (key_value.size() != 2) { // Unrecognized token. continue; } absl::string_view key = key_value[0]; absl::string_view value_str = key_value[1]; uint32 value = 0; double pct = 0.0; // Cases that consume a pair of tokens "key:value". if (key == "regs" && absl::SimpleAtoi(value_str, &value)) { kernel->set_registers_per_thread(value); } else if (key == "static_shared" && absl::SimpleAtoi(value_str, &value)) { kernel->set_static_shmem_bytes(value); } else if (key == "dynamic_shared" && absl::SimpleAtoi(value_str, &value)) { kernel->set_dynamic_shmem_bytes(value); } else if (key == "block") { const std::vector<absl::string_view>& block = absl::StrSplit(value_str, ','); uint32 tmp[3]; if (block.size() == 3 && absl::SimpleAtoi(block[0], &tmp[0]) && absl::SimpleAtoi(block[1], &tmp[1]) && absl::SimpleAtoi(block[2], &tmp[2])) { std::copy_n(tmp, 3, kernel->mutable_block_dim()->begin()); } } else if (key == "grid") { const std::vector<absl::string_view>& grid = absl::StrSplit(value_str, ','); uint32 tmp[3]; if (grid.size() == 3 && absl::SimpleAtoi(grid[0], &tmp[0]) && absl::SimpleAtoi(grid[1], &tmp[1]) && absl::SimpleAtoi(grid[2], &tmp[2])) { std::copy_n(tmp, 3, kernel->mutable_grid_dim()->begin()); } } else if (key == "occ_pct" && absl::SimpleAtod(value_str, &pct)) { kernel->set_occupancy_pct(pct); } } } bool IsKernelUsingTensorCore(absl::string_view kernel_name) { VLOG(1) << "kernel name: " << kernel_name; for (absl::string_view pattern : kTensorCoreKernelNamePatterns) { if (absl::StrContains(kernel_name, pattern)) { return true; } } return false; } // This list is not exhaustive. bool IsOpTensorCoreEligible(absl::string_view tf_op_name) { // Disable formatting to keep inline comments vertically aligned. // clang-format off return false // Using EndsWith to match Fused operations. || absl::EndsWith(tf_op_name, "Conv2D") || absl::EndsWith(tf_op_name, "Conv2DBackpropFilter") || absl::EndsWith(tf_op_name, "Conv2DBackpropInput") || absl::EndsWith(tf_op_name, "Conv3D") || absl::EndsWith(tf_op_name, "DepthwiseConv2dNative") || absl::EndsWith(tf_op_name, "DepthwiseConv2dNativeBackpropFilter") || absl::EndsWith(tf_op_name, "DepthwiseConv2dNativeBackpropInput") // Using Contains to match V2/V3 suffixes. || absl::StrContains(tf_op_name, "BatchMatMul") // MatMul requires exact matching. || absl::EndsWith(tf_op_name, "/MatMul") || absl::EndsWith(tf_op_name, "FusedMatMul") // cuDNN operations. || absl::EndsWith(tf_op_name, "/CudnnRNN") || absl::StrContains(tf_op_name, "CudnnRNNV") || absl::StrContains(tf_op_name, "CudnnRNNForward") || absl::StrContains(tf_op_name, "CudnnRNNBackprop") // Special cases. || absl::EndsWith(tf_op_name, "XlaDot") || absl::EndsWith(tf_op_name, "XlaDotV2"); // clang-format on } bool IsEinsumTensorCoreEligible(absl::string_view equation) { if (equation.empty()) { return false; } const std::vector<absl::string_view> input_output = absl::StrSplit(equation, "->"); if (input_output.size() != 2) { return false; } const std::vector<absl::string_view> lhs_rhs = absl::StrSplit(input_output[0], ','); return lhs_rhs.size() == 2; } bool KernelReportLessThanComparator::operator()(const KernelReport& lhs, const KernelReport& rhs) const { // Disable formatting to keep vertical alignment for better readability, // and make it easier to reorder columns. // clang-format off auto lhs_tuple = std::make_tuple( lhs.name(), lhs.grid_dim(0), lhs.grid_dim(1), lhs.grid_dim(2), lhs.block_dim(0), lhs.block_dim(1), lhs.block_dim(2), lhs.registers_per_thread(), lhs.static_shmem_bytes(), lhs.dynamic_shmem_bytes(), lhs.is_kernel_using_tensor_core(), lhs.is_op_tensor_core_eligible(), lhs.op_name()); auto rhs_tuple = std::make_tuple( rhs.name(), rhs.grid_dim(0), rhs.grid_dim(1), rhs.grid_dim(2), rhs.block_dim(0), rhs.block_dim(1), rhs.block_dim(2), rhs.registers_per_thread(), rhs.static_shmem_bytes(), rhs.dynamic_shmem_bytes(), rhs.is_kernel_using_tensor_core(), rhs.is_op_tensor_core_eligible(), rhs.op_name()); // clang-format on return lhs_tuple < rhs_tuple; } bool KernelReportEqualToComparator::operator()(const KernelReport& lhs, const KernelReport& rhs) const { // Disable formatting to keep vertical alignment for better readability, // and make it easier to reorder columns. // clang-format off // Put the most expensive string comparisons last. return ( lhs.is_kernel_using_tensor_core() == rhs.is_kernel_using_tensor_core() && lhs.is_op_tensor_core_eligible() == rhs.is_op_tensor_core_eligible() && lhs.block_dim(0) == rhs.block_dim(0) && lhs.block_dim(1) == rhs.block_dim(1) && lhs.block_dim(2) == rhs.block_dim(2) && lhs.grid_dim(0) == rhs.grid_dim(0) && lhs.grid_dim(1) == rhs.grid_dim(1) && lhs.grid_dim(2) == rhs.grid_dim(2) && lhs.registers_per_thread() == rhs.registers_per_thread() && lhs.static_shmem_bytes() == rhs.static_shmem_bytes() && lhs.dynamic_shmem_bytes() == rhs.dynamic_shmem_bytes() && lhs.name() == rhs.name() && lhs.op_name() == rhs.op_name()); // clang-format on } void SortAndKeepTopKDurationKernelReportsInDb(KernelStatsDb* kernel_stats_db) { auto comp = [](const KernelReport& lhs, const KernelReport& rhs) { return lhs.total_duration_ns() > rhs.total_duration_ns() || (lhs.total_duration_ns() == rhs.total_duration_ns() && KernelReportLessThanComparator()(lhs, rhs)); }; // Sort and keep at most <kMaxNumOfKernels> kernel reports. if (kernel_stats_db->reports_size() > kMaxNumOfKernels) { std::partial_sort( kernel_stats_db->mutable_reports()->begin(), kernel_stats_db->mutable_reports()->begin() + kMaxNumOfKernels, kernel_stats_db->mutable_reports()->end(), comp); kernel_stats_db->mutable_reports()->erase( kernel_stats_db->mutable_reports()->begin() + kMaxNumOfKernels, kernel_stats_db->mutable_reports()->end()); } else { std::sort(kernel_stats_db->mutable_reports()->begin(), kernel_stats_db->mutable_reports()->end(), comp); } } void CopyTopKDurationKernelReportsToDb(const KernelReportMap& reports, KernelStatsDb* dst) { std::vector<std::pair<const KernelReport*, const KernelReportValue*>> kernels_to_sort; kernels_to_sort.reserve(reports.size()); for (const auto& report_value : reports) { kernels_to_sort.push_back( std::make_pair(&report_value.first, &report_value.second)); } auto comp = [](const std::pair<const KernelReport*, const KernelReportValue*>& lhs, const std::pair<const KernelReport*, const KernelReportValue*>& rhs) { return lhs.second->total_duration_ns > rhs.second->total_duration_ns || (lhs.second->total_duration_ns == rhs.second->total_duration_ns && KernelReportLessThanComparator()(*lhs.first, *rhs.first)); }; // Sort and copy at most <kMaxNumOfKernels> kernels to <dst>. if (kernels_to_sort.size() > kMaxNumOfKernels) { absl::c_partial_sort(kernels_to_sort, kernels_to_sort.begin() + kMaxNumOfKernels, comp); } else { absl::c_sort(kernels_to_sort, comp); } int copy_size = std::min(kMaxNumOfKernels, static_cast<int>(kernels_to_sort.size())); for (int i = 0; i < copy_size; i++) { KernelReport* report = dst->add_reports(); *report = *kernels_to_sort[i].first; const KernelReportValue& kernel_value = *kernels_to_sort[i].second; // Set value using KernelReportValue. report->set_occurrences(kernel_value.occurrences); report->set_min_duration_ns(kernel_value.min_duration_ns); report->set_max_duration_ns(kernel_value.max_duration_ns); report->set_total_duration_ns(kernel_value.total_duration_ns); } } void InsertOrUpdateKernelReport(const KernelReport& kernel, const KernelReportValue& value, KernelReportMap* dst) { KernelReportValue& element = (*dst)[kernel]; if (element.occurrences == 0) { element = value; } else { element.total_duration_ns += value.total_duration_ns; element.min_duration_ns = std::min(element.min_duration_ns, value.min_duration_ns); element.max_duration_ns = std::max(element.max_duration_ns, value.max_duration_ns); element.occurrences += 1; } } void MergeKernelReports(const KernelReportMap& reports, KernelReportMap* dst) { for (auto& kernel_value : reports) { InsertOrUpdateKernelReport(kernel_value.first, kernel_value.second, dst); } } KernelStatsByOpName GroupKernelReportsByOpName( const KernelStatsDb& kernel_stats_db) { KernelStatsByOpName op_level_kernel_stats; for (const KernelReport& kernel_report : kernel_stats_db.reports()) { auto ret = op_level_kernel_stats.emplace(kernel_report.op_name(), OpLevelKernelStats()); if (ret.second) { // Inserted. Add a new op in <op_level_kernel_stats>. OpLevelKernelStats& stats = ret.first->second; stats.is_op_tensor_core_eligible = kernel_report.is_op_tensor_core_eligible(); stats.total_duration_ns += kernel_report.total_duration_ns(); if (kernel_report.is_kernel_using_tensor_core()) { stats.tensor_core_duration_ns += kernel_report.total_duration_ns(); } } else { // Not inserted. Aggregate kernel stats to op level. OpLevelKernelStats& stats = ret.first->second; // Verifies operations with the same name have the same TensorCore // eligibility. DCHECK_EQ(stats.is_op_tensor_core_eligible, kernel_report.is_op_tensor_core_eligible()); stats.total_duration_ns += kernel_report.total_duration_ns(); if (kernel_report.is_kernel_using_tensor_core()) { stats.tensor_core_duration_ns += kernel_report.total_duration_ns(); } } } return op_level_kernel_stats; } } // namespace profiler } // namespace tensorflow <|endoftext|>
<commit_before>e378d98c-2747-11e6-8d69-e0f84713e7b8<commit_msg>TODO: Add a beter commit message<commit_after>e3a37b91-2747-11e6-88f5-e0f84713e7b8<|endoftext|>
<commit_before>de68dd28-585a-11e5-b6c3-6c40088e03e4<commit_msg>de703da4-585a-11e5-b463-6c40088e03e4<commit_after>de703da4-585a-11e5-b463-6c40088e03e4<|endoftext|>
<commit_before>9b02ef4a-2e4f-11e5-8cec-28cfe91dbc4b<commit_msg>9b09769c-2e4f-11e5-9144-28cfe91dbc4b<commit_after>9b09769c-2e4f-11e5-9144-28cfe91dbc4b<|endoftext|>
<commit_before>7b265a46-5216-11e5-8877-6c40088e03e4<commit_msg>7b2d2ccc-5216-11e5-8493-6c40088e03e4<commit_after>7b2d2ccc-5216-11e5-8493-6c40088e03e4<|endoftext|>
<commit_before>81cf0dc2-2d15-11e5-af21-0401358ea401<commit_msg>81cf0dc3-2d15-11e5-af21-0401358ea401<commit_after>81cf0dc3-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7822e39c-2d53-11e5-baeb-247703a38240<commit_msg>782361fa-2d53-11e5-baeb-247703a38240<commit_after>782361fa-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>13d9ee5c-585b-11e5-ae56-6c40088e03e4<commit_msg>13e0de74-585b-11e5-b266-6c40088e03e4<commit_after>13e0de74-585b-11e5-b266-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <vector> #include <cstring> #include <sys/unistd.h> #include <cstdlib> using namespace std; class Input { protected: string input; public: Input() { input = ""; } Input(string s) { input = s; } void recieveinput(int &check) { cout << "$: "; getline(cin, input); check = 0; } string get_string() { return input; } }; class Command : public Input { protected: vector<string> v; public: Command() { for(unsigned int i = 0; i < v.size(); ++i) { v.at(i) = ""; } } vector<string> get_vector() { return v; } void parse_string(string s) { unsigned int index = 0; string temp = ""; unsigned int i = 0; unsigned int space = i; for(i = 0; i < s.length(); ++i) { for(i = space; i < s.length(); ++i) { if(s.at(i) != ' ' && s.at(i) != '\0') { temp += s.at(i); } else if(s.at(i) == ' ' || s.at(i) == '\0') { break; } } v.push_back(temp); temp = ""; ++index; space = i + 1; } } void exc_command(string command, int& passed) { passed = 1; char* arg[256]; string tempA = ""; string tempB = ""; string tempC = ""; string tempD = ""; int counter = 0; for(unsigned int i = 0; i < command.size(); i++) { if((command.at(i) != ' ' ) && (counter == 0)) { tempA += command.at(i); } else if((command.at(i) != ' ') && (counter == 1)) { tempB += command.at(i); } else if((command.at(i) != ' ') && (counter == 2)) { tempC += command.at(i); } else if((command.at(i) != ' ') && (counter == 3)) { tempD += command.at(i); } if(command.at(i) == ' ') { counter++; } } if(tempB.size() == 0) { arg[0] = (char*)tempA.c_str(); arg[1] = NULL; } else if(tempC.size() == 0) { arg[0] = (char*)tempA.c_str(); arg[1] = (char*)tempB.c_str(); arg[2] = NULL; } else if(tempD.size() == 0) { arg[0] = (char*)tempA.c_str(); arg[1] = (char*)tempB.c_str(); arg[2] = (char*)tempC.c_str(); arg[4] = NULL; } else { arg[0] = (char*)tempA.c_str(); arg[1] = (char*)tempB.c_str(); arg[2] = (char*)tempC.c_str(); arg[4] = (char*)tempD.c_str(); arg[5] = NULL; } pid_t pid = fork(); if(pid == 0) { if(execvp(arg[0],arg) == -1) { perror("exec"); passed = 0; } } if(pid > 1) { if(wait(0) == -1) { perror("wait"); passed = 0; } } } }; int main() { int check = 0; vector<char> vc1; vector<char> vc2; vector<string> vs1; vector<string> vs2; Input in; Command vc; in.recieveinput(check); vc.parse_string(in.get_string()); unsigned int index = 0; while(in.get_string() != "exit") { for(unsigned int i = 0; i < in.get_string().size(); i++) { if((in.get_string().at(i) == ';') || (in.get_string().at(i) == '&') || (in.get_string().at(i) == '|')) { check = 1; vc1.push_back(in.get_string().at(i)); } ++index; } if(check == 0) { int cmdcount = 1; vc.exc_command(in.get_string(), cmdcount); } else if(check == 1) { string tmp = ""; char *inp; inp = new char[in.get_string().length()]; for(unsigned int i = 0; i < in.get_string().length(); i++) { inp[i] = in.get_string()[i]; } inp[in.get_string().length()] = '\0'; char *pnt; pnt = strtok(inp, ";&&||"); while(pnt != NULL) { int i = 0; while((pnt[i] != '\0') && (pnt[i] != '#')) { tmp += pnt[i]; i++; } if(tmp.at(0) == ' ') { string tmpA = tmp; tmp.clear(); for(unsigned int i = 0; i < tmpA.size(); i++) { if(i == 0) {} else { tmp += tmpA.at(i); } } } vs1.push_back(tmp); pnt = strtok(NULL,";&&||"); tmp.clear(); } vs2 = vs1; vc2 = vc1; vc1.clear(); vs1.clear(); for(int i = vs2.size() - 1; i > -1; i--) { vs1.push_back(vs2.at(i)); } for(int i = vc2.size() - 1; i > -1; i--) { vc1.push_back(vc2.at(i)); } int cmdcnt = 0; int skp = 0; char track = vc1.at(vc1.size() - 1); string track2 = vs1.at(vs1.size() - 1); Command vect; vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); do { if(track == ';') { vc1.pop_back(); skp = 1; } if((track == '&') && (cmdcnt == 1) && (skp == 0)) { vc1.pop_back(); vc1.pop_back(); if((vs1.size() != 0) && (vc1.size() != 0)) { track = vc1.at(vc1.size() - 1); track2 = vs1.at(vs1.size() - 1); vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } skp = 1; } else if((track == '&') && (cmdcnt == 0) && (skp == 0)) { vc1.pop_back(); vc1.pop_back(); vs1.pop_back(); skp = 1; } if((track == '|') && (cmdcnt == 0) && (skp == 0)) { vc1.pop_back(); vc1.pop_back(); if(vs1.size() != 0) { track2 = vs1.at(vs1.size() - 1); vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } skp = 1; } else if((track == '|') && (cmdcnt == 1 ) && (skp = 0)) { vc1.pop_back(); vc1.pop_back(); vs1.pop_back(); skp = 1; } skp = 0; if(vc1.size() != 0) { track = vc1.at(vc1.size() - 1); } else { track = '0'; } if(vs1.size() != 0) { track2 = vs1.at(vs1.size() - 1); } else { track2 = ""; } if((track == ';') && (track2.size() > 1)) { vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } else if((track == '|') && (track2.size() > 1)) { if(cmdcnt == 0) { vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } } else if((track == '&') && (track2.size() > 1)) { if(cmdcnt == 1) { vect.parse_string(track2); vect.exc_command(track2,cmdcnt); vs1.pop_back(); } } else { if(track2.size() > 1) { vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } } } while((vc1.size() != 0) && (vs1.size() != 0)); } vs1.clear(); vs2.clear(); vc1.clear(); vc2.clear(); in.get_string().clear(); in.recieveinput(check); } return 0; }<commit_msg>final changes<commit_after>#include <iostream> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <vector> #include <cstring> #include <sys/unistd.h> #include <cstdlib> using namespace std; class Input { protected: string input; public: Input() { input = ""; } Input(string s) { input = s; } void recieveinput(int &check) { cout << "$: "; getline(cin, input); check = 0; } string get_string() { return input; } }; class Command : public Input { protected: vector<string> v; public: Command() { for(unsigned int i = 0; i < v.size(); ++i) { v.at(i) = ""; } } vector<string> get_vector() { return v; } void parse_string(string s) { unsigned int index = 0; string temp = ""; unsigned int i = 0; unsigned int space = i; for(i = 0; i < s.length(); ++i) { for(i = space; i < s.length(); ++i) { if(s.at(i) != ' ' && s.at(i) != '\0') { temp += s.at(i); } else if(s.at(i) == ' ' || s.at(i) == '\0') { break; } } v.push_back(temp); temp = ""; ++index; space = i + 1; } } void exc_command(string command, int& passed) { passed = 1; char* arg[256]; string tempA = ""; string tempB = ""; string tempC = ""; string tempD = ""; int counter = 0; for(unsigned int i = 0; i < command.size(); i++) { if((command.at(i) != ' ' ) && (counter == 0)) { tempA += command.at(i); } else if((command.at(i) != ' ') && (counter == 1)) { tempB += command.at(i); } else if((command.at(i) != ' ') && (counter == 2)) { tempC += command.at(i); } else if((command.at(i) != ' ') && (counter == 3)) { tempD += command.at(i); } if(command.at(i) == ' ') { counter++; } } if(tempB.size() == 0) { arg[0] = (char*)tempA.c_str(); arg[1] = NULL; } else if(tempC.size() == 0) { arg[0] = (char*)tempA.c_str(); arg[1] = (char*)tempB.c_str(); arg[2] = NULL; } else if(tempD.size() == 0) { arg[0] = (char*)tempA.c_str(); arg[1] = (char*)tempB.c_str(); arg[2] = (char*)tempC.c_str(); arg[4] = NULL; } else { arg[0] = (char*)tempA.c_str(); arg[1] = (char*)tempB.c_str(); arg[2] = (char*)tempC.c_str(); arg[4] = (char*)tempD.c_str(); arg[5] = NULL; } pid_t pid = fork(); if(pid == 0) { if(execvp(arg[0],arg) == -1) { perror("exec"); passed = 0; } } if(pid > 1) { if(wait(0) == -1) { perror("wait"); passed = 0; } } } }; int main() { int check = 0; vector<char> vc1; vector<char> vc2; vector<string> vs1; vector<string> vs2; Input in; Command vc; in.recieveinput(check); vc.parse_string(in.get_string()); unsigned int index = 0; while(in.get_string() != "exit") { for(unsigned int i = 0; i < in.get_string().size(); i++) { if((in.get_string().at(i) == ';') || (in.get_string().at(i) == '&') || (in.get_string().at(i) == '|')) { check = 1; vc1.push_back(in.get_string().at(i)); } ++index; } if(check == 0) { int cmdcount = 1; vc.exc_command(in.get_string(), cmdcount); } else if(check == 1) { string tmp = ""; char *inp; inp = new char[in.get_string().length()]; for(unsigned int i = 0; i < in.get_string().length(); i++) { inp[i] = in.get_string()[i]; } inp[in.get_string().length()] = '\0'; char *pnt; pnt = strtok(inp, ";&&||"); while(pnt != NULL) { int i = 0; while((pnt[i] != '\0') && (pnt[i] != '#')) { tmp += pnt[i]; i++; } if(tmp.at(0) == ' ') { string tmpA = tmp; tmp.clear(); for(unsigned int i = 0; i < tmpA.size(); i++) { if(i == 0) {} else { tmp += tmpA.at(i); } } } vs1.push_back(tmp); pnt = strtok(NULL,";&&||"); tmp.clear(); } vs2 = vs1; vc2 = vc1; vc1.clear(); vs1.clear(); for(int i = vs2.size() - 1; i > -1; i--) { vs1.push_back(vs2.at(i)); } for(int i = vc2.size() - 1; i > -1; i--) { vc1.push_back(vc2.at(i)); } int cmdcnt = 0; int skp = 0; char track = vc1.at(vc1.size() - 1); string track2 = vs1.at(vs1.size() - 1); Command vect; vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); do { if(track == ';') { vc1.pop_back(); skp = 1; } if((track == '&') && (cmdcnt == 1) && (skp == 0)) { vc1.pop_back(); vc1.pop_back(); if((vs1.size() != 0) && (vc1.size() != 0)) { track = vc1.at(vc1.size() - 1); track2 = vs1.at(vs1.size() - 1); vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } skp = 1; } else if((track == '&') && (cmdcnt == 0) && (skp == 0)) { vc1.pop_back(); vc1.pop_back(); vs1.pop_back(); skp = 1; } if((track == '|') && (cmdcnt == 0) && (skp == 0)) { vc1.pop_back(); vc1.pop_back(); if(vs1.size() != 0) { track2 = vs1.at(vs1.size() - 1); vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } skp = 1; } else if((track == '|') && (cmdcnt == 1 ) && (skp = 0)) { vc1.pop_back(); vc1.pop_back(); vs1.pop_back(); skp = 1; } skp = 0; if(vc1.size() != 0) { track = vc1.at(vc1.size() - 1); } else { track = '0'; } if(vs1.size() != 0) { track2 = vs1.at(vs1.size() - 1); } else { track2 = ""; } if((track == ';') && (track2.size() > 1)) { vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } else if((track == '|') && (track2.size() > 1)) { if(cmdcnt == 0) { vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } } else if((track == '&') && (track2.size() > 1)) { if(cmdcnt == 1) { vect.parse_string(track2); vect.exc_command(track2,cmdcnt); vs1.pop_back(); } } else { if(track2.size() > 1) { vect.get_vector().clear(); vect.parse_string(track2); vect.exc_command(track2, cmdcnt); vs1.pop_back(); } } } while((vc1.size() != 0) && (vs1.size() != 0)); } vs1.clear(); vs2.clear(); vc1.clear(); vc2.clear(); in.get_string().clear(); in.recieveinput(check); } return 0; } <|endoftext|>
<commit_before>856278bb-2d15-11e5-af21-0401358ea401<commit_msg>856278bc-2d15-11e5-af21-0401358ea401<commit_after>856278bc-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>69e06fbd-2e4f-11e5-b0ef-28cfe91dbc4b<commit_msg>69e9a930-2e4f-11e5-a93b-28cfe91dbc4b<commit_after>69e9a930-2e4f-11e5-a93b-28cfe91dbc4b<|endoftext|>
<commit_before>d2a738bd-2e4e-11e5-b281-28cfe91dbc4b<commit_msg>d2af271e-2e4e-11e5-9264-28cfe91dbc4b<commit_after>d2af271e-2e4e-11e5-9264-28cfe91dbc4b<|endoftext|>
<commit_before>#include "yael/network/TcpSocket.h" #include <sstream> #include <fcntl.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/types.h> #include <csignal> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <iostream> #include <cerrno> #include <stdexcept> #include <cstring> #include <unistd.h> #include <cassert> #include <glog/logging.h> #include "DatagramMessageSlicer.h" #include "StreamMessageSlicer.h" using namespace std; namespace yael::network { constexpr int TRUE_FLAG = 1; TcpSocket::TcpSocket(MessageMode mode, size_t max_send_queue_size) : m_port(0), m_is_ipv6(false), m_fd(-1), m_max_send_queue_size(max_send_queue_size) { if(mode == MessageMode::Datagram) { m_slicer = std::make_unique<DatagramMessageSlicer>(); } else if(mode == MessageMode::Stream) { m_slicer = std::make_unique<StreamMessageSlicer>(); } else { throw std::runtime_error("Invalid message mode"); } } TcpSocket::TcpSocket(MessageMode mode, int fd, size_t max_send_queue_size) : m_port(0), m_is_ipv6(false), m_fd(fd), m_max_send_queue_size(max_send_queue_size) { if(mode == MessageMode::Datagram) { m_slicer = std::make_unique<DatagramMessageSlicer>(); } else if(mode == MessageMode::Stream) { m_slicer = std::make_unique<StreamMessageSlicer>(); } else { throw std::runtime_error("Invalid message mode"); } uint32_t flags = fcntl(m_fd, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); update_port_number(); calculate_remote_address(); m_state = State::Connected; } TcpSocket::~TcpSocket() { TcpSocket::close(true); } bool TcpSocket::has_messages() const { return m_slicer->has_messages(); } bool TcpSocket::create_fd() { if(m_is_ipv6) { m_fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); } else { m_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } if(!is_valid()) { return false; } ::setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&TRUE_FLAG), sizeof(TRUE_FLAG)); return true; } void TcpSocket::update_port_number() { if(m_is_ipv6) { struct sockaddr_in6 addr; socklen_t addrlen = sizeof(addr); getsockname(m_fd, reinterpret_cast<sockaddr*>(&addr), &addrlen); m_port = htons(addr.sin6_port); } else { struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); getsockname(m_fd, reinterpret_cast<sockaddr*>(&addr), &addrlen); m_port = htons(addr.sin_port); } } bool TcpSocket::bind_socket(const Address& address) { m_is_ipv6 = address.IPv6; if(!create_fd()) { return false; } // Reuse address so we can quickly recover from crashes ::setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &TRUE_FLAG, sizeof(TRUE_FLAG)); if(m_is_ipv6) { sockaddr_in6 sock_addr; address.get_sock_address6(sock_addr); if(::bind(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { return false; } } else { sockaddr_in sock_addr; address.get_sock_address(sock_addr); if(::bind(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { return false; } } update_port_number(); return true; } bool TcpSocket::listen(const Address& address, uint32_t backlog) { if(!bind_socket(address)) { throw socket_error("Failed to bind socket!"); } uint32_t flags = fcntl(m_fd, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); if(::listen(m_fd, backlog) == 0) { m_state = State::Listening; return true; } else { return false; } } uint16_t TcpSocket::port() const { if(!is_valid()) { throw socket_error("Cannot get port of non-existent socket"); } return m_port; } bool TcpSocket::connect(const Address& address, const std::string& name) { if(address.PortNumber == 0) { throw std::invalid_argument("Need to specify a port number"); } if(name.empty()) { m_is_ipv6 = address.IPv6; if(!create_fd()) { throw socket_error(strerror(errno)); } } else { Address my_addr = resolve_URL(name, ANY_PORT, address.IPv6); if(!bind_socket(my_addr)) { throw socket_error(strerror(errno)); } } // Set it blocking just for connect uint32_t flags = fcntl(m_fd, F_GETFL, 0); flags = flags & ~O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); if(m_is_ipv6) { sockaddr_in6 sock_addr; address.get_sock_address6(sock_addr); if(::connect(m_fd, reinterpret_cast<const sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { close(); return false; } } else { sockaddr_in sock_addr; address.get_sock_address(sock_addr); if(::connect(m_fd, reinterpret_cast<const sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { close(); return false; } } flags = fcntl(m_fd, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); calculate_remote_address(); update_port_number(); m_state = State::Connected; return true; } int32_t TcpSocket::internal_accept() { int32_t s = 0; if(m_is_ipv6) { sockaddr_in6 sock_addr; socklen_t len = sizeof(sock_addr); s = ::accept(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), &len); } else { sockaddr_in sock_addr; socklen_t len = sizeof(sock_addr); s = ::accept(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), &len); } if(s < 0 && errno != EWOULDBLOCK) { close(); std::string str = "Failed to accept new connection; "; str += strerror(errno); throw socket_error(str); } return s; } std::vector<std::unique_ptr<Socket>> TcpSocket::accept() { if(!is_listening()) { throw socket_error("Cannot accept on connected TcpTcpSocket"); } std::vector<std::unique_ptr<Socket>> res; while(true) { auto fd = internal_accept(); if(fd >= 0) { auto ptr = new TcpSocket(m_slicer->type(), fd, m_max_send_queue_size); res.emplace_back(std::unique_ptr<Socket>(ptr)); } else { return res; } } } const Address& TcpSocket::get_remote_address() const { return m_remote_address; } void TcpSocket::calculate_remote_address() { char ipstring[16]; sockaddr_in sin; uint32_t len = sizeof(sin); if( getpeername(m_fd, reinterpret_cast<sockaddr*>(&sin), &len) == -1) { m_remote_address.reset(); } inet_ntop( AF_INET, dynamic_cast<in_addr*>(&sin.sin_addr), &ipstring[0], 16); uint16_t port = htons(sin.sin_port); m_remote_address.IP = &ipstring[0]; m_remote_address.PortNumber = port; } bool TcpSocket::close(bool fast) { if(m_state == State::Connected && !fast) { m_state = State::Shutdown; int i = ::shutdown(m_fd, SHUT_RD | SHUT_WR); (void)i; //unused return false; } if(m_fd > 0) { m_state = State::Closed; int i = ::close(m_fd); (void)i; //unused m_fd = -1; m_slicer->buffer().reset(); } else { if(!(m_state == State::Closed || m_state == State::Unknown)) { LOG(FATAL) << "Invalid state"; } //no-op } // threads might wait for send queue to be empty { std::unique_lock lock(m_send_mutex); m_send_queue_cond.notify_all(); } return true; } void TcpSocket::pull_messages() { auto &buffer = m_slicer->buffer(); if(!buffer.is_valid()) { bool res = receive_data(buffer); if(!res) { return; } } try { m_slicer->process_buffer(); } catch(std::exception &e) { // ignore } // read rest of buffer // always pull more until we get EAGAIN pull_messages(); } bool TcpSocket::receive_data(buffer_t &buffer) { if(!is_valid()) { return false; } if(buffer.is_valid()) { throw std::runtime_error("TcpSocket::receive_data failed: Still have data queued up in buffer"); } memset(&buffer.data[0], 0, yael::network::buffer_t::MAX_SIZE); auto x = ::recv(m_fd, buffer.data, yael::network::buffer_t::MAX_SIZE, 0); // Now act accordingly // > 0 -> data // = 0 -> disconnect // < 0 -> error/block if(x > 0) { buffer.size = x; buffer.position = 0; return true; } else if(x == 0) { close(true); return false; } else { const int e = errno; switch(e) { case EAGAIN: break; case ECONNRESET: close(true); break; default: { std::string str = "Failed to receive data; "; str += strerror(errno); // First close socket and then throw the error! close(true); throw socket_error(str); } } return false; } } std::optional<TcpSocket::message_in_t> TcpSocket::receive() { pull_messages(); if(m_slicer->has_messages()) { message_in_t msg; auto res = m_slicer->get_message(msg); if(!res) { throw socket_error("failed to get message"); } return { msg }; } else { return {}; } } bool TcpSocket::send(std::unique_ptr<uint8_t[]> &&data, uint32_t len) { if(len <= 0) { throw socket_error("Message size has to be > 0"); } m_slicer->prepare_message(data, len); auto msg_out = message_out_internal_t(std::move(data), len); { std::unique_lock lock(m_send_mutex); if(m_send_queue_size >= m_max_send_queue_size) { throw send_queue_full(); } m_send_queue_size += msg_out.length; m_send_queue.emplace_back(std::move(msg_out)); } return do_send(); } void TcpSocket::wait_send_queue_empty() { std::unique_lock lock(m_send_mutex); while(m_send_queue_size > 0 && is_valid()) { m_send_queue_cond.wait(lock); } } bool TcpSocket::do_send() { std::unique_lock lock(m_send_mutex); while(true) { auto it = m_send_queue.begin(); if(it == m_send_queue.end()) { // we sent everything! return false; } if(!is_valid()) { throw socket_error("Socket is closed"); } auto &message = *it; const uint32_t length = message.length; const uint8_t *rdata = message.data.get(); while(message.sent_pos < length) { auto s = ::write(m_fd, rdata + message.sent_pos, length - message.sent_pos); if(s > 0) { message.sent_pos += s; } else if(s == 0) { LOG(WARNING) << "Connection lost during send: Message may only be sent partially"; close(true); return false; } else if(s < 0) { auto e = errno; switch(e) { case EAGAIN: case ECONNRESET: // we did not finish sending return true; break; case EPIPE: lock.unlock(); close(true); return false; default: lock.unlock(); close(true); throw socket_error(strerror(errno)); } } } m_send_queue_size -= message.length; m_send_queue.erase(it); m_send_queue_cond.notify_all(); } } } //namespace yael::network <commit_msg>Check socket validity before queueing up more message<commit_after>#include "yael/network/TcpSocket.h" #include <sstream> #include <fcntl.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/types.h> #include <csignal> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <iostream> #include <cerrno> #include <stdexcept> #include <cstring> #include <unistd.h> #include <cassert> #include <glog/logging.h> #include "DatagramMessageSlicer.h" #include "StreamMessageSlicer.h" using namespace std; namespace yael::network { constexpr int TRUE_FLAG = 1; TcpSocket::TcpSocket(MessageMode mode, size_t max_send_queue_size) : m_port(0), m_is_ipv6(false), m_fd(-1), m_max_send_queue_size(max_send_queue_size) { if(mode == MessageMode::Datagram) { m_slicer = std::make_unique<DatagramMessageSlicer>(); } else if(mode == MessageMode::Stream) { m_slicer = std::make_unique<StreamMessageSlicer>(); } else { throw std::runtime_error("Invalid message mode"); } } TcpSocket::TcpSocket(MessageMode mode, int fd, size_t max_send_queue_size) : m_port(0), m_is_ipv6(false), m_fd(fd), m_max_send_queue_size(max_send_queue_size) { if(mode == MessageMode::Datagram) { m_slicer = std::make_unique<DatagramMessageSlicer>(); } else if(mode == MessageMode::Stream) { m_slicer = std::make_unique<StreamMessageSlicer>(); } else { throw std::runtime_error("Invalid message mode"); } uint32_t flags = fcntl(m_fd, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); update_port_number(); calculate_remote_address(); m_state = State::Connected; } TcpSocket::~TcpSocket() { TcpSocket::close(true); } bool TcpSocket::has_messages() const { return m_slicer->has_messages(); } bool TcpSocket::create_fd() { if(m_is_ipv6) { m_fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); } else { m_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } if(!is_valid()) { return false; } ::setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&TRUE_FLAG), sizeof(TRUE_FLAG)); return true; } void TcpSocket::update_port_number() { if(m_is_ipv6) { struct sockaddr_in6 addr; socklen_t addrlen = sizeof(addr); getsockname(m_fd, reinterpret_cast<sockaddr*>(&addr), &addrlen); m_port = htons(addr.sin6_port); } else { struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); getsockname(m_fd, reinterpret_cast<sockaddr*>(&addr), &addrlen); m_port = htons(addr.sin_port); } } bool TcpSocket::bind_socket(const Address& address) { m_is_ipv6 = address.IPv6; if(!create_fd()) { return false; } // Reuse address so we can quickly recover from crashes ::setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &TRUE_FLAG, sizeof(TRUE_FLAG)); if(m_is_ipv6) { sockaddr_in6 sock_addr; address.get_sock_address6(sock_addr); if(::bind(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { return false; } } else { sockaddr_in sock_addr; address.get_sock_address(sock_addr); if(::bind(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { return false; } } update_port_number(); return true; } bool TcpSocket::listen(const Address& address, uint32_t backlog) { if(!bind_socket(address)) { throw socket_error("Failed to bind socket!"); } uint32_t flags = fcntl(m_fd, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); if(::listen(m_fd, backlog) == 0) { m_state = State::Listening; return true; } else { return false; } } uint16_t TcpSocket::port() const { if(!is_valid()) { throw socket_error("Cannot get port of non-existent socket"); } return m_port; } bool TcpSocket::connect(const Address& address, const std::string& name) { if(address.PortNumber == 0) { throw std::invalid_argument("Need to specify a port number"); } if(name.empty()) { m_is_ipv6 = address.IPv6; if(!create_fd()) { throw socket_error(strerror(errno)); } } else { Address my_addr = resolve_URL(name, ANY_PORT, address.IPv6); if(!bind_socket(my_addr)) { throw socket_error(strerror(errno)); } } // Set it blocking just for connect uint32_t flags = fcntl(m_fd, F_GETFL, 0); flags = flags & ~O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); if(m_is_ipv6) { sockaddr_in6 sock_addr; address.get_sock_address6(sock_addr); if(::connect(m_fd, reinterpret_cast<const sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { close(); return false; } } else { sockaddr_in sock_addr; address.get_sock_address(sock_addr); if(::connect(m_fd, reinterpret_cast<const sockaddr*>(&sock_addr), sizeof(sock_addr)) != 0) { close(); return false; } } flags = fcntl(m_fd, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(m_fd, F_SETFL, flags); calculate_remote_address(); update_port_number(); m_state = State::Connected; return true; } int32_t TcpSocket::internal_accept() { int32_t s = 0; if(m_is_ipv6) { sockaddr_in6 sock_addr; socklen_t len = sizeof(sock_addr); s = ::accept(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), &len); } else { sockaddr_in sock_addr; socklen_t len = sizeof(sock_addr); s = ::accept(m_fd, reinterpret_cast<sockaddr*>(&sock_addr), &len); } if(s < 0 && errno != EWOULDBLOCK) { close(); std::string str = "Failed to accept new connection; "; str += strerror(errno); throw socket_error(str); } return s; } std::vector<std::unique_ptr<Socket>> TcpSocket::accept() { if(!is_listening()) { throw socket_error("Cannot accept on connected TcpTcpSocket"); } std::vector<std::unique_ptr<Socket>> res; while(true) { auto fd = internal_accept(); if(fd >= 0) { auto ptr = new TcpSocket(m_slicer->type(), fd, m_max_send_queue_size); res.emplace_back(std::unique_ptr<Socket>(ptr)); } else { return res; } } } const Address& TcpSocket::get_remote_address() const { return m_remote_address; } void TcpSocket::calculate_remote_address() { char ipstring[16]; sockaddr_in sin; uint32_t len = sizeof(sin); if( getpeername(m_fd, reinterpret_cast<sockaddr*>(&sin), &len) == -1) { m_remote_address.reset(); } inet_ntop( AF_INET, dynamic_cast<in_addr*>(&sin.sin_addr), &ipstring[0], 16); uint16_t port = htons(sin.sin_port); m_remote_address.IP = &ipstring[0]; m_remote_address.PortNumber = port; } bool TcpSocket::close(bool fast) { if(m_state == State::Connected && !fast) { m_state = State::Shutdown; int i = ::shutdown(m_fd, SHUT_RD | SHUT_WR); (void)i; //unused return false; } if(m_fd > 0) { m_state = State::Closed; int i = ::close(m_fd); (void)i; //unused m_fd = -1; m_slicer->buffer().reset(); } else { if(!(m_state == State::Closed || m_state == State::Unknown)) { LOG(FATAL) << "Invalid state"; } //no-op } // threads might wait for send queue to be empty { std::unique_lock lock(m_send_mutex); m_send_queue_cond.notify_all(); } return true; } void TcpSocket::pull_messages() { auto &buffer = m_slicer->buffer(); if(!buffer.is_valid()) { bool res = receive_data(buffer); if(!res) { return; } } try { m_slicer->process_buffer(); } catch(std::exception &e) { // ignore } // read rest of buffer // always pull more until we get EAGAIN pull_messages(); } bool TcpSocket::receive_data(buffer_t &buffer) { if(!is_valid()) { return false; } if(buffer.is_valid()) { throw std::runtime_error("TcpSocket::receive_data failed: Still have data queued up in buffer"); } memset(&buffer.data[0], 0, yael::network::buffer_t::MAX_SIZE); auto x = ::recv(m_fd, buffer.data, yael::network::buffer_t::MAX_SIZE, 0); // Now act accordingly // > 0 -> data // = 0 -> disconnect // < 0 -> error/block if(x > 0) { buffer.size = x; buffer.position = 0; return true; } else if(x == 0) { close(true); return false; } else { const int e = errno; switch(e) { case EAGAIN: break; case ECONNRESET: close(true); break; default: { std::string str = "Failed to receive data; "; str += strerror(errno); // First close socket and then throw the error! close(true); throw socket_error(str); } } return false; } } std::optional<TcpSocket::message_in_t> TcpSocket::receive() { pull_messages(); if(m_slicer->has_messages()) { message_in_t msg; auto res = m_slicer->get_message(msg); if(!res) { throw socket_error("failed to get message"); } return { msg }; } else { return {}; } } bool TcpSocket::send(std::unique_ptr<uint8_t[]> &&data, uint32_t len) { if(len <= 0) { throw socket_error("Message size has to be > 0"); } if(!is_valid()) { throw socket_error("Socket is closed"); } m_slicer->prepare_message(data, len); auto msg_out = message_out_internal_t(std::move(data), len); { std::unique_lock lock(m_send_mutex); if(m_send_queue_size >= m_max_send_queue_size) { throw send_queue_full(); } m_send_queue_size += msg_out.length; m_send_queue.emplace_back(std::move(msg_out)); } return do_send(); } void TcpSocket::wait_send_queue_empty() { std::unique_lock lock(m_send_mutex); while(m_send_queue_size > 0 && is_valid()) { m_send_queue_cond.wait(lock); } } bool TcpSocket::do_send() { std::unique_lock lock(m_send_mutex); while(true) { auto it = m_send_queue.begin(); if(it == m_send_queue.end()) { // we sent everything! return false; } if(!is_valid()) { throw socket_error("Socket is closed"); } auto &message = *it; const uint32_t length = message.length; const uint8_t *rdata = message.data.get(); while(message.sent_pos < length) { auto s = ::write(m_fd, rdata + message.sent_pos, length - message.sent_pos); if(s > 0) { message.sent_pos += s; } else if(s == 0) { LOG(WARNING) << "Connection lost during send: Message may only be sent partially"; close(true); return false; } else if(s < 0) { auto e = errno; switch(e) { case EAGAIN: case ECONNRESET: // we did not finish sending return true; break; case EPIPE: lock.unlock(); close(true); return false; default: lock.unlock(); close(true); throw socket_error(strerror(errno)); } } } m_send_queue_size -= message.length; m_send_queue.erase(it); m_send_queue_cond.notify_all(); } } } //namespace yael::network <|endoftext|>
<commit_before>03813487-ad5a-11e7-b635-ac87a332f658<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>040ac959-ad5a-11e7-8572-ac87a332f658<|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin/network/handshake.hpp> #include <cstdint> #include <functional> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> #include <bitcoin/bitcoin/constants.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/network.hpp> #include <bitcoin/bitcoin/primitives.hpp> #include <bitcoin/bitcoin/utility/async_parallel.hpp> #include <bitcoin/bitcoin/version.hpp> namespace libbitcoin { namespace network { using std::placeholders::_1; using std::placeholders::_2; #define BC_USER_AGENT "/libbitcoin:" LIBBITCOIN_VERSION "/" handshake::handshake(threadpool& pool, uint16_t port, uint32_t start_height) : strand_(pool.service()) { // TODO: shouldn't the nonce change on every handshake (like timestamp)? template_version_.nonce = rand(); // template_version_.timestamp = time(nullptr); // Set fixed values inversion template. template_version_.version = bc::protocol_version; template_version_.user_agent = BC_USER_AGENT; template_version_.services = 1; // Set default values inversion template. template_version_.start_height = start_height; template_version_.address_me.services = template_version_.services; template_version_.address_me.ip = bc::localhost_ip_address; template_version_.address_me.port = port; template_version_.address_you.services = template_version_.services; template_version_.address_you.ip = bc::localhost_ip_address; template_version_.address_you.port = port; } void handshake::start(start_handler handle_start) { discover_external_ip(std::bind(handle_start, _1)); } void handshake::ready(channel_ptr node, handshake::handshake_handler handle_handshake) { constexpr size_t sync = 3; // synchrnize three code paths (or error) before calling handle_handshake. const auto completion_callback = async_parallel(handle_handshake, sync); // Copy the version template and set its timestamp. auto session_version = template_version_; session_version.timestamp = time(nullptr); // TODO: where does session_version get customized? // Since we removed cURL discover_external_ip always returns localhost. // The port value was formerly hardwired to bc::protocol_port. node->send(session_version, strand_.wrap(std::bind(&handshake::handle_message_sent, this, _1, completion_callback))); node->subscribe_version( strand_.wrap(std::bind(&handshake::receive_version, this, _1, _2, node, completion_callback))); node->subscribe_verack( strand_.wrap(std::bind(&handshake::receive_verack, this, _1, _2, completion_callback))); } void handshake::handle_message_sent(const std::error_code& ec, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::receive_version(const std::error_code& ec, const version_type&, channel_ptr node, handshake::handshake_handler completion_callback) { if (ec) completion_callback(ec); else node->send(verack_type(), strand_.wrap(std::bind(&handshake::handle_message_sent, this, _1, completion_callback))); } void handshake::receive_verack(const std::error_code& ec, const verack_type&, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::discover_external_ip(discover_ip_handler handle_discover) { strand_.post( std::bind(&handshake::do_discover_external_ip, this, handle_discover)); } void handshake::do_discover_external_ip(discover_ip_handler handle_discover) { template_version_.address_me.ip = localhost_ip_address; handle_discover(std::error_code(), template_version_.address_me.ip); } void handshake::fetch_network_address( fetch_network_address_handler handle_fetch) { strand_.post( std::bind(&handshake::do_fetch_network_address, this, handle_fetch)); } void handshake::do_fetch_network_address( fetch_network_address_handler handle_fetch) { handle_fetch(std::error_code(), template_version_.address_me); } void handshake::set_port(uint16_t port, setter_handler handle_set) { strand_.post( std::bind(&handshake::do_set_port, this, port, handle_set)); } void handshake::do_set_port(uint16_t port, setter_handler handle_set) { template_version_.address_me.port = port; handle_set(std::error_code()); } // TODO: deprecate (any reason to set this dynamically)? void handshake::set_user_agent(const std::string& user_agent, setter_handler handle_set) { strand_.post( std::bind(&handshake::do_set_user_agent, this, user_agent, handle_set)); } // TODO: deprecate (any reason to set this dynamically)? void handshake::do_set_user_agent(const std::string& user_agent, setter_handler handle_set) { template_version_.user_agent = user_agent; handle_set(std::error_code()); } void handshake::set_start_height(uint64_t height, setter_handler handle_set) { strand_.post( std::bind(&handshake::do_set_start_height, this, height, handle_set)); } void handshake::do_set_start_height(uint64_t height, setter_handler handle_set) { // We type this method as uint64_t because that is what is returned by // fetch_last_height, whcih feeds directly into this method. But start_height // is uint32_t in the satoshi network protocol. BITCOIN_ASSERT(height <= bc::max_uint32); template_version_.start_height = static_cast<uint32_t>(height); handle_set(std::error_code()); } void finish_connect(const std::error_code& ec, channel_ptr node, handshake& shake, network::connect_handler handle_connect) { if (ec) handle_connect(ec, node); else shake.ready(node, std::bind(handle_connect, _1, node)); } void connect(handshake& shake, network& net, const std::string& hostname, uint16_t port, network::connect_handler handle_connect) { net.connect(hostname, port, std::bind(finish_connect, _1, _2, std::ref(shake), handle_connect)); } } // namespace network } // namespace libbitcoin <commit_msg>Remove dead code.<commit_after>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin/network/handshake.hpp> #include <cstdint> #include <functional> #include <boost/lexical_cast.hpp> #include <bitcoin/bitcoin/constants.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/network.hpp> #include <bitcoin/bitcoin/primitives.hpp> #include <bitcoin/bitcoin/utility/async_parallel.hpp> #include <bitcoin/bitcoin/version.hpp> namespace libbitcoin { namespace network { using std::placeholders::_1; using std::placeholders::_2; #define BC_USER_AGENT "/libbitcoin:" LIBBITCOIN_VERSION "/" handshake::handshake(threadpool& pool, uint16_t port, uint32_t start_height) : strand_(pool.service()) { // template_version_.nonce = rand(); // template_version_.timestamp = time(nullptr); // Set fixed values inversion template. template_version_.version = bc::protocol_version; template_version_.user_agent = BC_USER_AGENT; template_version_.services = 1; // Set default values inversion template. template_version_.start_height = start_height; template_version_.address_me.services = template_version_.services; template_version_.address_me.ip = bc::localhost_ip_address; template_version_.address_me.port = port; template_version_.address_you.services = template_version_.services; template_version_.address_you.ip = bc::localhost_ip_address; template_version_.address_you.port = port; } void handshake::start(start_handler handle_start) { discover_external_ip(std::bind(handle_start, _1)); } void handshake::ready(channel_ptr node, handshake::handshake_handler handle_handshake) { constexpr size_t sync = 3; // synchrnize three code paths (or error) before calling handle_handshake. const auto completion_callback = async_parallel(handle_handshake, sync); // Copy the version template and set its timestamp. auto session_version = template_version_; template_version_.nonce = rand(); session_version.timestamp = time(nullptr); // Since we removed cURL discover_external_ip always returns localhost. // The port value was formerly hardwired to bc::protocol_port. node->send(session_version, strand_.wrap(std::bind(&handshake::handle_message_sent, this, _1, completion_callback))); node->subscribe_version( strand_.wrap(std::bind(&handshake::receive_version, this, _1, _2, node, completion_callback))); node->subscribe_verack( strand_.wrap(std::bind(&handshake::receive_verack, this, _1, _2, completion_callback))); } void handshake::handle_message_sent(const std::error_code& ec, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::receive_version(const std::error_code& ec, const version_type&, channel_ptr node, handshake::handshake_handler completion_callback) { if (ec) completion_callback(ec); else node->send(verack_type(), strand_.wrap(std::bind(&handshake::handle_message_sent, this, _1, completion_callback))); } void handshake::receive_verack(const std::error_code& ec, const verack_type&, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::discover_external_ip(discover_ip_handler handle_discover) { strand_.post( std::bind(&handshake::do_discover_external_ip, this, handle_discover)); } void handshake::do_discover_external_ip(discover_ip_handler handle_discover) { template_version_.address_me.ip = localhost_ip_address; handle_discover(std::error_code(), template_version_.address_me.ip); } void handshake::fetch_network_address( fetch_network_address_handler handle_fetch) { strand_.post( std::bind(&handshake::do_fetch_network_address, this, handle_fetch)); } void handshake::do_fetch_network_address( fetch_network_address_handler handle_fetch) { handle_fetch(std::error_code(), template_version_.address_me); } void handshake::set_port(uint16_t port, setter_handler handle_set) { strand_.post( std::bind(&handshake::do_set_port, this, port, handle_set)); } void handshake::do_set_port(uint16_t port, setter_handler handle_set) { template_version_.address_me.port = port; handle_set(std::error_code()); } // TODO: deprecate (any reason to set this dynamically)? void handshake::set_user_agent(const std::string& user_agent, setter_handler handle_set) { strand_.post( std::bind(&handshake::do_set_user_agent, this, user_agent, handle_set)); } // TODO: deprecate (any reason to set this dynamically)? void handshake::do_set_user_agent(const std::string& user_agent, setter_handler handle_set) { template_version_.user_agent = user_agent; handle_set(std::error_code()); } void handshake::set_start_height(uint64_t height, setter_handler handle_set) { strand_.post( std::bind(&handshake::do_set_start_height, this, height, handle_set)); } void handshake::do_set_start_height(uint64_t height, setter_handler handle_set) { // We type this method as uint64_t because that is what is returned by // fetch_last_height, whcih feeds directly into this method. But start_height // is uint32_t in the satoshi network protocol. BITCOIN_ASSERT(height <= bc::max_uint32); template_version_.start_height = static_cast<uint32_t>(height); handle_set(std::error_code()); } void finish_connect(const std::error_code& ec, channel_ptr node, handshake& shake, network::connect_handler handle_connect) { if (ec) handle_connect(ec, node); else shake.ready(node, std::bind(handle_connect, _1, node)); } void connect(handshake& shake, network& net, const std::string& hostname, uint16_t port, network::connect_handler handle_connect) { net.connect(hostname, port, std::bind(finish_connect, _1, _2, std::ref(shake), handle_connect)); } } // namespace network } // namespace libbitcoin <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin/network/handshake.hpp> #include <cstdint> #include <functional> #include <system_error> #include <bitcoin/bitcoin/constants.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/network.hpp> #include <bitcoin/bitcoin/primitives.hpp> #include <bitcoin/bitcoin/utility/async_parallel.hpp> #include <bitcoin/bitcoin/version.hpp> namespace libbitcoin { namespace network { using std::placeholders::_1; using std::placeholders::_2; #define BC_USER_AGENT "/libbitcoin:" LIBBITCOIN_VERSION "/" handshake::handshake(threadpool& pool, uint16_t port, uint32_t start_height) : strand_(pool) { // Set fixed values inversion template. template_version_.version = bc::protocol_version; template_version_.user_agent = BC_USER_AGENT; template_version_.services = 1; // Set default values inversion template. template_version_.start_height = start_height; template_version_.address_me.services = template_version_.services; template_version_.address_me.ip = bc::localhost_ip_address; template_version_.address_me.port = port; template_version_.address_you.services = template_version_.services; template_version_.address_you.ip = bc::localhost_ip_address; template_version_.address_you.port = port; } void handshake::start(start_handler handle_start) { discover_external_ip(std::bind(handle_start, _1)); } void handshake::ready(channel_ptr node, handshake::handshake_handler handle_handshake) { constexpr size_t sync = 3; // synchrnize three code paths (or error) before calling handle_handshake. const auto completion_callback = async_parallel(handle_handshake, sync); // Copy the version template and set its timestamp. auto session_version = template_version_; template_version_.nonce = rand(); session_version.timestamp = time(nullptr); // Since we removed cURL discover_external_ip always returns localhost. // The port value was formerly hardwired to bc::protocol_port. node->send(session_version, strand_.wrap(&handshake::handle_message_sent, this, _1, completion_callback)); node->subscribe_version( strand_.wrap(&handshake::receive_version, this, _1, _2, node, completion_callback)); node->subscribe_verack( strand_.wrap(&handshake::receive_verack, this, _1, _2, completion_callback)); } void handshake::handle_message_sent(const std::error_code& ec, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::receive_version(const std::error_code& ec, const version_type&, channel_ptr node, handshake::handshake_handler completion_callback) { if (ec) completion_callback(ec); else node->send(verack_type(), strand_.wrap(&handshake::handle_message_sent, this, _1, completion_callback)); } void handshake::receive_verack(const std::error_code& ec, const verack_type&, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::discover_external_ip(discover_ip_handler handle_discover) { strand_.queue( &handshake::do_discover_external_ip, this, handle_discover); } void handshake::do_discover_external_ip(discover_ip_handler handle_discover) { template_version_.address_me.ip = localhost_ip_address; handle_discover(error::success, template_version_.address_me.ip); } void handshake::fetch_network_address( fetch_network_address_handler handle_fetch) { strand_.queue( &handshake::do_fetch_network_address, this, handle_fetch); } void handshake::do_fetch_network_address( fetch_network_address_handler handle_fetch) { handle_fetch(error::success, template_version_.address_me); } void handshake::set_port(uint16_t port, setter_handler handle_set) { strand_.queue( &handshake::do_set_port, this, port, handle_set); } void handshake::do_set_port(uint16_t port, setter_handler handle_set) { template_version_.address_me.port = port; handle_set(error::success); } // TODO: deprecate (any reason to set this dynamically)? void handshake::set_user_agent(const std::string& user_agent, setter_handler handle_set) { strand_.queue( &handshake::do_set_user_agent, this, user_agent, handle_set); } // TODO: deprecate (any reason to set this dynamically)? void handshake::do_set_user_agent(const std::string& user_agent, setter_handler handle_set) { template_version_.user_agent = user_agent; handle_set(error::success); } void handshake::set_start_height(uint64_t height, setter_handler handle_set) { strand_.queue( &handshake::do_set_start_height, this, height, handle_set); } void handshake::do_set_start_height(uint64_t height, setter_handler handle_set) { // We type this method as uint64_t because that is what is returned by // fetch_last_height, whcih feeds directly into this method. But start_height // is uint32_t in the satoshi network protocol. BITCOIN_ASSERT(height <= bc::max_uint32); template_version_.start_height = static_cast<uint32_t>(height); handle_set(error::success); } void finish_connect(const std::error_code& ec, channel_ptr node, handshake& shake, network::connect_handler handle_connect) { if (ec) handle_connect(ec, node); else shake.ready(node, std::bind(handle_connect, _1, node)); } void connect(handshake& shake, network& net, const std::string& hostname, uint16_t port, network::connect_handler handle_connect) { net.connect(hostname, port, std::bind(finish_connect, _1, _2, std::ref(shake), handle_connect)); } } // namespace network } // namespace libbitcoin <commit_msg>Set templated version nonce value on each instance.<commit_after>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin/network/handshake.hpp> #include <cstdint> #include <functional> #include <system_error> #include <bitcoin/bitcoin/constants.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/network.hpp> #include <bitcoin/bitcoin/primitives.hpp> #include <bitcoin/bitcoin/utility/async_parallel.hpp> #include <bitcoin/bitcoin/version.hpp> namespace libbitcoin { namespace network { using std::placeholders::_1; using std::placeholders::_2; #define BC_USER_AGENT "/libbitcoin:" LIBBITCOIN_VERSION "/" handshake::handshake(threadpool& pool, uint16_t port, uint32_t start_height) : strand_(pool) { // Set fixed values inversion template. template_version_.version = bc::protocol_version; template_version_.user_agent = BC_USER_AGENT; template_version_.services = 1; // Set default values inversion template. template_version_.start_height = start_height; template_version_.address_me.services = template_version_.services; template_version_.address_me.ip = bc::localhost_ip_address; template_version_.address_me.port = port; template_version_.address_you.services = template_version_.services; template_version_.address_you.ip = bc::localhost_ip_address; template_version_.address_you.port = port; } void handshake::start(start_handler handle_start) { discover_external_ip(std::bind(handle_start, _1)); } void handshake::ready(channel_ptr node, handshake::handshake_handler handle_handshake) { constexpr size_t sync = 3; // synchrnize three code paths (or error) before calling handle_handshake. const auto completion_callback = async_parallel(handle_handshake, sync); // Copy the version template and set its timestamp. auto session_version = template_version_; session_version.nonce = rand(); session_version.timestamp = time(nullptr); // Since we removed cURL discover_external_ip always returns localhost. // The port value was formerly hardwired to bc::protocol_port. node->send(session_version, strand_.wrap(&handshake::handle_message_sent, this, _1, completion_callback)); node->subscribe_version( strand_.wrap(&handshake::receive_version, this, _1, _2, node, completion_callback)); node->subscribe_verack( strand_.wrap(&handshake::receive_verack, this, _1, _2, completion_callback)); } void handshake::handle_message_sent(const std::error_code& ec, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::receive_version(const std::error_code& ec, const version_type&, channel_ptr node, handshake::handshake_handler completion_callback) { if (ec) completion_callback(ec); else node->send(verack_type(), strand_.wrap(&handshake::handle_message_sent, this, _1, completion_callback)); } void handshake::receive_verack(const std::error_code& ec, const verack_type&, handshake::handshake_handler completion_callback) { completion_callback(ec); } void handshake::discover_external_ip(discover_ip_handler handle_discover) { strand_.queue( &handshake::do_discover_external_ip, this, handle_discover); } void handshake::do_discover_external_ip(discover_ip_handler handle_discover) { template_version_.address_me.ip = localhost_ip_address; handle_discover(error::success, template_version_.address_me.ip); } void handshake::fetch_network_address( fetch_network_address_handler handle_fetch) { strand_.queue( &handshake::do_fetch_network_address, this, handle_fetch); } void handshake::do_fetch_network_address( fetch_network_address_handler handle_fetch) { handle_fetch(error::success, template_version_.address_me); } void handshake::set_port(uint16_t port, setter_handler handle_set) { strand_.queue( &handshake::do_set_port, this, port, handle_set); } void handshake::do_set_port(uint16_t port, setter_handler handle_set) { template_version_.address_me.port = port; handle_set(error::success); } // TODO: deprecate (any reason to set this dynamically)? void handshake::set_user_agent(const std::string& user_agent, setter_handler handle_set) { strand_.queue( &handshake::do_set_user_agent, this, user_agent, handle_set); } // TODO: deprecate (any reason to set this dynamically)? void handshake::do_set_user_agent(const std::string& user_agent, setter_handler handle_set) { template_version_.user_agent = user_agent; handle_set(error::success); } void handshake::set_start_height(uint64_t height, setter_handler handle_set) { strand_.queue( &handshake::do_set_start_height, this, height, handle_set); } void handshake::do_set_start_height(uint64_t height, setter_handler handle_set) { // We type this method as uint64_t because that is what is returned by // fetch_last_height, whcih feeds directly into this method. But start_height // is uint32_t in the satoshi network protocol. BITCOIN_ASSERT(height <= bc::max_uint32); template_version_.start_height = static_cast<uint32_t>(height); handle_set(error::success); } void finish_connect(const std::error_code& ec, channel_ptr node, handshake& shake, network::connect_handler handle_connect) { if (ec) handle_connect(ec, node); else shake.ready(node, std::bind(handle_connect, _1, node)); } void connect(handshake& shake, network& net, const std::string& hostname, uint16_t port, network::connect_handler handle_connect) { net.connect(hostname, port, std::bind(finish_connect, _1, _2, std::ref(shake), handle_connect)); } } // namespace network } // namespace libbitcoin <|endoftext|>
<commit_before>30d9aa10-2e3a-11e5-91e7-c03896053bdd<commit_msg>30e879c8-2e3a-11e5-a200-c03896053bdd<commit_after>30e879c8-2e3a-11e5-a200-c03896053bdd<|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <cstdlib> #include <bitset> #include <unistd.h> #define BUFSIZE 8192 enum VintState { GET_VINT_WIDTH, GET_VINT_DATA }; class simple_vint{ public: uint8_t width; uint8_t data[8]; uint64_t get_int(){ uint64_t value = 0; value = data[width - 1]; for(int i = width - 1; i > 0; --i){ value += ((uint32_t)data[i - 1] << ((width - i) * 8)); } return value; } }; class simple_ebml_element { public: simple_vint id; simple_vint size; uint8_t* data; }; int main(int argc, char** argv){ int len, mask; uint8_t buffer[BUFSIZE]; int total_bytes = 0; int from_bytes = 0; int to_bytes = 0; simple_vint* e_id; simple_vint* e_size; for(int i = 0; i < argc; i++){ if((std::strcmp(argv[i], "-f") == 0) && argc > i){ from_bytes = std::stoi(argv[i + 1]); }else if((std::strcmp(argv[i], "-t") == 0) && argc > i){ to_bytes = std::stoi(argv[i + 1]); }else if((std::strcmp(argv[i], "-l") == 0) && argc > i){ to_bytes = from_bytes + std::stoi(argv[i + 1]); } } if((len = read(STDIN_FILENO, buffer, BUFSIZE)) == -1){ std::cout << "Uh oh, read error!\n"; return 1; } for(int i = 0; i < len;){ if(total_bytes + i >= to_bytes){ break; } std::bitset<8> sbits(buffer[i]); std::cout << "Element Start: " << sbits << std::endl; e_id = new simple_vint(); e_id->width = 1; mask = 0x80; // Find the size of the element id. while(!(buffer[i] & mask)){ mask >>= 1; e_id->width += 1; } std::cout << "Id Vint Width: " << (int)e_id->width << std::endl; // Get rid of "vint marker" //buffer[i] = 0; //buffer[i] ^= mask; //vint->data[0] = buffer[i]; //vint->width = 1; //std::cout << "Value: " << std::dec << vint->get_int() << std::endl; std::cout << "Id Vint Bytes: "; for(int j = 0; j < e_id->width; ++j){ e_id->data[j] = buffer[i + j]; std::bitset<8> bits(e_id->data[j]); std::cout << bits; } i += e_id->width; std::cout << std::endl; std::cout << "Id Hex: 0x"; for(int j = 0; j < e_id->width; ++j){ std::cout << std::hex << (int)e_id->data[j]; } std::cout << std::endl; std::cout << "Id Value: " << std::dec << e_id->get_int() << std::endl; e_size = new simple_vint(); e_size->width = 1; mask = 0x80; // Find the size of the element data. while(!(buffer[i] & mask)){ mask >>= 1; e_size->width += 1; } std::cout << "Data Size Vint Width: " << (int)e_size->width << std::endl; buffer[i] ^= mask; std::cout << "Data Size Vint Bytes: "; for(int j = 0; j < e_size->width; ++j){ e_size->data[j] = buffer[i + j]; std::bitset<8> bits(e_size->data[j]); std::cout << bits; } i += e_size->width; std::cout << std::endl; std::cout << "Data Size: " << std::dec << e_size->get_int() << std::endl; delete e_id; delete e_size; std::cout << std::endl; } total_bytes += len; return 0; } <commit_msg>Starting to fill out the meat of the data. Supporting EBML data types.<commit_after>#include <iostream> #include <cstring> #include <cstdlib> #include <bitset> #include <unistd.h> #define BUFSIZE 8192 enum VintState { GET_VINT_WIDTH, GET_VINT_DATA }; class simple_vint{ public: uint8_t width; uint8_t data[8]; uint64_t get_int(){ uint64_t value = 0; value = data[width - 1]; for(int i = width - 1; i > 0; --i){ value += ((uint32_t)data[i - 1] << ((width - i) * 8)); } return value; } }; class simple_ebml_element { public: simple_vint id; simple_vint size; uint8_t* data; }; int main(int argc, char** argv){ int len, mask; uint8_t buffer[BUFSIZE]; int total_bytes = 0; int from_bytes = 0; int to_bytes = 0; simple_vint* e_id; simple_vint* e_size; for(int i = 0; i < argc; i++){ if((std::strcmp(argv[i], "-f") == 0) && argc > i){ from_bytes = std::stoi(argv[i + 1]); }else if((std::strcmp(argv[i], "-t") == 0) && argc > i){ to_bytes = std::stoi(argv[i + 1]); }else if((std::strcmp(argv[i], "-l") == 0) && argc > i){ to_bytes = from_bytes + std::stoi(argv[i + 1]); } } if((len = read(STDIN_FILENO, buffer, BUFSIZE)) == -1){ std::cout << "Uh oh, read error!\n"; return 1; } for(int i = 0; i < len;){ if(to_bytes > 0 && total_bytes + i >= to_bytes){ break; } std::bitset<8> sbits(buffer[i]); std::cout << "Element Start: " << sbits << std::endl; e_id = new simple_vint(); e_id->width = 1; mask = 0x80; // Find the size of the element id. while(!(buffer[i] & mask)){ mask >>= 1; e_id->width += 1; } std::cout << "Id Vint Width: " << (int)e_id->width << std::endl; // Get rid of "vint marker" //buffer[i] = 0; //buffer[i] ^= mask; //vint->data[0] = buffer[i]; //vint->width = 1; //std::cout << "Value: " << std::dec << vint->get_int() << std::endl; std::cout << "Id Vint Bytes: "; for(int j = 0; j < e_id->width; ++j){ e_id->data[j] = buffer[i + j]; std::bitset<8> bits(e_id->data[j]); std::cout << bits; } i += e_id->width; std::cout << std::endl; std::cout << "Id Hex: 0x"; for(int j = 0; j < e_id->width; ++j){ std::cout << std::hex << (int)e_id->data[j]; } std::cout << std::endl; std::cout << "Id Value: " << std::dec << e_id->get_int() << std::endl; e_size = new simple_vint(); e_size->width = 1; mask = 0x80; std::bitset<8> dbits(buffer[i]); std::cout << "Data Size Start: " << dbits << std::endl; // Find the size of the element data. while(!(buffer[i] & mask)){ mask >>= 1; e_size->width += 1; } std::cout << "Data Size Vint Width: " << (int)e_size->width << std::endl; buffer[i] ^= mask; std::cout << "Data Size Vint Bytes: "; for(int j = 0; j < e_size->width; ++j){ e_size->data[j] = buffer[i + j]; std::bitset<8> bits(e_size->data[j]); std::cout << bits; } i += e_size->width; std::cout << std::endl; std::cout << "Data Size: " << std::dec << e_size->get_int() << std::endl; // 0x1a45dfa3 if(e_id->get_int() == 440786851){ std::cout << "-----------------------------\n"; std::cout << "\tEBML HEADER\n"; std::cout << "-----------------------------\n"; // 0x18538067 }else if(e_id->get_int() == 408125543){ std::cout << "-----------------------------\n"; std::cout << "\tSEGMENT\n"; std::cout << "-----------------------------\n"; // 0x114d9b74 }else if(e_id->get_int() == 290298740){ std::cout << "-----------------------------\n"; std::cout << "\tSEEK INFO\n"; std::cout << "-----------------------------\n"; // 0x4dbb }else if(e_id->get_int() == 19899){ std::cout << "-----------------------------\n"; std::cout << "\tSEEK\n"; std::cout << "-----------------------------\n"; // 0xec }else if(e_id->get_int() == 236){ std::cout << "-----------------------------\n"; std::cout << "\tVOID\n"; std::cout << "-----------------------------\n"; i += e_size->get_int(); // 0x1549a966 }else if(e_id->get_int() == 357149030){ std::cout << "-----------------------------\n"; std::cout << "\tSEGMENT INFO\n"; std::cout << "-----------------------------\n"; // 0x1654ae6b }else if(e_id->get_int() == 374648427){ std::cout << "-----------------------------\n"; std::cout << "\tTRACKS\n"; std::cout << "-----------------------------\n"; // 0xae }else if(e_id->get_int() == 174){ std::cout << "-----------------------------\n"; std::cout << "\tTRACK ENTRY\n"; std::cout << "-----------------------------\n"; // 0xe0 }else if(e_id->get_int() == 224){ std::cout << "-----------------------------\n"; std::cout << "\tTRACK VIDEO\n"; std::cout << "-----------------------------\n"; // Other }else{ std::cout << "Data (bytes): " << std::endl; std::cout << "-----------------------------\n"; for(int j = 0, size = e_size->get_int(); j < size; ++j){ std::cout << "Byte: " << (int)buffer[i + j] << std::endl; } i += e_size->get_int(); std::cout << "-----------------------------\n"; } delete e_id; delete e_size; } total_bytes += len; return 0; } <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QCommandLineParser> #include <QStandardPaths> #include <QDir> #include "converter.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setApplicationName("pgserverconverter"); app.setApplicationVersion("1.0"); QCommandLineParser parser; parser.setApplicationDescription("Convert saved pgadmin3 servers to pgadmin4 db entries"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption inputFile(QStringList() << "i" << "input", #ifdef Q_OS_LINUX QCoreApplication::translate("main", "pgadmin3 config file. Defaults to ~/.pgadmin3"), #endif #ifdef Q_OS_MAC QCoreApplication::translate("main", "pgadmin3 config file. Defaults to ~/Library/Preferences/pgadmin3 Preferences"), #endif #ifdef Q_OS_WIN QCoreApplication::translate("main", "pgadmin3 config file. Defaults to the windows registry"), #endif QCoreApplication::translate("main", "inputfile")); parser.addOption(inputFile); QCommandLineOption database(QStringList() << "d" << "database", #ifdef Q_OS_WIN QCoreApplication::translate("main", "Path to pgAdmin4's SQLite database. Defaults to ~/AppData/Roaming/pgadmin/pgadmin4.db"), #else QCoreApplication::translate("main", "Path to pgAdmin4's SQLite database. Defaults to ~/.pgadmin/pgadmin4.db"), #endif QCoreApplication::translate("main", "database")); parser.addOption(database); parser.process(app); QString _input; QString _db; if (parser.isSet("input")) { _input = parser.value("input"); } else { #ifdef Q_OS_LINUX _input = QDir::homePath() + "/.pgadmin3"; #endif #ifdef Q_OS_MAC _input = QDir::homePath() + "/Library/Preferences/pgadmin3 Preferences"; #endif #ifdef Q_OS_WIN _input = "Windows Registry"; #endif } if (parser.isSet("database")) { _db = parser.value("database"); } else { #ifdef Q_OS_WIN _db = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)[0] + "/../pgadmin/pgadmin4.db"; #else _db = QDir::homePath() + "/.pgadmin/pgadmin4.db"; #endif } converter c(_input, _db); c.start(); return app.exec(); } <commit_msg>touchup<commit_after>#include <QCoreApplication> #include <QCommandLineParser> #include <QStandardPaths> #include <QDir> #include "converter.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setApplicationName("pgserverconverter"); app.setApplicationVersion("1.0"); QCommandLineParser parser; parser.setApplicationDescription("Convert saved pgadmin3 servers to pgadmin4 db entries"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption inputFile(QStringList() << "i" << "input", #ifdef Q_OS_LINUX QCoreApplication::translate("main", "pgadmin3 config file. Defaults to ~/.pgadmin3"), #endif #ifdef Q_OS_MAC QCoreApplication::translate("main", "pgadmin3 config file. Defaults to ~/Library/Preferences/pgadmin3 Preferences"), #endif #ifdef Q_OS_WIN QCoreApplication::translate("main", "pgadmin3 config file. Defaults to the windows registry"), #endif QCoreApplication::translate("main", "inputfile")); parser.addOption(inputFile); QCommandLineOption database(QStringList() << "d" << "database", #ifdef Q_OS_WIN QCoreApplication::translate("main", "Path to pgAdmin4's SQLite database. Defaults to ~/AppData/Roaming/pgadmin/pgadmin4.db"), #else QCoreApplication::translate("main", "Path to pgAdmin4's SQLite database. Defaults to ~/.pgadmin/pgadmin4.db"), #endif QCoreApplication::translate("main", "database")); parser.addOption(database); parser.process(app); QString _input; QString _db; if (parser.isSet("input")) { _input = parser.value("input"); } else { #ifdef Q_OS_LINUX _input = QDir::homePath() + "/.pgadmin3"; #endif #ifdef Q_OS_MAC _input = QDir::homePath() + "/Library/Preferences/pgadmin3 Preferences"; #endif #ifdef Q_OS_WIN _input = "Windows Registry"; #endif } if (parser.isSet("database")) { _db = parser.value("database"); } else { #ifdef Q_OS_WIN _db = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)[0] + "/../pgadmin/pgadmin4.db"; #else _db = QDir::homePath() + "/.pgadmin/pgadmin4.db"; #endif } converter c(_input, _db); c.start(); return app.exec(); } <|endoftext|>
<commit_before>d415c2eb-313a-11e5-94ef-3c15c2e10482<commit_msg>d41bc411-313a-11e5-9655-3c15c2e10482<commit_after>d41bc411-313a-11e5-9655-3c15c2e10482<|endoftext|>
<commit_before>#include <iostream> #include <string.h> #include <stdio.h> #include <vector> #include <map> #include <bits/stl_algo.h> #include <bitset> #include <fstream> #include <chrono> using namespace std; typedef struct GraphTree { unsigned char symbol; unsigned char symbolExtended; unsigned long long int nrOfApp; GraphTree *parent; GraphTree *left; GraphTree *right; unsigned long long int index; } ShannonTree; typedef std::vector<GraphTree *> GraphIndex; typedef std::map<int, std::pair<GraphTree *, std::string>> MappedSymbols; typedef std::chrono::duration<int, std::milli> miliseconds_type; typedef struct GraphSearch { std::string code; bool type; GraphTree *reference; }; int ENCODE_BITS = 8; int ESC_VALUE = 257; int EOS_VALUE = 256; MappedSymbols symbolMap; GraphIndex indexedGraph; auto cmp = [](std::pair<unsigned char, unsigned long int> const &a, std::pair<unsigned char, unsigned long int> const &b) { return a.second != b.second ? a.second > b.second : a.first < b.first; }; GraphTree *initGraph() { GraphTree *parent, *left, *right; parent = new GraphTree; left = new GraphTree; right = new GraphTree; parent->symbol = 0; parent->symbolExtended = 0; parent->nrOfApp = 2; parent->parent = NULL; parent->left = left; parent->right = right; parent->index = 1; indexedGraph.push_back(parent); left->parent = parent; right->parent = parent; left->left = NULL; left->right = NULL; right->left = NULL; right->right = NULL; left->symbol = 255; left->symbolExtended = 1; right->symbol = 255; right->symbolExtended = 2; left->nrOfApp = 1; right->nrOfApp = 1; left->index = 2; right->index = 3; indexedGraph.push_back(left); indexedGraph.push_back(right); symbolMap[right->symbol + right->symbolExtended].first = right; symbolMap[right->symbol + right->symbolExtended].second = "1"; symbolMap[left->symbol + left->symbolExtended].first = left; symbolMap[left->symbol + left->symbolExtended].second = "0"; return parent; } /** * find symbol in alphabet map, if it is first occurence for symbol return a reference for ESC symbol */ GraphSearch findSymbol(unsigned char symbol) { GraphSearch result; if (symbolMap.count(symbol) > 0) { result.code = symbolMap[symbol].second; result.type = true; result.reference = symbolMap[symbol].first; } else { result.code = symbolMap[ESC_VALUE].second; result.type = false; result.reference = symbolMap[ESC_VALUE].first; } return result; } void updateSymbol(GraphSearch result) { (result.reference)->nrOfApp = (result.reference)->nrOfApp + 1; } void addSymbol(GraphSearch result, unsigned char symbol) { GraphTree *left, *right; left = new GraphTree; left->nrOfApp = 1; left->right = NULL; left->left = NULL; left->symbol = symbol; left->symbolExtended = 0; left->parent = result.reference; left->index = (result.reference)->index + 1; right = new GraphTree; right->nrOfApp = 1; right->right = NULL; right->left = NULL; right->symbol = 255; right->symbolExtended = 2; right->parent = result.reference; right->index = (result.reference)->index + 2; (result.reference)->left = left; (result.reference)->right = right; (result.reference)->nrOfApp = 2; (result.reference)->symbol = 0; (result.reference)->symbolExtended = 0; indexedGraph.push_back(left); indexedGraph.push_back(right); symbolMap[ESC_VALUE].first = right; } void displayIndexedGraph() { GraphIndex::size_type iterator; for (iterator = 0; iterator < indexedGraph.size(); ++iterator) { std::cout << (indexedGraph[iterator])->nrOfApp << " " << (indexedGraph[iterator])->index << " -> " << iterator + 1 << "\n"; } } void displayGraph(GraphTree *root) { if ((root->symbol + root->symbolExtended) == 0) { std::cout << "Pondere: " << root->nrOfApp << "\n"; displayGraph(root->left); displayGraph(root->right); } else { std::cout << "Simbol: " << (root->symbol + root->symbolExtended) << "\n"; } } void balanceGraph(GraphTree *node) { GraphTree *aux, *changeAux, *parent; GraphIndex::size_type iterator, auxIndex; for (iterator = node->index - 1; iterator > 0; iterator--) { if ((indexedGraph[iterator - 1])->nrOfApp >= node->nrOfApp) { break; } } if (iterator == node->index - 1) { node->parent->nrOfApp++; if (node->parent->parent != NULL) { balanceGraph(node->parent); } } if (iterator == node->index - 2) { (indexedGraph[iterator - 1])->right = indexedGraph[iterator]; (indexedGraph[iterator - 1])->left = node; indexedGraph[iterator]->index++; node->index--; indexedGraph[iterator] = node; indexedGraph[iterator + 1] = (indexedGraph[iterator - 1])->right; balanceGraph(node); } if (iterator > node->index - 2 && node->index - 2 > 1) { aux = indexedGraph[iterator - 1]; indexedGraph[iterator - 1] = node; auxIndex = node->index; parent = aux->parent; changeAux = node->parent; if (iterator % 2 == 0) { parent->left = node; } else { parent->right = node; } node->parent = parent; indexedGraph[auxIndex - 1] = aux; if (auxIndex % 2 == 0) { changeAux->left = node; } else { changeAux->right = node; } balanceGraph(indexedGraph[iterator - 1]); } std::cout << "\n\n"; } void encodeSymbol(unsigned char symbol, GraphTree *parent) { GraphSearch result; result = findSymbol(symbol); if (result.type == true) { updateSymbol(result); } else { addSymbol(result, symbol); } balanceGraph(result.reference); } void swapChild(GraphTree *root) { GraphTree *aux; aux = root->left; root->left = root->right; root->right = aux; } void balanceTree(GraphTree *root) { if ((root->symbol + root->symbolExtended) == 0) { if (root->left->nrOfApp < root->right->nrOfApp) { swapChild(root); } } } void encodeFile() { } void compressFile(std::string fileName) { GraphTree *huffmanTree; huffmanTree = initGraph(); encodeSymbol('a', huffmanTree); encodeSymbol('b', huffmanTree); displayIndexedGraph(); std::cout << "\n\n"; displayGraph(huffmanTree); // balanceTree(huffmanTree); // encodeSymbol('b', huffmanTree); // balanceTree(huffmanTree); // std::cout << "\n\n"; // displayGraph(huffmanTree); } void uncompressFile(std::string fileName) { } void displayOptions() { std::cout << "Alege fisierul!" << "\n\n Audio:\n"; std::cout << "\t1.)instr_01.wav\n"; std::cout << "\t2.)sound_01.wav\n"; std::cout << "\t3.)speech_01.wav\n"; std::cout << "\nDocuments:\n"; std::cout << "\t4.)Documentatie_UMAPID.doc\n"; std::cout << "\t5.)Documentatie_UMAPID.pdf\n"; std::cout << "\t6.)Prefata_Undine.txt\n"; std::cout << "\t7.)show_audio.m\n"; std::cout << "\t8.)Y04.M\n"; std::cout << "\nExecutables:\n"; std::cout << "\t9.)KARMA_DATA482#1_5_V7.mat\n"; std::cout << "\t10.)quartz.dll\n"; std::cout << "\t11.)WinRar.exe\n"; std::cout << "\t12.)WINZIP32.EXE\n"; } std::ifstream::pos_type filesize(std::string fileName) { std::ifstream in(fileName.c_str(), std::ifstream::ate | std::ifstream::binary); return in.tellg(); } void displayInformations(std::string fileName) { std::ifstream::pos_type compressedFileSize, fileSize, uncompressedFileSize; std::string compressedFileName, uncompressedFileName; compressedFileName = fileName + ".psh"; uncompressedFileName = fileName + ".pshu"; compressedFileSize = filesize(compressedFileName); fileSize = filesize(fileName); uncompressedFileSize = filesize(uncompressedFileName); std::cout << "Norma: " << (fileSize - uncompressedFileSize) * (fileSize - uncompressedFileSize) << "\n"; std::cout << "Rata compresie: " << (1 - ((float) compressedFileSize) / ((float) uncompressedFileSize)) * 100 << "%\n"; std::cout << "Factor compresie: " << (((float) compressedFileSize) / ((float) fileSize)) * 100 << "%\n"; } int main() { std::vector<std::string> files = { ".\\audio\\instr_01.wav", ".\\audio\\sound_01.wav", ".\\audio\\speech_01.wav", ".\\documents\\Documentatie_UMAPID.doc", ".\\documents\\Documentatie_UMAPID.pdf", ".\\documents\\Prefata_Undine.txt", ".\\documents\\show_audio.m", ".\\documents\\Y04.M", ".\\executables\\KARMA_DATA482#1_5_V7.mat", ".\\executables\\quartz.dll", ".\\executables\\WinRar.exe", ".\\executables\\WINZIP32.EXE", ".\\documents\\input.txt", "D:\\input.txt", }; int option; //displayOptions(); //std::cout << "Select file!..\n"; //std::cin >> option; // if (option < 1 && option > 14) { // std::cout << "Invalid option!"; // return 0; // } auto startC = std::chrono::high_resolution_clock::now(); compressFile(files[2]); auto endC = std::chrono::high_resolution_clock::now(); auto timeC = endC - startC; std::cout << "Compressed time: " << std::chrono::duration_cast<miliseconds_type>(timeC).count() << " miliseconds.\n"; auto startU = std::chrono::high_resolution_clock::now(); // uncompressFile(files[option - 1]); auto endU = std::chrono::high_resolution_clock::now(); auto timeU = endU - startU; std::cout << "Uncompressed time: " << std::chrono::duration_cast<miliseconds_type>(timeU).count() << " miliseconds.\n"; // displayInformations(files[option - 1]); //std::cin >> option; return 0; }<commit_msg>Update encoding second symbol<commit_after>#include <iostream> #include <string.h> #include <stdio.h> #include <vector> #include <map> #include <bits/stl_algo.h> #include <bitset> #include <fstream> #include <chrono> using namespace std; typedef struct GraphTree { unsigned char symbol; unsigned char symbolExtended; unsigned long long int nrOfApp; GraphTree *parent; GraphTree *left; GraphTree *right; unsigned long long int index; } ShannonTree; typedef std::vector<GraphTree *> GraphIndex; typedef std::map<int, std::pair<GraphTree *, std::string>> MappedSymbols; typedef std::chrono::duration<int, std::milli> miliseconds_type; typedef struct GraphSearch { std::string code; bool type; GraphTree *reference; }; int ENCODE_BITS = 8; int ESC_VALUE = 257; int EOS_VALUE = 256; MappedSymbols symbolMap; GraphIndex indexedGraph; auto cmp = [](std::pair<unsigned char, unsigned long int> const &a, std::pair<unsigned char, unsigned long int> const &b) { return a.second != b.second ? a.second > b.second : a.first < b.first; }; GraphTree *initGraph() { GraphTree *parent, *left, *right; parent = new GraphTree; left = new GraphTree; right = new GraphTree; parent->symbol = 0; parent->symbolExtended = 0; parent->nrOfApp = 2; parent->parent = NULL; parent->left = left; parent->right = right; parent->index = 1; indexedGraph.push_back(parent); left->parent = parent; right->parent = parent; left->left = NULL; left->right = NULL; right->left = NULL; right->right = NULL; left->symbol = 255; left->symbolExtended = 1; right->symbol = 255; right->symbolExtended = 2; left->nrOfApp = 1; right->nrOfApp = 1; left->index = 2; right->index = 3; indexedGraph.push_back(left); indexedGraph.push_back(right); symbolMap[right->symbol + right->symbolExtended].first = right; symbolMap[right->symbol + right->symbolExtended].second = "1"; symbolMap[left->symbol + left->symbolExtended].first = left; symbolMap[left->symbol + left->symbolExtended].second = "0"; return parent; } /** * find symbol in alphabet map, if it is first occurence for symbol return a reference for ESC symbol */ GraphSearch findSymbol(unsigned char symbol) { GraphSearch result; if (symbolMap.count(symbol) > 0) { result.code = symbolMap[symbol].second; result.type = true; result.reference = symbolMap[symbol].first; } else { result.code = symbolMap[ESC_VALUE].second; result.type = false; result.reference = symbolMap[ESC_VALUE].first; } return result; } void updateSymbol(GraphSearch result) { (result.reference)->nrOfApp = (result.reference)->nrOfApp + 1; } void addSymbol(GraphSearch result, unsigned char symbol) { GraphTree *left, *right; left = new GraphTree; left->nrOfApp = 1; left->right = NULL; left->left = NULL; left->symbol = symbol; left->symbolExtended = 0; left->parent = result.reference; left->index = (result.reference)->index + 1; right = new GraphTree; right->nrOfApp = 1; right->right = NULL; right->left = NULL; right->symbol = 255; right->symbolExtended = 2; right->parent = result.reference; right->index = (result.reference)->index + 2; (result.reference)->left = left; (result.reference)->right = right; (result.reference)->nrOfApp = 2; (result.reference)->symbol = 0; (result.reference)->symbolExtended = 0; indexedGraph.push_back(left); indexedGraph.push_back(right); symbolMap[ESC_VALUE].first = right; } void displayIndexedGraph() { GraphIndex::size_type iterator; for (iterator = 0; iterator < indexedGraph.size(); ++iterator) { std::cout << (indexedGraph[iterator])->nrOfApp << " " << (indexedGraph[iterator])->index << " -> " << iterator + 1 << "\n"; } } void displayGraph(GraphTree *root) { if ((root->symbol + root->symbolExtended) == 0) { std::cout << "Pondere: " << root->nrOfApp << "\n"; displayGraph(root->left); displayGraph(root->right); } else { std::cout << "Simbol: " << (root->symbol + root->symbolExtended) << "\n"; } } void balanceGraph(GraphTree *node) { GraphTree *aux, *changeAux, *parent; GraphIndex::size_type iterator, auxIndex; for (iterator = node->index - 1; iterator > 0; iterator--) { if ((indexedGraph[iterator - 1])->nrOfApp >= node->nrOfApp) { break; } } if (iterator == node->index - 1) { node->parent->nrOfApp++; if (node->parent->parent != NULL) { balanceGraph(node->parent); } return void(); } if (iterator == node->index - 2) { (indexedGraph[iterator - 1])->right = indexedGraph[iterator]; (indexedGraph[iterator - 1])->left = node; indexedGraph[iterator]->index++; node->index--; indexedGraph[iterator] = node; indexedGraph[iterator + 1] = (indexedGraph[iterator - 1])->right; balanceGraph(node); return void(); } if ((iterator - (node->index - 2)) > 0 && node->index - 2 >= 0) { aux = indexedGraph[iterator - 1]; indexedGraph[iterator - 1] = node; auxIndex = node->index; parent = aux->parent; changeAux = node->parent; if (iterator % 2 == 0) { parent->left = node; } else { parent->right = node; } node->parent = parent; indexedGraph[auxIndex - 1] = aux; if (auxIndex % 2 == 0) { changeAux->left = node; } else { changeAux->right = node; } balanceGraph(indexedGraph[iterator - 1]); //return void(); } //return void(); } void encodeSymbol(unsigned char symbol, GraphTree *parent) { GraphSearch result; result = findSymbol(symbol); if (result.type == true) { updateSymbol(result); } else { addSymbol(result, symbol); } balanceGraph(result.reference); } void swapChild(GraphTree *root) { GraphTree *aux; aux = root->left; root->left = root->right; root->right = aux; } void balanceTree(GraphTree *root) { if ((root->symbol + root->symbolExtended) == 0) { if (root->left->nrOfApp < root->right->nrOfApp) { swapChild(root); } } } void encodeFile() { } void compressFile(std::string fileName) { GraphTree *huffmanTree; huffmanTree = initGraph(); encodeSymbol('a', huffmanTree); encodeSymbol('b', huffmanTree); displayIndexedGraph(); std::cout << "\n\n"; displayGraph(huffmanTree); // balanceTree(huffmanTree); // encodeSymbol('b', huffmanTree); // balanceTree(huffmanTree); // std::cout << "\n\n"; // displayGraph(huffmanTree); } void uncompressFile(std::string fileName) { } void displayOptions() { std::cout << "Alege fisierul!" << "\n\n Audio:\n"; std::cout << "\t1.)instr_01.wav\n"; std::cout << "\t2.)sound_01.wav\n"; std::cout << "\t3.)speech_01.wav\n"; std::cout << "\nDocuments:\n"; std::cout << "\t4.)Documentatie_UMAPID.doc\n"; std::cout << "\t5.)Documentatie_UMAPID.pdf\n"; std::cout << "\t6.)Prefata_Undine.txt\n"; std::cout << "\t7.)show_audio.m\n"; std::cout << "\t8.)Y04.M\n"; std::cout << "\nExecutables:\n"; std::cout << "\t9.)KARMA_DATA482#1_5_V7.mat\n"; std::cout << "\t10.)quartz.dll\n"; std::cout << "\t11.)WinRar.exe\n"; std::cout << "\t12.)WINZIP32.EXE\n"; } std::ifstream::pos_type filesize(std::string fileName) { std::ifstream in(fileName.c_str(), std::ifstream::ate | std::ifstream::binary); return in.tellg(); } void displayInformations(std::string fileName) { std::ifstream::pos_type compressedFileSize, fileSize, uncompressedFileSize; std::string compressedFileName, uncompressedFileName; compressedFileName = fileName + ".psh"; uncompressedFileName = fileName + ".pshu"; compressedFileSize = filesize(compressedFileName); fileSize = filesize(fileName); uncompressedFileSize = filesize(uncompressedFileName); std::cout << "Norma: " << (fileSize - uncompressedFileSize) * (fileSize - uncompressedFileSize) << "\n"; std::cout << "Rata compresie: " << (1 - ((float) compressedFileSize) / ((float) uncompressedFileSize)) * 100 << "%\n"; std::cout << "Factor compresie: " << (((float) compressedFileSize) / ((float) fileSize)) * 100 << "%\n"; } int main() { std::vector<std::string> files = { ".\\audio\\instr_01.wav", ".\\audio\\sound_01.wav", ".\\audio\\speech_01.wav", ".\\documents\\Documentatie_UMAPID.doc", ".\\documents\\Documentatie_UMAPID.pdf", ".\\documents\\Prefata_Undine.txt", ".\\documents\\show_audio.m", ".\\documents\\Y04.M", ".\\executables\\KARMA_DATA482#1_5_V7.mat", ".\\executables\\quartz.dll", ".\\executables\\WinRar.exe", ".\\executables\\WINZIP32.EXE", ".\\documents\\input.txt", "D:\\input.txt", }; int option; //displayOptions(); //std::cout << "Select file!..\n"; //std::cin >> option; // if (option < 1 && option > 14) { // std::cout << "Invalid option!"; // return 0; // } auto startC = std::chrono::high_resolution_clock::now(); compressFile(files[2]); auto endC = std::chrono::high_resolution_clock::now(); auto timeC = endC - startC; std::cout << "Compressed time: " << std::chrono::duration_cast<miliseconds_type>(timeC).count() << " miliseconds.\n"; auto startU = std::chrono::high_resolution_clock::now(); // uncompressFile(files[option - 1]); auto endU = std::chrono::high_resolution_clock::now(); auto timeU = endU - startU; std::cout << "Uncompressed time: " << std::chrono::duration_cast<miliseconds_type>(timeU).count() << " miliseconds.\n"; // displayInformations(files[option - 1]); //std::cin >> option; return 0; }<|endoftext|>
<commit_before>790068b6-2d53-11e5-baeb-247703a38240<commit_msg>7900e598-2d53-11e5-baeb-247703a38240<commit_after>7900e598-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>3391552b-2e4f-11e5-a40e-28cfe91dbc4b<commit_msg>33993135-2e4f-11e5-8c56-28cfe91dbc4b<commit_after>33993135-2e4f-11e5-8c56-28cfe91dbc4b<|endoftext|>
<commit_before>8b332550-2d14-11e5-af21-0401358ea401<commit_msg>8b332551-2d14-11e5-af21-0401358ea401<commit_after>8b332551-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5bf67380-2d16-11e5-af21-0401358ea401<commit_msg>5bf67381-2d16-11e5-af21-0401358ea401<commit_after>5bf67381-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2010 Bryan Ivory [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <assert.h> #include <iostream> #include <sstream> #include <string> #include <list> #include <vector> #include "png.hpp" #include "TexturePacker.h" #include "tclap/CmdLine.h" #define VERSION "2010.09.06" class TextureInfo; class TextureAtlasInfoVisitor { public: virtual void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) = 0; }; class TextureInfo { public: TextureInfo(int index, std::string path) : idx(index), im_path(path) { im = new png::image<png::rgba_pixel>(im_path, png::convert_color_space<png::rgba_pixel>()); } void index(size_t i) { idx = i; } int index() const { return idx; } std::string path() const { return im_path; } png::image<png::rgba_pixel>* image() const { return im; } void writeTo(png::image< png::rgba_pixel > &outimage, const size_t offset_x, const size_t offset_y, const size_t out_width, const size_t out_height, const bool rotate90) { for(size_t out_y = offset_y; out_y < (offset_y + out_height); ++out_y) { for(size_t out_x = offset_x; out_x < (offset_x + out_width); ++out_x) { if (rotate90) { size_t rot_y = im->get_height() - (out_x - offset_x) - 1; size_t rot_x = (out_y - offset_y); png::rgba_pixel px = (*im)[rot_y][rot_x]; outimage[out_y][out_x] = px; } else { size_t rot_y = out_y - offset_y; size_t rot_x = out_x - offset_x; outimage[out_y][out_x] = (*im)[rot_y][rot_x]; } } } } private: int idx; std::string im_path; png::image<png::rgba_pixel>* im; }; class TextureAtlasInfo { public: TextureAtlasInfo(size_t atlas_width, size_t atlas_height, size_t im_count) : atlas_max_width(atlas_width), atlas_max_height(atlas_height), atlas_unused_pixels(0), images() { atlas = TEXTURE_PACKER::createTexturePacker(); atlas->setTextureCount(im_count); } ~TextureAtlasInfo(void) { delete(atlas); } bool addTexture(TextureInfo* im_info) { png::image<png::rgba_pixel>* im = im_info->image(); bool fit = atlas->wouldTextureFit(im->get_width(), im->get_height(), true, false, atlas_max_width, atlas_max_height); if (!fit) { return false; } atlas->addTexture(im->get_width(), im->get_height()); im_info->index(atlas->getTextureCount() - 1); images.push_back(im_info); return true; } void packTextures(void) { int w, h; atlas_unused_pixels = atlas->packTextures(w, h, true, false); atlas_max_width = w; atlas_max_height = h; } size_t packedCount(void) { return atlas->getTextureCount(); } size_t packedUnusedPixels(void) { return atlas_unused_pixels; } size_t packedWidth(void) { return atlas_max_width; } size_t packedHeight(void) { return atlas_max_height; } void visit(TextureAtlasInfoVisitor &taiv) { for(std::list<TextureInfo *>::iterator images_iter = images.begin(); images_iter != images.end(); images_iter++) { TextureInfo* im_info = *images_iter; int x, y, width, height; bool rot90; rot90 = atlas->getTextureLocation(im_info->index(), x, y, width, height); taiv.visit(*im_info, x, y, width, height, rot90); } } private: size_t atlas_unused_pixels; size_t atlas_max_width; size_t atlas_max_height; TEXTURE_PACKER::TexturePacker* atlas; std::list<TextureInfo *> images; }; class TextureAtlasInfoWriteVisitor : public TextureAtlasInfoVisitor { public: TextureAtlasInfoWriteVisitor(std::string path, size_t w, size_t h) : out_image_path(path), out_image(w, h) { } ~TextureAtlasInfoWriteVisitor(void) { out_image.write(out_image_path + ".png"); } void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) { im_info.writeTo(out_image, x, y, width, height, rot90); } private: png::image<png::rgba_pixel> out_image; std::string out_image_path; }; class TextureAtlasInfoDebugWriteVisitor : public TextureAtlasInfoVisitor { public: TextureAtlasInfoDebugWriteVisitor(std::string path, size_t w, size_t h, size_t num_packed, size_t unused) : out_image_path(path), out_image_width(w), out_image_height(h) { std::cout << "Packed " << num_packed << " images to " << path << ".png" << " with " << unused << " unused area " << "Width (" << w << ") x Height (" << h << ")" << std::endl; } ~TextureAtlasInfoDebugWriteVisitor(void) { std::cout << std::endl; } void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) { std::cout << im_info.path() << " => "; if (rot90) std::cout << "rotated 90 "; std::cout << "x: " << x << " " << "y: " << y << " " << "width: " << width << " " << "height: " << height << " " << std::endl; } private: std::string out_image_path; size_t out_image_width; size_t out_image_height; }; class TextureAtlasInfoCSVWriteVisitor : public TextureAtlasInfoVisitor { public: TextureAtlasInfoCSVWriteVisitor(std::string path, size_t w, size_t h) : out_image_path(path), out_image_width(w), out_image_height(h) { } ~TextureAtlasInfoCSVWriteVisitor(void) { } void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) { } private: std::string out_image_path; size_t out_image_width; size_t out_image_height; }; int main(int argc, char* argv[]) { std::string out_atlas_name = ""; size_t out_atlas_height = 0; size_t out_atlas_width = 0; std::vector<std::string> image_names; std::list<TextureAtlasInfo *> atlases; // Read in the command line arguements try { TCLAP::CmdLine cmd("Creates a texture atlas from a list of PNG files.", ' ', VERSION, true); // Output atlas file name TCLAP::ValueArg<std::string> out_atlas_name_arg( "o","out_name", "Output atlas image's file name.", false, "out_atlas", "string"); cmd.add(out_atlas_name_arg); // Output atlas image dimensions TCLAP::ValueArg<size_t> out_atlas_width_arg( "x","out_width", "Maximum output atlas image's width.", false, 1024, "pixels"); cmd.add(out_atlas_width_arg); TCLAP::ValueArg<size_t> out_atlas_height_arg( "y","out_height", "Maximum output atlas image's height.", false, 1024, "pixels"); cmd.add(out_atlas_height_arg); // Input image files TCLAP::UnlabeledMultiArg<std::string> in_image_names_arg( "in_names", "List of the image filenames.", true, "PNG file path"); cmd.add(in_image_names_arg); cmd.parse(argc, argv); out_atlas_name = out_atlas_name_arg.getValue(); out_atlas_width = out_atlas_width_arg.getValue(); out_atlas_height = out_atlas_height_arg.getValue(); image_names = in_image_names_arg.getValue(); } catch (TCLAP::ArgException &e) { std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } // Create the initial texture atlas atlases.push_back(new TextureAtlasInfo(out_atlas_width, out_atlas_height, image_names.size())); // Load the textures for(size_t idx = 0; idx < image_names.size(); idx++) { try { // Load the image TextureInfo* ti = new TextureInfo(idx, image_names[idx]); if (ti->image()->get_width() > out_atlas_width || ti->image()->get_height() > out_atlas_height) { std::cerr << "Error: " << ti->path() << " is too big!" << std::endl; std::cerr << "Image dimensions: " << ti->image()->get_width() << " x " << ti->image()->get_height() << std::endl; std::cerr << "Atlas dimensions: " << out_atlas_width << " x " << out_atlas_height << std::endl; return 1; } // Add to the atlas TextureAtlasInfo* tai = atlases.back(); if (!tai->addTexture(ti)) { // Create a new atlas TextureAtlasInfo* tai_next = new TextureAtlasInfo(out_atlas_width, out_atlas_height, image_names.size()); tai_next->addTexture(ti); atlases.push_back(tai_next); } } catch(png::std_error &e) { std::cerr << e.what() << std::endl; return 1; } } // Pack and write out the atlases int idx = 0; for(std::list<TextureAtlasInfo *>::iterator atlases_iter = atlases.begin(); atlases_iter != atlases.end(); atlases_iter++, idx++) { std::ostringstream oss; oss << out_atlas_name << "_" << idx; std::string atlas_name(oss.str()); TextureAtlasInfo* tai = *atlases_iter; tai->packTextures(); TextureAtlasInfoWriteVisitor tai_writer(atlas_name, tai->packedWidth(), tai->packedHeight()); TextureAtlasInfoDebugWriteVisitor tai_debug(atlas_name, tai->packedWidth(), tai->packedHeight(), tai->packedCount(), tai->packedUnusedPixels()); tai->visit(tai_writer); tai->visit(tai_debug); } return 0; } <commit_msg>Added command line option for suppressing processing info to stdout<commit_after>/* The MIT License Copyright (c) 2010 Bryan Ivory [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <assert.h> #include <iostream> #include <sstream> #include <string> #include <list> #include <vector> #include "png.hpp" #include "TexturePacker.h" #include "tclap/CmdLine.h" #define VERSION "2010.09.06" class TextureInfo; class TextureAtlasInfoVisitor { public: virtual void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) = 0; }; class TextureInfo { public: TextureInfo(int index, std::string path) : idx(index), im_path(path) { im = new png::image<png::rgba_pixel>(im_path, png::convert_color_space<png::rgba_pixel>()); } void index(size_t i) { idx = i; } int index() const { return idx; } std::string path() const { return im_path; } png::image<png::rgba_pixel>* image() const { return im; } void writeTo(png::image< png::rgba_pixel > &outimage, const size_t offset_x, const size_t offset_y, const size_t out_width, const size_t out_height, const bool rotate90) { for(size_t out_y = offset_y; out_y < (offset_y + out_height); ++out_y) { for(size_t out_x = offset_x; out_x < (offset_x + out_width); ++out_x) { if (rotate90) { size_t rot_y = im->get_height() - (out_x - offset_x) - 1; size_t rot_x = (out_y - offset_y); png::rgba_pixel px = (*im)[rot_y][rot_x]; outimage[out_y][out_x] = px; } else { size_t rot_y = out_y - offset_y; size_t rot_x = out_x - offset_x; outimage[out_y][out_x] = (*im)[rot_y][rot_x]; } } } } private: int idx; std::string im_path; png::image<png::rgba_pixel>* im; }; class TextureAtlasInfo { public: TextureAtlasInfo(size_t atlas_width, size_t atlas_height, size_t im_count) : atlas_max_width(atlas_width), atlas_max_height(atlas_height), atlas_unused_pixels(0), images() { atlas = TEXTURE_PACKER::createTexturePacker(); atlas->setTextureCount(im_count); } ~TextureAtlasInfo(void) { delete(atlas); } bool addTexture(TextureInfo* im_info) { png::image<png::rgba_pixel>* im = im_info->image(); bool fit = atlas->wouldTextureFit(im->get_width(), im->get_height(), true, false, atlas_max_width, atlas_max_height); if (!fit) { return false; } atlas->addTexture(im->get_width(), im->get_height()); im_info->index(atlas->getTextureCount() - 1); images.push_back(im_info); return true; } void packTextures(void) { int w, h; atlas_unused_pixels = atlas->packTextures(w, h, true, false); atlas_max_width = w; atlas_max_height = h; } size_t packedCount(void) { return atlas->getTextureCount(); } size_t packedUnusedPixels(void) { return atlas_unused_pixels; } size_t packedWidth(void) { return atlas_max_width; } size_t packedHeight(void) { return atlas_max_height; } void visit(TextureAtlasInfoVisitor &taiv) { for(std::list<TextureInfo *>::iterator images_iter = images.begin(); images_iter != images.end(); images_iter++) { TextureInfo* im_info = *images_iter; int x, y, width, height; bool rot90; rot90 = atlas->getTextureLocation(im_info->index(), x, y, width, height); taiv.visit(*im_info, x, y, width, height, rot90); } } private: size_t atlas_unused_pixels; size_t atlas_max_width; size_t atlas_max_height; TEXTURE_PACKER::TexturePacker* atlas; std::list<TextureInfo *> images; }; class TextureAtlasInfoWriteVisitor : public TextureAtlasInfoVisitor { public: TextureAtlasInfoWriteVisitor(std::string path, size_t w, size_t h) : out_image_path(path), out_image(w, h) { } ~TextureAtlasInfoWriteVisitor(void) { out_image.write(out_image_path + ".png"); } void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) { im_info.writeTo(out_image, x, y, width, height, rot90); } private: png::image<png::rgba_pixel> out_image; std::string out_image_path; }; class TextureAtlasInfoDebugWriteVisitor : public TextureAtlasInfoVisitor { public: static std::string name() { return "debug"; } TextureAtlasInfoDebugWriteVisitor(std::string path, size_t w, size_t h, size_t num_packed, size_t unused) : out_image_path(path), out_image_width(w), out_image_height(h) { std::cout << "Packed " << num_packed << " images to " << path << ".png" << " with " << unused << " unused area " << "Width (" << w << ") x Height (" << h << ")" << std::endl; } ~TextureAtlasInfoDebugWriteVisitor(void) { std::cout << std::endl; } void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) { std::cout << im_info.path() << " => "; if (rot90) std::cout << "rotated 90 "; std::cout << "x: " << x << " " << "y: " << y << " " << "width: " << width << " " << "height: " << height << " " << std::endl; } private: std::string out_image_path; size_t out_image_width; size_t out_image_height; }; class TextureAtlasInfoCSVWriteVisitor : public TextureAtlasInfoVisitor { public: TextureAtlasInfoCSVWriteVisitor(std::string path, size_t w, size_t h) : out_image_path(path), out_image_width(w), out_image_height(h) { } ~TextureAtlasInfoCSVWriteVisitor(void) { } void visit(TextureInfo &im_info, int x, int y, int width, int height, bool rot90) { } private: std::string out_image_path; size_t out_image_width; size_t out_image_height; }; int main(int argc, char* argv[]) { std::string out_atlas_name = ""; size_t out_atlas_height = 0; size_t out_atlas_width = 0; std::vector<std::string> out_visitors_str; std::vector<std::string> image_names; std::list<TextureAtlasInfo *> atlases; // Read in the command line arguements try { TCLAP::CmdLine cmd("Creates a texture atlas from a list of PNG files.", ' ', VERSION, true); // Output atlas file name TCLAP::ValueArg<std::string> out_atlas_name_arg( "o","out_name", "Output atlas image's file name.", false, "out_atlas", "string"); cmd.add(out_atlas_name_arg); // Output atlas image dimensions TCLAP::ValueArg<size_t> out_atlas_width_arg( "x","out_width", "Maximum output atlas image's width.", false, 1024, "pixels"); cmd.add(out_atlas_width_arg); TCLAP::ValueArg<size_t> out_atlas_height_arg( "y","out_height", "Maximum output atlas image's height.", false, 1024, "pixels"); cmd.add(out_atlas_height_arg); // Input image files TCLAP::UnlabeledMultiArg<std::string> in_image_names_arg( "in_names", "List of the image filenames.", true, "PNG file path"); cmd.add(in_image_names_arg); // Output visitors TCLAP::SwitchArg quiet_arg("q", "quiet", "Suppress processing information output.", false); cmd.add(quiet_arg); TCLAP::MultiArg<std::string> out_vistors_arg("i", "info_writers", "Atlas information writers.", false, "string"); cmd.add(out_vistors_arg); // Parse the command line options cmd.parse(argc, argv); out_atlas_name = out_atlas_name_arg.getValue(); out_atlas_width = out_atlas_width_arg.getValue(); out_atlas_height = out_atlas_height_arg.getValue(); if (!quiet_arg.getValue()) { out_visitors_str.push_back(TextureAtlasInfoDebugWriteVisitor::name()); } #if 0 out_visitors_str = out_vistors_arg.getValue(); #endif image_names = in_image_names_arg.getValue(); } catch (TCLAP::ArgException &e) { std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } // Create the initial texture atlas atlases.push_back(new TextureAtlasInfo(out_atlas_width, out_atlas_height, image_names.size())); // Load the textures for(size_t idx = 0; idx < image_names.size(); idx++) { try { // Load the image TextureInfo* ti = new TextureInfo(idx, image_names[idx]); if (ti->image()->get_width() > out_atlas_width || ti->image()->get_height() > out_atlas_height) { std::cerr << "Error: " << ti->path() << " is too big!" << std::endl; std::cerr << "Image dimensions: " << ti->image()->get_width() << " x " << ti->image()->get_height() << std::endl; std::cerr << "Atlas dimensions: " << out_atlas_width << " x " << out_atlas_height << std::endl; return 1; } // Add to the atlas TextureAtlasInfo* tai = atlases.back(); if (!tai->addTexture(ti)) { // Create a new atlas TextureAtlasInfo* tai_next = new TextureAtlasInfo(out_atlas_width, out_atlas_height, image_names.size()); tai_next->addTexture(ti); atlases.push_back(tai_next); } } catch(png::std_error &e) { std::cerr << e.what() << std::endl; return 1; } } // Pack and write out the atlases int idx = 0; for(std::list<TextureAtlasInfo *>::iterator atlases_iter = atlases.begin(); atlases_iter != atlases.end(); atlases_iter++, idx++) { std::ostringstream oss; oss << out_atlas_name << "_" << idx; std::string atlas_name(oss.str()); TextureAtlasInfo* tai = *atlases_iter; tai->packTextures(); TextureAtlasInfoWriteVisitor tai_writer(atlas_name, tai->packedWidth(), tai->packedHeight()); tai->visit(tai_writer); // Ugly way to do this. for(std::vector<std::string>::iterator vis_iter = out_visitors_str.begin(); vis_iter != out_visitors_str.end(); vis_iter++) { TextureAtlasInfoVisitor* taiv = NULL; if (vis_iter->compare(TextureAtlasInfoDebugWriteVisitor::name()) == 0) { taiv = new TextureAtlasInfoDebugWriteVisitor(atlas_name, tai->packedWidth(), tai->packedHeight(), tai->packedCount(), tai->packedUnusedPixels()); } if (taiv != NULL) { tai->visit(*taiv); delete taiv; } } } return 0; } <|endoftext|>
<commit_before>#include "dbusgateway.h" #include <boost/shared_ptr.hpp> #include "logger.h" #include "types.h" DbusGateway::DbusGateway(const Config& config_in, command::Channel* command_channel_in) : stop(false), config(config_in), command_channel(command_channel_in), swlm(config) { dbus_threads_init_default(); dbus_error_init(&err); conn = dbus_bus_get(DBUS_BUS_SESSION, &err); if (dbus_error_is_set(&err)) { LOGGER_LOG(LVL_error, "D-Bus Connection Error: " << err.message); dbus_error_free(&err); return; } int ret = dbus_bus_request_name(conn, config_in.dbus.interface.c_str(), DBUS_NAME_FLAG_REPLACE_EXISTING, &err); if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) { LOGGER_LOG(LVL_error, "Cannot request D-Bus name '" << config_in.dbus.interface << "' as primary owner. D-Bus communication disabled"); return; } thread = boost::thread(boost::bind(&DbusGateway::run, this)); } DbusGateway::~DbusGateway() { stop = true; if (!thread.try_join_for(boost::chrono::seconds(10))) { LOGGER_LOG(LVL_error, "join()-ing DBusGateway thread timed out"); } dbus_bus_release_name(conn, config.dbus.interface.c_str(), NULL); dbus_connection_unref(conn); } void DbusGateway::processEvent(const boost::shared_ptr<event::BaseEvent>& event) { if (event->variant == "DownloadComplete") { event::DownloadComplete* download_complete_event = static_cast<event::DownloadComplete*>(event.get()); swlm.downloadComplete(download_complete_event->download_complete.update_image, download_complete_event->download_complete.signature); fireDownloadCompleteEvent(download_complete_event->download_complete); } else if (event->variant == "InstalledSoftwareNeeded") { fireInstalledSoftwareNeededEvent(); } else if (event->variant == "UpdateAvailable") { event::UpdateAvailable* update_available_event = static_cast<event::UpdateAvailable*>(event.get()); fireUpdateAvailableEvent(update_available_event->update_vailable); } } void DbusGateway::fireInstalledSoftwareNeededEvent() { DBusMessage* msg; msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), "InstalledSoftwareNeeded"); dbus_connection_send(conn, msg, NULL); dbus_message_unref(msg); } void DbusGateway::fireUpdateAvailableEvent(const data::UpdateAvailable& update_available) { DBusMessage* msg; DBusMessageIter iter; msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), "UpdateAvailable"); dbus_message_iter_init_append(msg, &iter); DBusMessageIter sub_iter; dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter); const char* update_id = update_available.update_id.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id); const char* description = update_available.description.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &description); const char* signature = update_available.signature.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature); unsigned long long size = update_available.size; dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_UINT64, &size); dbus_message_iter_close_container(&iter, &sub_iter); dbus_connection_send(conn, msg, NULL); dbus_message_unref(msg); } void DbusGateway::fireDownloadCompleteEvent(const data::DownloadComplete& download_complete) { DBusMessage* msg; DBusMessageIter iter; msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), "DownloadComplete"); dbus_message_iter_init_append(msg, &iter); DBusMessageIter sub_iter; dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter); const char* update_id = download_complete.update_id.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id); const char* update_image = download_complete.update_image.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_image); const char* signature = download_complete.signature.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature); dbus_message_iter_close_container(&iter, &sub_iter); dbus_connection_send(conn, msg, NULL); dbus_message_unref(msg); } void DbusGateway::run() { DBusMessage* msg; char* string_param = NULL; DBusMessageIter args; while (true) { dbus_connection_read_write(conn, 0); msg = dbus_connection_pop_message(conn); if (NULL == msg) { boost::this_thread::sleep_for(boost::chrono::seconds(1)); if (stop) { return; } continue; } if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "initiateDownload") || dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "abortDownload") || dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "updateReport")) { if (!dbus_message_iter_init(msg, &args) || DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) { LOGGER_LOG(LVL_error, "D-Bus method initiateDownload called with wrong arguments"); dbus_message_unref(msg); continue; } else { dbus_message_iter_get_basic(&args, &string_param); } } if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "initiateDownload")) { *command_channel << boost::shared_ptr<command::StartDownload>(new command::StartDownload(string_param)); } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "abortDownload")) { *command_channel << boost::shared_ptr<command::AbortDownload>(new command::AbortDownload(string_param)); } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "updateReport")) { data::UpdateReport update_report; update_report.update_id = string_param; if (dbus_message_iter_next(&args) && DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(&args)) { DBusMessageIter operation_result_args; int results_count = dbus_message_iter_get_element_count(&args); dbus_message_iter_recurse(&args, &operation_result_args); do { try { update_report.operation_results.push_back(getOperationResult(&operation_result_args)); } catch (...) { LOGGER_LOG(LVL_error, "D-Bus method 'updateReport' called with wrong arguments"); } dbus_message_iter_next(&operation_result_args); results_count--; } while (results_count); } else { LOGGER_LOG(LVL_error, "D-Bus method called with wrong arguments"); dbus_message_unref(msg); continue; } *command_channel << boost::shared_ptr<command::SendUpdateReport>(new command::SendUpdateReport(update_report)); } int message_type = dbus_message_get_type(msg); LOGGER_LOG(LVL_trace, "Got D-Bus message type:" << dbus_message_type_to_string(message_type)); if (message_type == DBUS_MESSAGE_TYPE_METHOD_CALL) { DBusMessage* reply = dbus_message_new_method_return(msg); dbus_bool_t ok = dbus_connection_send(conn, reply, NULL); if (!ok) { LOGGER_LOG(LVL_error, "D-Bus method send failed"); } dbus_connection_flush(conn); dbus_message_unref(reply); } dbus_message_unref(msg); } } data::OperationResult DbusGateway::getOperationResult(DBusMessageIter* iter) { DBusMessageIter subiter, dict_iter, variant_iter; char* string_param; int int_param; data::OperationResult result; int params = dbus_message_iter_get_element_count(iter); dbus_message_iter_recurse(iter, &subiter); if (DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(iter)) { while (params) { dbus_message_iter_recurse(&subiter, &dict_iter); dbus_message_iter_get_basic(&dict_iter, &string_param); dbus_message_iter_next(&dict_iter); dbus_message_iter_recurse(&dict_iter, &variant_iter); if (std::string(string_param) == "id") { dbus_message_iter_get_basic(&variant_iter, &string_param); result.id = string_param; dbus_message_iter_next(&subiter); } else if (std::string(string_param) == "result_code") { dbus_message_iter_get_basic(&variant_iter, &int_param); result.result_code = (data::UpdateResultCode)int_param; dbus_message_iter_next(&subiter); } else if (std::string(string_param) == "result_text") { dbus_message_iter_get_basic(&variant_iter, &string_param); result.result_text = string_param; dbus_message_iter_next(&subiter); } params--; } } return result; } <commit_msg>Do not use newer API<commit_after>#include "dbusgateway.h" #include <boost/shared_ptr.hpp> #include "logger.h" #include "types.h" DbusGateway::DbusGateway(const Config& config_in, command::Channel* command_channel_in) : stop(false), config(config_in), command_channel(command_channel_in), swlm(config) { dbus_threads_init_default(); dbus_error_init(&err); conn = dbus_bus_get(DBUS_BUS_SESSION, &err); if (dbus_error_is_set(&err)) { LOGGER_LOG(LVL_error, "D-Bus Connection Error: " << err.message); dbus_error_free(&err); return; } int ret = dbus_bus_request_name(conn, config_in.dbus.interface.c_str(), DBUS_NAME_FLAG_REPLACE_EXISTING, &err); if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) { LOGGER_LOG(LVL_error, "Cannot request D-Bus name '" << config_in.dbus.interface << "' as primary owner. D-Bus communication disabled"); return; } thread = boost::thread(boost::bind(&DbusGateway::run, this)); } DbusGateway::~DbusGateway() { stop = true; if (!thread.try_join_for(boost::chrono::seconds(10))) { LOGGER_LOG(LVL_error, "join()-ing DBusGateway thread timed out"); } dbus_bus_release_name(conn, config.dbus.interface.c_str(), NULL); dbus_connection_unref(conn); } void DbusGateway::processEvent(const boost::shared_ptr<event::BaseEvent>& event) { if (event->variant == "DownloadComplete") { event::DownloadComplete* download_complete_event = static_cast<event::DownloadComplete*>(event.get()); swlm.downloadComplete(download_complete_event->download_complete.update_image, download_complete_event->download_complete.signature); fireDownloadCompleteEvent(download_complete_event->download_complete); } else if (event->variant == "InstalledSoftwareNeeded") { fireInstalledSoftwareNeededEvent(); } else if (event->variant == "UpdateAvailable") { event::UpdateAvailable* update_available_event = static_cast<event::UpdateAvailable*>(event.get()); fireUpdateAvailableEvent(update_available_event->update_vailable); } } void DbusGateway::fireInstalledSoftwareNeededEvent() { DBusMessage* msg; msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), "InstalledSoftwareNeeded"); dbus_connection_send(conn, msg, NULL); dbus_message_unref(msg); } void DbusGateway::fireUpdateAvailableEvent(const data::UpdateAvailable& update_available) { DBusMessage* msg; DBusMessageIter iter; msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), "UpdateAvailable"); dbus_message_iter_init_append(msg, &iter); DBusMessageIter sub_iter; dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter); const char* update_id = update_available.update_id.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id); const char* description = update_available.description.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &description); const char* signature = update_available.signature.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature); unsigned long long size = update_available.size; dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_UINT64, &size); dbus_message_iter_close_container(&iter, &sub_iter); dbus_connection_send(conn, msg, NULL); dbus_message_unref(msg); } void DbusGateway::fireDownloadCompleteEvent(const data::DownloadComplete& download_complete) { DBusMessage* msg; DBusMessageIter iter; msg = dbus_message_new_signal(config.dbus.path.c_str(), config.dbus.interface.c_str(), "DownloadComplete"); dbus_message_iter_init_append(msg, &iter); DBusMessageIter sub_iter; dbus_message_iter_open_container(&iter, DBUS_TYPE_STRUCT, NULL, &sub_iter); const char* update_id = download_complete.update_id.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_id); const char* update_image = download_complete.update_image.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &update_image); const char* signature = download_complete.signature.c_str(); dbus_message_iter_append_basic(&sub_iter, DBUS_TYPE_STRING, &signature); dbus_message_iter_close_container(&iter, &sub_iter); dbus_connection_send(conn, msg, NULL); dbus_message_unref(msg); } void DbusGateway::run() { DBusMessage* msg; char* string_param = NULL; DBusMessageIter args; while (true) { dbus_connection_read_write(conn, 0); msg = dbus_connection_pop_message(conn); if (NULL == msg) { boost::this_thread::sleep_for(boost::chrono::seconds(1)); if (stop) { return; } continue; } if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "initiateDownload") || dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "abortDownload") || dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "updateReport")) { if (!dbus_message_iter_init(msg, &args) || DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) { LOGGER_LOG(LVL_error, "D-Bus method initiateDownload called with wrong arguments"); dbus_message_unref(msg); continue; } else { dbus_message_iter_get_basic(&args, &string_param); } } if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "initiateDownload")) { *command_channel << boost::shared_ptr<command::StartDownload>(new command::StartDownload(string_param)); } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "abortDownload")) { *command_channel << boost::shared_ptr<command::AbortDownload>(new command::AbortDownload(string_param)); } else if (dbus_message_is_method_call(msg, config.dbus.interface.c_str(), "updateReport")) { data::UpdateReport update_report; update_report.update_id = string_param; if (dbus_message_iter_next(&args) && DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(&args)) { DBusMessageIter operation_result_args; dbus_message_iter_recurse(&args, &operation_result_args); do { try { update_report.operation_results.push_back(getOperationResult(&operation_result_args)); } catch (...) { LOGGER_LOG(LVL_error, "D-Bus method 'updateReport' called with wrong arguments"); } } while (dbus_message_iter_next(&operation_result_args)); } else { LOGGER_LOG(LVL_error, "D-Bus method called with wrong arguments"); dbus_message_unref(msg); continue; } *command_channel << boost::shared_ptr<command::SendUpdateReport>(new command::SendUpdateReport(update_report)); } int message_type = dbus_message_get_type(msg); LOGGER_LOG(LVL_trace, "Got D-Bus message type:" << dbus_message_type_to_string(message_type)); if (message_type == DBUS_MESSAGE_TYPE_METHOD_CALL) { DBusMessage* reply = dbus_message_new_method_return(msg); dbus_bool_t ok = dbus_connection_send(conn, reply, NULL); if (!ok) { LOGGER_LOG(LVL_error, "D-Bus method send failed"); } dbus_connection_flush(conn); dbus_message_unref(reply); } dbus_message_unref(msg); } } data::OperationResult DbusGateway::getOperationResult(DBusMessageIter* iter) { DBusMessageIter subiter, dict_iter, variant_iter; char* string_param; int int_param; data::OperationResult result; int params = dbus_message_iter_get_element_count(iter); dbus_message_iter_recurse(iter, &subiter); if (DBUS_TYPE_ARRAY == dbus_message_iter_get_arg_type(iter)) { while (params) { dbus_message_iter_recurse(&subiter, &dict_iter); dbus_message_iter_get_basic(&dict_iter, &string_param); dbus_message_iter_next(&dict_iter); dbus_message_iter_recurse(&dict_iter, &variant_iter); if (std::string(string_param) == "id") { dbus_message_iter_get_basic(&variant_iter, &string_param); result.id = string_param; dbus_message_iter_next(&subiter); } else if (std::string(string_param) == "result_code") { dbus_message_iter_get_basic(&variant_iter, &int_param); result.result_code = (data::UpdateResultCode)int_param; dbus_message_iter_next(&subiter); } else if (std::string(string_param) == "result_text") { dbus_message_iter_get_basic(&variant_iter, &string_param); result.result_text = string_param; dbus_message_iter_next(&subiter); } params--; } } return result; } <|endoftext|>
<commit_before>e2d39a42-585a-11e5-89a1-6c40088e03e4<commit_msg>e2e06100-585a-11e5-bd33-6c40088e03e4<commit_after>e2e06100-585a-11e5-bd33-6c40088e03e4<|endoftext|>
<commit_before>d7366300-2d3e-11e5-b994-c82a142b6f9b<commit_msg>d7a12b99-2d3e-11e5-a9df-c82a142b6f9b<commit_after>d7a12b99-2d3e-11e5-a9df-c82a142b6f9b<|endoftext|>
<commit_before>5d28664d-2d16-11e5-af21-0401358ea401<commit_msg>5d28664e-2d16-11e5-af21-0401358ea401<commit_after>5d28664e-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[email protected]> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include "NormalMap.h" #include "Filter.h" #include "FloatImage.h" #include "Image.h" #include "nvmath/Color.inl" #include "nvmath/Vector.h" #include "nvcore/Ptr.h" using namespace nv; // Create normal map using the given kernels. static FloatImage * createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> fimage(new FloatImage()); fimage->allocate(4, w, h); // Compute height and store in alpha channel: float * alphaChannel = fimage->channel(3); for(uint i = 0; i < w * h; i++) { Vector4 color = toVector4(img->pixel(i)); alphaChannel[i] = dot(color, heightWeights); } float heightScale = 1.0f / 16.0f; // @@ Use a user defined factor. for(uint y = 0; y < h; y++) { for(uint x = 0; x < w; x++) { const float du = fimage->applyKernelXY(kdu, x, y, 0, 3, wm); const float dv = fimage->applyKernelXY(kdv, x, y, 0, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); fimage->pixel(x, y, 0, 0) = 0.5f * n.x + 0.5f; fimage->pixel(x, y, 0, 1) = 0.5f * n.y + 0.5f; fimage->pixel(x, y, 0, 2) = 0.5f * n.z + 0.5f; } } return fimage.release(); } // Create normal map using the given kernels. static FloatImage * createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); #pragma NV_MESSAGE("FIXME: Height scale parameter should go away. It should be a sensible value that produces good results when the heightmap is in the [0, 1] range.") const float heightScale = 1.0f / 16.0f; const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> img_out(new FloatImage()); img_out->allocate(4, w, h); for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { const float du = img->applyKernelXY(kdu, x, y, 0, 3, wm); const float dv = img->applyKernelXY(kdv, x, y, 0, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); img_out->pixel(x, y, 0, 0) = n.x; img_out->pixel(x, y, 0, 1) = n.y; img_out->pixel(x, y, 0, 2) = n.z; } } // Copy alpha channel. for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { img_out->pixel(x, y, 0, 3) = img->pixel(x, y, 0, 3); } } return img_out.release(); } /// Create normal map using the given filter. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, NormalMapFilter filter /*= Sobel3x3*/) { nvDebugCheck(img != NULL); // Init the kernels. Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; switch(filter) { case NormalMapFilter_Sobel3x3: kdu = new Kernel2(3); break; case NormalMapFilter_Sobel5x5: kdu = new Kernel2(5); break; case NormalMapFilter_Sobel7x7: kdu = new Kernel2(7); break; case NormalMapFilter_Sobel9x9: kdu = new Kernel2(9); break; default: nvDebugCheck(false); }; kdu->initSobel(); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } /// Create normal map combining multiple sobel filters. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } FloatImage * nv::createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, kdu, kdv); } /// Normalize the given image in place. void nv::normalizeNormalMap(FloatImage * img) { nvDebugCheck(img != NULL); img->normalize(0); } <commit_msg>Fix issue 206.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[email protected]> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include "NormalMap.h" #include "Filter.h" #include "FloatImage.h" #include "Image.h" #include "nvmath/Color.inl" #include "nvmath/Vector.h" #include "nvcore/Ptr.h" #include <string.h> // memcpy using namespace nv; // Create normal map using the given kernels. static FloatImage * createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> fimage(new FloatImage()); fimage->allocate(4, w, h); // Compute height and store in alpha channel: float * alphaChannel = fimage->channel(3); for(uint i = 0; i < w * h; i++) { Vector4 color = toVector4(img->pixel(i)); alphaChannel[i] = dot(color, heightWeights); } float heightScale = 1.0f / 16.0f; // @@ Use a user defined factor. for(uint y = 0; y < h; y++) { for(uint x = 0; x < w; x++) { const float du = fimage->applyKernelXY(kdu, x, y, 0, 3, wm); const float dv = fimage->applyKernelXY(kdv, x, y, 0, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); fimage->pixel(0, x, y, 0) = 0.5f * n.x + 0.5f; fimage->pixel(1, x, y, 0) = 0.5f * n.y + 0.5f; fimage->pixel(2, x, y, 0) = 0.5f * n.z + 0.5f; } } return fimage.release(); } // Create normal map using the given kernels. static FloatImage * createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, const Kernel2 * kdu, const Kernel2 * kdv) { nvDebugCheck(kdu != NULL); nvDebugCheck(kdv != NULL); nvDebugCheck(img != NULL); #pragma NV_MESSAGE("FIXME: Height scale parameter should go away. It should be a sensible value that produces good results when the heightmap is in the [0, 1] range.") const float heightScale = 1.0f / 16.0f; const uint w = img->width(); const uint h = img->height(); AutoPtr<FloatImage> img_out(new FloatImage()); img_out->allocate(4, w, h); for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { const float du = img->applyKernelXY(kdu, x, y, 0, 3, wm); const float dv = img->applyKernelXY(kdv, x, y, 0, 3, wm); Vector3 n = normalize(Vector3(du, dv, heightScale)); img_out->pixel(0, x, y, 0) = n.x; img_out->pixel(1, x, y, 0) = n.y; img_out->pixel(2, x, y, 0) = n.z; } } // Copy alpha channel. /*for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { img_out->pixel(3, x, y, 0) = img->pixel(3, x, y, 0); } }*/ memcpy(img_out->channel(3), img->channel(3), w * h * sizeof(float)); return img_out.release(); } /// Create normal map using the given filter. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, NormalMapFilter filter /*= Sobel3x3*/) { nvDebugCheck(img != NULL); // Init the kernels. Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; switch(filter) { case NormalMapFilter_Sobel3x3: kdu = new Kernel2(3); break; case NormalMapFilter_Sobel5x5: kdu = new Kernel2(5); break; case NormalMapFilter_Sobel7x7: kdu = new Kernel2(7); break; case NormalMapFilter_Sobel9x9: kdu = new Kernel2(9); break; default: nvDebugCheck(false); }; kdu->initSobel(); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } /// Create normal map combining multiple sobel filters. FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, heightWeights, kdu, kdv); } FloatImage * nv::createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, Vector4::Arg filterWeights) { nvDebugCheck(img != NULL); Kernel2 * kdu = NULL; Kernel2 * kdv = NULL; kdu = new Kernel2(9); kdu->initBlendedSobel(filterWeights); kdu->normalize(); kdv = new Kernel2(*kdu); kdv->transpose(); return ::createNormalMap(img, wm, kdu, kdv); } /// Normalize the given image in place. void nv::normalizeNormalMap(FloatImage * img) { nvDebugCheck(img != NULL); img->normalize(0); } <|endoftext|>
<commit_before>17ef1f30-585b-11e5-9127-6c40088e03e4<commit_msg>17f64f80-585b-11e5-a157-6c40088e03e4<commit_after>17f64f80-585b-11e5-a157-6c40088e03e4<|endoftext|>
<commit_before>#include "Halide.h" #include "HalideRuntimeCuda.h" using namespace Halide; int main(int argc, char **argv) { Target target = get_jit_target_from_environment(); if (!target.has_gpu_feature() && !target.has_feature(Target::OpenGLCompute)) { printf("This is a gpu-specific test. Skipping it\n"); return 0; } // We'll have two input buffers. For one we'll copy to the device // explicitly. For the other we'll do a device malloc and set // host_dirty. Buffer<float> a(100, 100), b(100, 100); assert(!a.host_dirty()); a.fill(2.0f); assert(!a.has_device_allocation()); assert(a.host_dirty()); a.copy_to_device(); assert(a.has_device_allocation()); assert(!a.host_dirty()); assert(!b.host_dirty()); b.fill(3.0f); assert(!b.has_device_allocation()); assert(b.host_dirty()); b.device_malloc(); assert(b.has_device_allocation()); assert(b.host_dirty()); Func f; Var x, y; f(x, y) = a(x, y) + b(x, y) + 2; f.gpu_tile(x, y, 8, 8); Buffer<float> out = f.realize(100, 100); // Here's a wart: b was copied to the device, but it still has // host_dirty set, because it is a *copy* of b's buffer_t that is // held by the pipeline, and this copy was passed to // copy_to_device. It's hard to fix this without keeping // references to user Buffers (which may leave scope before the // pipeline does!). assert(b.host_dirty()); // :( out.for_each_value([&](float f) { if (f != 7.0f) { printf("%f != 4.0f\n", f); abort(); } }); printf("Success!\n"); return 0; } <commit_msg>Delete unnecessary include<commit_after>#include "Halide.h" using namespace Halide; int main(int argc, char **argv) { Target target = get_jit_target_from_environment(); if (!target.has_gpu_feature() && !target.has_feature(Target::OpenGLCompute)) { printf("This is a gpu-specific test. Skipping it\n"); return 0; } // We'll have two input buffers. For one we'll copy to the device // explicitly. For the other we'll do a device malloc and set // host_dirty. Buffer<float> a(100, 100), b(100, 100); assert(!a.host_dirty()); a.fill(2.0f); assert(!a.has_device_allocation()); assert(a.host_dirty()); a.copy_to_device(); assert(a.has_device_allocation()); assert(!a.host_dirty()); assert(!b.host_dirty()); b.fill(3.0f); assert(!b.has_device_allocation()); assert(b.host_dirty()); b.device_malloc(); assert(b.has_device_allocation()); assert(b.host_dirty()); Func f; Var x, y; f(x, y) = a(x, y) + b(x, y) + 2; f.gpu_tile(x, y, 8, 8); Buffer<float> out = f.realize(100, 100); // Here's a wart: b was copied to the device, but it still has // host_dirty set, because it is a *copy* of b's buffer_t that is // held by the pipeline, and this copy was passed to // copy_to_device. It's hard to fix this without keeping // references to user Buffers (which may leave scope before the // pipeline does!). assert(b.host_dirty()); // :( out.for_each_value([&](float f) { if (f != 7.0f) { printf("%f != 4.0f\n", f); abort(); } }); printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>/** * Copyright (C) 2015 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //------------------------------------------------------------------------------ // GUI #include "repodialoguser.h" #include "ui_repodialoguser.h" #include "../primitives/repo_fontawesome.h" #include "../primitives/repocomboboxeditor.h" //------------------------------------------------------------------------------ // Qt #include <QComboBox> #include <QItemDelegate> #include <QItemEditorFactory> #include <QStandardItemEditorCreator> repo::gui::RepoDialogUser::RepoDialogUser( core::RepoUser user, const std::list<std::string> &databaseList, QWidget *parent) : QDialog(parent) , user(user) , databaseList(databaseList) , ui(new Ui::RepoDialogUser) { ui->setupUi(this); setWindowIcon(getIcon()); // ui->addPushButton->setIcon(RepoFontAwesome::getInstance().getIcon( // RepoFontAwesome::fa_plus, // QColor(Qt::darkGreen))); // ui->deletePushButton->setIcon(RepoFontAwesome::getInstance().getIcon( // RepoFontAwesome::fa_minus, // QColor(Qt::darkRed))); ui->avatarPushButton->setIcon(RepoFontAwesome::getInstance().getIcon( RepoFontAwesome::fa_user, QColor(Qt::gray))); // Enable drop down selectors for editing delegate // See http://doc.qt.io/qt-5/qtwidgets-itemviews-coloreditorfactory-example.html QItemEditorFactory *factory = new QItemEditorFactory(); // QItemEditorCreatorBase *itemListCreator = // new QStandardItemEditorCreator<RepoComboBoxEditor>(); QItemEditorCreatorBase * myCombo = new RepoComboBoxEditor(databaseList); factory->registerEditor(QVariant::Color, myCombo); //QItemEditorFactory::setDefaultFactory(factory); QItemDelegate *delegate = new QItemDelegate(); delegate->setItemEditorFactory(factory); ui->projectsTreeView->setItemDelegateForColumn(RepoProjectsColumns::OWNER, delegate); //-------------------------------------------------------------------------- // Projects projectsModel = new QStandardItemModel(this); projectsModel->setColumnCount(2); projectsModel->setHeaderData( RepoProjectsColumns::OWNER, Qt::Horizontal, tr("Owner")); projectsModel->setHeaderData( RepoProjectsColumns::PROJECT, Qt::Horizontal, tr("Project")); ui->projectsTreeView->setModel(projectsModel); ui->projectsTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder); //-------------------------------------------------------------------------- // DB Roles rolesModel = new QStandardItemModel(this); rolesModel->setColumnCount(2); rolesModel->setHeaderData( RepoProjectsColumns::OWNER, Qt::Horizontal, tr("Database")); rolesModel->setHeaderData( RepoProjectsColumns::PROJECT, Qt::Horizontal, tr("Role")); //ui->rolesTreeView->setModel(rolesModel); //ui->rolesTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder); //-------------------------------------------------------------------------- // Populate user data if (!user.isEmpty()) { ui->usernameLineEdit->setText(QString::fromStdString(user.getUsername())); ui->usernameLineEdit->setEnabled(false); ui->passwordLineEdit->setText(QString::fromStdString(user.getPassword())); ui->firstNameLineEdit->setText(QString::fromStdString(user.getFirstName())); ui->lastNameLineEdit->setText(QString::fromStdString(user.getLastName())); ui->emailLineEdit->setText(QString::fromStdString(user.getEmail())); //---------------------------------------------------------------------- // Projects std::vector<std::pair<std::string, std::string> > projects = user.getProjects(); this->populateModel(projectsModel, projects); //---------------------------------------------------------------------- // DB Roles std::vector<std::pair<std::string, std::string> > roles = user.getRoles(); this->populateModel(rolesModel, roles); QList<QTreeWidgetItem *> items; for (unsigned int i = 0; i < roles.size(); ++i) { QStringList list; list.append(QString::fromStdString(roles[i].first)); list.append(QString::fromStdString(roles[i].second)); QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, list); ui->rolesTreeWidget->insertTopLevelItem(0, item); QComboBox *databaseComboBox = new QComboBox(); databaseComboBox->addItem(QString::fromStdString(roles[i].first)); databaseComboBox->addItem("admin"); databaseComboBox->addItem("test"); ui->rolesTreeWidget->setItemWidget(item, 0, databaseComboBox); QComboBox *roleComboBox = new QComboBox(); roleComboBox->addItem(QString::fromStdString(roles[i].second)); roleComboBox->addItem("admin"); roleComboBox->addItem("test"); ui->rolesTreeWidget->setItemWidget(item, 1, roleComboBox); } } } repo::gui::RepoDialogUser::~RepoDialogUser() { delete projectsModel; delete rolesModel; delete ui; } QIcon repo::gui::RepoDialogUser::getIcon() { return RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_user); } void repo::gui::RepoDialogUser::populateModel( QStandardItemModel *model, const std::vector<std::pair<std::string, std::string> > &data) { for (unsigned int i = 0; i < data.size(); ++i) { QList<QStandardItem *> row; row.append(new QStandardItem(QString::fromStdString(data[i].first))); QStandardItem *item = new QStandardItem();//QString::fromStdString(data[i].second)); item->setData(QColor("springgreen"), Qt::DisplayRole); row.append(item); model->invisibleRootItem()->appendRow(row); // model->setData(model->index(i, 0), new QComboBox()); } } <commit_msg>Minor fix.<commit_after>/** * Copyright (C) 2015 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //------------------------------------------------------------------------------ // GUI #include "repodialoguser.h" #include "ui_repodialoguser.h" #include "../primitives/repo_fontawesome.h" #include "../primitives/repocomboboxeditor.h" //------------------------------------------------------------------------------ // Qt #include <QComboBox> #include <QItemDelegate> #include <QItemEditorFactory> #include <QStandardItemEditorCreator> repo::gui::RepoDialogUser::RepoDialogUser( core::RepoUser user, const std::list<std::string> &databaseList, QWidget *parent) : QDialog(parent) , user(user) , databaseList(databaseList) , ui(new Ui::RepoDialogUser) { ui->setupUi(this); setWindowIcon(getIcon()); // ui->addPushButton->setIcon(RepoFontAwesome::getInstance().getIcon( // RepoFontAwesome::fa_plus, // QColor(Qt::darkGreen))); // ui->deletePushButton->setIcon(RepoFontAwesome::getInstance().getIcon( // RepoFontAwesome::fa_minus, // QColor(Qt::darkRed))); ui->avatarPushButton->setIcon(RepoFontAwesome::getInstance().getIcon( RepoFontAwesome::fa_user, QColor(Qt::gray))); // Enable drop down selectors for editing delegate // See http://doc.qt.io/qt-5/qtwidgets-itemviews-coloreditorfactory-example.html QItemEditorFactory *factory = new QItemEditorFactory(); // QItemEditorCreatorBase *itemListCreator = // new QStandardItemEditorCreator<RepoComboBoxEditor>(); QItemEditorCreatorBase * myCombo = new RepoComboBoxEditor(databaseList); factory->registerEditor(QVariant::Color, myCombo); //QItemEditorFactory::setDefaultFactory(factory); QItemDelegate *delegate = new QItemDelegate(); delegate->setItemEditorFactory(factory); ui->projectsTreeView->setItemDelegateForColumn(RepoProjectsColumns::PROJECT, delegate); //-------------------------------------------------------------------------- // Projects projectsModel = new QStandardItemModel(this); projectsModel->setColumnCount(2); projectsModel->setHeaderData( RepoProjectsColumns::OWNER, Qt::Horizontal, tr("Owner")); projectsModel->setHeaderData( RepoProjectsColumns::PROJECT, Qt::Horizontal, tr("Project")); ui->projectsTreeView->setModel(projectsModel); ui->projectsTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder); //-------------------------------------------------------------------------- // DB Roles rolesModel = new QStandardItemModel(this); rolesModel->setColumnCount(2); rolesModel->setHeaderData( RepoProjectsColumns::OWNER, Qt::Horizontal, tr("Database")); rolesModel->setHeaderData( RepoProjectsColumns::PROJECT, Qt::Horizontal, tr("Role")); //ui->rolesTreeView->setModel(rolesModel); //ui->rolesTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder); //-------------------------------------------------------------------------- // Populate user data if (!user.isEmpty()) { ui->usernameLineEdit->setText(QString::fromStdString(user.getUsername())); ui->usernameLineEdit->setEnabled(false); ui->passwordLineEdit->setText(QString::fromStdString(user.getPassword())); ui->firstNameLineEdit->setText(QString::fromStdString(user.getFirstName())); ui->lastNameLineEdit->setText(QString::fromStdString(user.getLastName())); ui->emailLineEdit->setText(QString::fromStdString(user.getEmail())); //---------------------------------------------------------------------- // Projects std::vector<std::pair<std::string, std::string> > projects = user.getProjects(); this->populateModel(projectsModel, projects); //---------------------------------------------------------------------- // DB Roles std::vector<std::pair<std::string, std::string> > roles = user.getRoles(); this->populateModel(rolesModel, roles); QList<QTreeWidgetItem *> items; for (unsigned int i = 0; i < roles.size(); ++i) { QStringList list; list.append(QString::fromStdString(roles[i].first)); list.append(QString::fromStdString(roles[i].second)); QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, list); ui->rolesTreeWidget->insertTopLevelItem(0, item); QComboBox *databaseComboBox = new QComboBox(); databaseComboBox->addItem(QString::fromStdString(roles[i].first)); databaseComboBox->addItem("admin"); databaseComboBox->addItem("test"); ui->rolesTreeWidget->setItemWidget(item, 0, databaseComboBox); QComboBox *roleComboBox = new QComboBox(); roleComboBox->addItem(QString::fromStdString(roles[i].second)); roleComboBox->addItem("admin"); roleComboBox->addItem("test"); ui->rolesTreeWidget->setItemWidget(item, 1, roleComboBox); } } } repo::gui::RepoDialogUser::~RepoDialogUser() { delete projectsModel; delete rolesModel; delete ui; } QIcon repo::gui::RepoDialogUser::getIcon() { return RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_user); } void repo::gui::RepoDialogUser::populateModel( QStandardItemModel *model, const std::vector<std::pair<std::string, std::string> > &data) { for (unsigned int i = 0; i < data.size(); ++i) { QList<QStandardItem *> row; row.append(new QStandardItem(QString::fromStdString(data[i].first))); QStandardItem *item = new QStandardItem();//QString::fromStdString(data[i].second)); item->setData(QColor("springgreen"), Qt::DisplayRole); row.append(item); model->invisibleRootItem()->appendRow(row); // model->setData(model->index(i, 0), new QComboBox()); } } <|endoftext|>
<commit_before>777fd80a-2d53-11e5-baeb-247703a38240<commit_msg>77805fb4-2d53-11e5-baeb-247703a38240<commit_after>77805fb4-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "sppmphotontracer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/lighting/sppm/sppmphoton.h" #include "renderer/kernel/lighting/lightsampler.h" #include "renderer/kernel/lighting/pathtracer.h" #include "renderer/kernel/lighting/pathvertex.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/modeling/bsdf/bsdf.h" #include "renderer/modeling/edf/edf.h" #include "renderer/modeling/input/inputevaluator.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "renderer/utility/transformsequence.h" // appleseed.foundation headers. #include "foundation/math/basis.h" #include "foundation/math/hash.h" #include "foundation/math/rng.h" #include "foundation/math/vector.h" #include "foundation/platform/types.h" #include "foundation/utility/string.h" // Standard headers. #include <cassert> #include <cstddef> using namespace foundation; namespace renderer { SPPMPhotonTracer::SPPMPhotonTracer( const LightSampler& light_sampler, const TraceContext& trace_context, TextureStore& texture_store) : m_light_sampler(light_sampler) , m_texture_cache(texture_store) , m_intersector(trace_context, m_texture_cache /*, m_params.m_report_self_intersections*/) { } void SPPMPhotonTracer::trace_photons( SPPMPhotonVector& photons, const size_t pass_hash, const size_t photon_count) { RENDERER_LOG_INFO( "tracing %s sppm %s...", pretty_uint(photon_count).c_str(), photon_count > 1 ? "photons" : "photon"); MersenneTwister rng(static_cast<uint32>(pass_hash)); SamplingContext sampling_context( rng, 4, 0, // number of samples -- unknown pass_hash); photons.reserve(photon_count); for (size_t i = 0; i < photon_count; ++i) trace_photon(photons, sampling_context); } void SPPMPhotonTracer::trace_photon( SPPMPhotonVector& photons, SamplingContext& sampling_context) { LightSample light_sample; m_light_sampler.sample(sampling_context.next_vector2<4>(), light_sample); if (light_sample.m_triangle) { trace_emitting_triangle_photon( photons, sampling_context, light_sample); } else { trace_non_physical_light_photon( photons, sampling_context, light_sample); } } namespace { struct PathVisitor { const Spectrum m_initial_flux; // initial particle flux (in W) const bool m_cast_indirect_light; SPPMPhotonVector& m_photons; PathVisitor( const Spectrum& initial_flux, const bool cast_indirect_light, SPPMPhotonVector& photons) : m_initial_flux(initial_flux) , m_cast_indirect_light(cast_indirect_light) , m_photons(photons) { } bool accept_scattering_mode( const BSDF::Mode prev_bsdf_mode, const BSDF::Mode bsdf_mode) const { assert(bsdf_mode != BSDF::Absorption); return true; } bool visit_vertex(const PathVertex& vertex) { assert(vertex.m_path_length == 1 || m_cast_indirect_light); // Don't store photons on surfaces without a BSDF. if (vertex.m_bsdf == 0) return true; // Don't store photons on purely specular surfaces. if (vertex.m_bsdf->is_purely_specular()) return true; SPPMPhoton photon; photon.m_position = vertex.get_point(); photon.m_data.m_incoming = Vector3f(vertex.m_outgoing); photon.m_data.m_geometric_normal = Vector3f(vertex.get_geometric_normal()); photon.m_data.m_flux = m_initial_flux; photon.m_data.m_flux *= vertex.m_throughput; m_photons.push_back(photon); return m_cast_indirect_light; } void visit_environment( const ShadingPoint& shading_point, const Vector3d& outgoing, const BSDF::Mode prev_bsdf_mode, const double prev_bsdf_prob, const Spectrum& throughput) { // The photon escapes, nothing to do. } }; } void SPPMPhotonTracer::trace_emitting_triangle_photon( SPPMPhotonVector& photons, SamplingContext& sampling_context, LightSample& light_sample) { // Make sure the geometric normal of the light sample is in the same hemisphere as the shading normal. light_sample.m_geometric_normal = flip_to_same_hemisphere( light_sample.m_geometric_normal, light_sample.m_shading_normal); const EDF* edf = light_sample.m_triangle->m_edf; // Evaluate the EDF inputs. InputEvaluator input_evaluator(m_texture_cache); const void* edf_data = input_evaluator.evaluate(edf->get_inputs(), light_sample.m_bary); // Sample the EDF. SamplingContext child_sampling_context = sampling_context.split(2, 1); Vector3d emission_direction; Spectrum edf_value; double edf_prob; edf->sample( edf_data, light_sample.m_geometric_normal, Basis3d(light_sample.m_shading_normal), child_sampling_context.next_vector2<2>(), emission_direction, edf_value, edf_prob); // Compute the initial particle weight. Spectrum initial_flux = edf_value; initial_flux *= static_cast<float>( dot(emission_direction, light_sample.m_shading_normal) / (light_sample.m_probability * edf_prob)); // Make a shading point that will be used to avoid self-intersections with the light sample. ShadingPoint parent_shading_point; light_sample.make_shading_point( parent_shading_point, emission_direction, m_intersector); // Build the light ray. child_sampling_context.split_in_place(1, 1); const ShadingRay light_ray( light_sample.m_point, emission_direction, child_sampling_context.next_double2(), ~0); // Build the path tracer. const bool cast_indirect_light = (edf->get_flags() & EDF::CastIndirectLight) != 0; PathVisitor path_visitor( initial_flux, cast_indirect_light, photons); PathTracer<PathVisitor, true> path_tracer( // true = adjoint path_visitor, 3, // m_params.m_rr_min_path_length ~0, // m_params.m_max_path_length 1000); // m_params.m_max_iterations // Trace the light path. const size_t path_length = path_tracer.trace( child_sampling_context, m_intersector, m_texture_cache, light_ray, &parent_shading_point); // Update path statistics. //++m_path_count; //m_path_length.insert(path_length); } void SPPMPhotonTracer::trace_non_physical_light_photon( SPPMPhotonVector& photons, SamplingContext& sampling_context, LightSample& light_sample) { } } // namespace renderer <commit_msg>the sppm lighting engine now supports non-physical lights.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "sppmphotontracer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/lighting/sppm/sppmphoton.h" #include "renderer/kernel/lighting/lightsampler.h" #include "renderer/kernel/lighting/pathtracer.h" #include "renderer/kernel/lighting/pathvertex.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/modeling/bsdf/bsdf.h" #include "renderer/modeling/edf/edf.h" #include "renderer/modeling/input/inputevaluator.h" #include "renderer/modeling/light/light.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "renderer/utility/transformsequence.h" // appleseed.foundation headers. #include "foundation/math/basis.h" #include "foundation/math/hash.h" #include "foundation/math/rng.h" #include "foundation/math/transform.h" #include "foundation/math/vector.h" #include "foundation/platform/types.h" #include "foundation/utility/string.h" // Standard headers. #include <cassert> #include <cstddef> using namespace foundation; namespace renderer { SPPMPhotonTracer::SPPMPhotonTracer( const LightSampler& light_sampler, const TraceContext& trace_context, TextureStore& texture_store) : m_light_sampler(light_sampler) , m_texture_cache(texture_store) , m_intersector(trace_context, m_texture_cache /*, m_params.m_report_self_intersections*/) { } void SPPMPhotonTracer::trace_photons( SPPMPhotonVector& photons, const size_t pass_hash, const size_t photon_count) { RENDERER_LOG_INFO( "tracing %s sppm %s...", pretty_uint(photon_count).c_str(), photon_count > 1 ? "photons" : "photon"); MersenneTwister rng(static_cast<uint32>(pass_hash)); SamplingContext sampling_context( rng, 4, 0, // number of samples -- unknown pass_hash); photons.reserve(photon_count); for (size_t i = 0; i < photon_count; ++i) trace_photon(photons, sampling_context); } void SPPMPhotonTracer::trace_photon( SPPMPhotonVector& photons, SamplingContext& sampling_context) { LightSample light_sample; m_light_sampler.sample(sampling_context.next_vector2<4>(), light_sample); if (light_sample.m_triangle) { trace_emitting_triangle_photon( photons, sampling_context, light_sample); } else { trace_non_physical_light_photon( photons, sampling_context, light_sample); } } namespace { struct PathVisitor { const Spectrum m_initial_flux; // initial particle flux (in W) const bool m_cast_indirect_light; SPPMPhotonVector& m_photons; PathVisitor( const Spectrum& initial_flux, const bool cast_indirect_light, SPPMPhotonVector& photons) : m_initial_flux(initial_flux) , m_cast_indirect_light(cast_indirect_light) , m_photons(photons) { } bool accept_scattering_mode( const BSDF::Mode prev_bsdf_mode, const BSDF::Mode bsdf_mode) const { assert(bsdf_mode != BSDF::Absorption); return true; } bool visit_vertex(const PathVertex& vertex) { assert(vertex.m_path_length == 1 || m_cast_indirect_light); // Don't store photons on surfaces without a BSDF. if (vertex.m_bsdf == 0) return true; // Don't store photons on purely specular surfaces. if (vertex.m_bsdf->is_purely_specular()) return true; SPPMPhoton photon; photon.m_position = vertex.get_point(); photon.m_data.m_incoming = Vector3f(vertex.m_outgoing); photon.m_data.m_geometric_normal = Vector3f(vertex.get_geometric_normal()); photon.m_data.m_flux = m_initial_flux; photon.m_data.m_flux *= vertex.m_throughput; m_photons.push_back(photon); return m_cast_indirect_light; } void visit_environment( const ShadingPoint& shading_point, const Vector3d& outgoing, const BSDF::Mode prev_bsdf_mode, const double prev_bsdf_prob, const Spectrum& throughput) { // The photon escapes, nothing to do. } }; } void SPPMPhotonTracer::trace_emitting_triangle_photon( SPPMPhotonVector& photons, SamplingContext& sampling_context, LightSample& light_sample) { // Make sure the geometric normal of the light sample is in the same hemisphere as the shading normal. light_sample.m_geometric_normal = flip_to_same_hemisphere( light_sample.m_geometric_normal, light_sample.m_shading_normal); const EDF* edf = light_sample.m_triangle->m_edf; // Evaluate the EDF inputs. InputEvaluator input_evaluator(m_texture_cache); const void* edf_data = input_evaluator.evaluate(edf->get_inputs(), light_sample.m_bary); // Sample the EDF. SamplingContext child_sampling_context = sampling_context.split(2, 1); Vector3d emission_direction; Spectrum edf_value; double edf_prob; edf->sample( edf_data, light_sample.m_geometric_normal, Basis3d(light_sample.m_shading_normal), child_sampling_context.next_vector2<2>(), emission_direction, edf_value, edf_prob); // Compute the initial particle weight. Spectrum initial_flux = edf_value; initial_flux *= static_cast<float>( dot(emission_direction, light_sample.m_shading_normal) / (light_sample.m_probability * edf_prob)); // Make a shading point that will be used to avoid self-intersections with the light sample. ShadingPoint parent_shading_point; light_sample.make_shading_point( parent_shading_point, emission_direction, m_intersector); // Build the light ray. child_sampling_context.split_in_place(1, 1); const ShadingRay light_ray( light_sample.m_point, emission_direction, child_sampling_context.next_double2(), ~0); // Build the path tracer. const bool cast_indirect_light = (edf->get_flags() & EDF::CastIndirectLight) != 0; PathVisitor path_visitor( initial_flux, cast_indirect_light, photons); PathTracer<PathVisitor, true> path_tracer( // true = adjoint path_visitor, 3, // m_params.m_rr_min_path_length ~0, // m_params.m_max_path_length 1000); // m_params.m_max_iterations // Trace the light path. const size_t path_length = path_tracer.trace( child_sampling_context, m_intersector, m_texture_cache, light_ray, &parent_shading_point); // Update path statistics. //++m_path_count; //m_path_length.insert(path_length); } void SPPMPhotonTracer::trace_non_physical_light_photon( SPPMPhotonVector& photons, SamplingContext& sampling_context, LightSample& light_sample) { // Sample the light. InputEvaluator input_evaluator(m_texture_cache); SamplingContext child_sampling_context = sampling_context.split(2, 1); Vector3d emission_position, emission_direction; Spectrum light_value; double light_prob; light_sample.m_light->sample( input_evaluator, child_sampling_context.next_vector2<2>(), emission_position, emission_direction, light_value, light_prob); // Transform the emission position and direction from assembly space to world space. emission_position = light_sample.m_light_transform.point_to_parent(emission_position); emission_direction = normalize(light_sample.m_light_transform.vector_to_parent(emission_direction)); // Compute the initial particle weight. Spectrum initial_flux = light_value; initial_flux /= static_cast<float>(light_sample.m_probability * light_prob); // Build the light ray. child_sampling_context.split_in_place(1, 1); const ShadingRay light_ray( emission_position, emission_direction, child_sampling_context.next_double2(), ~0); // Build the path tracer. const bool cast_indirect_light = (light_sample.m_light->get_flags() & EDF::CastIndirectLight) != 0; PathVisitor path_visitor( initial_flux, cast_indirect_light, photons); PathTracer<PathVisitor, true> path_tracer( // true = adjoint path_visitor, 3, // m_params.m_rr_min_path_length ~0, // m_params.m_max_path_length 1000); // m_params.m_max_iterations // Trace the light path. const size_t path_length = path_tracer.trace( child_sampling_context, m_intersector, m_texture_cache, light_ray); // Update path statistics. //++m_path_count; //m_path_length.insert(path_length); } } // namespace renderer <|endoftext|>
<commit_before>// This file serves to seperate encoding of data outputs from the main mastercore.cpp/h files. #include "omnicore_encoding.h" #include "mastercore.h" #include "mastercore_script.h" #include "omnicore_utils.h" #include "base58.h" #include "pubkey.h" #include "random.h" #include "script/script.h" #include "script/standard.h" #include "utilstrencodings.h" #include <stdint.h> #include <string> #include <utility> #include <vector> bool OmniCore_Encode_ClassB(const std::string& senderAddress, const CPubKey& redeemingPubKey, const std::vector<unsigned char>& vecPayload, std::vector<std::pair <CScript,int64_t> >& vecOutputs) { int nRemainingBytes = vecPayload.size(); int nNextByte = 0; unsigned char seqNum = 1; std::string strObfuscatedHashes[1+MAX_SHA256_OBFUSCATION_TIMES]; PrepareObfuscatedHashes(senderAddress, strObfuscatedHashes); while (nRemainingBytes > 0) { int nKeys = 1; // assume one key of data since we have data remaining if (nRemainingBytes > (PACKET_SIZE - 1)) { nKeys += 1; } // we have enough data for 2 keys in this output std::vector<CPubKey> keys; keys.push_back(redeemingPubKey); // always include the redeeming pubkey for (int i = 0; i < nKeys; i++) { std::vector<unsigned char> fakeKey; fakeKey.push_back(seqNum); // add sequence number int numBytes = nRemainingBytes < (PACKET_SIZE - 1) ? nRemainingBytes: (PACKET_SIZE - 1); // add up to 30 bytes of data fakeKey.insert(fakeKey.end(), vecPayload.begin() + nNextByte, vecPayload.begin() + nNextByte + numBytes); nNextByte += numBytes; nRemainingBytes -= numBytes; while (fakeKey.size() < PACKET_SIZE) { fakeKey.push_back(0); } // pad to 31 total bytes with zeros std::vector<unsigned char>hash = ParseHex(strObfuscatedHashes[seqNum]); for (int j = 0; j < PACKET_SIZE; j++) { // xor in the obfuscation fakeKey[j] = fakeKey[j] ^ hash[j]; } fakeKey.insert(fakeKey.begin(), 2); // prepend the 2 CPubKey pubKey; fakeKey.resize(33); unsigned char random_byte = (unsigned char)(GetRand(256)); // fix up the ecdsa code point for (int j = 0; i < 256 ; j++) { fakeKey[32] = random_byte; pubKey = CPubKey(fakeKey); if (pubKey.IsFullyValid()) break; ++random_byte; // cycle 256 times, if we must to find a valid ECDSA point } keys.push_back(pubKey); seqNum++; } CScript multisig_output = GetScriptForMultisig(1, keys); vecOutputs.push_back(std::make_pair(multisig_output, GetDustThreshold(multisig_output))); } CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(exodus_address).Get()); vecOutputs.push_back(std::make_pair(scriptPubKey, GetDustThreshold(scriptPubKey))); // add the Exodus marker return true; } bool OmniCore_Encode_ClassC(const std::vector<unsigned char>& vecPayload, std::vector<std::pair <CScript,int64_t> >& vecOutputs) { const unsigned char bytes[] = {0x6f,0x6d}; // define Omni marker bytes if (vecPayload.size()+sizeof(bytes)/sizeof(bytes[0]) > nMaxDatacarrierBytes) { return false; } // we shouldn't see this since classAgnostic_send handles size vs class, but include check here for safety std::vector<unsigned char> omniBytesPlusData(bytes, bytes+sizeof(bytes)/sizeof(bytes[0])); omniBytesPlusData.insert(omniBytesPlusData.end(), vecPayload.begin(), vecPayload.end()); CScript script; script << OP_RETURN << omniBytesPlusData; vecOutputs.push_back(std::make_pair(script, 0)); return true; } <commit_msg>Encoding: add encoding documentation and refine code consistency<commit_after>#include "omnicore_encoding.h" #include "mastercore.h" #include "mastercore_script.h" #include "omnicore_utils.h" #include "base58.h" #include "pubkey.h" #include "random.h" #include "script/script.h" #include "script/standard.h" #include "utilstrencodings.h" #include <stdint.h> #include <string> #include <utility> #include <vector> /** * Embedds a payload in obfuscated multisig outputs, and adds an Exodus marker output. * * @see The class B transaction encoding specification: * https://github.com/mastercoin-MSC/spec#class-b-transactions-also-known-as-the-multisig-method */ bool OmniCore_Encode_ClassB(const std::string& senderAddress, const CPubKey& redeemingPubKey, const std::vector<unsigned char>& vchPayload, std::vector<std::pair<CScript, int64_t> >& vecOutputs) { int nRemainingBytes = vchPayload.size(); int nNextByte = 0; unsigned char chSeqNum = 1; std::string strObfuscatedHashes[1+MAX_SHA256_OBFUSCATION_TIMES]; PrepareObfuscatedHashes(senderAddress, strObfuscatedHashes); while (nRemainingBytes > 0) { int nKeys = 1; // Assume one key of data, because we have data remaining if (nRemainingBytes > (PACKET_SIZE - 1)) { nKeys += 1; } // ... or enough data to embed in 2 keys std::vector<CPubKey> vKeys; vKeys.push_back(redeemingPubKey); // Always include the redeeming pubkey for (int i = 0; i < nKeys; i++) { // Add up to 30 bytes of data int nCurrentBytes = nRemainingBytes < (PACKET_SIZE - 1) ? nRemainingBytes: (PACKET_SIZE - 1); std::vector<unsigned char> vchFakeKey; vchFakeKey.insert(vchFakeKey.end(), chSeqNum); // Add sequence number vchFakeKey.insert(vchFakeKey.end(), vchPayload.begin() + nNextByte, vchPayload.begin() + nNextByte + nCurrentBytes); vchFakeKey.resize(PACKET_SIZE); // Pad to 31 total bytes with zeros nNextByte += nCurrentBytes; nRemainingBytes -= nCurrentBytes; std::vector<unsigned char> vchHash = ParseHex(strObfuscatedHashes[chSeqNum]); for (int j = 0; j < PACKET_SIZE; j++) { // Xor in the obfuscation vchFakeKey[j] = vchFakeKey[j] ^ vchHash[j]; } vchFakeKey.insert(vchFakeKey.begin(), 0x02); // Prepend a public key prefix vchFakeKey.resize(33); CPubKey pubKey; unsigned char chRandom = static_cast<unsigned char>(GetRand(256)); for (int j = 0; i < 256 ; j++) { // Fix ECDSA coodinate vchFakeKey[32] = chRandom; pubKey = CPubKey(vchFakeKey); if (pubKey.IsFullyValid()) break; ++chRandom; // ... but cycle no more than 256 times to find a valid point } vKeys.push_back(pubKey); chSeqNum++; } // Push back a bare multisig output with obfuscated data CScript scriptMultisigOut = GetScriptForMultisig(1, vKeys); vecOutputs.push_back(std::make_pair(scriptMultisigOut, GetDustThreshold(scriptMultisigOut))); } // Add the Exodus marker output CScript scriptExodusOut = GetScriptForDestination(CBitcoinAddress(exodus_address).Get()); vecOutputs.push_back(std::make_pair(scriptExodusOut, GetDustThreshold(scriptExodusOut))); return true; } /** * @return The marker for class C transactions. */ static inline std::vector<unsigned char> GetOmMarker() { const unsigned char pch[] = {0x6f, 0x6d}; // Hex-encoded: "om" return std::vector<unsigned char>(pch, pch + sizeof (pch) / sizeof (pch[0])); } /** * Embedds a payload in an OP_RETURN output, prefixed with a transaction marker. * * The request is rejected, if the size of the payload with marker is larger than * the allowed data carrier size ("-datacarriersize=n"). */ bool OmniCore_Encode_ClassC(const std::vector<unsigned char>& vchPayload, std::vector<std::pair <CScript, int64_t> >& vecOutputs) { std::vector<unsigned char> vchData; std::vector<unsigned char> vchOmBytes = GetOmMarker(); vchData.insert(vchData.end(), vchOmBytes.begin(), vchOmBytes.end()); vchData.insert(vchData.end(), vchPayload.begin(), vchPayload.end()); if (vchData.size() > nMaxDatacarrierBytes) { return false; } CScript script; script << OP_RETURN << vchData; vecOutputs.push_back(std::make_pair(script, 0)); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" #include "googleurl/src/gurl.h" #include "net/base/mock_host_resolver.h" class ExtensionResourceRequestPolicyTest : public ExtensionApiTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kAllowLegacyExtensionManifests); } }; // Note, this mostly tests the logic of chrome/renderer/extensions/ // extension_resource_request_policy.*, but we have it as a browser test so that // can make sure it works end-to-end. IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, OriginPrivileges) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("extension"))); GURL web_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "index.html")); std::string host_a("a.com"); GURL::Replacements make_host_a_com; make_host_a_com.SetHostStr(host_a); std::string host_b("b.com"); GURL::Replacements make_host_b_com; make_host_b_com.SetHostStr(host_b); // A web host that has permission. ui_test_utils::NavigateToURL( browser(), web_resource.ReplaceComponents(make_host_a_com)); std::string result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Loaded"); // A web host that loads a non-existent extension. GURL non_existent_extension( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "non_existent_extension.html")); ui_test_utils::NavigateToURL(browser(), non_existent_extension); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Image failed to load"); // A data URL. Data URLs should always be able to load chrome-extension:// // resources. std::string file_source; ASSERT_TRUE(file_util::ReadFileToString( test_data_dir_.AppendASCII("extension_resource_request_policy") .AppendASCII("index.html"), &file_source)); ui_test_utils::NavigateToURL(browser(), GURL(std::string("data:text/html;charset=utf-8,") + file_source)); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Loaded"); // A different extension. Extensions should always be able to load each // other's resources. ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("extension2"))); ui_test_utils::NavigateToURL( browser(), GURL("chrome-extension://pbkkcbgdkliohhfaeefcijaghglkahja/index.html")); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Loaded"); } IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, ExtensionCanLoadHostedAppIcons) { ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("extension"))); ASSERT_TRUE(RunExtensionSubtest( "extension_resource_request_policy/extension2/", "can_load_icons_from_hosted_apps.html")); } IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, Audio) { EXPECT_TRUE(RunExtensionSubtest( "extension_resource_request_policy/extension2", "audio.html")); } #if defined(OS_MACOSX) // http://crbug.com/95274 - Video is flaky on Mac. #define MAYBE_Video DISABLED_Video #else #define MAYBE_Video Video #endif IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Video) { EXPECT_TRUE(RunExtensionSubtest( "extension_resource_request_policy/extension2", "video.html")); } IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, WebAccessibleResources) { std::string result; ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("web_accessible"))); GURL accessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/accessible_resource.html")); ui_test_utils::NavigateToURL(browser(), accessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("Loaded", result); GURL xhr_accessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/xhr_accessible_resource.html")); ui_test_utils::NavigateToURL( browser(), xhr_accessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("XHR completed with status: 200", result); GURL xhr_inaccessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/xhr_inaccessible_resource.html")); ui_test_utils::NavigateToURL( browser(), xhr_inaccessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("XHR failed to load resource", result); GURL nonaccessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/nonaccessible_resource.html")); ui_test_utils::NavigateToURL(browser(), nonaccessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("Image failed to load", result); GURL nonexistent_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/nonexistent_resource.html")); ui_test_utils::NavigateToURL(browser(), nonexistent_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("Image failed to load", result); } <commit_msg>Mark ExtensionResourceRequestPolicyTest.Audio as FLAKY on ChromeOS<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" #include "googleurl/src/gurl.h" #include "net/base/mock_host_resolver.h" class ExtensionResourceRequestPolicyTest : public ExtensionApiTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kAllowLegacyExtensionManifests); } }; // Note, this mostly tests the logic of chrome/renderer/extensions/ // extension_resource_request_policy.*, but we have it as a browser test so that // can make sure it works end-to-end. IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, OriginPrivileges) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("extension"))); GURL web_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "index.html")); std::string host_a("a.com"); GURL::Replacements make_host_a_com; make_host_a_com.SetHostStr(host_a); std::string host_b("b.com"); GURL::Replacements make_host_b_com; make_host_b_com.SetHostStr(host_b); // A web host that has permission. ui_test_utils::NavigateToURL( browser(), web_resource.ReplaceComponents(make_host_a_com)); std::string result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Loaded"); // A web host that loads a non-existent extension. GURL non_existent_extension( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "non_existent_extension.html")); ui_test_utils::NavigateToURL(browser(), non_existent_extension); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Image failed to load"); // A data URL. Data URLs should always be able to load chrome-extension:// // resources. std::string file_source; ASSERT_TRUE(file_util::ReadFileToString( test_data_dir_.AppendASCII("extension_resource_request_policy") .AppendASCII("index.html"), &file_source)); ui_test_utils::NavigateToURL(browser(), GURL(std::string("data:text/html;charset=utf-8,") + file_source)); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Loaded"); // A different extension. Extensions should always be able to load each // other's resources. ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("extension2"))); ui_test_utils::NavigateToURL( browser(), GURL("chrome-extension://pbkkcbgdkliohhfaeefcijaghglkahja/index.html")); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ(result, "Loaded"); } IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, ExtensionCanLoadHostedAppIcons) { ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("extension"))); ASSERT_TRUE(RunExtensionSubtest( "extension_resource_request_policy/extension2/", "can_load_icons_from_hosted_apps.html")); } #if defined(OS_CHROMEOS) // http://crbug.com/114478 - Audio crashes occasionally on ChromeOS #define MAYBE_Audio FLAKY_Audio #else #define MAYBE_Audio Audio #endif IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Audio) { EXPECT_TRUE(RunExtensionSubtest( "extension_resource_request_policy/extension2", "audio.html")); } #if defined(OS_MACOSX) // http://crbug.com/95274 - Video is flaky on Mac. #define MAYBE_Video DISABLED_Video #else #define MAYBE_Video Video #endif IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Video) { EXPECT_TRUE(RunExtensionSubtest( "extension_resource_request_policy/extension2", "video.html")); } IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, WebAccessibleResources) { std::string result; ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("extension_resource_request_policy") .AppendASCII("web_accessible"))); GURL accessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/accessible_resource.html")); ui_test_utils::NavigateToURL(browser(), accessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("Loaded", result); GURL xhr_accessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/xhr_accessible_resource.html")); ui_test_utils::NavigateToURL( browser(), xhr_accessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("XHR completed with status: 200", result); GURL xhr_inaccessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/xhr_inaccessible_resource.html")); ui_test_utils::NavigateToURL( browser(), xhr_inaccessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("XHR failed to load resource", result); GURL nonaccessible_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/nonaccessible_resource.html")); ui_test_utils::NavigateToURL(browser(), nonaccessible_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("Image failed to load", result); GURL nonexistent_resource( test_server()->GetURL( "files/extensions/api_test/extension_resource_request_policy/" "web_accessible/nonexistent_resource.html")); ui_test_utils::NavigateToURL(browser(), nonexistent_resource); ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedWebContents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(document.title)", &result)); EXPECT_EQ("Image failed to load", result); } <|endoftext|>
<commit_before><commit_msg>fix2<commit_after><|endoftext|>
<commit_before>#include <stan/math/prim.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> TEST(MathMatrixPrim, Zero) { stan::math::matrix_d m0(0, 0); stan::math::matrix_d ginv = stan::math::generalized_inverse(m0); EXPECT_EQ(0, ginv.rows()); EXPECT_EQ(0, ginv.cols()); } TEST(MathMatrixPrim, Equal) { using stan::math::generalized_inverse; stan::math::matrix_d m1(3, 2); m1 << 1, 2, 2, 4, 1, 2; stan::math::matrix_d m2(2, 3); m2 << 1 / 30.0, 1 / 15.0, 1 / 30.0, 1 / 15.0, 2 / 15.0, 1 / 15.0; stan::math::matrix_d m3 = generalized_inverse(m1); for (int j = 0; j < m3.cols(); j++) for (int i = 0; i < m3.rows(); i++) EXPECT_NEAR(m2(i, j), m3(i, j), 1e-5); } <commit_msg>Update test/unit/math/prim/fun/generalized_inverse_test.cpp<commit_after>#include <stan/math/prim.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> TEST(MathMatrixPrim, Zero) { stan::math::matrix_d m0(0, 0); stan::math::matrix_d ginv = stan::math::generalized_inverse(m0); EXPECT_EQ(0, ginv.rows()); EXPECT_EQ(0, ginv.cols()); } TEST(MathMatrixPrim, Equal) { using stan::math::generalized_inverse; stan::math::matrix_d m1(3, 2); m1 << 1, 2, 2, 4, 1, 2; stan::math::matrix_d m2(2, 3); m2 << 1 / 30.0, 1 / 15.0, 1 / 30.0, 1 / 15.0, 2 / 15.0, 1 / 15.0; stan::math::matrix_d m3 = generalized_inverse(m1); EXPECT_MATRIX_NEAR(m2, m3, 1e-5); } <|endoftext|>
<commit_before>//Code for COP 3503 Computer Programming for CS Majors II Lab/HW - Andrew Silver Problem 1. Code compiles. with g++ -std=c++0x -o p1 p1.cpp on Ubuntu 12.04 and with current stuff on Mac OS X. Implementation of RLE encoding for the Lab 3 for COP3503. Version 6.0 - includes working implementation of new-style encoding for COP 3503 HW 6. 1 + 1 = 2 ---> 11 + 11 = 12. Single digits get 1s before, and the no digit check was commented out. //for more information, look up variations of the run-length encoding algorithm. for hello world, it prints he2lo world. for 1111, it prints 41, etc. #include <iostream> bool makestring(char* p1){ bool result = false; //result of this function while(*p1){ //as long as the cstring is not at the delimiting whitespace. If the number 0 is in the cstring, this loop will stop evaluating and the else st if(!(*p1 - '0' < 10 && *p1 - '0' >= 0)){ //casts the element to an int. If it was a character, then the output would be not between 1 and 9, and this would execute (since it is ! ). If it was an int, then the output would be nonzero (the value of the int) and because of the ! this following code would not evaluate. result = true; //no number found, so good to go } else{ //if there is a number in the list. result = false; break; //ends the for loop, a number was found } ++p1; //go to the next address to check } //ends while loop return result; //if there is a 0 digit in the cstring that is not the whitespace, then it will obviously return false, since a number exists, and it does not need to cycle through any more positions. } //this function takes a pointer to element at index 0 of an array (a cstring). It will cycle through and determine the length. unsigned int lengthstring(char* p2){ unsigned int length = 0; //the length of the cstring that will be determined. while(*p2){ //as long as the value at the address the pointer points to is not the delimiter 0. i.e., as long as the pointer does not point to the end of the array. Note that this does not include the delimiting 0 at the end in the calculation, as expected by the sample output. This could be added by just setting length to 1 at the start. ++length; //adds 1 to the length ++p2; //goes to the next address in the array } // std::cout << length; this part prints 5 if hello is passed in return length; } //function takes a cstring and replaces matching characters with the number of times they match char* matchingstring(char* p3){ int looptimes = 0; //the number of times the loop has occured through the values unsigned int length = 0; //length of the inputted cstring, which will be called from the function lengthstring char counting = '1'; //conversion for counter to a char to be stored int counter = 1; //the counter to track how many times the same element appears, starts at 1. char* repeat = p3; //tracker pointer to store the character that repeats, I don't want to increment the original array, copies address of p3 into repeat length = lengthstring(p3); //gets the length of the inputted string and stores it in counter char* output = new char[length](); //creates memory for pointer to the first element of a new array and default initializes the values to 0. char* array = output; //gets the value of the array, i.e., the address of the first element while(*p3){ //while not at the end of the array, i.e. the delimiter if((*(p3 + 1) == *p3)){ //if the next element in the array is equal to the current while(*(p3 + 1) == *repeat && counter != 11){ //runs until the next element in the array is different than the current element and the numbers for counter are between 1 and 10 ++counter; //increase the counter to determine the number of repeats ++p3; //moves p3 forward in the array to keep checking for more repeats // this evaluates std::cout << "yea this works" << std::endl; } if(counter >= 11){ //if the counter is greater than 10, then add a 0 for the first ten and keep going *array = '0'; ++array; *array = *p3; } else if (counter == 10){ //if the counter is equal to 10, change it to 0 *array = '0'; } else { counting = (counter + '0'); //converts the int counter to a character *array = counting; //the element in the array gets the number of repeats } ++array; //go to the next index *array = *repeat; //the element in the array gets the repeated char } else if ( ((*p3 - '0' >= 0) && (*p3 - '0' < 10)) && ( ( (((*p3 - '0')/10 == 0 ) && (looptimes != 1) && (*(p3 + 1) == ' ' || *(p3 + 1) == '\0') )) || ( (*(p3 + 1) == ' ') && (*(p3 - 1) == ' ')) || ( (*(p3 +1) == '\0') && (*(p3 - 1) == ' '))) ) { //additional implementation to RLE encoding. If there is a digit by itself, a 1 comes before it. The ' ' statements don't seem to work in the beginning of the pointer, so I created a "looptimes" variable that increments each time p3 goes to the next index. This means that this condition will always be false and I wouldn't have random '1's everywhere. *array = '1'; //1 digit found ++array; *array = *p3; ++p3; //goes to next index in P3 *repeat = *p3; //resets repeat to current element at p3 ++array; //goes to the next index position for the array } else{ //base case, if no matches are found, i.e. if the next element is not equal to the current *array = *p3; ++p3; //go to the next index in p3 *repeat = *p3; //resets repeat to the current element at p3 ++array; //goes to next index position for the array } counter = 1; // reset counter to 1 looptimes = 1; //once past the first element of the cstring, no longer run the first if condition } *array = '\0'; //adds the delimiting character to the end, making this a cstring return output; //returns a pointer to the first element of a cstring. Since the array was default initialized to 0, the last element will be '0'. } //the starting point of the program int main(){ int const buffer_size = 256; //create a buffer size char buffer[ buffer_size ]; //make a buffer char* pointer = buffer; //pointer to the first element of buffer // old version with no digits std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; std::cout << "Type a sentence and press [RETURN], please." << std::endl; std::cin.getline( buffer, buffer_size ); //grab the input from the shell while(lengthstring(pointer)) //as long as length does not equal 0, i.e. the null string { char* checklength = buffer; //a pointer to the first element of buffer that will be passed into the length method call unsigned int originallength = lengthstring(buffer); //length of the original cstring, originally checklength unsigned int RLElength = 0; //length of the new cstring, which will be checked later /* if(makestring(test) == false){ //calls the makestring method on the pointer, if the user enters a number, keep prompting. not used in new-style version std::cout << "Yeaaa bro don't give me numbers. That's not cool. Only use characters." << std::endl; std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; std::cin.getline( buffer, buffer_size ); } */ // else{ //if makestring(test) is true, i.e., there are no numbers in the cstring, removed in new style version char* RLE = matchingstring(buffer); //grabs a pointer to the first element of the RLE encoded version of the array, originally pointer RLElength = lengthstring(RLE); //checks the length of RLE version while(*RLE){ //while not at a delimeter std::cout << *RLE; ++RLE; //go to the next index position } std::cout << "" <<std::endl; //prints a newline if(originallength >= RLElength){ //if the RLE compressed version is shorter than the original std::cout << "The RLE version is " << (originallength - RLElength) << " shorter than the original" << std::endl; } else{ //when using new style RLE compression, the RLElength could actually be longer. std::cout << "The RLE version is " << (RLElength - originallength) << " longer than the original" << std::endl; } if(lengthstring(pointer)){ delete []RLE; //deletes the memory allocated for the encoded array } //std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; NOT USED IN RLE NEW STYLE ENCODING std::cout << "Type a sentence and press [RETURN], please." <<std::endl; std::cin.getline( buffer, buffer_size ); } //} closes else statement, removed in new style version return 0; } <commit_msg>deleted unneeded pointers<commit_after>//Code for COP 3503 Computer Programming for CS Majors II Lab/HW - Andrew Silver Problem 1. Code compiles. with g++ -std=c++0x -o p1 p1.cpp on Ubuntu 12.04 and with current stuff on Mac OS X. Implementation of RLE encoding for the Lab 3 for COP3503. Version 6.0 - includes working implementation of new-style encoding for COP 3503 HW 6. 1 + 1 = 2 ---> 11 + 11 = 12. Single digits get 1s before, and the no digit check was commented out. //for more information, look up variations of the run-length encoding algorithm. for hello world, it prints he2lo world. for 1111, it prints 41, etc. #include <iostream> bool makestring(char* p1){ bool result = false; //result of this function while(*p1){ //as long as the cstring is not at the delimiting whitespace. If the number 0 is in the cstring, this loop will stop evaluating and the else st if(!(*p1 - '0' < 10 && *p1 - '0' >= 0)){ //casts the element to an int. If it was a character, then the output would be not between 1 and 9, and this would execute (since it is ! ). If it was an int, then the output would be nonzero (the value of the int) and because of the ! this following code would not evaluate. result = true; //no number found, so good to go } else{ //if there is a number in the list. result = false; break; //ends the for loop, a number was found } ++p1; //go to the next address to check } //ends while loop return result; //if there is a 0 digit in the cstring that is not the whitespace, then it will obviously return false, since a number exists, and it does not need to cycle through any more positions. } //this function takes a pointer to element at index 0 of an array (a cstring). It will cycle through and determine the length. unsigned int lengthstring(char* p2){ unsigned int length = 0; //the length of the cstring that will be determined. while(*p2){ //as long as the value at the address the pointer points to is not the delimiter 0. i.e., as long as the pointer does not point to the end of the array. Note that this does not include the delimiting 0 at the end in the calculation, as expected by the sample output. This could be added by just setting length to 1 at the start. ++length; //adds 1 to the length ++p2; //goes to the next address in the array } // std::cout << length; this part prints 5 if hello is passed in return length; } //function takes a cstring and replaces matching characters with the number of times they match char* matchingstring(char* p3){ int looptimes = 0; //the number of times the loop has occured through the values unsigned int length = 0; //length of the inputted cstring, which will be called from the function lengthstring char counting = '1'; //conversion for counter to a char to be stored int counter = 1; //the counter to track how many times the same element appears, starts at 1. char* repeat = p3; //tracker pointer to store the character that repeats, I don't want to increment the original array, copies address of p3 into repeat length = lengthstring(p3); //gets the length of the inputted string and stores it in counter char* output = new char[length](); //creates memory for pointer to the first element of a new array and default initializes the values to 0. char* array = output; //gets the value of the array, i.e., the address of the first element while(*p3){ //while not at the end of the array, i.e. the delimiter if((*(p3 + 1) == *p3)){ //if the next element in the array is equal to the current while(*(p3 + 1) == *repeat && counter != 11){ //runs until the next element in the array is different than the current element and the numbers for counter are between 1 and 10 ++counter; //increase the counter to determine the number of repeats ++p3; //moves p3 forward in the array to keep checking for more repeats // this evaluates std::cout << "yea this works" << std::endl; } if(counter >= 11){ //if the counter is greater than 10, then add a 0 for the first ten and keep going *array = '0'; ++array; *array = *p3; } else if (counter == 10){ //if the counter is equal to 10, change it to 0 *array = '0'; } else { counting = (counter + '0'); //converts the int counter to a character *array = counting; //the element in the array gets the number of repeats } ++array; //go to the next index *array = *repeat; //the element in the array gets the repeated char } else if ( ((*p3 - '0' >= 0) && (*p3 - '0' < 10)) && ( ( (((*p3 - '0')/10 == 0 ) && (looptimes != 1) && (*(p3 + 1) == ' ' || *(p3 + 1) == '\0') )) || ( (*(p3 + 1) == ' ') && (*(p3 - 1) == ' ')) || ( (*(p3 +1) == '\0') && (*(p3 - 1) == ' '))) ) { //additional implementation to RLE encoding. If there is a digit by itself, a 1 comes before it. The ' ' statements don't seem to work in the beginning of the pointer, so I created a "looptimes" variable that increments each time p3 goes to the next index. This means that this condition will always be false and I wouldn't have random '1's everywhere. *array = '1'; //1 digit found ++array; *array = *p3; ++p3; //goes to next index in P3 *repeat = *p3; //resets repeat to current element at p3 ++array; //goes to the next index position for the array } else{ //base case, if no matches are found, i.e. if the next element is not equal to the current *array = *p3; ++p3; //go to the next index in p3 *repeat = *p3; //resets repeat to the current element at p3 ++array; //goes to next index position for the array } counter = 1; // reset counter to 1 looptimes = 1; //once past the first element of the cstring, no longer run the first if condition } *array = '\0'; //adds the delimiting character to the end, making this a cstring return output; //returns a pointer to the first element of a cstring. Since the array was default initialized to 0, the last element will be '0'. } //the starting point of the program int main(){ int const buffer_size = 256; //create a buffer size char buffer[ buffer_size ]; //make a buffer // old version with no digits std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; std::cout << "Type a sentence and press [RETURN], please." << std::endl; std::cin.getline( buffer, buffer_size ); //grab the input from the shell while(lengthstring(buffer)) //as long as pointer length does not equal 0, i.e. the null string { unsigned int originallength = lengthstring(buffer); //length of the original cstring, originally checklength unsigned int RLElength = 0; //length of the new cstring, which will be checked later /* if(makestring(test) == false){ //calls the makestring method on the pointer, if the user enters a number, keep prompting. not used in new-style version std::cout << "Yeaaa bro don't give me numbers. That's not cool. Only use characters." << std::endl; std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; std::cin.getline( buffer, buffer_size ); } */ // else{ //if makestring(test) is true, i.e., there are no numbers in the cstring, removed in new style version char* RLE = matchingstring(buffer); //grabs a pointer to the first element of the RLE encoded version of the array, originally pointer RLElength = lengthstring(RLE); //checks the length of RLE version while(*RLE){ //while not at a delimeter std::cout << *RLE; ++RLE; //go to the next index position } std::cout << "" <<std::endl; //prints a newline if(originallength >= RLElength){ //if the RLE compressed version is shorter than the original std::cout << "The RLE version is " << (originallength - RLElength) << " shorter than the original" << std::endl; } else{ //when using new style RLE compression, the RLElength could actually be longer. std::cout << "The RLE version is " << (RLElength - originallength) << " longer than the original" << std::endl; } if(lengthstring(buffer)){ delete []RLE; //deletes the memory allocated for the encoded array } //std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; NOT USED IN RLE NEW STYLE ENCODING std::cout << "Type a sentence and press [RETURN], please." <<std::endl; std::cin.getline( buffer, buffer_size ); } //} closes else statement, removed in new style version return 0; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <geometry_msgs/Twist.h> void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd) { ROS_INFO("I heard: [%f]", vel_cmd.linear.y); std::cout << "Twist Received " << std::endl; } int main( int argc, char* argv[] ) { ros::init(argc, argv, "toeminator_publisher" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback); while( n.ok() ) { ros::spin(); } return 1; } <commit_msg>change base_controller_node.cpp<commit_after>#include <iostream> #include <stdio.h> /* Standard input/output definitions */ #include <stdlib.h> /* exit */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> #include <geometry_msgs/Twist.h> struct termios orig; int filedesc; int fd; unsigned char serialBuffer[16]; // Serial buffer to store data for I/O int openSerialPort(const char * device, int bps) { struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd) { ROS_INFO("I heard: [%f]", vel_cmd.linear.y); std::cout << "Twist Received " << std::endl; //hier code um msg in seriellen Befehl umzuwandeln //code // } int main( int argc, char* argv[] ) { ros::init(argc, argv, "toeminator_publisher" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback); filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options printf("serial Port opened \n"); while( n.ok() ) { ros::spin(); } return 1; } <|endoftext|>
<commit_before><commit_msg>drt: fix compiler warning<commit_after><|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <OpenThreads/ScopedLock> #include <osg/ImageSequence> #include <osg/Notify> #include <osg/Camera> #include <osg/NodeVisitor> #include <osg/Texture2D> #include <math.h> using namespace osg; ImageSequence::ImageData::ImageData() { } ImageSequence::ImageData::ImageData(const ImageData& id): _filename(id._filename), _image(id._image), _imageRequest(id._imageRequest) { } ImageSequence::ImageData& ImageSequence::ImageData::operator = (const ImageSequence::ImageData& rhs) { if (&rhs!=this) { _filename = rhs._filename; _image = rhs._image; _imageRequest = rhs._imageRequest; } return *this; } ImageSequence::ImageSequence() { _referenceTime = DBL_MAX; _timeMultiplier = 1.0; _mode = PRE_LOAD_ALL_IMAGES; _length = 1.0; _timePerImage = 1.0; _seekTime = 0.0; _seekTimeSet = false; _previousAppliedImageIndex = -1; } ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop): osg::ImageStream(is,copyop), _referenceTime(is._referenceTime), _timeMultiplier(is._timeMultiplier), _mode(is._mode), _length(is._length), _timePerImage(is._timePerImage) { _seekTime = is._seekTime; _seekTimeSet = is._seekTimeSet; _previousAppliedImageIndex = -1; } int ImageSequence::compare(const Image& rhs) const { return ImageStream::compare(rhs); } void ImageSequence::seek(double time) { _seekTime = time; _seekTimeSet = true; } void ImageSequence::play() { _status=PLAYING; } void ImageSequence::pause() { _status=PAUSED; } void ImageSequence::rewind() { seek(0.0f); } void ImageSequence::setMode(Mode mode) { _mode = mode; } void ImageSequence::setLength(double length) { if (length<=0.0) { OSG_NOTICE<<"ImageSequence::setLength("<<length<<") invalid length value, must be greater than 0."<<std::endl; return; } _length = length; computeTimePerImage(); } void ImageSequence::computeTimePerImage() { if (!_imageDataList.empty()) _timePerImage = _length / double(_imageDataList.size()); else _timePerImage = _length; } void ImageSequence::setImageFile(unsigned int pos, const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (pos>=_imageDataList.size()) _imageDataList.resize(pos); _imageDataList[pos]._filename = fileName; } std::string ImageSequence::getImageFile(unsigned int pos) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); return pos<_imageDataList.size() ? _imageDataList[pos]._filename : std::string(); } void ImageSequence::addImageFile(const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); _imageDataList.push_back(ImageData()); _imageDataList.back()._filename = fileName; computeTimePerImage(); } void ImageSequence::setImage(unsigned int pos, osg::Image* image) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (pos>=_imageDataList.size()) _imageDataList.resize(pos+1); _imageDataList[pos]._image = image; _imageDataList[pos]._filename = image->getFileName(); } Image* ImageSequence::getImage(unsigned int pos) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); return pos<_imageDataList.size() ? _imageDataList[pos]._image.get() : 0; } const Image* ImageSequence::getImage(unsigned int pos) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); return pos<_imageDataList.size() ? _imageDataList[pos]._image.get() : 0; } void ImageSequence::addImage(osg::Image* image) { if (image==0) return; OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); // OSG_NOTICE<<"merging image in order expected : "<<image->getFileName()<<std::endl; _imageDataList.push_back(ImageData()); _imageDataList.back()._image = image; computeTimePerImage(); if (data()==0) { setImageToChild(_imageDataList.size()-1); } } void ImageSequence::setImageToChild(int pos) { const osg::Image* image = (pos>=0 && pos<static_cast<int>(_imageDataList.size())) ? _imageDataList[pos]._image.get() : 0; if (image==0) return; // check to see if data is changing, if not don't apply if (image->data() == data()) { return; } if (_mode==PAGE_AND_DISCARD_USED_IMAGES && _previousAppliedImageIndex>=0) { if (_previousAppliedImageIndex<pos) { OSG_INFO<<"Moving forward from "<<_previousAppliedImageIndex<<" to "<<pos<<std::endl; while(_previousAppliedImageIndex<pos) { _imageDataList[_previousAppliedImageIndex]._image = 0; OSG_INFO<<" deleting "<<_previousAppliedImageIndex<<std::endl; ++_previousAppliedImageIndex; } } else if (_previousAppliedImageIndex>pos) { OSG_INFO<<"Moving back from "<<_previousAppliedImageIndex<<" to "<<pos<<std::endl; while(_previousAppliedImageIndex>pos) { _imageDataList[_previousAppliedImageIndex]._image = 0; OSG_INFO<<" deleting "<<_previousAppliedImageIndex<<std::endl; --_previousAppliedImageIndex; } } } _previousAppliedImageIndex = pos; setImage(image->s(),image->t(),image->r(), image->getInternalTextureFormat(), image->getPixelFormat(),image->getDataType(), const_cast<unsigned char*>(image->data()), osg::Image::NO_DELETE, image->getPacking()); } void ImageSequence::applyLoopingMode() { } int ImageSequence::imageIndex(double time) { if (getLoopingMode()==LOOPING) { double positionRatio = time/_length; time = (positionRatio - floor(positionRatio))*_length; } if (time<0.0) return 0; int index = int(time/_timePerImage); if (index>=int(_imageDataList.size())) return int(_imageDataList.size())-1; return index; } void ImageSequence::update(osg::NodeVisitor* nv) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler(); const osg::FrameStamp* fs = nv->getFrameStamp(); // OSG_NOTICE<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl; if (_referenceTime == DBL_MAX) { _referenceTime = fs->getSimulationTime(); } bool looping = getLoopingMode()==LOOPING; double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier; bool useDirectTimeRequest = _seekTimeSet; if (_seekTimeSet || _status==PAUSED || _status==INVALID) { time = _seekTime; useDirectTimeRequest = true; _referenceTime = fs->getSimulationTime() - time/_timeMultiplier; } else { if (looping) { while (time>_length) { _referenceTime += _length/_timeMultiplier; time -= _length; } } else { if (time>_length) { _referenceTime = fs->getSimulationTime() - _length/_timeMultiplier; time = _length; } } } _seekTime = time; _seekTimeSet = false; if (irh && _mode==PRE_LOAD_ALL_IMAGES) { for(ImageDataList::iterator itr = _imageDataList.begin(); itr != _imageDataList.end(); ++itr) { if (!(itr->_image) && !(itr->_filename.empty())) { itr->_image = irh->readImageFile(itr->_filename); } } } int index = int(time/_timePerImage); // OSG_NOTICE<<"time= "<<time<<" _timePerImage="<<_timePerImage<<" index="<<index<<" _length="<<_length<<std::endl; if (index>=int(_imageDataList.size())) index = int(_imageDataList.size())-1; if (index>=0 && index<int(_imageDataList.size())) { // need to find the nearest relevant change. if (!_imageDataList[index]._image) { if (_previousAppliedImageIndex<index) { OSG_DEBUG<<"ImageSequence::update(..) Moving forward by "<<index-_previousAppliedImageIndex<<std::endl; while (index>=0 && !_imageDataList[index]._image.valid()) { --index; } } else if (_previousAppliedImageIndex>index) { OSG_DEBUG<<"ImageSequence::update(..) Moving back by "<<_previousAppliedImageIndex-index<<std::endl; while (index<static_cast<int>(_imageDataList.size()) && !_imageDataList[index]._image.valid()) { ++index; } } } if (index>=0 && index!=_previousAppliedImageIndex) { setImageToChild(index); } } // OSG_NOTICE<<"time = "<<time<<std::endl; if (!irh) return; if (useDirectTimeRequest) { int i = int(time/_timePerImage); if ((i>=int(_imageDataList.size()) || !_imageDataList[i]._image)) { i = osg::clampTo<int>(i, 0, _imageDataList.size()-1); OSG_INFO<<"Requesting file, entry="<<i<<" : _fileNames[i]="<<_imageDataList[i]._filename<<std::endl; irh->requestImageFile(_imageDataList[i]._filename, this, i, time, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } } else { double preLoadTime = time + osg::minimum(irh->getPreLoadTime()*_timeMultiplier, _length); int startLoadIndex = int(time/_timePerImage); if (startLoadIndex>=int(_imageDataList.size())) startLoadIndex = int(_imageDataList.size())-1; if (startLoadIndex<0) startLoadIndex = 0; int endLoadIndex = int(preLoadTime/_timePerImage); if (endLoadIndex>=int(_imageDataList.size())) { if (looping) { endLoadIndex -= int(_imageDataList.size()); } else { endLoadIndex = int(_imageDataList.size())-1; } } if (endLoadIndex<0) endLoadIndex = 0; double requestTime = time; if (endLoadIndex<startLoadIndex) { for(int i=startLoadIndex; i<int(_imageDataList.size()); ++i) { if (!_imageDataList[i]._image) { irh->requestImageFile(_imageDataList[i]._filename, this, i, requestTime, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } requestTime += _timePerImage; } for(int i=0; i<=endLoadIndex; ++i) { if (!_imageDataList[i]._image) { irh->requestImageFile(_imageDataList[i]._filename, this, i, requestTime, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } requestTime += _timePerImage; } } else { for(int i=startLoadIndex; i<=endLoadIndex; ++i) { if (!_imageDataList[i]._image) { irh->requestImageFile(_imageDataList[i]._filename, this, i, requestTime, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } requestTime += _timePerImage; } } } } <commit_msg>Added check to avoid doing update when the imagesequence is empty.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <OpenThreads/ScopedLock> #include <osg/ImageSequence> #include <osg/Notify> #include <osg/Camera> #include <osg/NodeVisitor> #include <osg/Texture2D> #include <math.h> using namespace osg; ImageSequence::ImageData::ImageData() { } ImageSequence::ImageData::ImageData(const ImageData& id): _filename(id._filename), _image(id._image), _imageRequest(id._imageRequest) { } ImageSequence::ImageData& ImageSequence::ImageData::operator = (const ImageSequence::ImageData& rhs) { if (&rhs!=this) { _filename = rhs._filename; _image = rhs._image; _imageRequest = rhs._imageRequest; } return *this; } ImageSequence::ImageSequence() { _referenceTime = DBL_MAX; _timeMultiplier = 1.0; _mode = PRE_LOAD_ALL_IMAGES; _length = 1.0; _timePerImage = 1.0; _seekTime = 0.0; _seekTimeSet = false; _previousAppliedImageIndex = -1; } ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop): osg::ImageStream(is,copyop), _referenceTime(is._referenceTime), _timeMultiplier(is._timeMultiplier), _mode(is._mode), _length(is._length), _timePerImage(is._timePerImage) { _seekTime = is._seekTime; _seekTimeSet = is._seekTimeSet; _previousAppliedImageIndex = -1; } int ImageSequence::compare(const Image& rhs) const { return ImageStream::compare(rhs); } void ImageSequence::seek(double time) { _seekTime = time; _seekTimeSet = true; } void ImageSequence::play() { _status=PLAYING; } void ImageSequence::pause() { _status=PAUSED; } void ImageSequence::rewind() { seek(0.0f); } void ImageSequence::setMode(Mode mode) { _mode = mode; } void ImageSequence::setLength(double length) { if (length<=0.0) { OSG_NOTICE<<"ImageSequence::setLength("<<length<<") invalid length value, must be greater than 0."<<std::endl; return; } _length = length; computeTimePerImage(); } void ImageSequence::computeTimePerImage() { if (!_imageDataList.empty()) _timePerImage = _length / double(_imageDataList.size()); else _timePerImage = _length; } void ImageSequence::setImageFile(unsigned int pos, const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (pos>=_imageDataList.size()) _imageDataList.resize(pos); _imageDataList[pos]._filename = fileName; } std::string ImageSequence::getImageFile(unsigned int pos) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); return pos<_imageDataList.size() ? _imageDataList[pos]._filename : std::string(); } void ImageSequence::addImageFile(const std::string& fileName) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); _imageDataList.push_back(ImageData()); _imageDataList.back()._filename = fileName; computeTimePerImage(); } void ImageSequence::setImage(unsigned int pos, osg::Image* image) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); if (pos>=_imageDataList.size()) _imageDataList.resize(pos+1); _imageDataList[pos]._image = image; _imageDataList[pos]._filename = image->getFileName(); } Image* ImageSequence::getImage(unsigned int pos) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); return pos<_imageDataList.size() ? _imageDataList[pos]._image.get() : 0; } const Image* ImageSequence::getImage(unsigned int pos) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); return pos<_imageDataList.size() ? _imageDataList[pos]._image.get() : 0; } void ImageSequence::addImage(osg::Image* image) { if (image==0) return; OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); // OSG_NOTICE<<"merging image in order expected : "<<image->getFileName()<<std::endl; _imageDataList.push_back(ImageData()); _imageDataList.back()._image = image; computeTimePerImage(); if (data()==0) { setImageToChild(_imageDataList.size()-1); } } void ImageSequence::setImageToChild(int pos) { const osg::Image* image = (pos>=0 && pos<static_cast<int>(_imageDataList.size())) ? _imageDataList[pos]._image.get() : 0; if (image==0) return; // check to see if data is changing, if not don't apply if (image->data() == data()) { return; } if (_mode==PAGE_AND_DISCARD_USED_IMAGES && _previousAppliedImageIndex>=0) { if (_previousAppliedImageIndex<pos) { OSG_INFO<<"Moving forward from "<<_previousAppliedImageIndex<<" to "<<pos<<std::endl; while(_previousAppliedImageIndex<pos) { _imageDataList[_previousAppliedImageIndex]._image = 0; OSG_INFO<<" deleting "<<_previousAppliedImageIndex<<std::endl; ++_previousAppliedImageIndex; } } else if (_previousAppliedImageIndex>pos) { OSG_INFO<<"Moving back from "<<_previousAppliedImageIndex<<" to "<<pos<<std::endl; while(_previousAppliedImageIndex>pos) { _imageDataList[_previousAppliedImageIndex]._image = 0; OSG_INFO<<" deleting "<<_previousAppliedImageIndex<<std::endl; --_previousAppliedImageIndex; } } } _previousAppliedImageIndex = pos; setImage(image->s(),image->t(),image->r(), image->getInternalTextureFormat(), image->getPixelFormat(),image->getDataType(), const_cast<unsigned char*>(image->data()), osg::Image::NO_DELETE, image->getPacking()); } void ImageSequence::applyLoopingMode() { } int ImageSequence::imageIndex(double time) { if (getLoopingMode()==LOOPING) { double positionRatio = time/_length; time = (positionRatio - floor(positionRatio))*_length; } if (time<0.0) return 0; int index = int(time/_timePerImage); if (index>=int(_imageDataList.size())) return int(_imageDataList.size())-1; return index; } void ImageSequence::update(osg::NodeVisitor* nv) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); // if imageDataList is empty then there is nothing update can do. if (_imageDataList.empty()) return; osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler(); const osg::FrameStamp* fs = nv->getFrameStamp(); // OSG_NOTICE<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl; if (_referenceTime == DBL_MAX) { _referenceTime = fs->getSimulationTime(); } bool looping = getLoopingMode()==LOOPING; double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier; bool useDirectTimeRequest = _seekTimeSet; if (_seekTimeSet || _status==PAUSED || _status==INVALID) { time = _seekTime; useDirectTimeRequest = true; _referenceTime = fs->getSimulationTime() - time/_timeMultiplier; } else { if (looping) { while (time>_length) { _referenceTime += _length/_timeMultiplier; time -= _length; } } else { if (time>_length) { _referenceTime = fs->getSimulationTime() - _length/_timeMultiplier; time = _length; } } } _seekTime = time; _seekTimeSet = false; if (irh && _mode==PRE_LOAD_ALL_IMAGES) { for(ImageDataList::iterator itr = _imageDataList.begin(); itr != _imageDataList.end(); ++itr) { if (!(itr->_image) && !(itr->_filename.empty())) { itr->_image = irh->readImageFile(itr->_filename); } } } int index = int(time/_timePerImage); // OSG_NOTICE<<"time= "<<time<<" _timePerImage="<<_timePerImage<<" index="<<index<<" _length="<<_length<<std::endl; if (index>=int(_imageDataList.size())) index = int(_imageDataList.size())-1; if (index>=0 && index<int(_imageDataList.size())) { // need to find the nearest relevant change. if (!_imageDataList[index]._image) { if (_previousAppliedImageIndex<index) { OSG_DEBUG<<"ImageSequence::update(..) Moving forward by "<<index-_previousAppliedImageIndex<<std::endl; while (index>=0 && !_imageDataList[index]._image.valid()) { --index; } } else if (_previousAppliedImageIndex>index) { OSG_DEBUG<<"ImageSequence::update(..) Moving back by "<<_previousAppliedImageIndex-index<<std::endl; while (index<static_cast<int>(_imageDataList.size()) && !_imageDataList[index]._image.valid()) { ++index; } } } if (index>=0 && index!=_previousAppliedImageIndex) { setImageToChild(index); } } // OSG_NOTICE<<"time = "<<time<<std::endl; if (!irh) return; if (useDirectTimeRequest) { int i = int(time/_timePerImage); if ((i>=int(_imageDataList.size()) || !_imageDataList[i]._image)) { i = osg::clampTo<int>(i, 0, _imageDataList.size()-1); OSG_INFO<<"Requesting file, entry="<<i<<" : _fileNames[i]="<<_imageDataList[i]._filename<<std::endl; irh->requestImageFile(_imageDataList[i]._filename, this, i, time, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } } else { double preLoadTime = time + osg::minimum(irh->getPreLoadTime()*_timeMultiplier, _length); int startLoadIndex = int(time/_timePerImage); if (startLoadIndex>=int(_imageDataList.size())) startLoadIndex = int(_imageDataList.size())-1; if (startLoadIndex<0) startLoadIndex = 0; int endLoadIndex = int(preLoadTime/_timePerImage); if (endLoadIndex>=int(_imageDataList.size())) { if (looping) { endLoadIndex -= int(_imageDataList.size()); } else { endLoadIndex = int(_imageDataList.size())-1; } } if (endLoadIndex<0) endLoadIndex = 0; double requestTime = time; if (endLoadIndex<startLoadIndex) { for(int i=startLoadIndex; i<int(_imageDataList.size()); ++i) { if (!_imageDataList[i]._image) { irh->requestImageFile(_imageDataList[i]._filename, this, i, requestTime, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } requestTime += _timePerImage; } for(int i=0; i<=endLoadIndex; ++i) { if (!_imageDataList[i]._image) { irh->requestImageFile(_imageDataList[i]._filename, this, i, requestTime, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } requestTime += _timePerImage; } } else { for(int i=startLoadIndex; i<=endLoadIndex; ++i) { if (!_imageDataList[i]._image) { irh->requestImageFile(_imageDataList[i]._filename, this, i, requestTime, fs, _imageDataList[i]._imageRequest, _readOptions.get()); } requestTime += _timePerImage; } } } } <|endoftext|>
<commit_before>// Author: Jingyue // // Checks whether a specified call graph is sound by comparing it with another // call graph generated on DynamicAliasAnalysis #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/CommandLine.h" #include "common/typedefs.h" #include "dyn-aa/DynamicAliasAnalysis.h" using namespace llvm; using namespace rcs; using namespace dyn_aa; namespace dyn_aa { struct AliasAnalysisChecker: public ModulePass { static char ID; AliasAnalysisChecker(): ModulePass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool runOnModule(Module &M); private: static void PrintValue(raw_ostream &O, const Value *V); }; } static RegisterPass<AliasAnalysisChecker> X( "check-aa", "Check whether the alias analysis is sound", false, // Is CFG Only? true); // Is Analysis? char AliasAnalysisChecker::ID = 0; void AliasAnalysisChecker::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); // Note that DynamicAliasAnalysis is not registered to the // AliasAnalysis group. AU.addRequired<DynamicAliasAnalysis>(); AU.addRequired<AliasAnalysis>(); } bool AliasAnalysisChecker::runOnModule(Module &M) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); AliasAnalysis &DAA = getAnalysis<DynamicAliasAnalysis>(); // We don't want to include all pointers yet. // For now, we include all pointers used as a pointer operand of // a Load/Store instruction. ValueSet PointerOperands; for (Module::iterator F = M.begin(); F != M.end(); ++F) { for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) { for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ++Ins) { if (StoreInst *SI = dyn_cast<StoreInst>(Ins)) PointerOperands.insert(SI->getPointerOperand()); if (LoadInst *LI = dyn_cast<LoadInst>(Ins)) PointerOperands.insert(LI->getPointerOperand()); } } } errs() << "# of pointer operands to process = " << PointerOperands.size() << "\n"; unsigned NumMissingAliases = 0; for (ValueSet::iterator I = PointerOperands.begin(); I != PointerOperands.end(); ++I) { Value *V1 = *I; ValueSet::iterator J = I; for (++J; J != PointerOperands.end(); ++J) { Value *V2 = *J; if (AA.alias(V1, V2) == AliasAnalysis::NoAlias && DAA.alias(V1, V2) != AliasAnalysis::NoAlias) { ++NumMissingAliases; errs().changeColor(raw_ostream::RED); errs() << "Missing alias:\n"; errs().resetColor(); PrintValue(errs(), V1); errs() << "\n"; PrintValue(errs(), V2); errs() << "\n"; } } } if (NumMissingAliases == 0) { errs().changeColor(raw_ostream::GREEN, true); errs() << "Congrats! You passed all the tests.\n"; errs().resetColor(); } else { errs().changeColor(raw_ostream::RED, true); errs() << "Detected " << NumMissingAliases << " missing aliases.\n"; errs().resetColor(); } return false; } void AliasAnalysisChecker::PrintValue(raw_ostream &O, const Value *V) { if (isa<Function>(V)) { O << V->getName(); } else if (const Argument *Arg = dyn_cast<Argument>(V)) { O << Arg->getParent()->getName() << ": " << *Arg; } else if (const Instruction *Ins = dyn_cast<Instruction>(V)) { O << Ins->getParent()->getParent()->getName(); O << "." << Ins->getParent()->getName() << ":"; O << *Ins; } else { O << *V; } } <commit_msg>New features:<commit_after>// Author: Jingyue // // Checks whether a specified call graph is sound by comparing it with another // call graph generated on DynamicAliasAnalysis #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/CommandLine.h" #include "common/typedefs.h" #include "dyn-aa/DynamicAliasAnalysis.h" using namespace llvm; using namespace rcs; using namespace dyn_aa; namespace dyn_aa { struct AliasAnalysisChecker: public ModulePass { static char ID; AliasAnalysisChecker(): ModulePass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool runOnModule(Module &M); private: static void PrintValue(raw_ostream &O, const Value *V); static bool isIntraProcQuery(const Value *V1, const Value *V2); static const Function *getContainingFunction(const Value *V); }; } static cl::opt<bool> IntraProc( "intra", cl::desc("Whether the checked AA supports intra-procedural queries only")); static RegisterPass<AliasAnalysisChecker> X( "check-aa", "Check whether the alias analysis is sound", false, // Is CFG Only? true); // Is Analysis? char AliasAnalysisChecker::ID = 0; void AliasAnalysisChecker::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); // Note that DynamicAliasAnalysis is not registered to the // AliasAnalysis group. AU.addRequired<DynamicAliasAnalysis>(); AU.addRequired<AliasAnalysis>(); } bool AliasAnalysisChecker::runOnModule(Module &M) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); AliasAnalysis &DAA = getAnalysis<DynamicAliasAnalysis>(); // We don't want to include all pointers yet. // For now, we include all pointers used as a pointer operand of // a Load/Store instruction. ValueSet PointerOperands; for (Module::iterator F = M.begin(); F != M.end(); ++F) { for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) { for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ++Ins) { if (StoreInst *SI = dyn_cast<StoreInst>(Ins)) PointerOperands.insert(SI->getPointerOperand()); if (LoadInst *LI = dyn_cast<LoadInst>(Ins)) PointerOperands.insert(LI->getPointerOperand()); } } } errs() << "# of pointer operands to process = " << PointerOperands.size() << "\n"; unsigned NumMissingAliases = 0; for (ValueSet::iterator I = PointerOperands.begin(); I != PointerOperands.end(); ++I) { Value *V1 = *I; ValueSet::iterator J = I; for (++J; J != PointerOperands.end(); ++J) { Value *V2 = *J; // If the checked AA supports only intra-procedural queries, // and V1 and V2 belong to different functions, skip this query. if (IntraProc && !isIntraProcQuery(V1, V2)) continue; if (AA.alias(V1, V2) == AliasAnalysis::NoAlias && DAA.alias(V1, V2) != AliasAnalysis::NoAlias) { ++NumMissingAliases; errs().changeColor(raw_ostream::RED); errs() << "Missing alias:\n"; errs().resetColor(); PrintValue(errs(), V1); errs() << "\n"; PrintValue(errs(), V2); errs() << "\n"; } } } if (NumMissingAliases == 0) { errs().changeColor(raw_ostream::GREEN, true); errs() << "Congrats! You passed all the tests.\n"; errs().resetColor(); } else { errs().changeColor(raw_ostream::RED, true); errs() << "Detected " << NumMissingAliases << " missing aliases.\n"; errs().resetColor(); } return false; } void AliasAnalysisChecker::PrintValue(raw_ostream &O, const Value *V) { if (isa<Function>(V)) { O << V->getName(); } else if (const Argument *Arg = dyn_cast<Argument>(V)) { O << Arg->getParent()->getName() << ": " << *Arg; } else if (const Instruction *Ins = dyn_cast<Instruction>(V)) { O << Ins->getParent()->getParent()->getName(); O << "." << Ins->getParent()->getName() << ":"; O << *Ins; } else { O << *V; } } bool AliasAnalysisChecker::isIntraProcQuery(const Value *V1, const Value *V2) { assert(V1->getType()->isPointerTy() && V2->getType()->isPointerTy()); const Function *F1 = getContainingFunction(V1); const Function *F2 = getContainingFunction(V2); return F1 == NULL || F2 == NULL || F1 == F2; } const Function *AliasAnalysisChecker::getContainingFunction(const Value *V) { if (const Instruction *Ins = dyn_cast<Instruction>(V)) return Ins->getParent()->getParent(); if (const Argument *Arg = dyn_cast<Argument>(V)) return Arg->getParent(); return NULL; } <|endoftext|>
<commit_before>80669d9c-4b02-11e5-97d0-28cfe9171a43<commit_msg>Did a thing<commit_after>8072c8ba-4b02-11e5-8b0f-28cfe9171a43<|endoftext|>
<commit_before>9c0e4c14-4b02-11e5-be6c-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>9c19bc35-4b02-11e5-b8e2-28cfe9171a43<|endoftext|>
<commit_before>c119844c-327f-11e5-8ed6-9cf387a8033e<commit_msg>c11f6c54-327f-11e5-a2f0-9cf387a8033e<commit_after>c11f6c54-327f-11e5-a2f0-9cf387a8033e<|endoftext|>
<commit_before>#include "../include/string.h" #include <algorithm> using std::string; string myto_string(long long a) { string w; bool minus = false; if (a < 0) { minus = true; a = -a; } while (a > 0) { w += static_cast<char>(a % 10 + '0'); a /= 10; } if (minus) w += "-"; if (w.empty()) w = "0"; else std::reverse(w.begin(), w.end()); return w; } string myto_string(size_t a) { string w; while (a > 0) { w += static_cast<char>(a % 10 + '0'); a /= 10; } if (w.empty()) w = "0"; else std::reverse(w.begin(), w.end()); return w; } size_t strtosize_t(const string& s) { size_t res = 0; for (size_t i = 0; i < s.size(); ++i) res = res * 10 + s[i] - '0'; return res; } int strtosize_t(size_t& x, const string& s, size_t beg, size_t end) { if (end > s.size()) end = s.size(); if (beg > end) beg = end; x = 0; for (size_t i = beg; i < end; ++i) { if (isdigit(s[i])) x = x * 10 + s[i] - '0'; else return -1; } return end - beg; } int strtonum(string& x, const string& s, size_t beg, size_t end) { if (end > s.size()) end = s.size(); if (beg > end) beg = end; for (size_t i = beg; i < end; ++i) if (!isdigit(s[i])) return -1; s.substr(beg, end - beg).swap(x); return end - beg; } size_t find(const string& str, char c, size_t beg, size_t end) { if (end > str.size()) end = str.size(); for (; beg < end; ++beg) if (str[beg] == c) return beg; return string::npos; } string encodeURI(const string& str, size_t beg, size_t end) { // a-z A-Z 0-9 - _ . ~ static bool is_safe[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1}; if (end > str.size()) end = str.size(); string ret; for (; beg < end; ++beg) { unsigned char c = str[beg]; if (is_safe[c]) ret += c; else { ret += '%'; ret += dectohex(c >> 4); ret += dectohex(c & 15); } } return ret; } string decodeURI(const string& str, size_t beg, size_t end) { if (end > str.size()) end = str.size(); string ret; for (; beg < end; ++beg) { if (str[beg] == '%' && beg + 2 < end) { ret += static_cast<char>((hextodec(str[beg+1]) << 4) + hextodec(str[beg+2])); beg += 2; } else if (str[beg] == '+') ret += ' '; else ret += str[beg]; } return ret; } string tolower(string str) { for (size_t i = 0, s = str.size(); i < s; ++i) str[i] = tolower(str[i]); return str; } string abspath(const string& path, size_t beg, size_t end, string root) { if (end > path.size()) end = path.size(); while (beg < end) { while (beg < end && path[beg] == '/') ++beg; size_t next_slash = std::min(end, find(path, '/', beg, end)); // If [beg, next_slash) == ("." or "..") if ((next_slash - beg == 1 && path[beg] == '.') || (next_slash - beg == 2 && path[beg] == '.' && path[beg + 1] == '.')) { beg = next_slash; continue; } if (*--root.end() != '/') root += '/'; root.append(path, beg, next_slash - beg); beg = next_slash; } return root; } string htmlSpecialChars(const string& s) { string res; for (size_t i = 0; i < s.size(); ++i) switch (s[i]) { case '&': res += "&amp;"; case '"': res += "&quot;"; case '\'': res += "&apos;"; case '<': res += "&lt;"; case '>': res += "&gt;"; default: res += s[i]; } return res; } <commit_msg>Fix bug in htmlSpecialChars, improve forms (CSS, add FormValidator)<commit_after>#include "../include/string.h" #include "../include/debug.h" #include <algorithm> using std::string; string myto_string(long long a) { string w; bool minus = false; if (a < 0) { minus = true; a = -a; } while (a > 0) { w += static_cast<char>(a % 10 + '0'); a /= 10; } if (minus) w += "-"; if (w.empty()) w = "0"; else std::reverse(w.begin(), w.end()); return w; } string myto_string(size_t a) { string w; while (a > 0) { w += static_cast<char>(a % 10 + '0'); a /= 10; } if (w.empty()) w = "0"; else std::reverse(w.begin(), w.end()); return w; } size_t strtosize_t(const string& s) { size_t res = 0; for (size_t i = 0; i < s.size(); ++i) res = res * 10 + s[i] - '0'; return res; } int strtosize_t(size_t& x, const string& s, size_t beg, size_t end) { if (end > s.size()) end = s.size(); if (beg > end) beg = end; x = 0; for (size_t i = beg; i < end; ++i) { if (isdigit(s[i])) x = x * 10 + s[i] - '0'; else return -1; } return end - beg; } int strtonum(string& x, const string& s, size_t beg, size_t end) { if (end > s.size()) end = s.size(); if (beg > end) beg = end; for (size_t i = beg; i < end; ++i) if (!isdigit(s[i])) return -1; s.substr(beg, end - beg).swap(x); return end - beg; } size_t find(const string& str, char c, size_t beg, size_t end) { if (end > str.size()) end = str.size(); for (; beg < end; ++beg) if (str[beg] == c) return beg; return string::npos; } string encodeURI(const string& str, size_t beg, size_t end) { // a-z A-Z 0-9 - _ . ~ static bool is_safe[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1}; if (end > str.size()) end = str.size(); string ret; for (; beg < end; ++beg) { unsigned char c = str[beg]; if (is_safe[c]) ret += c; else { ret += '%'; ret += dectohex(c >> 4); ret += dectohex(c & 15); } } return ret; } string decodeURI(const string& str, size_t beg, size_t end) { if (end > str.size()) end = str.size(); string ret; for (; beg < end; ++beg) { if (str[beg] == '%' && beg + 2 < end) { ret += static_cast<char>((hextodec(str[beg+1]) << 4) + hextodec(str[beg+2])); beg += 2; } else if (str[beg] == '+') ret += ' '; else ret += str[beg]; } return ret; } string tolower(string str) { for (size_t i = 0, s = str.size(); i < s; ++i) str[i] = tolower(str[i]); return str; } string abspath(const string& path, size_t beg, size_t end, string root) { if (end > path.size()) end = path.size(); while (beg < end) { while (beg < end && path[beg] == '/') ++beg; size_t next_slash = std::min(end, find(path, '/', beg, end)); // If [beg, next_slash) == ("." or "..") if ((next_slash - beg == 1 && path[beg] == '.') || (next_slash - beg == 2 && path[beg] == '.' && path[beg + 1] == '.')) { beg = next_slash; continue; } if (*--root.end() != '/') root += '/'; root.append(path, beg, next_slash - beg); beg = next_slash; } return root; } string htmlSpecialChars(const string& s) { string res; for (size_t i = 0; i < s.size(); ++i) switch (s[i]) { case '&': res += "&amp;"; break; case '"': res += "&quot;"; break; case '\'': res += "&apos;"; break; case '<': res += "&lt;"; break; case '>': res += "&gt;"; break; default: res += s[i]; } return res; } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <vector> #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/lite/testing/kernel_test/diff_analyzer.h" int main(int argc, char** argv) { std::string base, test, output; std::vector<tensorflow::Flag> flag_list = { tensorflow::Flag("base", &base, "Path to the base serialized tensor."), tensorflow::Flag("test", &test, "Path to the test serialized tensor."), tensorflow::Flag("output", &output, "Path to the output file."), }; tensorflow::Flags::Parse(&argc, argv, flag_list); tflite::testing::DiffAnalyzer diff_analyzer; diff_analyzer.ReadFiles(base, test); diff_analyzer.WriteReport(output); return 0; } <commit_msg>Update generate_diff_report.cc<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <string> #include <vector> #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/lite/testing/kernel_test/diff_analyzer.h" int main(int argc, char** argv) { std::string base, test, output; std::vector<tensorflow::Flag> flag_list = { tensorflow::Flag("base", &base, "Path to the base serialized tensor."), tensorflow::Flag("test", &test, "Path to the test serialized tensor."), tensorflow::Flag("output", &output, "Path to the output file."), }; tensorflow::Flags::Parse(&argc, argv, flag_list); tflite::testing::DiffAnalyzer diff_analyzer; diff_analyzer.ReadFiles(base, test); diff_analyzer.WriteReport(output); return 0; } <|endoftext|>
<commit_before>8d6dfd7d-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd7e-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd7e-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5e589449-2d16-11e5-af21-0401358ea401<commit_msg>5e58944a-2d16-11e5-af21-0401358ea401<commit_after>5e58944a-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>b7efb475-2e4f-11e5-97b0-28cfe91dbc4b<commit_msg>b7f63863-2e4f-11e5-abe3-28cfe91dbc4b<commit_after>b7f63863-2e4f-11e5-abe3-28cfe91dbc4b<|endoftext|>
<commit_before>33e78e40-2f67-11e5-a2b1-6c40088e03e4<commit_msg>33eefe5c-2f67-11e5-9f58-6c40088e03e4<commit_after>33eefe5c-2f67-11e5-9f58-6c40088e03e4<|endoftext|>
<commit_before>a47e3ad4-35ca-11e5-b03e-6c40088e03e4<commit_msg>a4863c82-35ca-11e5-b9e8-6c40088e03e4<commit_after>a4863c82-35ca-11e5-b9e8-6c40088e03e4<|endoftext|>
<commit_before>b3056833-ad5a-11e7-94b1-ac87a332f658<commit_msg>That didn't fix it<commit_after>b385f11e-ad5a-11e7-883d-ac87a332f658<|endoftext|>
<commit_before>53b81700-2e4f-11e5-b6f2-28cfe91dbc4b<commit_msg>53bea7e6-2e4f-11e5-b36d-28cfe91dbc4b<commit_after>53bea7e6-2e4f-11e5-b36d-28cfe91dbc4b<|endoftext|>
<commit_before>bcdffb07-4b02-11e5-a7b5-28cfe9171a43<commit_msg>My Life for Auir<commit_after>bcec00b8-4b02-11e5-9b61-28cfe9171a43<|endoftext|>
<commit_before>//===-- WebAssemblyRegColoring.cpp - Register coloring --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements a virtual register coloring pass. /// /// WebAssembly doesn't have a fixed number of registers, but it is still /// desirable to minimize the total number of registers used in each function. /// /// This code is modeled after lib/CodeGen/StackSlotColoring.cpp. /// //===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "WebAssemblyMachineFunctionInfo.h" #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_* #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "wasm-reg-coloring" namespace { class WebAssemblyRegColoring final : public MachineFunctionPass { public: static char ID; // Pass identification, replacement for typeid WebAssemblyRegColoring() : MachineFunctionPass(ID) {} const char *getPassName() const override { return "WebAssembly Register Coloring"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addRequired<LiveIntervals>(); AU.addRequired<MachineBlockFrequencyInfo>(); AU.addPreserved<MachineBlockFrequencyInfo>(); AU.addPreservedID(MachineDominatorsID); AU.addRequired<SlotIndexes>(); // for ARGUMENT fixups MachineFunctionPass::getAnalysisUsage(AU); } bool runOnMachineFunction(MachineFunction &MF) override; private: }; } // end anonymous namespace char WebAssemblyRegColoring::ID = 0; FunctionPass *llvm::createWebAssemblyRegColoring() { return new WebAssemblyRegColoring(); } // Compute the total spill weight for VReg. static float computeWeight(const MachineRegisterInfo *MRI, const MachineBlockFrequencyInfo *MBFI, unsigned VReg) { float weight = 0.0f; for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg)) weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI, MO.getParent()); return weight; } bool WebAssemblyRegColoring::runOnMachineFunction(MachineFunction &MF) { DEBUG({ dbgs() << "********** Register Coloring **********\n" << "********** Function: " << MF.getName() << '\n'; }); // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual // registers could be modified before the longjmp is executed, resulting in // the wrong value being used afterwards. (See <rdar://problem/8007500>.) // TODO: Does WebAssembly need to care about setjmp for register coloring? if (MF.exposesReturnsTwice()) return false; MachineRegisterInfo *MRI = &MF.getRegInfo(); LiveIntervals *Liveness = &getAnalysis<LiveIntervals>(); const MachineBlockFrequencyInfo *MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); // Gather all register intervals into a list and sort them. unsigned NumVRegs = MRI->getNumVirtRegs(); SmallVector<LiveInterval *, 0> SortedIntervals; SortedIntervals.reserve(NumVRegs); // FIXME: If scheduling has moved an ARGUMENT virtual register, move it back, // and recompute liveness. This is a temporary hack. bool SawNonArg = false; bool MovedArg = false; MachineBasicBlock &EntryMBB = MF.front(); for (auto MII = EntryMBB.begin(); MII != EntryMBB.end(); ) { MachineInstr *MI = &*MII++; if (MI->getOpcode() == WebAssembly::ARGUMENT_I32 || MI->getOpcode() == WebAssembly::ARGUMENT_I64 || MI->getOpcode() == WebAssembly::ARGUMENT_F32 || MI->getOpcode() == WebAssembly::ARGUMENT_F64) { EntryMBB.insert(EntryMBB.begin(), MI->removeFromParent()); if (SawNonArg) MovedArg = true; } else { SawNonArg = true; } } if (MovedArg) { SlotIndexes &Slots = getAnalysis<SlotIndexes>(); Liveness->releaseMemory(); Slots.releaseMemory(); Slots.runOnMachineFunction(MF); Liveness->runOnMachineFunction(MF); } DEBUG(dbgs() << "Interesting register intervals:\n"); for (unsigned i = 0; i < NumVRegs; ++i) { unsigned VReg = TargetRegisterInfo::index2VirtReg(i); if (MFI.isVRegStackified(VReg)) continue; LiveInterval *LI = &Liveness->getInterval(VReg); assert(LI->weight == 0.0f); LI->weight = computeWeight(MRI, MBFI, VReg); DEBUG(LI->dump()); SortedIntervals.push_back(LI); } DEBUG(dbgs() << '\n'); // Sort them to put arguments first (since we don't want to rename live-in // registers), by weight next, and then by position. // TODO: Investigate more intelligent sorting heuristics. For starters, we // should try to coalesce adjacent live intervals before non-adjacent ones. std::sort(SortedIntervals.begin(), SortedIntervals.end(), [MRI](LiveInterval *LHS, LiveInterval *RHS) { if (MRI->isLiveIn(LHS->reg) != MRI->isLiveIn(RHS->reg)) return MRI->isLiveIn(LHS->reg); if (LHS->weight != RHS->weight) return LHS->weight > RHS->weight; if (LHS->empty() || RHS->empty()) return !LHS->empty() && RHS->empty(); return *LHS < *RHS; }); DEBUG(dbgs() << "Coloring register intervals:\n"); SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u); SmallVector<SmallVector<LiveInterval *, 4>, 16> Assignments( SortedIntervals.size()); BitVector UsedColors(SortedIntervals.size()); bool Changed = false; for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) { LiveInterval *LI = SortedIntervals[i]; unsigned Old = LI->reg; size_t Color = i; const TargetRegisterClass *RC = MRI->getRegClass(Old); // Check if it's possible to reuse any of the used colors. if (!MRI->isLiveIn(Old)) for (int C(UsedColors.find_first()); C != -1; C = UsedColors.find_next(C)) { if (MRI->getRegClass(SortedIntervals[C]->reg) != RC) continue; for (LiveInterval *OtherLI : Assignments[C]) if (!OtherLI->empty() && OtherLI->overlaps(*LI)) goto continue_outer; Color = C; break; continue_outer:; } unsigned New = SortedIntervals[Color]->reg; SlotMapping[i] = New; Changed |= Old != New; UsedColors.set(Color); Assignments[Color].push_back(LI); DEBUG(dbgs() << "Assigning vreg" << TargetRegisterInfo::virtReg2Index(LI->reg) << " to vreg" << TargetRegisterInfo::virtReg2Index(New) << "\n"); } if (!Changed) return false; // Rewrite register operands. for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) { unsigned Old = SortedIntervals[i]->reg; unsigned New = SlotMapping[i]; if (Old != New) MRI->replaceRegWith(Old, New); } return true; } <commit_msg>Split the argument unscheduling loop in the WebAssembly register coloring pass. Turn the logic into "look for an insert point and then move things past the insert point".<commit_after>//===-- WebAssemblyRegColoring.cpp - Register coloring --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements a virtual register coloring pass. /// /// WebAssembly doesn't have a fixed number of registers, but it is still /// desirable to minimize the total number of registers used in each function. /// /// This code is modeled after lib/CodeGen/StackSlotColoring.cpp. /// //===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "WebAssemblyMachineFunctionInfo.h" #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_* #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "wasm-reg-coloring" namespace { class WebAssemblyRegColoring final : public MachineFunctionPass { public: static char ID; // Pass identification, replacement for typeid WebAssemblyRegColoring() : MachineFunctionPass(ID) {} const char *getPassName() const override { return "WebAssembly Register Coloring"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addRequired<LiveIntervals>(); AU.addRequired<MachineBlockFrequencyInfo>(); AU.addPreserved<MachineBlockFrequencyInfo>(); AU.addPreservedID(MachineDominatorsID); AU.addRequired<SlotIndexes>(); // for ARGUMENT fixups MachineFunctionPass::getAnalysisUsage(AU); } bool runOnMachineFunction(MachineFunction &MF) override; private: }; } // end anonymous namespace char WebAssemblyRegColoring::ID = 0; FunctionPass *llvm::createWebAssemblyRegColoring() { return new WebAssemblyRegColoring(); } // Compute the total spill weight for VReg. static float computeWeight(const MachineRegisterInfo *MRI, const MachineBlockFrequencyInfo *MBFI, unsigned VReg) { float weight = 0.0f; for (MachineOperand &MO : MRI->reg_nodbg_operands(VReg)) weight += LiveIntervals::getSpillWeight(MO.isDef(), MO.isUse(), MBFI, MO.getParent()); return weight; } bool WebAssemblyRegColoring::runOnMachineFunction(MachineFunction &MF) { DEBUG({ dbgs() << "********** Register Coloring **********\n" << "********** Function: " << MF.getName() << '\n'; }); // If there are calls to setjmp or sigsetjmp, don't perform coloring. Virtual // registers could be modified before the longjmp is executed, resulting in // the wrong value being used afterwards. (See <rdar://problem/8007500>.) // TODO: Does WebAssembly need to care about setjmp for register coloring? if (MF.exposesReturnsTwice()) return false; MachineRegisterInfo *MRI = &MF.getRegInfo(); LiveIntervals *Liveness = &getAnalysis<LiveIntervals>(); const MachineBlockFrequencyInfo *MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); // Gather all register intervals into a list and sort them. unsigned NumVRegs = MRI->getNumVirtRegs(); SmallVector<LiveInterval *, 0> SortedIntervals; SortedIntervals.reserve(NumVRegs); // FIXME: If scheduling has moved an ARGUMENT virtual register, move it back, // and recompute liveness. This is a temporary hack. bool MovedArg = false; MachineBasicBlock &EntryMBB = MF.front(); MachineBasicBlock::iterator InsertPt = EntryMBB.end(); // Look for the first NonArg instruction. for (auto MII = EntryMBB.begin(), MIE = EntryMBB.end(); MII != MIE; ++MII) { MachineInstr *MI = MII; if (MI->getOpcode() != WebAssembly::ARGUMENT_I32 && MI->getOpcode() != WebAssembly::ARGUMENT_I64 && MI->getOpcode() != WebAssembly::ARGUMENT_F32 && MI->getOpcode() != WebAssembly::ARGUMENT_F64) { InsertPt = MII; break; } } // Now move any argument instructions later in the block // to before our first NonArg instruction. for (auto I = InsertPt, E = EntryMBB.end(); I != E; ++I) { MachineInstr *MI = I; if (MI->getOpcode() == WebAssembly::ARGUMENT_I32 || MI->getOpcode() == WebAssembly::ARGUMENT_I64 || MI->getOpcode() == WebAssembly::ARGUMENT_F32 || MI->getOpcode() == WebAssembly::ARGUMENT_F64) { EntryMBB.insert(InsertPt, MI->removeFromParent()); MovedArg = true; } } if (MovedArg) { SlotIndexes &Slots = getAnalysis<SlotIndexes>(); Liveness->releaseMemory(); Slots.releaseMemory(); Slots.runOnMachineFunction(MF); Liveness->runOnMachineFunction(MF); } DEBUG(dbgs() << "Interesting register intervals:\n"); for (unsigned i = 0; i < NumVRegs; ++i) { unsigned VReg = TargetRegisterInfo::index2VirtReg(i); if (MFI.isVRegStackified(VReg)) continue; LiveInterval *LI = &Liveness->getInterval(VReg); assert(LI->weight == 0.0f); LI->weight = computeWeight(MRI, MBFI, VReg); DEBUG(LI->dump()); SortedIntervals.push_back(LI); } DEBUG(dbgs() << '\n'); // Sort them to put arguments first (since we don't want to rename live-in // registers), by weight next, and then by position. // TODO: Investigate more intelligent sorting heuristics. For starters, we // should try to coalesce adjacent live intervals before non-adjacent ones. std::sort(SortedIntervals.begin(), SortedIntervals.end(), [MRI](LiveInterval *LHS, LiveInterval *RHS) { if (MRI->isLiveIn(LHS->reg) != MRI->isLiveIn(RHS->reg)) return MRI->isLiveIn(LHS->reg); if (LHS->weight != RHS->weight) return LHS->weight > RHS->weight; if (LHS->empty() || RHS->empty()) return !LHS->empty() && RHS->empty(); return *LHS < *RHS; }); DEBUG(dbgs() << "Coloring register intervals:\n"); SmallVector<unsigned, 16> SlotMapping(SortedIntervals.size(), -1u); SmallVector<SmallVector<LiveInterval *, 4>, 16> Assignments( SortedIntervals.size()); BitVector UsedColors(SortedIntervals.size()); bool Changed = false; for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) { LiveInterval *LI = SortedIntervals[i]; unsigned Old = LI->reg; size_t Color = i; const TargetRegisterClass *RC = MRI->getRegClass(Old); // Check if it's possible to reuse any of the used colors. if (!MRI->isLiveIn(Old)) for (int C(UsedColors.find_first()); C != -1; C = UsedColors.find_next(C)) { if (MRI->getRegClass(SortedIntervals[C]->reg) != RC) continue; for (LiveInterval *OtherLI : Assignments[C]) if (!OtherLI->empty() && OtherLI->overlaps(*LI)) goto continue_outer; Color = C; break; continue_outer:; } unsigned New = SortedIntervals[Color]->reg; SlotMapping[i] = New; Changed |= Old != New; UsedColors.set(Color); Assignments[Color].push_back(LI); DEBUG(dbgs() << "Assigning vreg" << TargetRegisterInfo::virtReg2Index(LI->reg) << " to vreg" << TargetRegisterInfo::virtReg2Index(New) << "\n"); } if (!Changed) return false; // Rewrite register operands. for (size_t i = 0, e = SortedIntervals.size(); i < e; ++i) { unsigned Old = SortedIntervals[i]->reg; unsigned New = SlotMapping[i]; if (Old != New) MRI->replaceRegWith(Old, New); } return true; } <|endoftext|>
<commit_before> #include "Globals.h" #include "ItemHandler.h" #include "../Item.h" #include "../World.h" #include "../Player.h" //Handler #include "ItemCloth.h" #include "ItemHoe.h" #include "ItemSlab.h" #include "ItemWood.h" #include "ItemShears.h" #include "ItemLeaves.h" #include "ItemSapling.h" #include "ItemBucket.h" #include "ItemLighter.h" #include "ItemRedstoneDust.h" #include "ItemRedstoneRepeater.h" #include "ItemSeeds.h" #include "ItemDye.h" #include "ItemSugarcane.h" #include "ItemPickaxe.h" #include "ItemShovel.h" #include "ItemSword.h" #include "ItemDoor.h" #include "ItemFood.h" #include "ItemSign.h" #include "ItemBed.h" #include "ItemSpawnEgg.h" #include "../Blocks/BlockHandler.h" bool cItemHandler::m_HandlerInitialized = false; cItemHandler * cItemHandler::m_ItemHandler[2266]; cItemHandler *cItemHandler::GetItemHandler(int a_ItemType) { if(a_ItemType < 0) a_ItemType = 0; if(!m_HandlerInitialized) { //We have to initialize memset(m_ItemHandler, 0, sizeof(m_ItemHandler)); m_HandlerInitialized = true; } if(m_ItemHandler[a_ItemType]) return m_ItemHandler[a_ItemType]; m_ItemHandler[a_ItemType] = CreateItemHandler(a_ItemType); return m_ItemHandler[a_ItemType]; } cItemHandler *cItemHandler::CreateItemHandler(int a_ItemType) { switch(a_ItemType) { default: return new cItemHandler(a_ItemType); // Single item per handler, alphabetically sorted: case E_ITEM_BED: return new cItemBedHandler(a_ItemType); case E_ITEM_DYE: return new cItemDyeHandler(a_ItemType); case E_ITEM_FLINT_AND_STEEL: return new cItemLighterHandler(a_ItemType); case E_ITEM_LEAVES: return new cItemLeavesHandler(a_ItemType); case E_ITEM_REDSTONE_DUST: return new cItemRedstoneDustHandler(a_ItemType); case E_ITEM_REDSTONE_REPEATER: return new cItemRedstoneRepeaterHandler(a_ItemType); case E_ITEM_SAPLING: return new cItemSaplingHandler(a_ItemType); case E_ITEM_SHEARS: return new cItemShearsHandler(a_ItemType); case E_ITEM_SIGN: return new cItemSignHandler(a_ItemType); case E_ITEM_SPAWN_EGG: return new cItemSpawnEggHandler(a_ItemType); case E_ITEM_SUGARCANE: return new cItemSugarcaneHandler(a_ItemType); case E_ITEM_WOOL: return new cItemClothHandler(a_ItemType); case E_ITEM_WOODEN_HOE: case E_ITEM_STONE_HOE: case E_ITEM_IRON_HOE: case E_ITEM_GOLD_HOE: case E_ITEM_DIAMOND_HOE: { return new cItemHoeHandler(a_ItemType); } case E_ITEM_WOODEN_PICKAXE: case E_ITEM_STONE_PICKAXE: case E_ITEM_IRON_PICKAXE: case E_ITEM_GOLD_PICKAXE: case E_ITEM_DIAMOND_PICKAXE: { return new cItemPickaxeHandler(a_ItemType); } case E_ITEM_WOODEN_SHOVEL: case E_ITEM_STONE_SHOVEL: case E_ITEM_IRON_SHOVEL: case E_ITEM_GOLD_SHOVEL: case E_ITEM_DIAMOND_SHOVEL: { return new cItemShovelHandler(a_ItemType); } case E_ITEM_WOODEN_SWORD: case E_ITEM_STONE_SWORD: case E_ITEM_IRON_SWORD: case E_ITEM_GOLD_SWORD: case E_ITEM_DIAMOND_SWORD: { return new cItemSwordHandler(a_ItemType); } case E_ITEM_STONE_SLAB: case E_ITEM_WOODEN_SLAB: { return new cItemSlabHandler(a_ItemType); } case E_ITEM_LOG: case E_ITEM_PLANKS: { return new cItemWoodHandler(a_ItemType); } case E_ITEM_BUCKET: case E_ITEM_WATER_BUCKET: case E_ITEM_LAVA_BUCKET: { return new cItemBucketHandler(a_ItemType); } case E_ITEM_PUMPKIN_SEEDS: case E_ITEM_MELON_SEEDS: case E_ITEM_SEEDS: { return new cItemSeedsHandler(a_ItemType); } case E_ITEM_IRON_DOOR: case E_ITEM_WOODEN_DOOR: { return new cItemDoorHandler(a_ItemType); } // Food: case E_ITEM_BREAD: case E_ITEM_COOKIE: case E_ITEM_MELON_SLICE: case E_ITEM_RAW_CHICKEN: case E_ITEM_COOKED_CHICKEN: case E_ITEM_RAW_BEEF: case E_ITEM_RAW_MEAT: case E_ITEM_STEAK: case E_ITEM_COOKED_MEAT: case E_ITEM_RAW_FISH: case E_ITEM_COOKED_FISH: case E_ITEM_RED_APPLE: case E_ITEM_GOLDEN_APPLE: case E_ITEM_ROTTEN_FLESH: case E_ITEM_SPIDER_EYE: { return new cItemFoodHandler(a_ItemType); } } } void cItemHandler::Deinit() { for(int i = 0; i < 2266; i++) { delete m_ItemHandler[i]; } m_HandlerInitialized = false; } cItemHandler::cItemHandler(int a_ItemType) { m_ItemType = a_ItemType; } bool cItemHandler::OnItemUse(cWorld * a_World, cPlayer * a_Player, cItem * a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Dir) { return false; } bool cItemHandler::OnDiggingBlock(cWorld * a_World, cPlayer * a_Player, cItem * a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Dir) { return false; } void cItemHandler::OnBlockDestroyed(cWorld *a_World, cPlayer *a_Player, cItem *a_Item, int a_X, int a_Y, int a_Z) { char Block = a_World->GetBlock(a_X, a_Y, a_Z); cBlockHandler *Handler = cBlockHandler::GetBlockHandler(Block); if(a_Player->GetGameMode() == eGameMode_Survival) { if(!BlockRequiresSpecialTool(Block) || CanHarvestBlock(Block)) { Handler->DropBlock(a_World, a_X, a_Y, a_Z); } } a_Player->UseEquippedItem(); } void cItemHandler::OnFoodEaten(cWorld *a_World, cPlayer *a_Player, cItem *a_Item) { } char cItemHandler::GetMaxStackSize(void) { if (m_ItemType < 256) { // All blocks can stack up to 64 return 64; } switch (m_ItemType) { case E_ITEM_APPLE: return 64; case E_ITEM_ARROW: return 64; case E_ITEM_BLAZE_POWDER: return 64; case E_ITEM_BLAZE_ROD: return 64; case E_ITEM_BONE: return 64; case E_ITEM_BOOK: return 64; case E_ITEM_BOWL: return 64; case E_ITEM_BREAD: return 64; case E_ITEM_BROWN_MUSHROOM: return 64; case E_ITEM_BUCKET: return 1; // TODO: change this to 16 when turning compatibility to 1.3 case E_ITEM_COAL: return 64; case E_ITEM_COOKED_CHICKEN: return 64; case E_ITEM_COOKED_FISH: return 64; case E_ITEM_COOKED_PORKCHOP: return 64; case E_ITEM_DIAMOND: return 64; case E_ITEM_FEATHER: return 64; case E_ITEM_FLINT: return 64; case E_ITEM_GOLD: return 64; case E_ITEM_GUNPOWDER: return 64; case E_ITEM_IRON: return 64; case E_ITEM_RAW_PORKCHOP: return 64; case E_ITEM_SEEDS: return 64; case E_ITEM_STICK: return 64; case E_ITEM_STRING: return 64; case E_ITEM_WHEAT: return 64; } // By default items don't stack: return 1; } bool cItemHandler::IsTool() { return (m_ItemType >= 256 && m_ItemType <= 259) || (m_ItemType == 261) || (m_ItemType >= 267 && m_ItemType <= 279) || (m_ItemType >= 283 && m_ItemType <= 286) || (m_ItemType >= 290 && m_ItemType <= 294) || (m_ItemType >= 256 && m_ItemType <= 259) || (m_ItemType == 325) || (m_ItemType == 346); } bool cItemHandler::IsFood() { return (m_ItemType == 260) || (m_ItemType == 282) || (m_ItemType == 297) || (m_ItemType >= 319 && m_ItemType <= 320) || (m_ItemType == 335) || (m_ItemType >= 349 && m_ItemType <= 350) || (m_ItemType == 357) || (m_ItemType == 360) || (m_ItemType >= 363 && m_ItemType <= 366); } bool cItemHandler::IsPlaceable() { return m_ItemType >= 1 && m_ItemType <= 136; } bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) { return false; } BLOCKTYPE cItemHandler::GetBlockType() { ASSERT(m_ItemType < 256); // Items with IDs above 255 should all be handled by specific handlers #ifdef _DEBUG if (m_ItemType > 256) { LOGERROR("Item %d has no valid block!", m_ItemType); } #endif // _DEBUG return (BLOCKTYPE) m_ItemType; } NIBBLETYPE cItemHandler::GetBlockMeta(short a_ItemDamage) { return (NIBBLETYPE)a_ItemDamage & 0x0f; // This keeps most textures. The few other items have to override this } void cItemHandler::PlaceBlock(cWorld *a_World, cPlayer *a_Player, cItem *a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Dir) { BLOCKTYPE Block = GetBlockType(); cBlockHandler *Handler = cBlockHandler::GetBlockHandler(Block); Handler->PlaceBlock(a_World, a_Player, GetBlockMeta(a_Item->m_ItemHealth), a_BlockX, a_BlockY, a_BlockZ, a_Dir); if(a_Player->GetGameMode() == eGameMode_Survival) { cItem Item(a_Item->m_ItemType, 1); a_Player->GetInventory().RemoveItem(Item); } } bool cItemHandler::EatItem(cPlayer *a_Player, cItem *a_Item) { FoodInfo Info = GetFoodInfo(); if(Info.FoodLevel > 0 || Info.Saturation > 0.f) { bool Success = a_Player->Feed(Info.FoodLevel, Info.Saturation); if(Success && Info.PoisionChance > 0) { MTRand r1; if((r1.randInt(100) - Info.PoisionChance) <= 0) { //Unlucky guy :D //TODO: Make player ill } } return Success; } return false; } cItemHandler::FoodInfo cItemHandler::GetFoodInfo() { return FoodInfo(0, 0.f); } <commit_msg>Added more item stacking sizes (patch contributed by Hanfer)<commit_after> #include "Globals.h" #include "ItemHandler.h" #include "../Item.h" #include "../World.h" #include "../Player.h" //Handler #include "ItemCloth.h" #include "ItemHoe.h" #include "ItemSlab.h" #include "ItemWood.h" #include "ItemShears.h" #include "ItemLeaves.h" #include "ItemSapling.h" #include "ItemBucket.h" #include "ItemLighter.h" #include "ItemRedstoneDust.h" #include "ItemRedstoneRepeater.h" #include "ItemSeeds.h" #include "ItemDye.h" #include "ItemSugarcane.h" #include "ItemPickaxe.h" #include "ItemShovel.h" #include "ItemSword.h" #include "ItemDoor.h" #include "ItemFood.h" #include "ItemSign.h" #include "ItemBed.h" #include "ItemSpawnEgg.h" #include "../Blocks/BlockHandler.h" bool cItemHandler::m_HandlerInitialized = false; cItemHandler * cItemHandler::m_ItemHandler[2266]; cItemHandler *cItemHandler::GetItemHandler(int a_ItemType) { if(a_ItemType < 0) a_ItemType = 0; if(!m_HandlerInitialized) { //We have to initialize memset(m_ItemHandler, 0, sizeof(m_ItemHandler)); m_HandlerInitialized = true; } if(m_ItemHandler[a_ItemType]) return m_ItemHandler[a_ItemType]; m_ItemHandler[a_ItemType] = CreateItemHandler(a_ItemType); return m_ItemHandler[a_ItemType]; } cItemHandler *cItemHandler::CreateItemHandler(int a_ItemType) { switch(a_ItemType) { default: return new cItemHandler(a_ItemType); // Single item per handler, alphabetically sorted: case E_ITEM_BED: return new cItemBedHandler(a_ItemType); case E_ITEM_DYE: return new cItemDyeHandler(a_ItemType); case E_ITEM_FLINT_AND_STEEL: return new cItemLighterHandler(a_ItemType); case E_ITEM_LEAVES: return new cItemLeavesHandler(a_ItemType); case E_ITEM_REDSTONE_DUST: return new cItemRedstoneDustHandler(a_ItemType); case E_ITEM_REDSTONE_REPEATER: return new cItemRedstoneRepeaterHandler(a_ItemType); case E_ITEM_SAPLING: return new cItemSaplingHandler(a_ItemType); case E_ITEM_SHEARS: return new cItemShearsHandler(a_ItemType); case E_ITEM_SIGN: return new cItemSignHandler(a_ItemType); case E_ITEM_SPAWN_EGG: return new cItemSpawnEggHandler(a_ItemType); case E_ITEM_SUGARCANE: return new cItemSugarcaneHandler(a_ItemType); case E_ITEM_WOOL: return new cItemClothHandler(a_ItemType); case E_ITEM_WOODEN_HOE: case E_ITEM_STONE_HOE: case E_ITEM_IRON_HOE: case E_ITEM_GOLD_HOE: case E_ITEM_DIAMOND_HOE: { return new cItemHoeHandler(a_ItemType); } case E_ITEM_WOODEN_PICKAXE: case E_ITEM_STONE_PICKAXE: case E_ITEM_IRON_PICKAXE: case E_ITEM_GOLD_PICKAXE: case E_ITEM_DIAMOND_PICKAXE: { return new cItemPickaxeHandler(a_ItemType); } case E_ITEM_WOODEN_SHOVEL: case E_ITEM_STONE_SHOVEL: case E_ITEM_IRON_SHOVEL: case E_ITEM_GOLD_SHOVEL: case E_ITEM_DIAMOND_SHOVEL: { return new cItemShovelHandler(a_ItemType); } case E_ITEM_WOODEN_SWORD: case E_ITEM_STONE_SWORD: case E_ITEM_IRON_SWORD: case E_ITEM_GOLD_SWORD: case E_ITEM_DIAMOND_SWORD: { return new cItemSwordHandler(a_ItemType); } case E_ITEM_STONE_SLAB: case E_ITEM_WOODEN_SLAB: { return new cItemSlabHandler(a_ItemType); } case E_ITEM_LOG: case E_ITEM_PLANKS: { return new cItemWoodHandler(a_ItemType); } case E_ITEM_BUCKET: case E_ITEM_WATER_BUCKET: case E_ITEM_LAVA_BUCKET: { return new cItemBucketHandler(a_ItemType); } case E_ITEM_PUMPKIN_SEEDS: case E_ITEM_MELON_SEEDS: case E_ITEM_SEEDS: { return new cItemSeedsHandler(a_ItemType); } case E_ITEM_IRON_DOOR: case E_ITEM_WOODEN_DOOR: { return new cItemDoorHandler(a_ItemType); } // Food: case E_ITEM_BREAD: case E_ITEM_COOKIE: case E_ITEM_MELON_SLICE: case E_ITEM_RAW_CHICKEN: case E_ITEM_COOKED_CHICKEN: case E_ITEM_RAW_BEEF: case E_ITEM_RAW_MEAT: case E_ITEM_STEAK: case E_ITEM_COOKED_MEAT: case E_ITEM_RAW_FISH: case E_ITEM_COOKED_FISH: case E_ITEM_RED_APPLE: case E_ITEM_GOLDEN_APPLE: case E_ITEM_ROTTEN_FLESH: case E_ITEM_SPIDER_EYE: { return new cItemFoodHandler(a_ItemType); } } } void cItemHandler::Deinit() { for(int i = 0; i < 2266; i++) { delete m_ItemHandler[i]; } m_HandlerInitialized = false; } cItemHandler::cItemHandler(int a_ItemType) { m_ItemType = a_ItemType; } bool cItemHandler::OnItemUse(cWorld * a_World, cPlayer * a_Player, cItem * a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Dir) { return false; } bool cItemHandler::OnDiggingBlock(cWorld * a_World, cPlayer * a_Player, cItem * a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Dir) { return false; } void cItemHandler::OnBlockDestroyed(cWorld *a_World, cPlayer *a_Player, cItem *a_Item, int a_X, int a_Y, int a_Z) { char Block = a_World->GetBlock(a_X, a_Y, a_Z); cBlockHandler *Handler = cBlockHandler::GetBlockHandler(Block); if(a_Player->GetGameMode() == eGameMode_Survival) { if(!BlockRequiresSpecialTool(Block) || CanHarvestBlock(Block)) { Handler->DropBlock(a_World, a_X, a_Y, a_Z); } } a_Player->UseEquippedItem(); } void cItemHandler::OnFoodEaten(cWorld *a_World, cPlayer *a_Player, cItem *a_Item) { } char cItemHandler::GetMaxStackSize(void) { if (m_ItemType < 256) { // All blocks can stack up to 64 return 64; } switch (m_ItemType) //sorted by id { case E_ITEM_APPLE: return 64; case E_ITEM_ARROW: return 64; case E_ITEM_BLAZE_POWDER: return 64; case E_ITEM_BLAZE_ROD: return 64; case E_ITEM_BONE: return 64; case E_ITEM_BOOK: return 64; case E_ITEM_BOTTLE_O_ENCHANTING: return 64; case E_ITEM_BOWL: return 64; case E_ITEM_BREAD: return 64; case E_ITEM_BREWING_STAND: return 64; case E_ITEM_BUCKET: return 1; // TODO: change this to 16 when turning compatibility to 1.3 case E_ITEM_CLAY: return 64; case E_ITEM_CLAY_BRICK: return 64; case E_ITEM_CLOCK: return 64; case E_ITEM_COAL: return 64; case E_ITEM_COMPASS: return 64; case E_ITEM_COOKED_CHICKEN: return 64; case E_ITEM_COOKED_FISH: return 64; case E_ITEM_COOKED_PORKCHOP: return 64; case E_ITEM_COOKIE: return 64; case E_ITEM_DIAMOND: return 64; case E_ITEM_DYE: return 64; case E_ITEM_EGG: return 16; case E_ITEM_EMERALD: return 64; case E_ITEM_ENDER_PEARL: return 16; case E_ITEM_EYE_OF_ENDER: return 64; case E_ITEM_FEATHER: return 64; case E_ITEM_FERMENTED_SPIDER_EYE: return 64; case E_ITEM_FIRE_CHARGE: return 64; case E_ITEM_FLINT: return 64; case E_ITEM_GHAST_TEAR: return 64; case E_ITEM_GLASS_BOTTLE: return 64; case E_ITEM_GLISTERING_MELON: return 64; case E_ITEM_GLOWSTONE_DUST: return 64; case E_ITEM_GOLD: return 64; case E_ITEM_GOLDEN_APPLE: return 64; case E_ITEM_GOLD_NUGGET: return 64; case E_ITEM_GUNPOWDER: return 64; case E_ITEM_IRON: return 64; case E_ITEM_LEATHER: return 64; case E_ITEM_MAGMA_CREAM: return 64; case E_ITEM_MELON_SEEDS: return 64; case E_ITEM_MELON_SLICE: return 64; case E_ITEM_PAINTINGS: return 64; case E_ITEM_PAPER: return 64; case E_ITEM_PUMPKIN_SEEDS: return 64; case E_ITEM_RAW_BEEF: return 64; case E_ITEM_RAW_CHICKEN: return 64; case E_ITEM_RAW_FISH: return 64; case E_ITEM_RAW_PORKCHOP: return 64; case E_ITEM_REDSTONE_DUST: return 64; case E_ITEM_REDSTONE_REPEATER: return 64; case E_ITEM_ROTTEN_FLESH: return 64; case E_ITEM_SEEDS: return 64; case E_ITEM_SIGN: return 16; case E_ITEM_SLIMEBALL: return 64; case E_ITEM_SNOWBALL: return 16; case E_ITEM_SPIDER_EYE: return 64; case E_ITEM_STEAK: return 64; case E_ITEM_STICK: return 64; case E_ITEM_STRING: return 64; case E_ITEM_SUGAR: return 64; case E_ITEM_SUGAR_CANE: return 64; case E_ITEM_WHEAT: return 64; } // By default items don't stack: return 1; } bool cItemHandler::IsTool() { return (m_ItemType >= 256 && m_ItemType <= 259) || (m_ItemType == 261) || (m_ItemType >= 267 && m_ItemType <= 279) || (m_ItemType >= 283 && m_ItemType <= 286) || (m_ItemType >= 290 && m_ItemType <= 294) || (m_ItemType >= 256 && m_ItemType <= 259) || (m_ItemType == 325) || (m_ItemType == 346); } bool cItemHandler::IsFood() { return (m_ItemType == 260) || (m_ItemType == 282) || (m_ItemType == 297) || (m_ItemType >= 319 && m_ItemType <= 320) || (m_ItemType == 335) || (m_ItemType >= 349 && m_ItemType <= 350) || (m_ItemType == 357) || (m_ItemType == 360) || (m_ItemType >= 363 && m_ItemType <= 366); } bool cItemHandler::IsPlaceable() { return m_ItemType >= 1 && m_ItemType <= 136; } bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) { return false; } BLOCKTYPE cItemHandler::GetBlockType() { ASSERT(m_ItemType < 256); // Items with IDs above 255 should all be handled by specific handlers #ifdef _DEBUG if (m_ItemType > 256) { LOGERROR("Item %d has no valid block!", m_ItemType); } #endif // _DEBUG return (BLOCKTYPE) m_ItemType; } NIBBLETYPE cItemHandler::GetBlockMeta(short a_ItemDamage) { return (NIBBLETYPE)a_ItemDamage & 0x0f; // This keeps most textures. The few other items have to override this } void cItemHandler::PlaceBlock(cWorld *a_World, cPlayer *a_Player, cItem *a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Dir) { BLOCKTYPE Block = GetBlockType(); cBlockHandler *Handler = cBlockHandler::GetBlockHandler(Block); Handler->PlaceBlock(a_World, a_Player, GetBlockMeta(a_Item->m_ItemHealth), a_BlockX, a_BlockY, a_BlockZ, a_Dir); if(a_Player->GetGameMode() == eGameMode_Survival) { cItem Item(a_Item->m_ItemType, 1); a_Player->GetInventory().RemoveItem(Item); } } bool cItemHandler::EatItem(cPlayer *a_Player, cItem *a_Item) { FoodInfo Info = GetFoodInfo(); if(Info.FoodLevel > 0 || Info.Saturation > 0.f) { bool Success = a_Player->Feed(Info.FoodLevel, Info.Saturation); if(Success && Info.PoisionChance > 0) { MTRand r1; if((r1.randInt(100) - Info.PoisionChance) <= 0) { //Unlucky guy :D //TODO: Make player ill } } return Success; } return false; } cItemHandler::FoodInfo cItemHandler::GetFoodInfo() { return FoodInfo(0, 0.f); } <|endoftext|>
<commit_before>#include "ServerPeer.h" #include "Parameter.h" #include "MessageDecoder.h" using namespace std; ServerPeer::ServerPeer(char* _listen_hostname, int _listen_port):Server(_listen_hostname, _listen_port){ } ServerPeer::~ServerPeer(){ } std::vector<std::string> ServerPeer::getListofImages(std::string token, std::string userID){ //TODO: AUTHENTICATE WITH SERVER DISCOVERY return imageList; } std::string ServerPeer::getImage(std::string token, std::string userID, std::string imageID){ //TODO: LOAD IMAGES } void ServerPeer::updateViews(std::string token, std::string userID, int count){ } void ServerPeer::revokeViews(std::string token, std::string userID){ } Message* ServerPeer::doOperation(Message* _message){ Message reply_message(Reply); vector<Parameter> args; vector<Parameter> reply_args; int operation = _message->getOperation(); MessageType = _message->getMessageType(); MessageDecoder::decode(_message, args); switch(operation){ case 7: break; case 8: break; case 9: break; } MessageDecoder::encode(reply_message, reply_args, operation, Reply); return reply_message; } <commit_msg>Implemented Image functions of Peer Server<commit_after>#include "ServerPeer.h" #include "Parameter.h" #include "MessageDecoder.h" #include <iostream> #include <fstream> #include <string> using namespace std; ServerPeer::ServerPeer(char* _listen_hostname, int _listen_port):Server(_listen_hostname, _listen_port){ system("mkdir MyImages"); system("mkdir LoadedImages"); } ServerPeer::~ServerPeer(){ } std::vector<std::string> ServerPeer::getListofImages(std::string token, std::string userID){ //TODO: AUTHENTICATE WITH SERVER DISCOVERY return imageList; } std::string ServerPeer::getImage(std::string token, std::string userID, std::string imageID){ //TODO: AUTHENTICATE WITH SERVER DISCOVERY streampos size; char * memblock; ifstream file (imageID, ios::in|ios::binary|ios::ate); if (file.is_open()){ size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); string image(memblock, size); delete[] memblock; return image; } else return NULL; } void ServerPeer::updateViews(std::string token, std::string userID, int count){ } void ServerPeer::revokeViews(std::string token, std::string userID){ } Message* ServerPeer::doOperation(Message* _message){ Message reply_message(Reply); vector<Parameter> args; vector<Parameter> reply_args; int operation = _message->getOperation(); MessageType = _message->getMessageType(); MessageDecoder::decode(_message, args); switch(operation){ case 7:{ std::vector<std::string> imageList = getListofImages(args[0].getString(), args[1].getString()); Parameter arg1; arg1.setVectorString(imageList); reply_args.push_back(arg1); } break; case 8:{ string image = getImage(args[0].getString(), args[1].getString(), args[2].getString()); Parameter arg1; arg1.setString(image); reply_args.push_back(arg1); } break; case 9:{ } break; } MessageDecoder::encode(reply_message, reply_args, operation, Reply); return reply_message; } <|endoftext|>
<commit_before>/** * 2-D Steady State Conduction without Heat Generation | main.cpp * * @libs [Nodes.a, NodesHelper.a] * @header [Nodes.h, NodesHelper.h] * * @author Samuel0Paul <[email protected]> **/ #include <iostream> #include <iomanip> #include <cstdlib> #include <cstdint> #include <chrono> #include <thread> #include <atomic> #include "header/Nodes.h" #include "header/NodesHelper.h" #include "test/test.cpp" using std::cout; using std::endl; using std::clog; using std::cin; using std::make_pair; using prec_t = long double; int main(int argc, char const *argv[]) { cout << std::nounitbuf; cout << std::setprecision(4) << std::fixed << std::boolalpha; cout << "############################ HMT Assignment ##########################" << endl << " 2-D Steady State Conduction with and withour Heat Generation" << endl << endl << " Author: Samuel Paul Vishesh [UR11ME145] <[email protected]>" << endl << "######################################################################" << endl << endl; /*HMT::NodesHelper<prec_t> nodes; nodes.init(); nodes.canUseThreads(false); nodes.calculate(); cout << nodes; cout << "Time taken: " << nodes.getDuration<std::chrono::nanoseconds>().count() << "ns" << endl;*/ test::NodesWithoutHeatSrc<prec_t> testNodesWOHSrcTE{12, 12, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, true}; testNodesWOHSrcTE.test(); test::NodesWithoutHeatSrc<prec_t> testNodesWOHSrcWTE{12, 12, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, false}; testNodesWOHSrcWTE.test(); std::vector<std::pair<std::pair<uint64_t, uint64_t>, prec_t>> heatSrcs = { make_pair(make_pair(2, 2), 300.0f), make_pair(make_pair(5, 5), -1000.0f) }; test::NodesWithHeatSrc<prec_t> testNodesWHSrcTE{12, 12, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, false, heatSrcs}; testNodesWHSrcTE.test(); test::NodesWithHeatSrc<prec_t> testNodesWHSrcWTE{12, 12, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, true, heatSrcs}; testNodesWHSrcWTE.test(); return 0; }<commit_msg>some changes and code refactor<commit_after>/** * 2-D Steady State Conduction without Heat Generation | main.cpp * * @libs [Nodes.a, NodesHelper.a] * @header [Nodes.h, NodesHelper.h] * * @author Samuel0Paul <[email protected]> **/ #include <iostream> #include <iomanip> #include <cstdlib> #include <cstdint> #include <chrono> #include <thread> #include <atomic> #include "header/Nodes.h" #include "header/NodesHelper.h" #include "test/test.cpp" using std::cout; using std::endl; using std::clog; using std::cin; using std::make_pair; using prec_t = long double; void runTest(void) { test::NodesWithoutHeatSrc<prec_t> testNodesWOHSrcTE{12, 30, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, true}; testNodesWOHSrcTE.test(); test::NodesWithoutHeatSrc<prec_t> testNodesWOHSrcWTE{12, 30, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, false}; testNodesWOHSrcWTE.test(); std::vector<std::pair<std::pair<uint64_t, uint64_t>, prec_t>> heatSrcs = { make_pair(make_pair(2, 2), 300.0f), make_pair(make_pair(5, 5), -1000.0f) }; test::NodesWithHeatSrc<prec_t> testNodesWHSrcTE{12, 30, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, false, heatSrcs}; testNodesWHSrcTE.test(); test::NodesWithHeatSrc<prec_t> testNodesWHSrcWTE{12, 30, 500.0f, 100.0f, 100.0f, 100.0f, 0.0000001f, true, heatSrcs}; testNodesWHSrcWTE.test(); } int main(int argc, char const *argv[]) { cout << std::nounitbuf; cout << std::setprecision(4) << std::fixed << std::boolalpha; cout << "############################ HMT Assignment ##########################" << endl << " 2-D Steady State Conduction with and withour Heat Generation" << endl << endl << " Author: Samuel Paul Vishesh [UR11ME145] <[email protected]>" << endl << "######################################################################" << endl << endl; /*HMT::NodesHelper<prec_t> nodes; nodes.init(); nodes.canUseThreads(false); nodes.calculate(); cout << nodes; cout << "Time taken: " << nodes.getDuration<std::chrono::nanoseconds>().count() << "ns" << endl;*/ runTest(); return 0; }<|endoftext|>
<commit_before>e0ae01d7-313a-11e5-97c0-3c15c2e10482<commit_msg>e0b405d7-313a-11e5-b728-3c15c2e10482<commit_after>e0b405d7-313a-11e5-b728-3c15c2e10482<|endoftext|>
<commit_before>7f6cf603-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf604-2d15-11e5-af21-0401358ea401<commit_after>7f6cf604-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0faae4d4-2f67-11e5-bc1c-6c40088e03e4<commit_msg>0fb58de4-2f67-11e5-b51a-6c40088e03e4<commit_after>0fb58de4-2f67-11e5-b51a-6c40088e03e4<|endoftext|>
<commit_before>ba47d500-2e4f-11e5-8b8b-28cfe91dbc4b<commit_msg>ba4ea291-2e4f-11e5-80b1-28cfe91dbc4b<commit_after>ba4ea291-2e4f-11e5-80b1-28cfe91dbc4b<|endoftext|>
<commit_before>#include "ewa_base/testing/test.h" #include "ewa_base/ipc.h" #include <iostream> using namespace ew; TEST_DEFINE(TEST_Shm) { SharedMem sm1,sm2; String filetext="helloworld"; // create a file and write some text TEST_ASSERT(sm1.OpenFile("shm_sample.txt",1024,FLAG_FILE_RW|FLAG_FILE_CR)); if(sm1.data()) { strcpy(sm1.data(),filetext.c_str()); } sm1.Close(); TEST_ASSERT(sm1.data()==NULL); // open the file and read the text TEST_ASSERT(sm2.OpenFile("shm_sample.txt",0,FLAG_FILE_RD)); if(sm1.data() && sm2.data()) { TEST_ASSERT(strcmp(sm2.data(),filetext.c_str())==0); } sm2.Close(); // open SharedMem with a name; TEST_ASSERT_MSG(sm1.Open("local_shm",1024,FLAG_FILE_RD|FLAG_FILE_WR|FLAG_FILE_CR),"ShmOpen"); TEST_ASSERT_MSG(sm2.Open("local_shm",1024,FLAG_FILE_RD|FLAG_FILE_WR),"ShmOpen"); char* p1=sm1.data(); char* p2=sm2.data(); if(p1 && p2) { TEST_ASSERT(p1!=p2); int *p=(int*)p1; for(size_t i=0; i<sm1.size()/sizeof(int); i++) { p[i]=rand(); } TEST_ASSERT(memcmp(p1,p2,1024)==0); } else { TEST_ASSERT_MSG(false,"ShmOpen"); } // open SharedMem without a name; TEST_ASSERT_MSG(sm2.Alloc(4096*8),"ShmOpen"); p1=sm2.data(); TEST_ASSERT_MSG(p1!=NULL,"SharedMem::Alloc failed"); if(p1) { memset(p1,1,4096*8); } sm1.Close(); sm2.Close(); } <commit_msg>update<commit_after>#include "ewa_base/testing/test.h" #include "ewa_base/ipc.h" #include <iostream> using namespace ew; TEST_DEFINE(TEST_Shm) { SharedMem sm1,sm2; String filetext="helloworld"; // create a file and write some text TEST_ASSERT(sm1.OpenFile("shm_sample.txt",1024,FLAG_FILE_RW|FLAG_FILE_CR)); if(sm1.data()) { strcpy(sm1.data(),filetext.c_str()); } sm1.Close(); TEST_ASSERT(sm1.data()==NULL); // open the file and read the text TEST_ASSERT(sm2.OpenFile("shm_sample.txt",0,FLAG_FILE_RD)); if(sm2.data()) { TEST_ASSERT(strcmp(sm2.data(),filetext.c_str())==0); } sm2.Close(); // open SharedMem with a name; TEST_ASSERT_MSG(sm1.Open("local_shm",1024,FLAG_FILE_RD|FLAG_FILE_WR|FLAG_FILE_CR),"ShmOpen"); TEST_ASSERT_MSG(sm2.Open("local_shm",1024,FLAG_FILE_RD|FLAG_FILE_WR),"ShmOpen"); char* p1=sm1.data(); char* p2=sm2.data(); if(p1 && p2) { TEST_ASSERT(p1!=p2); int *p=(int*)p1; for(size_t i=0; i<sm1.size()/sizeof(int); i++) { p[i]=rand(); } TEST_ASSERT(memcmp(p1,p2,1024)==0); } else { TEST_ASSERT_MSG(false,"ShmOpen"); } // open SharedMem without a name; TEST_ASSERT_MSG(sm2.Alloc(4096*8),"ShmOpen"); p1=sm2.data(); TEST_ASSERT_MSG(p1!=NULL,"SharedMem::Alloc failed"); if(p1) { memset(p1,1,4096*8); } sm1.Close(); sm2.Close(); } <|endoftext|>
<commit_before>/* * Copyright © 2008, 2009 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <cstdio> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> extern "C" { #include <talloc.h> } #include "ast.h" #include "glsl_parser_extras.h" #include "glsl_parser.h" #include "ir_optimization.h" #include "ir_print_visitor.h" #include "program.h" static char * load_text_file(const char *file_name, size_t *size) { char *text = NULL; struct stat st; ssize_t total_read = 0; int fd = open(file_name, O_RDONLY); *size = 0; if (fd < 0) { return NULL; } if (fstat(fd, & st) == 0) { text = (char *) malloc(st.st_size + 1); if (text != NULL) { do { ssize_t bytes = read(fd, text + total_read, st.st_size - total_read); if (bytes < 0) { free(text); text = NULL; break; } if (bytes == 0) { break; } total_read += bytes; } while (total_read < st.st_size); text[total_read] = '\0'; *size = total_read; } } close(fd); return text; } void usage_fail(const char *name) { printf("%s <filename.frag|filename.vert>\n", name); exit(EXIT_FAILURE); } int dump_ast = 0; int dump_lir = 0; int do_link = 0; const struct option compiler_opts[] = { { "dump-ast", 0, &dump_ast, 1 }, { "dump-lir", 0, &dump_lir, 1 }, { "link", 0, &do_link, 1 }, { NULL, 0, NULL, 0 } }; void compile_shader(struct glsl_shader *shader) { struct _mesa_glsl_parse_state state; memset(& state, 0, sizeof(state)); switch (shader->Type) { case GL_VERTEX_SHADER: state.target = vertex_shader; break; case GL_FRAGMENT_SHADER: state.target = fragment_shader; break; case GL_GEOMETRY_SHADER: state.target = geometry_shader; break; } state.scanner = NULL; state.translation_unit.make_empty(); state.symbols = new glsl_symbol_table; state.info_log = talloc_strdup(shader, ""); state.error = false; state.temp_index = 0; state.loop_or_switch_nesting = NULL; state.ARB_texture_rectangle_enable = true; _mesa_glsl_lexer_ctor(& state, shader->Source, shader->SourceLen); _mesa_glsl_parse(& state); _mesa_glsl_lexer_dtor(& state); if (dump_ast) { foreach_list_const(n, &state.translation_unit) { ast_node *ast = exec_node_data(ast_node, n, link); ast->print(); } printf("\n\n"); } shader->ir.make_empty(); if (!state.error && !state.translation_unit.is_empty()) _mesa_ast_to_hir(&shader->ir, &state); /* Optimization passes */ if (!state.error && !shader->ir.is_empty()) { bool progress; do { progress = false; progress = do_function_inlining(&shader->ir) || progress; progress = do_if_simplification(&shader->ir) || progress; progress = do_copy_propagation(&shader->ir) || progress; progress = do_dead_code_local(&shader->ir) || progress; progress = do_dead_code_unlinked(&shader->ir) || progress; progress = do_constant_variable_unlinked(&shader->ir) || progress; progress = do_constant_folding(&shader->ir) || progress; progress = do_vec_index_to_swizzle(&shader->ir) || progress; progress = do_swizzle_swizzle(&shader->ir) || progress; } while (progress); } /* Print out the resulting IR */ if (!state.error && dump_lir) { _mesa_print_ir(&shader->ir, &state); } shader->symbols = state.symbols; shader->CompileStatus = !state.error; if (shader->InfoLog) talloc_free(shader->InfoLog); shader->InfoLog = state.info_log; return; } int main(int argc, char **argv) { int status = EXIT_SUCCESS; int c; int idx = 0; while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1) /* empty */ ; if (argc <= optind) usage_fail(argv[0]); struct glsl_program whole_program; memset(&whole_program, 0, sizeof(whole_program)); for (/* empty */; argc > optind; optind++) { whole_program.Shaders = (struct glsl_shader **) realloc(whole_program.Shaders, sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1)); assert(whole_program.Shaders != NULL); /* talloc context should probably be whole_program */ struct glsl_shader *shader = talloc_zero(NULL, glsl_shader); whole_program.Shaders[whole_program.NumShaders] = shader; whole_program.NumShaders++; const unsigned len = strlen(argv[optind]); if (len < 6) usage_fail(argv[0]); const char *const ext = & argv[optind][len - 5]; if (strncmp(".vert", ext, 5) == 0) shader->Type = GL_VERTEX_SHADER; else if (strncmp(".geom", ext, 5) == 0) shader->Type = GL_GEOMETRY_SHADER; else if (strncmp(".frag", ext, 5) == 0) shader->Type = GL_FRAGMENT_SHADER; else usage_fail(argv[0]); shader->Source = load_text_file(argv[optind], &shader->SourceLen); compile_shader(shader); if (!shader->CompileStatus) { printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog); status = EXIT_FAILURE; break; } } if ((status == EXIT_SUCCESS) && do_link) { link_shaders(&whole_program); status = (whole_program.LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE; } return status; } <commit_msg>Complain and exit if the given shader file doesn't exist.<commit_after>/* * Copyright © 2008, 2009 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <cstdio> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> extern "C" { #include <talloc.h> } #include "ast.h" #include "glsl_parser_extras.h" #include "glsl_parser.h" #include "ir_optimization.h" #include "ir_print_visitor.h" #include "program.h" static char * load_text_file(const char *file_name, size_t *size) { char *text = NULL; struct stat st; ssize_t total_read = 0; int fd = open(file_name, O_RDONLY); *size = 0; if (fd < 0) { return NULL; } if (fstat(fd, & st) == 0) { text = (char *) malloc(st.st_size + 1); if (text != NULL) { do { ssize_t bytes = read(fd, text + total_read, st.st_size - total_read); if (bytes < 0) { free(text); text = NULL; break; } if (bytes == 0) { break; } total_read += bytes; } while (total_read < st.st_size); text[total_read] = '\0'; *size = total_read; } } close(fd); return text; } void usage_fail(const char *name) { printf("%s <filename.frag|filename.vert>\n", name); exit(EXIT_FAILURE); } int dump_ast = 0; int dump_lir = 0; int do_link = 0; const struct option compiler_opts[] = { { "dump-ast", 0, &dump_ast, 1 }, { "dump-lir", 0, &dump_lir, 1 }, { "link", 0, &do_link, 1 }, { NULL, 0, NULL, 0 } }; void compile_shader(struct glsl_shader *shader) { struct _mesa_glsl_parse_state state; memset(& state, 0, sizeof(state)); switch (shader->Type) { case GL_VERTEX_SHADER: state.target = vertex_shader; break; case GL_FRAGMENT_SHADER: state.target = fragment_shader; break; case GL_GEOMETRY_SHADER: state.target = geometry_shader; break; } state.scanner = NULL; state.translation_unit.make_empty(); state.symbols = new glsl_symbol_table; state.info_log = talloc_strdup(shader, ""); state.error = false; state.temp_index = 0; state.loop_or_switch_nesting = NULL; state.ARB_texture_rectangle_enable = true; _mesa_glsl_lexer_ctor(& state, shader->Source, shader->SourceLen); _mesa_glsl_parse(& state); _mesa_glsl_lexer_dtor(& state); if (dump_ast) { foreach_list_const(n, &state.translation_unit) { ast_node *ast = exec_node_data(ast_node, n, link); ast->print(); } printf("\n\n"); } shader->ir.make_empty(); if (!state.error && !state.translation_unit.is_empty()) _mesa_ast_to_hir(&shader->ir, &state); /* Optimization passes */ if (!state.error && !shader->ir.is_empty()) { bool progress; do { progress = false; progress = do_function_inlining(&shader->ir) || progress; progress = do_if_simplification(&shader->ir) || progress; progress = do_copy_propagation(&shader->ir) || progress; progress = do_dead_code_local(&shader->ir) || progress; progress = do_dead_code_unlinked(&shader->ir) || progress; progress = do_constant_variable_unlinked(&shader->ir) || progress; progress = do_constant_folding(&shader->ir) || progress; progress = do_vec_index_to_swizzle(&shader->ir) || progress; progress = do_swizzle_swizzle(&shader->ir) || progress; } while (progress); } /* Print out the resulting IR */ if (!state.error && dump_lir) { _mesa_print_ir(&shader->ir, &state); } shader->symbols = state.symbols; shader->CompileStatus = !state.error; if (shader->InfoLog) talloc_free(shader->InfoLog); shader->InfoLog = state.info_log; return; } int main(int argc, char **argv) { int status = EXIT_SUCCESS; int c; int idx = 0; while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1) /* empty */ ; if (argc <= optind) usage_fail(argv[0]); struct glsl_program whole_program; memset(&whole_program, 0, sizeof(whole_program)); for (/* empty */; argc > optind; optind++) { whole_program.Shaders = (struct glsl_shader **) realloc(whole_program.Shaders, sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1)); assert(whole_program.Shaders != NULL); /* talloc context should probably be whole_program */ struct glsl_shader *shader = talloc_zero(NULL, glsl_shader); whole_program.Shaders[whole_program.NumShaders] = shader; whole_program.NumShaders++; const unsigned len = strlen(argv[optind]); if (len < 6) usage_fail(argv[0]); const char *const ext = & argv[optind][len - 5]; if (strncmp(".vert", ext, 5) == 0) shader->Type = GL_VERTEX_SHADER; else if (strncmp(".geom", ext, 5) == 0) shader->Type = GL_GEOMETRY_SHADER; else if (strncmp(".frag", ext, 5) == 0) shader->Type = GL_FRAGMENT_SHADER; else usage_fail(argv[0]); shader->Source = load_text_file(argv[optind], &shader->SourceLen); if (shader->Source == NULL) { printf("File \"%s\" does not exist.\n", argv[optind]); exit(EXIT_FAILURE); } compile_shader(shader); if (!shader->CompileStatus) { printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog); status = EXIT_FAILURE; break; } } if ((status == EXIT_SUCCESS) && do_link) { link_shaders(&whole_program); status = (whole_program.LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE; } return status; } <|endoftext|>
<commit_before>2ff009fa-2e3a-11e5-9d0f-c03896053bdd<commit_msg>3005b8cc-2e3a-11e5-98bf-c03896053bdd<commit_after>3005b8cc-2e3a-11e5-98bf-c03896053bdd<|endoftext|>
<commit_before>1dd55882-2e4f-11e5-863b-28cfe91dbc4b<commit_msg>1dddc2d7-2e4f-11e5-b567-28cfe91dbc4b<commit_after>1dddc2d7-2e4f-11e5-b567-28cfe91dbc4b<|endoftext|>
<commit_before>293c8f2e-2e4f-11e5-a2ad-28cfe91dbc4b<commit_msg>2943373d-2e4f-11e5-adc7-28cfe91dbc4b<commit_after>2943373d-2e4f-11e5-adc7-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <random> #include <vector> #include <SFML/System/Vector2.hpp> #include <SFML/Graphics/Image.hpp> bool done = false; std::mt19937 generator; std::uniform_real_distribution<double> heightDist(0, 1); std::uniform_int_distribution<int> startDist(-10000, 10000); sf::Vector2u size; std::vector<double> heights; void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4); int main(int argc, char** argv) { if(argc != 3) { std::cerr << "Incorrect # of args, must be 2.\n"; return 1; } size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))}; // resize vector to correct size heights.resize(size.x * size.y, 0); // seed generator generator.seed(std::chrono::system_clock::now().time_since_epoch().count()); // make the image sf::Image heightMap; heightMap.create(size.x, size.y); // begin the recursive algo! divideSquare(true, 0, 0, size.x, size.y, -1, -1, -1, -1); // fill the image for(unsigned i = 0; i < size.x * size.y; i++) { sf::Uint8 r = 255.0 * heights[i]; sf::Uint8 g = 255.0 * heights[i]; sf::Uint8 b = 255.0 * heights[i]; heightMap.setPixel(i % size.x, i / size.y, {r, g, b}); } heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png"); return 0; } void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4) { // get corners double topLeft, topRight, botLeft, botRight; if((c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) || first) { topLeft = heightDist(generator); topRight = heightDist(generator); botLeft = heightDist(generator); botRight = heightDist(generator); } else { topLeft = c1; topRight = c2; botLeft = c3; botRight = c4; } // get midpoints on edges double topEdge, leftEdge, rightEdge, botEdge; if(first) { topEdge = heightDist(generator); leftEdge = heightDist(generator); rightEdge = heightDist(generator); botEdge = heightDist(generator); } else { topEdge = (topLeft + topRight) / 2.0; leftEdge = (topLeft + botLeft) / 2.0; rightEdge = (topRight + botRight) / 2.0; botEdge = (botLeft + botRight) / 2.0; } // middle point of the square, add a random amount to keep the map less uniform double middle; if(first) middle = heightDist(generator); else middle = (topLeft + topRight + botLeft + botRight + heightDist(generator)) / 5.0; // assign values // corners heights[(x % size.x) + (y % size.y) * size.x] = topLeft; heights[(x + w) % size.x + (y % size.y) * size.x] = topRight; heights[(x % size.x) + ((y + h) % size.y) * size.x] = botLeft; heights[(x + w) % size.x + ((y + h) % size.y) * size.x] = botRight; // midpoints heights[(x + (w / 2)) % size.x + (y % size.y) * size.x] = topEdge; heights[(x % size.x) + ((y + (h / 2)) % size.y) * size.x] = leftEdge; heights[(x + w) % size.x + ((y + (h / 2)) % size.y) * size.x] = rightEdge; heights[(x + (w / 2)) % size.x + ((y + h) % size.y) * size.x] = botEdge; heights[(x + (w / 2)) % size.x + ((y + (h / 2)) % size.y) * size.x] = middle; // if we're too small to continue if(!(w > 1 || h > 1)) return; divideSquare(false, x, y, w / 2.0, h / 2.0, topLeft, topEdge, leftEdge, middle); // top left quad divideSquare(false, x + w / 2.0, y, w / 2.0, h / 2.0, topEdge, topRight, middle, rightEdge); // top right quad divideSquare(false, x, y + h / 2.0, w / 2.0, h / 2.0, leftEdge, middle, botLeft, botEdge); // bot left quad divideSquare(false, x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0, middle, rightEdge, botEdge, botRight); // bot right quad } <commit_msg>Added a roughness parameter<commit_after>#include <iostream> #include <chrono> #include <random> #include <vector> #include <SFML/System/Vector2.hpp> #include <SFML/Graphics/Image.hpp> bool done = false; std::mt19937 generator; std::uniform_real_distribution<double> heightDist(0, 1); std::uniform_real_distribution<double> roughDist; std::uniform_int_distribution<int> startDist(-10000, 10000); sf::Vector2u size; std::vector<double> heights; void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4); int main(int argc, char** argv) { if(argc != 4) { std::cerr << "Incorrect # of args, must be 3.\n"; return 1; } size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))}; // resize vector to correct size heights.resize(size.x * size.y, 0); double roughness = std::stod(argv[3]); // clamp roughness variable to 0..1 if(roughness < 0) roughness = 0; if(roughness > 1) roughness = 1; roughDist = std::uniform_real_distribution<double>(-roughness, roughness); // seed generator generator.seed(std::chrono::system_clock::now().time_since_epoch().count()); // make the image sf::Image heightMap; heightMap.create(size.x, size.y); // begin the recursive algo! divideSquare(true, 0, 0, size.x, size.y, -1, -1, -1, -1); // fill the image for(unsigned i = 0; i < size.x * size.y; i++) { sf::Uint8 r = 255.0 * heights[i]; sf::Uint8 g = 255.0 * heights[i]; sf::Uint8 b = 255.0 * heights[i]; heightMap.setPixel(i % size.x, i / size.y, {r, g, b}); } heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png"); return 0; } void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4) { // get corners double topLeft, topRight, botLeft, botRight; if((c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) || first) { topLeft = heightDist(generator); topRight = heightDist(generator); botLeft = heightDist(generator); botRight = heightDist(generator); } else { topLeft = c1; topRight = c2; botLeft = c3; botRight = c4; } // get midpoints on edges double topEdge, leftEdge, rightEdge, botEdge; if(first) { topEdge = heightDist(generator); leftEdge = heightDist(generator); rightEdge = heightDist(generator); botEdge = heightDist(generator); } else { topEdge = (topLeft + topRight) / 2.0; leftEdge = (topLeft + botLeft) / 2.0; rightEdge = (topRight + botRight) / 2.0; botEdge = (botLeft + botRight) / 2.0; } // middle point of the square, add a random amount to keep the map less uniform double middle; if(first) middle = heightDist(generator); else //middle = (topLeft + topRight + botLeft + botRight + heightDist(generator)) / 5.0; middle = (topLeft + topRight + botLeft + botRight) / 4.0 + roughDist(generator); // keep bounds if(middle < 0) middle = 0; if(middle > 1) middle = 1; // assign values // corners heights[(x % size.x) + (y % size.y) * size.x] = topLeft; heights[(x + w) % size.x + (y % size.y) * size.x] = topRight; heights[(x % size.x) + ((y + h) % size.y) * size.x] = botLeft; heights[(x + w) % size.x + ((y + h) % size.y) * size.x] = botRight; // midpoints heights[(x + (w / 2)) % size.x + (y % size.y) * size.x] = topEdge; heights[(x % size.x) + ((y + (h / 2)) % size.y) * size.x] = leftEdge; heights[(x + w) % size.x + ((y + (h / 2)) % size.y) * size.x] = rightEdge; heights[(x + (w / 2)) % size.x + ((y + h) % size.y) * size.x] = botEdge; heights[(x + (w / 2)) % size.x + ((y + (h / 2)) % size.y) * size.x] = middle; // if we're too small to continue if(!(w > 1 || h > 1)) return; divideSquare(false, x, y, w / 2.0, h / 2.0, topLeft, topEdge, leftEdge, middle); // top left quad divideSquare(false, x + w / 2.0, y, w / 2.0, h / 2.0, topEdge, topRight, middle, rightEdge); // top right quad divideSquare(false, x, y + h / 2.0, w / 2.0, h / 2.0, leftEdge, middle, botLeft, botEdge); // bot left quad divideSquare(false, x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0, middle, rightEdge, botEdge, botRight); // bot right quad } <|endoftext|>
<commit_before>69b1fd94-2fa5-11e5-8447-00012e3d3f12<commit_msg>69b44786-2fa5-11e5-a6fd-00012e3d3f12<commit_after>69b44786-2fa5-11e5-a6fd-00012e3d3f12<|endoftext|>
<commit_before>5ae7ec1b-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec1c-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec1c-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include "fs_options.h" #include "fs_meta_ops.h" #include "file_meta_ops.h" #include "dir_meta_ops.h" #include "fs_logger.h" #include <unistd.h> #include <iostream> #include <fuse.h> using namespace mgridfs; namespace mgridfs { FSOptions globalFSOptions; } namespace { struct fuse_operations mgridfsOps = {}; } int main(int argc, char* argv[], char* arge[]) { std::cout << "MongoDB-GridFS" << std::endl; mgridfsOps.init = mgridfs::mgridfs_init; mgridfsOps.destroy = mgridfs::mgridfs_destroy; mgridfsOps.getattr = mgridfs::mgridfs_getattr; mgridfsOps.readlink = mgridfs::mgridfs_readlink; mgridfsOps.mknod = mgridfs::mgridfs_mknod; mgridfsOps.mkdir = mgridfs::mgridfs_mkdir; mgridfsOps.rmdir = mgridfs::mgridfs_rmdir; mgridfsOps.opendir = mgridfs::mgridfs_opendir; mgridfsOps.readdir = mgridfs::mgridfs_readdir; mgridfsOps.releasedir = mgridfs::mgridfs_releasedir; mgridfsOps.fsyncdir = mgridfs::mgridfs_fsyncdir; mgridfsOps.unlink = mgridfs::mgridfs_unlink; mgridfsOps.symlink = mgridfs::mgridfs_symlink; mgridfsOps.rename = mgridfs::mgridfs_rename; mgridfsOps.link = mgridfs::mgridfs_link; mgridfsOps.chmod = mgridfs::mgridfs_chmod; mgridfsOps.chown = mgridfs::mgridfs_chown; mgridfsOps.truncate = mgridfs::mgridfs_truncate; mgridfsOps.utime = mgridfs::mgridfs_utime; mgridfsOps.open = mgridfs::mgridfs_open; mgridfsOps.read = mgridfs::mgridfs_read; mgridfsOps.write = mgridfs::mgridfs_write; mgridfsOps.statfs = mgridfs::mgridfs_statfs; mgridfsOps.flush = mgridfs::mgridfs_flush; mgridfsOps.release = mgridfs::mgridfs_release; mgridfsOps.fsync = mgridfs::mgridfs_fsync; mgridfsOps.setxattr = mgridfs::mgridfs_setxattr; mgridfsOps.getxattr = mgridfs::mgridfs_getxattr; mgridfsOps.listxattr = mgridfs::mgridfs_listxattr; mgridfsOps.removexattr = mgridfs::mgridfs_removexattr; mgridfsOps.create = mgridfs::mgridfs_create; mgridfsOps.ftruncate = mgridfs::mgridfs_ftruncate; mgridfsOps.fgetattr = mgridfs::mgridfs_fgetattr; mgridfsOps.lock = mgridfs::mgridfs_lock; mgridfsOps.utimens = mgridfs::mgridfs_utimens; mgridfsOps.bmap = mgridfs::mgridfs_bmap; mgridfsOps.ioctl = mgridfs::mgridfs_ioctl; mgridfsOps.poll = mgridfs::mgridfs_poll; mgridfsOps.write_buf = mgridfs::mgridfs_write_buf; mgridfsOps.read_buf = mgridfs::mgridfs_read_buf; mgridfsOps.flock = mgridfs::mgridfs_flock; mgridfsOps.fallocate = mgridfs::mgridfs_fallocate; struct fuse_args fuseArgs = FUSE_ARGS_INIT(argc, argv); if (!mgridfs::globalFSOptions.fromCommandLine(fuseArgs)) { std::cerr << "ERROR: Failed to parse options passed to program, will not mount file system" << std::endl; return 1; } fuse_main(fuseArgs.argc, fuseArgs.argv, &mgridfsOps, NULL); return 0; } <commit_msg>Reorganized the function call assignments into appropriate grouping<commit_after>#include "fs_options.h" #include "fs_meta_ops.h" #include "file_meta_ops.h" #include "dir_meta_ops.h" #include "fs_logger.h" #include <unistd.h> #include <iostream> #include <fuse.h> using namespace mgridfs; namespace mgridfs { FSOptions globalFSOptions; } namespace { struct fuse_operations mgridfsOps = {}; } int main(int argc, char* argv[], char* arge[]) { std::cout << "MongoDB-GridFS" << std::endl; // File-system meta / setup / cleanup functions mgridfsOps.init = mgridfs::mgridfs_init; mgridfsOps.destroy = mgridfs::mgridfs_destroy; mgridfsOps.statfs = mgridfs::mgridfs_statfs; // File/Directory attribute management functionality mgridfsOps.getattr = mgridfs::mgridfs_getattr; mgridfsOps.fgetattr = mgridfs::mgridfs_fgetattr; mgridfsOps.access = NULL; // optional, un-implemented functionality mgridfsOps.setxattr = mgridfs::mgridfs_setxattr; mgridfsOps.getxattr = mgridfs::mgridfs_getxattr; mgridfsOps.listxattr = mgridfs::mgridfs_listxattr; mgridfsOps.removexattr = mgridfs::mgridfs_removexattr; mgridfsOps.chmod = mgridfs::mgridfs_chmod; mgridfsOps.chown = mgridfs::mgridfs_chown; mgridfsOps.utime = mgridfs::mgridfs_utime; mgridfsOps.utimens = mgridfs::mgridfs_utimens; mgridfsOps.mknod = mgridfs::mgridfs_mknod; // Directory functionality mgridfsOps.mkdir = mgridfs::mgridfs_mkdir; mgridfsOps.rmdir = mgridfs::mgridfs_rmdir; mgridfsOps.opendir = mgridfs::mgridfs_opendir; mgridfsOps.readdir = mgridfs::mgridfs_readdir; mgridfsOps.releasedir = mgridfs::mgridfs_releasedir; mgridfsOps.fsyncdir = mgridfs::mgridfs_fsyncdir; // File linking functionality functions mgridfsOps.link = NULL; // Hard-links are not supported mgridfsOps.readlink = mgridfs::mgridfs_readlink; mgridfsOps.unlink = mgridfs::mgridfs_unlink; mgridfsOps.symlink = mgridfs::mgridfs_symlink; // Normal file related operations mgridfsOps.rename = mgridfs::mgridfs_rename; mgridfsOps.truncate = mgridfs::mgridfs_truncate; mgridfsOps.ftruncate = mgridfs::mgridfs_ftruncate; mgridfsOps.open = mgridfs::mgridfs_open; mgridfsOps.read = mgridfs::mgridfs_read; mgridfsOps.write = mgridfs::mgridfs_write; mgridfsOps.flush = mgridfs::mgridfs_flush; mgridfsOps.release = mgridfs::mgridfs_release; mgridfsOps.fsync = mgridfs::mgridfs_fsync; mgridfsOps.create = mgridfs::mgridfs_create; mgridfsOps.lock = mgridfs::mgridfs_lock; mgridfsOps.bmap = mgridfs::mgridfs_bmap; mgridfsOps.ioctl = mgridfs::mgridfs_ioctl; mgridfsOps.poll = mgridfs::mgridfs_poll; mgridfsOps.write_buf = mgridfs::mgridfs_write_buf; mgridfsOps.read_buf = mgridfs::mgridfs_read_buf; mgridfsOps.flock = mgridfs::mgridfs_flock; mgridfsOps.fallocate = mgridfs::mgridfs_fallocate; struct fuse_args fuseArgs = FUSE_ARGS_INIT(argc, argv); if (!mgridfs::globalFSOptions.fromCommandLine(fuseArgs)) { std::cerr << "ERROR: Failed to parse options passed to program, will not mount file system" << std::endl; return 1; } fuse_main(fuseArgs.argc, fuseArgs.argv, &mgridfsOps, NULL); return 0; } <|endoftext|>
<commit_before>// // scheduler_object.cpp // fibio // // Created by Chen Xu on 14-3-5. // Copyright (c) 2014 0d0a.com. All rights reserved. // #include <fibio/fibers/fiber.hpp> #include "scheduler_object.hpp" namespace fibio { namespace fibers { namespace detail { std::once_flag scheduler_object::instance_inited_; std::shared_ptr<scheduler_object> scheduler_object::the_instance_; scheduler_object::scheduler_object() : fiber_count_(0) , started_(false) {} fiber_ptr_t scheduler_object::make_fiber(std::function<void()> &&entry) { std::lock_guard<std::mutex> guard(m_); fiber_count_++; fiber_ptr_t ret(std::make_shared<fiber_object>(shared_from_this(), std::move(entry))); if (!started_) { started_=true; } ret->schedule(); return ret; } void scheduler_object::start(size_t nthr) { std::lock_guard<std::mutex> guard(m_); if (threads_.size()>0) { // Already started return; } else { //fiber_count_=0; } if (!check_timer_) { check_timer_=std::make_shared<timer_t>(io_service_); } check_timer_->expires_from_now(std::chrono::seconds(1)); scheduler_ptr_t pthis(shared_from_this()); check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); }); for(size_t i=0; i<nthr; i++) { threads_.push_back(std::thread([pthis](){ pthis->io_service_.run(); })); } } void scheduler_object::join() { for(std::thread &t : threads_) { t.join(); } } /* void scheduler_object::add_thread(size_t nthr) { std::lock_guard<std::mutex> guard(m_); scheduler_ptr_t pthis(shared_from_this()); for(size_t i=0; i<nthr; i++) { threads_.push_back(std::thread([pthis](){ pthis->io_service_.run(); })); } } */ void scheduler_object::on_fiber_exit() { std::lock_guard<std::mutex> guard(m_); fiber_count_--; } void scheduler_object::on_check_timer(std::error_code ec) { std::lock_guard<std::mutex> guard(m_); if (fiber_count_>0 || !started_) { //printf("Active fiber %lu", size_t(fiber_count_)); check_timer_->expires_from_now(std::chrono::milliseconds(50)); scheduler_ptr_t pthis(shared_from_this()); check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); }); } else { io_service_.stop(); } } std::shared_ptr<scheduler_object> scheduler_object::get_instance() { std::call_once(instance_inited_, [](){ scheduler_object::the_instance_=std::make_shared<scheduler_object>(); }); return scheduler_object::the_instance_; } }}} // End of namespace fibio::fibers::detail namespace fibio { namespace fibers { scheduler::scheduler() : m_(std::make_shared<detail::scheduler_object>()) {} scheduler::scheduler(std::shared_ptr<detail::scheduler_object> m) : m_(m) {} void scheduler::start(size_t nthr) { m_->start(nthr); } void scheduler::join() { m_->join(); } /* void scheduler::add_worker_thread(size_t nthr) { m_->add_thread(nthr); } */ scheduler scheduler::get_instance() { return scheduler(detail::scheduler_object::get_instance()); } }} // End of namespace fibio::fibers <commit_msg>Reset scheduler after joining<commit_after>// // scheduler_object.cpp // fibio // // Created by Chen Xu on 14-3-5. // Copyright (c) 2014 0d0a.com. All rights reserved. // #include <fibio/fibers/fiber.hpp> #include "scheduler_object.hpp" namespace fibio { namespace fibers { namespace detail { std::once_flag scheduler_object::instance_inited_; std::shared_ptr<scheduler_object> scheduler_object::the_instance_; scheduler_object::scheduler_object() : fiber_count_(0) , started_(false) {} fiber_ptr_t scheduler_object::make_fiber(std::function<void()> &&entry) { std::lock_guard<std::mutex> guard(m_); fiber_count_++; fiber_ptr_t ret(std::make_shared<fiber_object>(shared_from_this(), std::move(entry))); if (!started_) { started_=true; } ret->schedule(); return ret; } void scheduler_object::start(size_t nthr) { std::lock_guard<std::mutex> guard(m_); if (threads_.size()>0) { // Already started return; } else { //fiber_count_=0; } if (!check_timer_) { check_timer_=std::make_shared<timer_t>(io_service_); } check_timer_->expires_from_now(std::chrono::seconds(1)); scheduler_ptr_t pthis(shared_from_this()); check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); }); for(size_t i=0; i<nthr; i++) { threads_.push_back(std::thread([pthis](){ pthis->io_service_.run(); })); } } void scheduler_object::join() { for(std::thread &t : threads_) { t.join(); } threads_.clear(); started_=false; io_service_.reset(); } /* void scheduler_object::add_thread(size_t nthr) { std::lock_guard<std::mutex> guard(m_); scheduler_ptr_t pthis(shared_from_this()); for(size_t i=0; i<nthr; i++) { threads_.push_back(std::thread([pthis](){ pthis->io_service_.run(); })); } } */ void scheduler_object::on_fiber_exit() { std::lock_guard<std::mutex> guard(m_); fiber_count_--; } void scheduler_object::on_check_timer(std::error_code ec) { std::lock_guard<std::mutex> guard(m_); if (fiber_count_>0 || !started_) { //printf("Active fiber %lu", size_t(fiber_count_)); check_timer_->expires_from_now(std::chrono::milliseconds(50)); scheduler_ptr_t pthis(shared_from_this()); check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); }); } else { io_service_.stop(); } } std::shared_ptr<scheduler_object> scheduler_object::get_instance() { std::call_once(instance_inited_, [](){ scheduler_object::the_instance_=std::make_shared<scheduler_object>(); }); return scheduler_object::the_instance_; } }}} // End of namespace fibio::fibers::detail namespace fibio { namespace fibers { scheduler::scheduler() : m_(std::make_shared<detail::scheduler_object>()) {} scheduler::scheduler(std::shared_ptr<detail::scheduler_object> m) : m_(m) {} void scheduler::start(size_t nthr) { m_->start(nthr); } void scheduler::join() { m_->join(); } /* void scheduler::add_worker_thread(size_t nthr) { m_->add_thread(nthr); } */ scheduler scheduler::get_instance() { return scheduler(detail::scheduler_object::get_instance()); } }} // End of namespace fibio::fibers <|endoftext|>
<commit_before>8fd04912-2d14-11e5-af21-0401358ea401<commit_msg>8fd04913-2d14-11e5-af21-0401358ea401<commit_after>8fd04913-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>78a20910-2d53-11e5-baeb-247703a38240<commit_msg>78a29330-2d53-11e5-baeb-247703a38240<commit_after>78a29330-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>// Main.cpp //============================ //=========================== // Include Dependencies #include <iostream> #include <math.h> #include <string> #include <vector> #include <fstream> #include "phys.h" #include "coord.h" //#include "node.h" #include "cell.h" #include "tissue.h" //============================== using namespace std; //============================ int main() { string init_tissue = "cell_start.txt"; //make a new cell object Tissue growing_Tissue(init_tissue); cout << "Finished creating Cell" << endl; //parameters for time step double numSteps = 40; // Variable for dataoutput int digits; string format = ".vtk"; string Number; string initial = "Animation/Plant_Cell_"; string Filename; ofstream ofs; int out = 0; //counter for creating output/vtk files //loop for time steps for(int Ti = 0; Ti*dt < numSteps; Ti++) { //loop through all cells //for now only one cell //Print to dataOutput and VTK files if (Ti % 250 == 0) { digits = ceil(log10(out + 1)); if (digits == 1 || digits == 0) { Number = "0000" + to_string(out); } else if (digits == 2) { Number = "000" + to_string(out); } else if (digits == 3) { Number = "00" + to_string(out); } else if (digits == 4) { Number = "0" + to_string(out); } Filename = initial + Number + format; ofs.open(Filename.c_str()); growing_Tissue.print_VTK_File(ofs); ofs.close(); out++; } if (Ti % 1000 == 0) { cout << "Simulation still running. Ti: " << Ti << endl; } //New Tissue GRowth growing_Tissue.grow_Cells(Ti); //Calculate new forces on cells and nodes growing_Tissue.calc_New_Forces(); //Update node positions growing_Tissue.update_Cell_Locations(); } return 0; } <commit_msg>setup for timing<commit_after>// Main.cpp //============================ //=========================== // Include Dependencies #include <iostream> #include <math.h> #include <string> #include <vector> #include <fstream> #include <ctime> #include "phys.h" #include "coord.h" //#include "node.h" #include "cell.h" #include "tissue.h" //============================== using namespace std; //============================ int main() { int start = clock(); string init_tissue = "cell_start.txt"; //make a new cell object Tissue growing_Tissue(init_tissue); cout << "Finished creating Cell" << endl; //parameters for time step double numSteps = 20; // Variable for dataoutput int digits; string format = ".vtk"; string Number; string initial = "Animation/Plant_Cell_"; string Filename; ofstream ofs; int out = 0; //counter for creating output/vtk files //loop for time steps for(int Ti = 0; Ti*dt < numSteps; Ti++) { //loop through all cells //for now only one cell //Print to dataOutput and VTK files if (Ti % 250 == 0) { digits = ceil(log10(out + 1)); if (digits == 1 || digits == 0) { Number = "0000" + to_string(out); } else if (digits == 2) { Number = "000" + to_string(out); } else if (digits == 3) { Number = "00" + to_string(out); } else if (digits == 4) { Number = "0" + to_string(out); } Filename = initial + Number + format; ofs.open(Filename.c_str()); growing_Tissue.print_VTK_File(ofs); ofs.close(); out++; } if (Ti % 1000 == 0) { cout << "Simulation still running. Ti: " << Ti << endl; } //New Tissue GRowth growing_Tissue.grow_Cells(Ti); //Calculate new forces on cells and nodes growing_Tissue.calc_New_Forces(); //Update node positions growing_Tissue.update_Cell_Locations(); } int stop = clock(); cout << "Time: " << (stop - start) / double(CLOCKS_PER_SEC) * 1000 << endl; return 0; } <|endoftext|>
<commit_before>4098431c-5216-11e5-ab40-6c40088e03e4<commit_msg>409fa6f4-5216-11e5-8fc0-6c40088e03e4<commit_after>409fa6f4-5216-11e5-8fc0-6c40088e03e4<|endoftext|>
<commit_before>0c718d5c-2748-11e6-bc80-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>0c7d205e-2748-11e6-bc2c-e0f84713e7b8<|endoftext|>
<commit_before>f56d62d2-585a-11e5-bb9f-6c40088e03e4<commit_msg>f573c56e-585a-11e5-a64c-6c40088e03e4<commit_after>f573c56e-585a-11e5-a64c-6c40088e03e4<|endoftext|>
<commit_before>/** * Released under the same permissive MIT-license as Urho3D. * https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt */ #include <string> #include <memory> #include <fstream> #include <sstream> #include <Urho3D/Urho3D.h> #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Graphics/RenderPath.h> #include <Urho3D/Engine/Application.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/IO/Log.h> #include <Urho3D/UI/UI.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/Font.h> #include <Urho3D/UI/Button.h> #include <Urho3D/UI/UIEvents.h> #include <Urho3D/UI/Window.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Graphics/Geometry.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/DebugRenderer.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/Graphics/Light.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/Graphics/StaticModel.h> #include <Urho3D/Graphics/Material.h> #include <Urho3D/Graphics/Skybox.h> #include <Urho3D/Graphics/Zone.h> #include <Urho3D/Audio/Sound.h> #include <Urho3D/Audio/SoundSource3D.h> #include <Urho3D/Audio/SoundListener.h> #include <Urho3D/Audio/Audio.h> #include <Urho3D/Graphics/ParticleEmitter.h> #include <Urho3D/Graphics/ParticleEffect.h> #include <Urho3D/Graphics/Terrain.h> using namespace Urho3D; /// \brief Calls SetModel on the given model and tries to load the model file and all texture files mentioned in a model_name+".txt". /// model_name is supposed to have no file extension. Example: "Data/Models/Box", loads the model "Data/Models/Box.mdl". /// It's a template to support all model classes like AnimatedModel and StaticModel. template<typename T> void set_model(T* model,Urho3D::ResourceCache* cache,std::string model_name) { std::string filename_model=model_name; model->SetModel(cache->GetResource<Urho3D::Model>(Urho3D::String(filename_model.append(".mdl").c_str()))); std::string filename_txt=model_name; filename_txt.append(".txt"); std::ifstream file(filename_txt.c_str()); std::string line; if(file.is_open()) for(int i=0;getline(file,line);i++) model->SetMaterial(i,cache->GetResource<Urho3D::Material>(Urho3D::String(line.c_str()))); } /// SampleApplication main class mainly used for setup. The control is then given to the game states (starting with gs_main_menu). class SampleApplication : public Application { public: SharedPtr<Scene> scene_; Node* cameraNode_; SharedPtr<Urho3D::Node> node_rotating_planet; Urho3D::Text* window_text; SharedPtr<Urho3D::Window> window; Urho3D::Terrain* terrain; Urho3D::Camera* camera_; SharedPtr<Node> skyNode; SharedPtr<Node> node_torch; SharedPtr<Node> lightNode; SampleApplication(Context * context) : Application(context) {} virtual void Setup() { engineParameters_["FullScreen"]=false; engineParameters_["WindowWidth"]=1280; engineParameters_["WindowHeight"]=720; engineParameters_["WindowResizable"]=true; //engineParameters_["Multisample"]=16; } virtual void Start() { ResourceCache* cache=GetSubsystem<ResourceCache>(); GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml")); scene_=new Scene(context_); scene_->CreateComponent<Octree>(); scene_->CreateComponent<DebugRenderer>(); cameraNode_=scene_->CreateChild("Camera"); camera_=cameraNode_->CreateComponent<Camera>(); camera_->SetFarClip(50000); camera_->SetNearClip(0.01); camera_->SetFov(75); SoundListener* listener=cameraNode_->CreateComponent<SoundListener>(); GetSubsystem<Audio>()->SetListener(listener); GetSubsystem<Audio>()->SetMasterGain(SOUND_MUSIC,0.3); Renderer* renderer=GetSubsystem<Renderer>(); SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>())); renderer->SetViewport(0,viewport); renderer->SetShadowMapSize(1024); renderer->SetHDRRendering(true); RenderPath* effectRenderPath=viewport->GetRenderPath(); effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml")); //effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR.xml")); effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR_stronger.xml")); effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml")); Node* zoneNode=scene_->CreateChild("Zone"); Zone* zone=zoneNode->CreateComponent<Zone>(); zone->SetBoundingBox(BoundingBox(-50000.0f,50000.0f)); zone->SetFogStart(100000.0f); zone->SetFogEnd(200000.0f); zone->SetAmbientColor(Color(0.1,0.1,0.1)); SubscribeToEvent(E_KEYDOWN,URHO3D_HANDLER(SampleApplication,HandleKeyDown)); SubscribeToEvent(E_UPDATE,URHO3D_HANDLER(SampleApplication,HandleUpdate)); cameraNode_->SetPosition(Vector3(0,0,0)); cameraNode_->SetDirection(Vector3::FORWARD); // create a transparent window with some text to display things like help and FPS { window=new Window(context_); GetSubsystem<UI>()->GetRoot()->AddChild(window); window->SetStyle("Window"); window->SetSize(600,70); window->SetColor(Color(.0,.15,.3,.5)); window->SetAlignment(HA_LEFT,VA_TOP); window_text=new Text(context_); window_text->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),14); window_text->SetColor(Color(.8,.85,.9)); window_text->SetAlignment(HA_LEFT,VA_TOP); window->AddChild(window_text); } // a rotating planet { node_rotating_planet=scene_->CreateChild("Planet"); node_rotating_planet->SetPosition(Vector3(-4,1.6,6)); node_rotating_planet->Scale(2); StaticModel* boxObject=node_rotating_planet->CreateComponent<StaticModel>(); boxObject->SetModel(cache->GetResource<Model>("Models/planet.mdl")); boxObject->SetMaterial(cache->GetResource<Material>("Materials/planet_dsn.xml")); boxObject->SetCastShadows(true); } // skybox { skyNode=scene_->CreateChild("Sky"); skyNode->SetScale(1500.0f); Skybox* skybox=skyNode->CreateComponent<Skybox>(); skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl")); skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml")); } // a torch with a light, sound and particle effects { node_torch=scene_->CreateChild("Light"); Vector3 pos(Vector3(3,-0.5,6)); node_torch->SetPosition(pos); StaticModel* boxObject=node_torch->CreateComponent<StaticModel>(); set_model(boxObject,cache,"Data/Models/torch"); boxObject->SetCastShadows(true); boxObject->SetOccludee(true); boxObject->SetShadowDistance(200); boxObject->SetDrawDistance(200); Node* lightNode=node_torch->CreateChild(); lightNode->Translate(Vector3(0,2,0)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(50); light->SetBrightness(1.2); light->SetColor(Color(1.0,0.6,0.3,1.0)); light->SetCastShadows(true); light->SetShadowDistance(200); light->SetDrawDistance(200); Node* n_particle=node_torch->CreateChild(); n_particle->Translate(Vector3(0,1.6,0)); ParticleEmitter* emitter=n_particle->CreateComponent<ParticleEmitter>(); emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_fire.xml")); emitter=n_particle->CreateComponent<ParticleEmitter>(); emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_smoke.xml")); Sound* sound_torch=cache->GetResource<Sound>("Sounds/torch.ogg"); sound_torch->SetLooped(true); SoundSource3D* sound_torch_source=n_particle->CreateComponent<SoundSource3D>(); sound_torch_source->SetNearDistance(1); sound_torch_source->SetFarDistance(50); sound_torch_source->SetSoundType(SOUND_EFFECT); sound_torch_source->Play(sound_torch); } // sun { lightNode=scene_->CreateChild("Light"); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_DIRECTIONAL); light->SetCastShadows(true); light->SetShadowBias(BiasParameters(0.00000025f,0.1f)); light->SetShadowCascade(CascadeParameters(20.0f,60.0f,180.0f,560.0f,100.0f,100.0f)); light->SetShadowResolution(1.0); light->SetBrightness(1.0); light->SetColor(Color(1.0,0.9,0.8,1)); lightNode->SetDirection(Vector3::FORWARD); lightNode->Yaw(-150); // horizontal lightNode->Pitch(30); // vertical lightNode->Translate(Vector3(0,0,-20000)); BillboardSet* billboardObject=lightNode->CreateComponent<BillboardSet>(); billboardObject->SetNumBillboards(1); billboardObject->SetMaterial(cache->GetResource<Material>("Materials/sun.xml")); billboardObject->SetSorted(true); Billboard* bb=billboardObject->GetBillboard(0); bb->size_=Vector2(10000,10000); bb->rotation_=Random()*360.0f; bb->enabled_=true; billboardObject->Commit(); } { Node* terrainNode=scene_->CreateChild("Terrain"); terrainNode->SetPosition(Vector3(3.0f,-0.4f)); terrain=terrainNode->CreateComponent<Terrain>(); terrain->SetPatchSize(128); terrain->SetSpacing(Vector3(2,0.5,2)); terrain->SetSmoothing(true); terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png")); terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml")); terrain->SetCastShadows(true); terrain->SetOccluder(true); } } virtual void Stop() { } void HandleUpdate(StringHash eventType,VariantMap& eventData) { float timeStep=eventData[Update::P_TIMESTEP].GetFloat(); std::string str="WASD, mouse and shift to move. T to toggle fill mode,\nG to toggle GUI, Tab to toggle mouse mode, Esc to quit.\n"; { std::ostringstream ss; ss<<1/timeStep; std::string s(ss.str()); str.append(s.substr(0,6)); } str.append(" FPS "); String s(str.c_str(),str.size()); window_text->SetText(s); node_rotating_planet->Rotate(Quaternion(0,-22*timeStep,0)); // Movement speed as world units per second float MOVE_SPEED=10.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY=0.1f; // camera movement Input* input=GetSubsystem<Input>(); if(input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt MOVE_SPEED*=10; if(input->GetKeyDown('W')) cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep); if(input->GetKeyDown('S')) cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep); if(input->GetKeyDown('A')) cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep); if(input->GetKeyDown('D')) cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep); if(!GetSubsystem<Input>()->IsMouseVisible()) { IntVector2 mouseMove=input->GetMouseMove(); if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000) { static float yaw_=0; static float pitch_=0; yaw_+=MOUSE_SENSITIVITY*mouseMove.x_; pitch_+=MOUSE_SENSITIVITY*mouseMove.y_; pitch_=Clamp(pitch_,-90.0f,90.0f); // Reset rotation and set yaw and pitch again cameraNode_->SetDirection(Vector3::FORWARD); cameraNode_->Yaw(yaw_); cameraNode_->Pitch(pitch_); } } } void HandleKeyDown(StringHash eventType,VariantMap& eventData) { using namespace KeyDown; int key=eventData[P_KEY].GetInt(); if(key==KEY_TAB) { GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible()); GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed()); } else if(key==KEY_ESC) engine_->Exit(); else if(key==KEY_G) window_text->SetVisible(!window_text->IsVisible()); else if(key==KEY_T) camera_->SetFillMode(camera_->GetFillMode()==FILL_WIREFRAME?FILL_SOLID:FILL_WIREFRAME); } }; URHO3D_DEFINE_APPLICATION_MAIN(SampleApplication) <commit_msg>Fixed shadow stripe issue in DX11 and torch position.<commit_after>/** * Released under the same permissive MIT-license as Urho3D. * https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt */ #include <string> #include <memory> #include <fstream> #include <sstream> #include <Urho3D/Urho3D.h> #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Graphics/RenderPath.h> #include <Urho3D/Engine/Application.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/IO/Log.h> #include <Urho3D/UI/UI.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/Font.h> #include <Urho3D/UI/Button.h> #include <Urho3D/UI/UIEvents.h> #include <Urho3D/UI/Window.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Graphics/Geometry.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/DebugRenderer.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/Graphics/Light.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/Graphics/StaticModel.h> #include <Urho3D/Graphics/Material.h> #include <Urho3D/Graphics/Skybox.h> #include <Urho3D/Graphics/Zone.h> #include <Urho3D/Audio/Sound.h> #include <Urho3D/Audio/SoundSource3D.h> #include <Urho3D/Audio/SoundListener.h> #include <Urho3D/Audio/Audio.h> #include <Urho3D/Graphics/ParticleEmitter.h> #include <Urho3D/Graphics/ParticleEffect.h> #include <Urho3D/Graphics/Terrain.h> using namespace Urho3D; /// \brief Calls SetModel on the given model and tries to load the model file and all texture files mentioned in a model_name+".txt". /// model_name is supposed to have no file extension. Example: "Data/Models/Box", loads the model "Data/Models/Box.mdl". /// It's a template to support all model classes like AnimatedModel and StaticModel. template<typename T> void set_model(T* model,Urho3D::ResourceCache* cache,std::string model_name) { std::string filename_model=model_name; model->SetModel(cache->GetResource<Urho3D::Model>(Urho3D::String(filename_model.append(".mdl").c_str()))); std::string filename_txt=model_name; filename_txt.append(".txt"); std::ifstream file(filename_txt.c_str()); std::string line; if(file.is_open()) for(int i=0;getline(file,line);i++) model->SetMaterial(i,cache->GetResource<Urho3D::Material>(Urho3D::String(line.c_str()))); } /// SampleApplication main class mainly used for setup. The control is then given to the game states (starting with gs_main_menu). class SampleApplication : public Application { public: SharedPtr<Scene> scene_; Node* cameraNode_; SharedPtr<Urho3D::Node> node_rotating_planet; Urho3D::Text* window_text; SharedPtr<Urho3D::Window> window; Urho3D::Terrain* terrain; Urho3D::Camera* camera_; SharedPtr<Node> skyNode; SharedPtr<Node> node_torch; SharedPtr<Node> lightNode; SampleApplication(Context * context) : Application(context) {} virtual void Setup() { engineParameters_["FullScreen"]=false; engineParameters_["WindowWidth"]=1280; engineParameters_["WindowHeight"]=720; engineParameters_["WindowResizable"]=true; //engineParameters_["Multisample"]=16; } virtual void Start() { ResourceCache* cache=GetSubsystem<ResourceCache>(); GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml")); scene_=new Scene(context_); scene_->CreateComponent<Octree>(); scene_->CreateComponent<DebugRenderer>(); cameraNode_=scene_->CreateChild("Camera"); camera_=cameraNode_->CreateComponent<Camera>(); camera_->SetFarClip(50000); camera_->SetNearClip(0.01); camera_->SetFov(75); SoundListener* listener=cameraNode_->CreateComponent<SoundListener>(); GetSubsystem<Audio>()->SetListener(listener); GetSubsystem<Audio>()->SetMasterGain(SOUND_MUSIC,0.3); Renderer* renderer=GetSubsystem<Renderer>(); SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>())); renderer->SetViewport(0,viewport); renderer->SetShadowMapSize(1024); renderer->SetHDRRendering(true); RenderPath* effectRenderPath=viewport->GetRenderPath(); effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml")); //effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR.xml")); effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR_stronger.xml")); effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml")); Node* zoneNode=scene_->CreateChild("Zone"); Zone* zone=zoneNode->CreateComponent<Zone>(); zone->SetBoundingBox(BoundingBox(-50000.0f,50000.0f)); zone->SetFogStart(100000.0f); zone->SetFogEnd(200000.0f); zone->SetAmbientColor(Color(0.1,0.1,0.1)); SubscribeToEvent(E_KEYDOWN,URHO3D_HANDLER(SampleApplication,HandleKeyDown)); SubscribeToEvent(E_UPDATE,URHO3D_HANDLER(SampleApplication,HandleUpdate)); cameraNode_->SetPosition(Vector3(0,0,0)); cameraNode_->SetDirection(Vector3::FORWARD); // create a transparent window with some text to display things like help and FPS { window=new Window(context_); GetSubsystem<UI>()->GetRoot()->AddChild(window); window->SetStyle("Window"); window->SetSize(600,70); window->SetColor(Color(.0,.15,.3,.5)); window->SetAlignment(HA_LEFT,VA_TOP); window_text=new Text(context_); window_text->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),14); window_text->SetColor(Color(.8,.85,.9)); window_text->SetAlignment(HA_LEFT,VA_TOP); window->AddChild(window_text); } // a rotating planet { node_rotating_planet=scene_->CreateChild("Planet"); node_rotating_planet->SetPosition(Vector3(-4,1.6,6)); node_rotating_planet->Scale(2); StaticModel* boxObject=node_rotating_planet->CreateComponent<StaticModel>(); boxObject->SetModel(cache->GetResource<Model>("Models/planet.mdl")); boxObject->SetMaterial(cache->GetResource<Material>("Materials/planet_dsn.xml")); boxObject->SetCastShadows(true); } // skybox { skyNode=scene_->CreateChild("Sky"); skyNode->SetScale(1500.0f); Skybox* skybox=skyNode->CreateComponent<Skybox>(); skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl")); skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml")); } // a torch with a light, sound and particle effects { node_torch=scene_->CreateChild("Torch"); Vector3 pos(Vector3(3,-0.3,6)); node_torch->SetPosition(pos); StaticModel* boxObject=node_torch->CreateComponent<StaticModel>(); set_model(boxObject,cache,"Data/Models/torch"); boxObject->SetCastShadows(true); boxObject->SetOccludee(true); boxObject->SetShadowDistance(200); boxObject->SetDrawDistance(200); Node* lightNode=node_torch->CreateChild(); lightNode->Translate(Vector3(0,2,0)); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_POINT); light->SetRange(50); light->SetBrightness(1.2); light->SetColor(Color(1.0,0.6,0.3,1.0)); light->SetCastShadows(true); light->SetShadowDistance(200); light->SetDrawDistance(200); Node* n_particle=node_torch->CreateChild(); n_particle->Translate(Vector3(0,1.6,0)); ParticleEmitter* emitter=n_particle->CreateComponent<ParticleEmitter>(); emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_fire.xml")); emitter=n_particle->CreateComponent<ParticleEmitter>(); emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_smoke.xml")); Sound* sound_torch=cache->GetResource<Sound>("Sounds/torch.ogg"); sound_torch->SetLooped(true); SoundSource3D* sound_torch_source=n_particle->CreateComponent<SoundSource3D>(); sound_torch_source->SetNearDistance(1); sound_torch_source->SetFarDistance(50); sound_torch_source->SetSoundType(SOUND_EFFECT); sound_torch_source->Play(sound_torch); } // sun { lightNode=scene_->CreateChild("Light"); Light* light=lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_DIRECTIONAL); light->SetCastShadows(true); light->SetShadowBias(BiasParameters(0.00002f,0.5f)); light->SetShadowCascade(CascadeParameters(10.0f,50.0f,200.0f,400.0f,0.8f)); light->SetShadowResolution(1.0); light->SetBrightness(1.0); light->SetColor(Color(1.0,0.9,0.8,1)); lightNode->SetDirection(Vector3::FORWARD); lightNode->Yaw(-150); // horizontal lightNode->Pitch(30); // vertical lightNode->Translate(Vector3(0,0,-20000)); BillboardSet* billboardObject=lightNode->CreateComponent<BillboardSet>(); billboardObject->SetNumBillboards(1); billboardObject->SetMaterial(cache->GetResource<Material>("Materials/sun.xml")); billboardObject->SetSorted(true); Billboard* bb=billboardObject->GetBillboard(0); bb->size_=Vector2(10000,10000); bb->rotation_=Random()*360.0f; bb->enabled_=true; billboardObject->Commit(); } { Node* terrainNode=scene_->CreateChild("Terrain"); terrainNode->SetPosition(Vector3(3.0f,-0.4f)); terrain=terrainNode->CreateComponent<Terrain>(); terrain->SetPatchSize(128); terrain->SetSpacing(Vector3(2,0.5,2)); terrain->SetSmoothing(true); terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png")); terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml")); terrain->SetCastShadows(true); terrain->SetOccluder(true); } } virtual void Stop() { } void HandleUpdate(StringHash eventType,VariantMap& eventData) { float timeStep=eventData[Update::P_TIMESTEP].GetFloat(); std::string str="WASD, mouse and shift to move. T to toggle fill mode,\nG to toggle GUI, Tab to toggle mouse mode, Esc to quit.\n"; { std::ostringstream ss; ss<<1/timeStep; std::string s(ss.str()); str.append(s.substr(0,6)); } str.append(" FPS "); String s(str.c_str(),str.size()); window_text->SetText(s); node_rotating_planet->Rotate(Quaternion(0,-22*timeStep,0)); // Movement speed as world units per second float MOVE_SPEED=10.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY=0.1f; // camera movement Input* input=GetSubsystem<Input>(); if(input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt MOVE_SPEED*=10; if(input->GetKeyDown('W')) cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep); if(input->GetKeyDown('S')) cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep); if(input->GetKeyDown('A')) cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep); if(input->GetKeyDown('D')) cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep); if(!GetSubsystem<Input>()->IsMouseVisible()) { IntVector2 mouseMove=input->GetMouseMove(); if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000) { static float yaw_=0; static float pitch_=0; yaw_+=MOUSE_SENSITIVITY*mouseMove.x_; pitch_+=MOUSE_SENSITIVITY*mouseMove.y_; pitch_=Clamp(pitch_,-90.0f,90.0f); // Reset rotation and set yaw and pitch again cameraNode_->SetDirection(Vector3::FORWARD); cameraNode_->Yaw(yaw_); cameraNode_->Pitch(pitch_); } } } void HandleKeyDown(StringHash eventType,VariantMap& eventData) { using namespace KeyDown; int key=eventData[P_KEY].GetInt(); if(key==KEY_TAB) { GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible()); GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed()); } else if(key==KEY_ESC) engine_->Exit(); else if(key==KEY_G) window_text->SetVisible(!window_text->IsVisible()); else if(key==KEY_T) camera_->SetFillMode(camera_->GetFillMode()==FILL_WIREFRAME?FILL_SOLID:FILL_WIREFRAME); } }; URHO3D_DEFINE_APPLICATION_MAIN(SampleApplication) <|endoftext|>
<commit_before>30ceaf5c-ad5c-11e7-88a7-ac87a332f658<commit_msg>GOD DAMNED IT!<commit_after>31252c26-ad5c-11e7-90fc-ac87a332f658<|endoftext|>
<commit_before>8fd04999-2d14-11e5-af21-0401358ea401<commit_msg>8fd0499a-2d14-11e5-af21-0401358ea401<commit_after>8fd0499a-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>a6cee2b0-2d3d-11e5-9e59-c82a142b6f9b<commit_msg>a7772bab-2d3d-11e5-8427-c82a142b6f9b<commit_after>a7772bab-2d3d-11e5-8427-c82a142b6f9b<|endoftext|>