text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tool to upload an exe/dll and its associated symbols to an HTTP server. // The PDB file is located automatically, using the path embedded in the // executable. The upload is sent as a multipart/form-data POST request, // with the following parameters: // code_file: the basename of the module, e.g. "app.exe" // debug_file: the basename of the debugging file, e.g. "app.pdb" // debug_identifier: the debug file's identifier, usually consisting of // the guid and age embedded in the pdb, e.g. // "11111111BBBB3333DDDD555555555555F" // product: the HTTP-friendly product name, e.g. "MyApp" // version: the file version of the module, e.g. "1.2.3.4" // os: the operating system that the module was built for, always // "windows" in this implementation. // cpu: the CPU that the module was built for, typically "x86". // symbol_file: the contents of the breakpad-format symbol file #include <windows.h> #include <dbghelp.h> #include <wininet.h> #include <cstdio> #include <map> #include <string> #include <vector> #include "common/windows/string_utils-inl.h" #include "common/windows/http_upload.h" #include "common/windows/pdb_source_line_writer.h" using std::string; using std::wstring; using std::vector; using std::map; using google_breakpad::HTTPUpload; using google_breakpad::PDBModuleInfo; using google_breakpad::PDBSourceLineWriter; using google_breakpad::WindowsStringUtils; // Extracts the file version information for the given filename, // as a string, for example, "1.2.3.4". Returns true on success. static bool GetFileVersionString(const wchar_t *filename, wstring *version) { DWORD handle; DWORD version_size = GetFileVersionInfoSize(filename, &handle); if (version_size < sizeof(VS_FIXEDFILEINFO)) { return false; } vector<char> version_info(version_size); if (!GetFileVersionInfo(filename, handle, version_size, &version_info[0])) { return false; } void *file_info_buffer = NULL; unsigned int file_info_length; if (!VerQueryValue(&version_info[0], L"\\", &file_info_buffer, &file_info_length)) { return false; } // The maximum value of each version component is 65535 (0xffff), // so the max length is 24, including the terminating null. wchar_t ver_string[24]; VS_FIXEDFILEINFO *file_info = reinterpret_cast<VS_FIXEDFILEINFO*>(file_info_buffer); swprintf(ver_string, sizeof(ver_string) / sizeof(ver_string[0]), L"%d.%d.%d.%d", file_info->dwFileVersionMS >> 16, file_info->dwFileVersionMS & 0xffff, file_info->dwFileVersionLS >> 16, file_info->dwFileVersionLS & 0xffff); // remove when VC++7.1 is no longer supported ver_string[sizeof(ver_string) / sizeof(ver_string[0]) - 1] = L'\0'; *version = ver_string; return true; } // Creates a new temporary file and writes the symbol data from the given // exe/dll file to it. Returns the path to the temp file in temp_file_path // and information about the pdb in pdb_info. static bool DumpSymbolsToTempFile(const wchar_t *file, wstring *temp_file_path, PDBModuleInfo *pdb_info) { google_breakpad::PDBSourceLineWriter writer; // Use EXE_FILE to get information out of the exe/dll in addition to the // pdb. The name and version number of the exe/dll are of value, and // there's no way to locate an exe/dll given a pdb. if (!writer.Open(file, PDBSourceLineWriter::EXE_FILE)) { return false; } wchar_t temp_path[_MAX_PATH]; if (GetTempPath(_MAX_PATH, temp_path) == 0) { return false; } wchar_t temp_filename[_MAX_PATH]; if (GetTempFileName(temp_path, L"sym", 0, temp_filename) == 0) { return false; } FILE *temp_file = NULL; #if _MSC_VER >= 1400 // MSVC 2005/8 if (_wfopen_s(&temp_file, temp_filename, L"w") != 0) #else // _MSC_VER >= 1400 // _wfopen_s was introduced in MSVC8. Use _wfopen for earlier environments. // Don't use it with MSVC8 and later, because it's deprecated. if (!(temp_file = _wfopen(temp_filename, L"w"))) #endif // _MSC_VER >= 1400 { return false; } bool success = writer.WriteMap(temp_file); fclose(temp_file); if (!success) { _wunlink(temp_filename); return false; } *temp_file_path = temp_filename; return writer.GetModuleInfo(pdb_info); } __declspec(noreturn) void printUsageAndExit() { wprintf(L"Usage:\n\n" L" symupload [--timeout NN] [--product product_name] ^\n" L" <file.exe|file.dll> <symbol upload URL> ^\n" L" [...<symbol upload URLs>]\n\n"); wprintf(L" - Timeout is in milliseconds, or can be 0 to be unlimited.\n"); wprintf(L" - product_name is an HTTP-friendly product name. It must only\n" L" contain an ascii subset: alphanumeric and punctuation.\n" L" This string is case-sensitive.\n\n"); wprintf(L"Example:\n\n" L" symupload.exe --timeout 0 --product Chrome ^\n" L" chrome.dll http://no.free.symbol.server.for.you\n"); exit(0); } int wmain(int argc, wchar_t *argv[]) { const wchar_t *module; const wchar_t *product = nullptr; int timeout = -1; int currentarg = 1; while (argc > currentarg + 1) { if (!wcscmp(L"--timeout", argv[currentarg])) { timeout = _wtoi(argv[currentarg + 1]); currentarg += 2; continue; } if (!wcscmp(L"--product", argv[currentarg])) { product = argv[currentarg + 1]; currentarg += 2; continue; } break; } if (argc >= currentarg + 2) module = argv[currentarg++]; else printUsageAndExit(); wstring symbol_file; PDBModuleInfo pdb_info; if (!DumpSymbolsToTempFile(module, &symbol_file, &pdb_info)) { fwprintf(stderr, L"Could not get symbol data from %s\n", module); return 1; } wstring code_file = WindowsStringUtils::GetBaseName(wstring(module)); map<wstring, wstring> parameters; parameters[L"code_file"] = code_file; parameters[L"debug_file"] = pdb_info.debug_file; parameters[L"debug_identifier"] = pdb_info.debug_identifier; parameters[L"os"] = L"windows"; // This version of symupload is Windows-only parameters[L"cpu"] = pdb_info.cpu; // Don't make a missing product name a hard error. Issue a warning and let // the server decide whether to reject files without product name. if (product) { parameters[L"product"] = product; } else { fwprintf( stderr, L"Warning: No product name (flag --product) was specified for %s\n", module); } // Don't make a missing version a hard error. Issue a warning, and let the // server decide whether to reject files without versions. wstring file_version; if (GetFileVersionString(module, &file_version)) { parameters[L"version"] = file_version; } else { fwprintf(stderr, L"Warning: Could not get file version for %s\n", module); } map<wstring, wstring> files; files[L"symbol_file"] = symbol_file; bool success = true; while (currentarg < argc) { int response_code; if (!HTTPUpload::SendRequest(argv[currentarg], parameters, files, timeout == -1 ? NULL : &timeout, nullptr, &response_code)) { success = false; fwprintf(stderr, L"Symbol file upload to %s failed. Response code = %ld\n", argv[currentarg], response_code); } currentarg++; } _wunlink(symbol_file.c_str()); if (success) { wprintf(L"Uploaded symbols for windows-%s/%s/%s (%s %s)\n", pdb_info.cpu.c_str(), pdb_info.debug_file.c_str(), pdb_info.debug_identifier.c_str(), code_file.c_str(), file_version.c_str()); } return success ? 0 : 1; } <commit_msg>Change symbol upload message to include 'breakpad'<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tool to upload an exe/dll and its associated symbols to an HTTP server. // The PDB file is located automatically, using the path embedded in the // executable. The upload is sent as a multipart/form-data POST request, // with the following parameters: // code_file: the basename of the module, e.g. "app.exe" // debug_file: the basename of the debugging file, e.g. "app.pdb" // debug_identifier: the debug file's identifier, usually consisting of // the guid and age embedded in the pdb, e.g. // "11111111BBBB3333DDDD555555555555F" // product: the HTTP-friendly product name, e.g. "MyApp" // version: the file version of the module, e.g. "1.2.3.4" // os: the operating system that the module was built for, always // "windows" in this implementation. // cpu: the CPU that the module was built for, typically "x86". // symbol_file: the contents of the breakpad-format symbol file #include <windows.h> #include <dbghelp.h> #include <wininet.h> #include <cstdio> #include <map> #include <string> #include <vector> #include "common/windows/string_utils-inl.h" #include "common/windows/http_upload.h" #include "common/windows/pdb_source_line_writer.h" using std::string; using std::wstring; using std::vector; using std::map; using google_breakpad::HTTPUpload; using google_breakpad::PDBModuleInfo; using google_breakpad::PDBSourceLineWriter; using google_breakpad::WindowsStringUtils; // Extracts the file version information for the given filename, // as a string, for example, "1.2.3.4". Returns true on success. static bool GetFileVersionString(const wchar_t *filename, wstring *version) { DWORD handle; DWORD version_size = GetFileVersionInfoSize(filename, &handle); if (version_size < sizeof(VS_FIXEDFILEINFO)) { return false; } vector<char> version_info(version_size); if (!GetFileVersionInfo(filename, handle, version_size, &version_info[0])) { return false; } void *file_info_buffer = NULL; unsigned int file_info_length; if (!VerQueryValue(&version_info[0], L"\\", &file_info_buffer, &file_info_length)) { return false; } // The maximum value of each version component is 65535 (0xffff), // so the max length is 24, including the terminating null. wchar_t ver_string[24]; VS_FIXEDFILEINFO *file_info = reinterpret_cast<VS_FIXEDFILEINFO*>(file_info_buffer); swprintf(ver_string, sizeof(ver_string) / sizeof(ver_string[0]), L"%d.%d.%d.%d", file_info->dwFileVersionMS >> 16, file_info->dwFileVersionMS & 0xffff, file_info->dwFileVersionLS >> 16, file_info->dwFileVersionLS & 0xffff); // remove when VC++7.1 is no longer supported ver_string[sizeof(ver_string) / sizeof(ver_string[0]) - 1] = L'\0'; *version = ver_string; return true; } // Creates a new temporary file and writes the symbol data from the given // exe/dll file to it. Returns the path to the temp file in temp_file_path // and information about the pdb in pdb_info. static bool DumpSymbolsToTempFile(const wchar_t *file, wstring *temp_file_path, PDBModuleInfo *pdb_info) { google_breakpad::PDBSourceLineWriter writer; // Use EXE_FILE to get information out of the exe/dll in addition to the // pdb. The name and version number of the exe/dll are of value, and // there's no way to locate an exe/dll given a pdb. if (!writer.Open(file, PDBSourceLineWriter::EXE_FILE)) { return false; } wchar_t temp_path[_MAX_PATH]; if (GetTempPath(_MAX_PATH, temp_path) == 0) { return false; } wchar_t temp_filename[_MAX_PATH]; if (GetTempFileName(temp_path, L"sym", 0, temp_filename) == 0) { return false; } FILE *temp_file = NULL; #if _MSC_VER >= 1400 // MSVC 2005/8 if (_wfopen_s(&temp_file, temp_filename, L"w") != 0) #else // _MSC_VER >= 1400 // _wfopen_s was introduced in MSVC8. Use _wfopen for earlier environments. // Don't use it with MSVC8 and later, because it's deprecated. if (!(temp_file = _wfopen(temp_filename, L"w"))) #endif // _MSC_VER >= 1400 { return false; } bool success = writer.WriteMap(temp_file); fclose(temp_file); if (!success) { _wunlink(temp_filename); return false; } *temp_file_path = temp_filename; return writer.GetModuleInfo(pdb_info); } __declspec(noreturn) void printUsageAndExit() { wprintf(L"Usage:\n\n" L" symupload [--timeout NN] [--product product_name] ^\n" L" <file.exe|file.dll> <symbol upload URL> ^\n" L" [...<symbol upload URLs>]\n\n"); wprintf(L" - Timeout is in milliseconds, or can be 0 to be unlimited.\n"); wprintf(L" - product_name is an HTTP-friendly product name. It must only\n" L" contain an ascii subset: alphanumeric and punctuation.\n" L" This string is case-sensitive.\n\n"); wprintf(L"Example:\n\n" L" symupload.exe --timeout 0 --product Chrome ^\n" L" chrome.dll http://no.free.symbol.server.for.you\n"); exit(0); } int wmain(int argc, wchar_t *argv[]) { const wchar_t *module; const wchar_t *product = nullptr; int timeout = -1; int currentarg = 1; while (argc > currentarg + 1) { if (!wcscmp(L"--timeout", argv[currentarg])) { timeout = _wtoi(argv[currentarg + 1]); currentarg += 2; continue; } if (!wcscmp(L"--product", argv[currentarg])) { product = argv[currentarg + 1]; currentarg += 2; continue; } break; } if (argc >= currentarg + 2) module = argv[currentarg++]; else printUsageAndExit(); wstring symbol_file; PDBModuleInfo pdb_info; if (!DumpSymbolsToTempFile(module, &symbol_file, &pdb_info)) { fwprintf(stderr, L"Could not get symbol data from %s\n", module); return 1; } wstring code_file = WindowsStringUtils::GetBaseName(wstring(module)); map<wstring, wstring> parameters; parameters[L"code_file"] = code_file; parameters[L"debug_file"] = pdb_info.debug_file; parameters[L"debug_identifier"] = pdb_info.debug_identifier; parameters[L"os"] = L"windows"; // This version of symupload is Windows-only parameters[L"cpu"] = pdb_info.cpu; // Don't make a missing product name a hard error. Issue a warning and let // the server decide whether to reject files without product name. if (product) { parameters[L"product"] = product; } else { fwprintf( stderr, L"Warning: No product name (flag --product) was specified for %s\n", module); } // Don't make a missing version a hard error. Issue a warning, and let the // server decide whether to reject files without versions. wstring file_version; if (GetFileVersionString(module, &file_version)) { parameters[L"version"] = file_version; } else { fwprintf(stderr, L"Warning: Could not get file version for %s\n", module); } map<wstring, wstring> files; files[L"symbol_file"] = symbol_file; bool success = true; while (currentarg < argc) { int response_code; if (!HTTPUpload::SendRequest(argv[currentarg], parameters, files, timeout == -1 ? NULL : &timeout, nullptr, &response_code)) { success = false; fwprintf(stderr, L"Symbol file upload to %s failed. Response code = %ld\n", argv[currentarg], response_code); } currentarg++; } _wunlink(symbol_file.c_str()); if (success) { wprintf(L"Uploaded breakpad symbols for windows-%s/%s/%s (%s %s)\n", pdb_info.cpu.c_str(), pdb_info.debug_file.c_str(), pdb_info.debug_identifier.c_str(), code_file.c_str(), file_version.c_str()); } return success ? 0 : 1; } <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGPercentageTest.html #include <gtest/gtest.h> #include <yoga/Yoga.h> TEST(YogaTest, cloning_shared_root) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child0, 1); YGNodeStyleSetFlexBasis(root_child0, 50); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child1, 1); YGNodeInsertChild(root, root_child1, 1); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetTop(root_child1)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child1)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1)); const YGNodeRef root2 = YGNodeClone(root); YGNodeStyleSetWidth(root2, 100); ASSERT_EQ(2, YGNodeGetChildCount(root2)); // The children should have referential equality at this point. ASSERT_EQ(root_child0, YGNodeGetChild(root2, 0)); ASSERT_EQ(root_child1, YGNodeGetChild(root2, 1)); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_EQ(2, YGNodeGetChildCount(root2)); // Relayout with no changed input should result in referential equality. ASSERT_EQ(root_child0, YGNodeGetChild(root2, 0)); ASSERT_EQ(root_child1, YGNodeGetChild(root2, 1)); YGNodeStyleSetWidth(root2, 150); YGNodeStyleSetHeight(root2, 200); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_EQ(2, YGNodeGetChildCount(root2)); // Relayout with changed input should result in cloned children. const YGNodeRef root2_child0 = YGNodeGetChild(root2, 0); const YGNodeRef root2_child1 = YGNodeGetChild(root2, 1); ASSERT_NE(root_child0, root2_child0); ASSERT_NE(root_child1, root2_child1); // Everything in the root should remain unchanged. ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetTop(root_child1)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child1)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1)); // The new root now has new layout. ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root2)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root2)); ASSERT_FLOAT_EQ(150, YGNodeLayoutGetWidth(root2)); ASSERT_FLOAT_EQ(200, YGNodeLayoutGetHeight(root2)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root2_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root2_child0)); ASSERT_FLOAT_EQ(150, YGNodeLayoutGetWidth(root2_child0)); ASSERT_FLOAT_EQ(125, YGNodeLayoutGetHeight(root2_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root2_child1)); ASSERT_FLOAT_EQ(125, YGNodeLayoutGetTop(root2_child1)); ASSERT_FLOAT_EQ(150, YGNodeLayoutGetWidth(root2_child1)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetHeight(root2_child1)); YGNodeFreeRecursive(root2); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, mutating_children_of_a_clone_clones) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); ASSERT_EQ(0, YGNodeGetChildCount(root)); const YGNodeRef root2 = YGNodeClone(root); ASSERT_EQ(0, YGNodeGetChildCount(root2)); const YGNodeRef root2_child0 = YGNodeNewWithConfig(config); YGNodeInsertChild(root2, root2_child0, 0); ASSERT_EQ(0, YGNodeGetChildCount(root)); ASSERT_EQ(1, YGNodeGetChildCount(root2)); const YGNodeRef root3 = YGNodeClone(root2); ASSERT_EQ(1, YGNodeGetChildCount(root2)); ASSERT_EQ(1, YGNodeGetChildCount(root3)); ASSERT_EQ(YGNodeGetChild(root2, 0), YGNodeGetChild(root3, 0)); const YGNodeRef root3_child1 = YGNodeNewWithConfig(config); YGNodeInsertChild(root3, root3_child1, 1); ASSERT_EQ(1, YGNodeGetChildCount(root2)); ASSERT_EQ(2, YGNodeGetChildCount(root3)); ASSERT_EQ(root3_child1, YGNodeGetChild(root3, 1)); ASSERT_NE(YGNodeGetChild(root2, 0), YGNodeGetChild(root3, 0)); const YGNodeRef root4 = YGNodeClone(root3); ASSERT_EQ(root3_child1, YGNodeGetChild(root4, 1)); YGNodeRemoveChild(root4, root3_child1); ASSERT_EQ(2, YGNodeGetChildCount(root3)); ASSERT_EQ(1, YGNodeGetChildCount(root4)); ASSERT_NE(YGNodeGetChild(root3, 0), YGNodeGetChild(root4, 0)); YGNodeFreeRecursive(root4); YGNodeFreeRecursive(root3); YGNodeFreeRecursive(root2); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, cloning_two_levels) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child0, 1); YGNodeStyleSetFlexBasis(root_child0, 15); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child1, 1); YGNodeInsertChild(root, root_child1, 1); const YGNodeRef root_child1_0 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexBasis(root_child1_0, 10); YGNodeStyleSetFlexGrow(root_child1_0, 1); YGNodeInsertChild(root_child1, root_child1_0, 0); const YGNodeRef root_child1_1 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexBasis(root_child1_1, 25); YGNodeInsertChild(root_child1, root_child1_1, 1); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(40, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(60, YGNodeLayoutGetHeight(root_child1)); ASSERT_FLOAT_EQ(35, YGNodeLayoutGetHeight(root_child1_0)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1_1)); const YGNodeRef root2_child0 = YGNodeClone(root_child0); const YGNodeRef root2_child1 = YGNodeClone(root_child1); const YGNodeRef root2 = YGNodeClone(root); YGNodeStyleSetFlexGrow(root2_child0, 0); YGNodeStyleSetFlexBasis(root2_child0, 40); YGNodeRemoveAllChildren(root2); YGNodeInsertChild(root2, root2_child0, 0); YGNodeInsertChild(root2, root2_child1, 1); ASSERT_EQ(2, YGNodeGetChildCount(root2)); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); // Original root is unchanged ASSERT_FLOAT_EQ(40, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(60, YGNodeLayoutGetHeight(root_child1)); ASSERT_FLOAT_EQ(35, YGNodeLayoutGetHeight(root_child1_0)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1_1)); // New root has new layout at the top ASSERT_FLOAT_EQ(40, YGNodeLayoutGetHeight(root2_child0)); ASSERT_FLOAT_EQ(60, YGNodeLayoutGetHeight(root2_child1)); // The deeper children are untouched. ASSERT_EQ(YGNodeGetChild(root2_child1, 0), root_child1_0); ASSERT_EQ(YGNodeGetChild(root2_child1, 1), root_child1_1); YGNodeFreeRecursive(root2); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, cloning_and_freeing) { const int32_t initialInstanceCount = YGNodeGetInstanceCount(); const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeInsertChild(root, root_child1, 1); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); const YGNodeRef root2 = YGNodeClone(root); // Freeing the original root should be safe as long as we don't free its // children. YGNodeFree(root); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); YGNodeFreeRecursive(root2); YGNodeFree(root_child0); YGNodeFree(root_child1); YGConfigFree(config); ASSERT_EQ(initialInstanceCount, YGNodeGetInstanceCount()); } <commit_msg>Removed misleading comment in YGPersistenceTest<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gtest/gtest.h> #include <yoga/Yoga.h> TEST(YogaTest, cloning_shared_root) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child0, 1); YGNodeStyleSetFlexBasis(root_child0, 50); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child1, 1); YGNodeInsertChild(root, root_child1, 1); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetTop(root_child1)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child1)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1)); const YGNodeRef root2 = YGNodeClone(root); YGNodeStyleSetWidth(root2, 100); ASSERT_EQ(2, YGNodeGetChildCount(root2)); // The children should have referential equality at this point. ASSERT_EQ(root_child0, YGNodeGetChild(root2, 0)); ASSERT_EQ(root_child1, YGNodeGetChild(root2, 1)); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_EQ(2, YGNodeGetChildCount(root2)); // Relayout with no changed input should result in referential equality. ASSERT_EQ(root_child0, YGNodeGetChild(root2, 0)); ASSERT_EQ(root_child1, YGNodeGetChild(root2, 1)); YGNodeStyleSetWidth(root2, 150); YGNodeStyleSetHeight(root2, 200); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_EQ(2, YGNodeGetChildCount(root2)); // Relayout with changed input should result in cloned children. const YGNodeRef root2_child0 = YGNodeGetChild(root2, 0); const YGNodeRef root2_child1 = YGNodeGetChild(root2, 1); ASSERT_NE(root_child0, root2_child0); ASSERT_NE(root_child1, root2_child1); // Everything in the root should remain unchanged. ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child0)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child1)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetTop(root_child1)); ASSERT_FLOAT_EQ(100, YGNodeLayoutGetWidth(root_child1)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1)); // The new root now has new layout. ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root2)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root2)); ASSERT_FLOAT_EQ(150, YGNodeLayoutGetWidth(root2)); ASSERT_FLOAT_EQ(200, YGNodeLayoutGetHeight(root2)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root2_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root2_child0)); ASSERT_FLOAT_EQ(150, YGNodeLayoutGetWidth(root2_child0)); ASSERT_FLOAT_EQ(125, YGNodeLayoutGetHeight(root2_child0)); ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root2_child1)); ASSERT_FLOAT_EQ(125, YGNodeLayoutGetTop(root2_child1)); ASSERT_FLOAT_EQ(150, YGNodeLayoutGetWidth(root2_child1)); ASSERT_FLOAT_EQ(75, YGNodeLayoutGetHeight(root2_child1)); YGNodeFreeRecursive(root2); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, mutating_children_of_a_clone_clones) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); ASSERT_EQ(0, YGNodeGetChildCount(root)); const YGNodeRef root2 = YGNodeClone(root); ASSERT_EQ(0, YGNodeGetChildCount(root2)); const YGNodeRef root2_child0 = YGNodeNewWithConfig(config); YGNodeInsertChild(root2, root2_child0, 0); ASSERT_EQ(0, YGNodeGetChildCount(root)); ASSERT_EQ(1, YGNodeGetChildCount(root2)); const YGNodeRef root3 = YGNodeClone(root2); ASSERT_EQ(1, YGNodeGetChildCount(root2)); ASSERT_EQ(1, YGNodeGetChildCount(root3)); ASSERT_EQ(YGNodeGetChild(root2, 0), YGNodeGetChild(root3, 0)); const YGNodeRef root3_child1 = YGNodeNewWithConfig(config); YGNodeInsertChild(root3, root3_child1, 1); ASSERT_EQ(1, YGNodeGetChildCount(root2)); ASSERT_EQ(2, YGNodeGetChildCount(root3)); ASSERT_EQ(root3_child1, YGNodeGetChild(root3, 1)); ASSERT_NE(YGNodeGetChild(root2, 0), YGNodeGetChild(root3, 0)); const YGNodeRef root4 = YGNodeClone(root3); ASSERT_EQ(root3_child1, YGNodeGetChild(root4, 1)); YGNodeRemoveChild(root4, root3_child1); ASSERT_EQ(2, YGNodeGetChildCount(root3)); ASSERT_EQ(1, YGNodeGetChildCount(root4)); ASSERT_NE(YGNodeGetChild(root3, 0), YGNodeGetChild(root4, 0)); YGNodeFreeRecursive(root4); YGNodeFreeRecursive(root3); YGNodeFreeRecursive(root2); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, cloning_two_levels) { const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child0, 1); YGNodeStyleSetFlexBasis(root_child0, 15); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexGrow(root_child1, 1); YGNodeInsertChild(root, root_child1, 1); const YGNodeRef root_child1_0 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexBasis(root_child1_0, 10); YGNodeStyleSetFlexGrow(root_child1_0, 1); YGNodeInsertChild(root_child1, root_child1_0, 0); const YGNodeRef root_child1_1 = YGNodeNewWithConfig(config); YGNodeStyleSetFlexBasis(root_child1_1, 25); YGNodeInsertChild(root_child1, root_child1_1, 1); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_FLOAT_EQ(40, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(60, YGNodeLayoutGetHeight(root_child1)); ASSERT_FLOAT_EQ(35, YGNodeLayoutGetHeight(root_child1_0)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1_1)); const YGNodeRef root2_child0 = YGNodeClone(root_child0); const YGNodeRef root2_child1 = YGNodeClone(root_child1); const YGNodeRef root2 = YGNodeClone(root); YGNodeStyleSetFlexGrow(root2_child0, 0); YGNodeStyleSetFlexBasis(root2_child0, 40); YGNodeRemoveAllChildren(root2); YGNodeInsertChild(root2, root2_child0, 0); YGNodeInsertChild(root2, root2_child1, 1); ASSERT_EQ(2, YGNodeGetChildCount(root2)); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); // Original root is unchanged ASSERT_FLOAT_EQ(40, YGNodeLayoutGetHeight(root_child0)); ASSERT_FLOAT_EQ(60, YGNodeLayoutGetHeight(root_child1)); ASSERT_FLOAT_EQ(35, YGNodeLayoutGetHeight(root_child1_0)); ASSERT_FLOAT_EQ(25, YGNodeLayoutGetHeight(root_child1_1)); // New root has new layout at the top ASSERT_FLOAT_EQ(40, YGNodeLayoutGetHeight(root2_child0)); ASSERT_FLOAT_EQ(60, YGNodeLayoutGetHeight(root2_child1)); // The deeper children are untouched. ASSERT_EQ(YGNodeGetChild(root2_child1, 0), root_child1_0); ASSERT_EQ(YGNodeGetChild(root2_child1, 1), root_child1_1); YGNodeFreeRecursive(root2); YGNodeFreeRecursive(root); YGConfigFree(config); } TEST(YogaTest, cloning_and_freeing) { const int32_t initialInstanceCount = YGNodeGetInstanceCount(); const YGConfigRef config = YGConfigNew(); const YGNodeRef root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 100); YGNodeStyleSetHeight(root, 100); const YGNodeRef root_child0 = YGNodeNewWithConfig(config); YGNodeInsertChild(root, root_child0, 0); const YGNodeRef root_child1 = YGNodeNewWithConfig(config); YGNodeInsertChild(root, root_child1, 1); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); const YGNodeRef root2 = YGNodeClone(root); // Freeing the original root should be safe as long as we don't free its // children. YGNodeFree(root); YGNodeCalculateLayout(root2, YGUndefined, YGUndefined, YGDirectionLTR); YGNodeFreeRecursive(root2); YGNodeFree(root_child0); YGNodeFree(root_child1); YGConfigFree(config); ASSERT_EQ(initialInstanceCount, YGNodeGetInstanceCount()); } <|endoftext|>
<commit_before>#pragma once #include <microscopes/common/assert.hpp> namespace lda_util { inline bool valid_probability_vector(const std::vector<float> &p){ float sum = 0; for(auto x: p){ if(isfinite(x) == false) return false; if(x < 0) return false; sum+=x; } return (std::abs(1 - sum) < 0.01); } template<typename T> void removeFirst(std::vector<T> &v, T element){ auto it = std::find(v.begin(),v.end(), element); if (it != v.end()) { v.erase(it); } } // http://stackoverflow.com/a/1267878/982745 template< class T > std::vector<T> selectByIndex(const std::vector<T> &v, const std::vector<size_t> &index ) { std::vector<T> new_v; new_v.reserve(index.size()); for(size_t i: index){ new_v.push_back(v[i]); } return new_v; } template<class T> void normalize(std::vector<T> &v){ Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> vec(v.data(), v.size()); vec /= vec.sum(); } template<class T, class J> class defaultdict{ J default_value; std::map<T, J> map; public: defaultdict(J val){ default_value = val; map = std::map<T, J>(); } J get(T t) { if(map.count(t) > 0){ return map[t]; } else{ return default_value; } } void set(T t, J j){ map[t] = j; } void incr(T t, J by){ if(map.count(t) > 0){ map[t] += by; } else{ map[t] = by + default_value; } } void decr(T t, J by){ if(map.count(t) > 0){ map[t] -= by; } else{ map[t] = default_value - by; } } bool contains(T t){ return map.count(t) > 0; } }; }<commit_msg>isfinite is in math.h<commit_after>#pragma once #include <math.h> namespace lda_util { inline bool valid_probability_vector(const std::vector<float> &p){ float sum = 0; for(auto x: p){ if(std::isfinite(x) == false) return false; if(x < 0) return false; sum+=x; } return (std::abs(1 - sum) < 0.01); } template<typename T> void removeFirst(std::vector<T> &v, T element){ auto it = std::find(v.begin(),v.end(), element); if (it != v.end()) { v.erase(it); } } // http://stackoverflow.com/a/1267878/982745 template< class T > std::vector<T> selectByIndex(const std::vector<T> &v, const std::vector<size_t> &index ) { std::vector<T> new_v; new_v.reserve(index.size()); for(size_t i: index){ new_v.push_back(v[i]); } return new_v; } template<class T> void normalize(std::vector<T> &v){ Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> vec(v.data(), v.size()); vec /= vec.sum(); } template<class T, class J> class defaultdict{ J default_value; std::map<T, J> map; public: defaultdict(J val){ default_value = val; map = std::map<T, J>(); } J get(T t) { if(map.count(t) > 0){ return map[t]; } else{ return default_value; } } void set(T t, J j){ map[t] = j; } void incr(T t, J by){ if(map.count(t) > 0){ map[t] += by; } else{ map[t] = by + default_value; } } void decr(T t, J by){ if(map.count(t) > 0){ map[t] -= by; } else{ map[t] = default_value - by; } } bool contains(T t){ return map.count(t) > 0; } }; }<|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <pcrecpp.h> #include "net/net.h" extern "C" { #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <netinet/if_ether.h> } static inline std::string ipv4addressToString(const void * src) { char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, src, ip, INET_ADDRSTRLEN); return std::string(ip); } namespace mckeys { using namespace std; // Like getInstance. Used for creating commands from packets. MemcacheCommand MemcacheCommand::create(const Packet& pkt, const bpf_u_int32 captureAddress, const memcache_command_t expectedCmdType) { static ssize_t ether_header_sz = sizeof(struct ether_header); static ssize_t ip_sz = sizeof(struct ip); const struct ether_header* ethernetHeader; const struct ip* ipHeader; const struct tcphdr* tcpHeader; const Packet::Header* pkthdr = &pkt.getHeader(); const Packet::Data* packet = pkt.getData(); u_char *data; uint32_t dataLength = 0; uint32_t dataOffset; string sourceAddress = ""; string destinationAddress = ""; // must be an IP packet // TODO add support for dumping localhost ethernetHeader = (struct ether_header*)packet; auto etype = ntohs(ethernetHeader->ether_type); if (etype != ETHERTYPE_IP) { return MemcacheCommand(); } // must be TCP - TODO add support for UDP ipHeader = (struct ip*)(packet + ether_header_sz); auto itype = ipHeader->ip_p; if (itype != IPPROTO_TCP) { return MemcacheCommand(); } sourceAddress = ipv4addressToString(&(ipHeader->ip_src)); destinationAddress = ipv4addressToString(&(ipHeader->ip_dst)); tcpHeader = (struct tcphdr*)(packet + ether_header_sz + ip_sz); dataOffset = ether_header_sz + ip_sz + (tcpHeader->doff * 4); data = (u_char*)(packet + dataOffset); dataLength = pkthdr->len - dataOffset; if (dataLength > pkthdr->caplen) { dataLength = pkthdr->caplen; } // The packet was destined for our capture address, this is a request // This bit of optimization lets us ignore a reasonably large percentage of // traffic if (expectedCmdType == MC_REQUEST) { if (ipHeader->ip_dst.s_addr == captureAddress) { // a request packet to server return makeRequestCommand(data, dataLength, sourceAddress, destinationAddress); } } else if (expectedCmdType == MC_RESPONSE) { if (ipHeader->ip_src.s_addr == captureAddress) { // a response packet from server return makeResponseCommand(data, dataLength, sourceAddress, destinationAddress); } } return MemcacheCommand(); } // protected default constructor MemcacheCommand::MemcacheCommand() : cmdType_(MC_UNKNOWN), sourceAddress_(), destinationAddress_(), commandName_(), objectKey_(), objectSize_(0) {} // protected constructor MemcacheCommand::MemcacheCommand(const memcache_command_t cmdType, const string sourceAddress, const string destinationAddress, const string commandName, const string objectKey, uint32_t objectSize) : cmdType_(cmdType), sourceAddress_(sourceAddress), destinationAddress_(destinationAddress), commandName_(commandName), objectKey_(objectKey), objectSize_(objectSize) {} // static protected MemcacheCommand MemcacheCommand::makeRequestCommand(u_char* data, int length, string sourceAddress, string destinationAddress) { // set <key> <flags> <exptime> <bytes> [noreply]\r\n static string commandName = "set"; static pcrecpp::RE re(commandName + string(" (\\S+) \\d+ \\d+ (\\d+)"), pcrecpp::RE_Options(PCRE_MULTILINE)); string key; int size = -1; if (length < 11) { // set k 0 0 1 return MemcacheCommand(); } for (int i = 0; i < length; i++) { int cid = (int)data[i]; if (!(isprint(cid) || cid == 10 || cid == 13)) { return MemcacheCommand(); } } string input = string((char*)data, length); re.PartialMatch(input, &key, &size); if (size >= 0) { return MemcacheCommand(MC_REQUEST, sourceAddress, destinationAddress, commandName, key, size); } return MemcacheCommand(); } // static protected MemcacheCommand MemcacheCommand::makeResponseCommand(u_char *data, int length, string sourceAddress, string destinationAddress) { // VALUE <key> <flags> <bytes> [<cas unique>]\r\n static string commandName = "get"; static pcrecpp::RE re("VALUE (\\S+) \\d+ (\\d+)", pcrecpp::RE_Options(PCRE_MULTILINE)); string key; int size = -1; if (length < 11) { // VALUE k 0 1 return MemcacheCommand(); } for (int i = 0; i < length; i++) { int cid = (int)data[i]; if (!(isprint(cid) || cid == 10 || cid == 13)) { return MemcacheCommand(); } } string input = string((char*)data, length); re.PartialMatch(input, &key, &size); if (size >= 0) { return MemcacheCommand(MC_RESPONSE, sourceAddress, destinationAddress, commandName, key, size); } else { return MemcacheCommand(); } } } // end namespace <commit_msg>Fix packet parsing<commit_after>#include <iostream> #include <iomanip> #include <string> #include <pcrecpp.h> #include "net/net.h" extern "C" { #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <netinet/if_ether.h> } static inline std::string ipv4addressToString(const void * src) { char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, src, ip, INET_ADDRSTRLEN); return std::string(ip); } namespace mckeys { using namespace std; // Like getInstance. Used for creating commands from packets. MemcacheCommand MemcacheCommand::create(const Packet& pkt, const bpf_u_int32 captureAddress, const memcache_command_t expectedCmdType) { static ssize_t ether_header_sz = sizeof(struct ether_header); static ssize_t ip_sz = sizeof(struct ip); const struct ether_header* ethernetHeader; const struct ip* ipHeader; const struct tcphdr* tcpHeader; const Packet::Header* pkthdr = &pkt.getHeader(); const Packet::Data* packet = pkt.getData(); u_char *data; uint32_t dataLength = 0; uint32_t dataOffset; string sourceAddress = ""; string destinationAddress = ""; // must be an IP packet // TODO add support for dumping localhost ethernetHeader = (struct ether_header*)packet; auto etype = ntohs(ethernetHeader->ether_type); if (etype != ETHERTYPE_IP) { return MemcacheCommand(); } // must be TCP - TODO add support for UDP ipHeader = (struct ip*)(packet + ether_header_sz); auto itype = ipHeader->ip_p; if (itype != IPPROTO_TCP) { return MemcacheCommand(); } sourceAddress = ipv4addressToString(&(ipHeader->ip_src)); destinationAddress = ipv4addressToString(&(ipHeader->ip_dst)); tcpHeader = (struct tcphdr*)(packet + ether_header_sz + ip_sz); dataOffset = ether_header_sz + ip_sz + (tcpHeader->doff * 4); data = (u_char*)(packet + dataOffset); dataLength = pkthdr->len - dataOffset; if (dataLength > pkthdr->caplen) { dataLength = pkthdr->caplen; } // The packet was destined for our capture address, this is a request // This bit of optimization lets us ignore a reasonably large percentage of // traffic if (expectedCmdType == MC_REQUEST) { if (ipHeader->ip_dst.s_addr == captureAddress) { // a request packet to server return makeRequestCommand(data, dataLength, sourceAddress, destinationAddress); } } else if (expectedCmdType == MC_RESPONSE) { if (ipHeader->ip_src.s_addr == captureAddress) { // a response packet from server return makeResponseCommand(data, dataLength, sourceAddress, destinationAddress); } } return MemcacheCommand(); } // protected default constructor MemcacheCommand::MemcacheCommand() : cmdType_(MC_UNKNOWN), sourceAddress_(), destinationAddress_(), commandName_(), objectKey_(), objectSize_(0) {} // protected constructor MemcacheCommand::MemcacheCommand(const memcache_command_t cmdType, const string sourceAddress, const string destinationAddress, const string commandName, const string objectKey, uint32_t objectSize) : cmdType_(cmdType), sourceAddress_(sourceAddress), destinationAddress_(destinationAddress), commandName_(commandName), objectKey_(objectKey), objectSize_(objectSize) {} // static protected MemcacheCommand MemcacheCommand::makeRequestCommand(u_char* data, int length, string sourceAddress, string destinationAddress) { // set <key> <flags> <exptime> <bytes> [noreply]\r\n static string commandName = "set"; static pcrecpp::RE re(commandName + string(" (\\S+) \\d+ \\d+ (\\d+)"), pcrecpp::RE_Options(PCRE_MULTILINE)); string key; int size = -1; string input = ""; for (int i = 0; i < length; i++) { int cid = (int)data[i]; if (isprint(cid) || cid == 10 || cid == 13) { input += static_cast<char>(cid); } } if (input.length() < 11) { // set k 0 0 1 return MemcacheCommand(); } re.PartialMatch(input, &key, &size); if (size >= 0) { return MemcacheCommand(MC_REQUEST, sourceAddress, destinationAddress, commandName, key, size); } return MemcacheCommand(); } // static protected MemcacheCommand MemcacheCommand::makeResponseCommand(u_char *data, int length, string sourceAddress, string destinationAddress) { // VALUE <key> <flags> <bytes> [<cas unique>]\r\n static string commandName = "get"; static pcrecpp::RE re("VALUE (\\S+) \\d+ (\\d+)", pcrecpp::RE_Options(PCRE_MULTILINE)); string key; int size = -1; string input = ""; for (int i = 0; i < length; i++) { int cid = (int)data[i]; if (isprint(cid) || cid == 10 || cid == 13) { input += static_cast<char>(cid); } } if (input.length() < 11) { // VALUE k 0 1 return MemcacheCommand(); } re.PartialMatch(input, &key, &size); if (size >= 0) { return MemcacheCommand(MC_RESPONSE, sourceAddress, destinationAddress, commandName, key, size); } else { return MemcacheCommand(); } } } // end namespace <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ // // Buffered input and output streams // // Two abstract classes (data_source and data_sink) provide means // to acquire bulk data from, or push bulk data to, some provider. // These could be tied to a TCP connection, a disk file, or a memory // buffer. // // Two concrete classes (input_stream and output_stream) buffer data // from data_source and data_sink and provide easier means to process // it. // #pragma once #include <seastar/core/future.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/core/scattered_message.hh> #include <seastar/util/std-compat.hh> namespace seastar { namespace net { class packet; } class data_source_impl { public: virtual ~data_source_impl() {} virtual future<temporary_buffer<char>> get() = 0; virtual future<temporary_buffer<char>> skip(uint64_t n); virtual future<> close() { return make_ready_future<>(); } }; class data_source { std::unique_ptr<data_source_impl> _dsi; protected: data_source_impl* impl() const { return _dsi.get(); } public: data_source() = default; explicit data_source(std::unique_ptr<data_source_impl> dsi) : _dsi(std::move(dsi)) {} data_source(data_source&& x) = default; data_source& operator=(data_source&& x) = default; future<temporary_buffer<char>> get() { return _dsi->get(); } future<temporary_buffer<char>> skip(uint64_t n) { return _dsi->skip(n); } future<> close() { return _dsi->close(); } }; class data_sink_impl { public: virtual ~data_sink_impl() {} virtual temporary_buffer<char> allocate_buffer(size_t size) { return temporary_buffer<char>(size); } virtual future<> put(net::packet data) = 0; virtual future<> put(std::vector<temporary_buffer<char>> data) { net::packet p; p.reserve(data.size()); for (auto& buf : data) { p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release()); } return put(std::move(p)); } virtual future<> put(temporary_buffer<char> buf) { return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release())); } virtual future<> flush() { return make_ready_future<>(); } virtual future<> close() = 0; }; class data_sink { std::unique_ptr<data_sink_impl> _dsi; public: data_sink() = default; explicit data_sink(std::unique_ptr<data_sink_impl> dsi) : _dsi(std::move(dsi)) {} data_sink(data_sink&& x) = default; data_sink& operator=(data_sink&& x) = default; temporary_buffer<char> allocate_buffer(size_t size) { return _dsi->allocate_buffer(size); } future<> put(std::vector<temporary_buffer<char>> data) { return _dsi->put(std::move(data)); } future<> put(temporary_buffer<char> data) { return _dsi->put(std::move(data)); } future<> put(net::packet p) { return _dsi->put(std::move(p)); } future<> flush() { return _dsi->flush(); } future<> close() { return _dsi->close(); } }; struct continue_consuming {}; template <typename CharType> class stop_consuming { public: using tmp_buf = temporary_buffer<CharType>; explicit stop_consuming(tmp_buf buf) : _buf(std::move(buf)) {} tmp_buf& get_buffer() { return _buf; } const tmp_buf& get_buffer() const { return _buf; } private: tmp_buf _buf; }; class skip_bytes { public: explicit skip_bytes(uint64_t v) : _value(v) {} uint64_t get_value() const { return _value; } private: uint64_t _value; }; template <typename CharType> class consumption_result { public: using stop_consuming_type = stop_consuming<CharType>; using consumption_variant = compat::variant<continue_consuming, stop_consuming_type, skip_bytes>; using tmp_buf = typename stop_consuming_type::tmp_buf; /*[[deprecated]]*/ consumption_result(compat::optional<tmp_buf> opt_buf) { if (opt_buf) { _result = stop_consuming_type{std::move(opt_buf.value())}; } } consumption_result(const continue_consuming&) {} consumption_result(stop_consuming_type&& stop) : _result(std::move(stop)) {} consumption_result(skip_bytes&& skip) : _result(std::move(skip)) {} consumption_variant& get() { return _result; } const consumption_variant& get() const { return _result; } private: consumption_variant _result; }; // Consumer concept, for consume() method GCC6_CONCEPT( // The consumer should operate on the data given to it, and // return a future "consumption result", which can be // - continue_consuming, if the consumer has consumed all the input given // to it and is ready for more // - stop_consuming, when the consumer is done (and in that case // the contained buffer is the unconsumed part of the last data buffer - this // can also happen to be empty). // - skip_bytes, when the consumer has consumed all the input given to it // and wants to skip before processing the next chunk // // For backward compatibility reasons, we also support the deprecated return value // of type "unconsumed remainder" which can be // - empty optional, if the consumer consumed all the input given to it // and is ready for more // - non-empty optional, when the consumer is done (and in that case // the value is the unconsumed part of the last data buffer - this // can also happen to be empty). template <typename Consumer, typename CharType> concept bool InputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> future<consumption_result<CharType>>; }; template <typename Consumer, typename CharType> concept bool ObsoleteInputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> future<compat::optional<temporary_buffer<CharType>>>; }; ) template <typename CharType> class input_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_source _fd; temporary_buffer<CharType> _buf; bool _eof = false; private: using tmp_buf = temporary_buffer<CharType>; size_t available() const { return _buf.size(); } protected: void reset() { _buf = {}; } data_source* fd() { return &_fd; } public: using consumption_result_type = consumption_result<CharType>; // unconsumed_remainder is mapped for compatibility only; new code should use consumption_result_type using unconsumed_remainder = compat::optional<tmp_buf>; using char_type = CharType; input_stream() = default; explicit input_stream(data_source fd) : _fd(std::move(fd)), _buf(0) {} input_stream(input_stream&&) = default; input_stream& operator=(input_stream&&) = default; future<temporary_buffer<CharType>> read_exactly(size_t n); template <typename Consumer> GCC6_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer&& c); template <typename Consumer> GCC6_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer& c); bool eof() { return _eof; } /// Returns some data from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read(); /// Returns up to n bytes from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read_up_to(size_t n); /// Detaches the \c input_stream from the underlying data source. /// /// Waits for any background operations (for example, read-ahead) to /// complete, so that the any resources the stream is using can be /// safely destroyed. An example is a \ref file resource used by /// the stream returned by make_file_input_stream(). /// /// \return a future that becomes ready when this stream no longer /// needs the data source. future<> close() { return _fd.close(); } /// Ignores n next bytes from the stream. future<> skip(uint64_t n); /// Detaches the underlying \c data_source from the \c input_stream. /// /// The intended usage is custom \c data_source_impl implementations /// wrapping an existing \c input_stream, therefore it shouldn't be /// called on an \c input_stream that was already used. /// After calling \c detach() the \c input_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_source data_source detach() &&; private: future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed); }; // Facilitates data buffering before it's handed over to data_sink. // // When trim_to_size is true it's guaranteed that data sink will not receive // chunks larger than the configured size, which could be the case when a // single write call is made with data larger than the configured size. // // The data sink will not receive empty chunks. // // \note All methods must be called sequentially. That is, no method // may be invoked before the previous method's returned future is // resolved. template <typename CharType> class output_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_sink _fd; temporary_buffer<CharType> _buf; net::packet _zc_bufs = net::packet::make_null_packet(); //zero copy buffers size_t _size = 0; size_t _begin = 0; size_t _end = 0; bool _trim_to_size = false; bool _batch_flushes = false; compat::optional<promise<>> _in_batch; bool _flush = false; bool _flushing = false; std::exception_ptr _ex; private: size_t available() const { return _end - _begin; } size_t possibly_available() const { return _size - _begin; } future<> split_and_put(temporary_buffer<CharType> buf); future<> put(temporary_buffer<CharType> buf); void poll_flush(); future<> zero_copy_put(net::packet p); future<> zero_copy_split_and_put(net::packet p); [[gnu::noinline]] future<> slow_write(const CharType* buf, size_t n); public: using char_type = CharType; output_stream() = default; output_stream(data_sink fd, size_t size, bool trim_to_size = false, bool batch_flushes = false) : _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size), _batch_flushes(batch_flushes) {} output_stream(output_stream&&) = default; output_stream& operator=(output_stream&&) = default; ~output_stream() { assert(!_in_batch && "Was this stream properly closed?"); } future<> write(const char_type* buf, size_t n); future<> write(const char_type* buf); template <typename StringChar, typename SizeType, SizeType MaxSize, bool NulTerminate> future<> write(const basic_sstring<StringChar, SizeType, MaxSize, NulTerminate>& s); future<> write(const std::basic_string<char_type>& s); future<> write(net::packet p); future<> write(scattered_message<char_type> msg); future<> write(temporary_buffer<char_type>); future<> flush(); /// Flushes the stream before closing it (and the underlying data sink) to /// any further writes. The resulting future must be waited on before /// destroying this object. future<> close(); /// Detaches the underlying \c data_sink from the \c output_stream. /// /// The intended usage is custom \c data_sink_impl implementations /// wrapping an existing \c output_stream, therefore it shouldn't be /// called on an \c output_stream that was already used. /// After calling \c detach() the \c output_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_sink data_sink detach() &&; private: friend class reactor; }; /*! * \brief copy all the content from the input stream to the output stream */ template <typename CharType> future<> copy(input_stream<CharType>&, output_stream<CharType>&); } #include "iostream-impl.hh" <commit_msg>iostream: Constify eof() function<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ // // Buffered input and output streams // // Two abstract classes (data_source and data_sink) provide means // to acquire bulk data from, or push bulk data to, some provider. // These could be tied to a TCP connection, a disk file, or a memory // buffer. // // Two concrete classes (input_stream and output_stream) buffer data // from data_source and data_sink and provide easier means to process // it. // #pragma once #include <seastar/core/future.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/core/scattered_message.hh> #include <seastar/util/std-compat.hh> namespace seastar { namespace net { class packet; } class data_source_impl { public: virtual ~data_source_impl() {} virtual future<temporary_buffer<char>> get() = 0; virtual future<temporary_buffer<char>> skip(uint64_t n); virtual future<> close() { return make_ready_future<>(); } }; class data_source { std::unique_ptr<data_source_impl> _dsi; protected: data_source_impl* impl() const { return _dsi.get(); } public: data_source() = default; explicit data_source(std::unique_ptr<data_source_impl> dsi) : _dsi(std::move(dsi)) {} data_source(data_source&& x) = default; data_source& operator=(data_source&& x) = default; future<temporary_buffer<char>> get() { return _dsi->get(); } future<temporary_buffer<char>> skip(uint64_t n) { return _dsi->skip(n); } future<> close() { return _dsi->close(); } }; class data_sink_impl { public: virtual ~data_sink_impl() {} virtual temporary_buffer<char> allocate_buffer(size_t size) { return temporary_buffer<char>(size); } virtual future<> put(net::packet data) = 0; virtual future<> put(std::vector<temporary_buffer<char>> data) { net::packet p; p.reserve(data.size()); for (auto& buf : data) { p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release()); } return put(std::move(p)); } virtual future<> put(temporary_buffer<char> buf) { return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release())); } virtual future<> flush() { return make_ready_future<>(); } virtual future<> close() = 0; }; class data_sink { std::unique_ptr<data_sink_impl> _dsi; public: data_sink() = default; explicit data_sink(std::unique_ptr<data_sink_impl> dsi) : _dsi(std::move(dsi)) {} data_sink(data_sink&& x) = default; data_sink& operator=(data_sink&& x) = default; temporary_buffer<char> allocate_buffer(size_t size) { return _dsi->allocate_buffer(size); } future<> put(std::vector<temporary_buffer<char>> data) { return _dsi->put(std::move(data)); } future<> put(temporary_buffer<char> data) { return _dsi->put(std::move(data)); } future<> put(net::packet p) { return _dsi->put(std::move(p)); } future<> flush() { return _dsi->flush(); } future<> close() { return _dsi->close(); } }; struct continue_consuming {}; template <typename CharType> class stop_consuming { public: using tmp_buf = temporary_buffer<CharType>; explicit stop_consuming(tmp_buf buf) : _buf(std::move(buf)) {} tmp_buf& get_buffer() { return _buf; } const tmp_buf& get_buffer() const { return _buf; } private: tmp_buf _buf; }; class skip_bytes { public: explicit skip_bytes(uint64_t v) : _value(v) {} uint64_t get_value() const { return _value; } private: uint64_t _value; }; template <typename CharType> class consumption_result { public: using stop_consuming_type = stop_consuming<CharType>; using consumption_variant = compat::variant<continue_consuming, stop_consuming_type, skip_bytes>; using tmp_buf = typename stop_consuming_type::tmp_buf; /*[[deprecated]]*/ consumption_result(compat::optional<tmp_buf> opt_buf) { if (opt_buf) { _result = stop_consuming_type{std::move(opt_buf.value())}; } } consumption_result(const continue_consuming&) {} consumption_result(stop_consuming_type&& stop) : _result(std::move(stop)) {} consumption_result(skip_bytes&& skip) : _result(std::move(skip)) {} consumption_variant& get() { return _result; } const consumption_variant& get() const { return _result; } private: consumption_variant _result; }; // Consumer concept, for consume() method GCC6_CONCEPT( // The consumer should operate on the data given to it, and // return a future "consumption result", which can be // - continue_consuming, if the consumer has consumed all the input given // to it and is ready for more // - stop_consuming, when the consumer is done (and in that case // the contained buffer is the unconsumed part of the last data buffer - this // can also happen to be empty). // - skip_bytes, when the consumer has consumed all the input given to it // and wants to skip before processing the next chunk // // For backward compatibility reasons, we also support the deprecated return value // of type "unconsumed remainder" which can be // - empty optional, if the consumer consumed all the input given to it // and is ready for more // - non-empty optional, when the consumer is done (and in that case // the value is the unconsumed part of the last data buffer - this // can also happen to be empty). template <typename Consumer, typename CharType> concept bool InputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> future<consumption_result<CharType>>; }; template <typename Consumer, typename CharType> concept bool ObsoleteInputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> future<compat::optional<temporary_buffer<CharType>>>; }; ) template <typename CharType> class input_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_source _fd; temporary_buffer<CharType> _buf; bool _eof = false; private: using tmp_buf = temporary_buffer<CharType>; size_t available() const { return _buf.size(); } protected: void reset() { _buf = {}; } data_source* fd() { return &_fd; } public: using consumption_result_type = consumption_result<CharType>; // unconsumed_remainder is mapped for compatibility only; new code should use consumption_result_type using unconsumed_remainder = compat::optional<tmp_buf>; using char_type = CharType; input_stream() = default; explicit input_stream(data_source fd) : _fd(std::move(fd)), _buf(0) {} input_stream(input_stream&&) = default; input_stream& operator=(input_stream&&) = default; future<temporary_buffer<CharType>> read_exactly(size_t n); template <typename Consumer> GCC6_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer&& c); template <typename Consumer> GCC6_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer& c); bool eof() const { return _eof; } /// Returns some data from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read(); /// Returns up to n bytes from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read_up_to(size_t n); /// Detaches the \c input_stream from the underlying data source. /// /// Waits for any background operations (for example, read-ahead) to /// complete, so that the any resources the stream is using can be /// safely destroyed. An example is a \ref file resource used by /// the stream returned by make_file_input_stream(). /// /// \return a future that becomes ready when this stream no longer /// needs the data source. future<> close() { return _fd.close(); } /// Ignores n next bytes from the stream. future<> skip(uint64_t n); /// Detaches the underlying \c data_source from the \c input_stream. /// /// The intended usage is custom \c data_source_impl implementations /// wrapping an existing \c input_stream, therefore it shouldn't be /// called on an \c input_stream that was already used. /// After calling \c detach() the \c input_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_source data_source detach() &&; private: future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed); }; // Facilitates data buffering before it's handed over to data_sink. // // When trim_to_size is true it's guaranteed that data sink will not receive // chunks larger than the configured size, which could be the case when a // single write call is made with data larger than the configured size. // // The data sink will not receive empty chunks. // // \note All methods must be called sequentially. That is, no method // may be invoked before the previous method's returned future is // resolved. template <typename CharType> class output_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_sink _fd; temporary_buffer<CharType> _buf; net::packet _zc_bufs = net::packet::make_null_packet(); //zero copy buffers size_t _size = 0; size_t _begin = 0; size_t _end = 0; bool _trim_to_size = false; bool _batch_flushes = false; compat::optional<promise<>> _in_batch; bool _flush = false; bool _flushing = false; std::exception_ptr _ex; private: size_t available() const { return _end - _begin; } size_t possibly_available() const { return _size - _begin; } future<> split_and_put(temporary_buffer<CharType> buf); future<> put(temporary_buffer<CharType> buf); void poll_flush(); future<> zero_copy_put(net::packet p); future<> zero_copy_split_and_put(net::packet p); [[gnu::noinline]] future<> slow_write(const CharType* buf, size_t n); public: using char_type = CharType; output_stream() = default; output_stream(data_sink fd, size_t size, bool trim_to_size = false, bool batch_flushes = false) : _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size), _batch_flushes(batch_flushes) {} output_stream(output_stream&&) = default; output_stream& operator=(output_stream&&) = default; ~output_stream() { assert(!_in_batch && "Was this stream properly closed?"); } future<> write(const char_type* buf, size_t n); future<> write(const char_type* buf); template <typename StringChar, typename SizeType, SizeType MaxSize, bool NulTerminate> future<> write(const basic_sstring<StringChar, SizeType, MaxSize, NulTerminate>& s); future<> write(const std::basic_string<char_type>& s); future<> write(net::packet p); future<> write(scattered_message<char_type> msg); future<> write(temporary_buffer<char_type>); future<> flush(); /// Flushes the stream before closing it (and the underlying data sink) to /// any further writes. The resulting future must be waited on before /// destroying this object. future<> close(); /// Detaches the underlying \c data_sink from the \c output_stream. /// /// The intended usage is custom \c data_sink_impl implementations /// wrapping an existing \c output_stream, therefore it shouldn't be /// called on an \c output_stream that was already used. /// After calling \c detach() the \c output_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_sink data_sink detach() &&; private: friend class reactor; }; /*! * \brief copy all the content from the input stream to the output stream */ template <typename CharType> future<> copy(input_stream<CharType>&, output_stream<CharType>&); } #include "iostream-impl.hh" <|endoftext|>
<commit_before>//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// // // This transformation implements the well known scalar replacement of // aggregates transformation. This xform breaks up alloca instructions of // aggregate type (structure or array) into individual alloca instructions for // each member (if possible). Then, if possible, it transforms the individual // alloca instructions into nice clean scalar SSA form. // // This combines a simple SRoA algorithm with the Mem2Reg algorithm because // often interact, especially for C++ programs. As such, iterating between // SRoA, then Mem2Reg until we run out of things to promote works well. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/iMemory.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/PromoteMemToReg.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include "Support/StringExtras.h" namespace { Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up"); Statistic<> NumPromoted("scalarrepl", "Number of alloca's promoted"); struct SROA : public FunctionPass { bool runOnFunction(Function &F); bool performScalarRepl(Function &F); bool performPromotion(Function &F); // getAnalysisUsage - This pass does not require any passes, but we know it // will not alter the CFG, so say so. virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<DominanceFrontier>(); AU.addRequired<TargetData>(); AU.setPreservesCFG(); } private: bool isSafeElementUse(Value *Ptr); bool isSafeUseOfAllocation(Instruction *User); bool isSafeStructAllocaToPromote(AllocationInst *AI); bool isSafeArrayAllocaToPromote(AllocationInst *AI); AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); }; RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); } Pass *createScalarReplAggregatesPass() { return new SROA(); } bool SROA::runOnFunction(Function &F) { bool Changed = false, LocalChange; do { LocalChange = performScalarRepl(F); LocalChange |= performPromotion(F); Changed |= LocalChange; } while (LocalChange); return Changed; } bool SROA::performPromotion(Function &F) { std::vector<AllocaInst*> Allocas; const TargetData &TD = getAnalysis<TargetData>(); BasicBlock &BB = F.getEntryNode(); // Get the entry node for the function bool Changed = false; while (1) { Allocas.clear(); // Find allocas that are safe to promote, by looking at all instructions in // the entry node for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca? if (isAllocaPromotable(AI, TD)) Allocas.push_back(AI); if (Allocas.empty()) break; PromoteMemToReg(Allocas, getAnalysis<DominanceFrontier>(), TD); NumPromoted += Allocas.size(); Changed = true; } return Changed; } // performScalarRepl - This algorithm is a simple worklist driven algorithm, // which runs on all of the malloc/alloca instructions in the function, removing // them if they are only used by getelementptr instructions. // bool SROA::performScalarRepl(Function &F) { std::vector<AllocationInst*> WorkList; // Scan the entry basic block, adding any alloca's and mallocs to the worklist BasicBlock &BB = F.getEntryNode(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (AllocationInst *A = dyn_cast<AllocationInst>(I)) WorkList.push_back(A); // Process the worklist bool Changed = false; while (!WorkList.empty()) { AllocationInst *AI = WorkList.back(); WorkList.pop_back(); // We cannot transform the allocation instruction if it is an array // allocation (allocations OF arrays are ok though), and an allocation of a // scalar value cannot be decomposed at all. // if (AI->isArrayAllocation() || (!isa<StructType>(AI->getAllocatedType()) && !isa<ArrayType>(AI->getAllocatedType()))) continue; // Check that all of the users of the allocation are capable of being // transformed. if (isa<StructType>(AI->getAllocatedType())) { if (!isSafeStructAllocaToPromote(AI)) continue; } else if (!isSafeArrayAllocaToPromote(AI)) continue; DEBUG(std::cerr << "Found inst to xform: " << *AI); Changed = true; std::vector<AllocaInst*> ElementAllocas; if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { ElementAllocas.reserve(ST->getNumContainedTypes()); for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } else { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); ElementAllocas.reserve(AT->getNumElements()); const Type *ElTy = AT->getElementType(); for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } // Now that we have created the alloca instructions that we want to use, // expand the getelementptr instructions to use them. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue(); assert(Idx < ElementAllocas.size() && "Index out of range?"); AllocaInst *AllocaToUse = ElementAllocas[Idx]; Value *RepValue; if (GEPI->getNumOperands() == 3) { // Do not insert a new getelementptr instruction with zero indices, // only to have it optimized out later. RepValue = AllocaToUse; } else { // We are indexing deeply into the structure, so we still need a // getelement ptr instruction to finish the indexing. This may be // expanded itself once the worklist is rerun. // std::string OldName = GEPI->getName(); // Steal the old name... std::vector<Value*> NewArgs; NewArgs.push_back(Constant::getNullValue(Type::LongTy)); NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end()); GEPI->setName(""); RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI); } // Move all of the users over to the new GEP. GEPI->replaceAllUsesWith(RepValue); // Delete the old GEP GEPI->getParent()->getInstList().erase(GEPI); } else { assert(0 && "Unexpected instruction type!"); } } // Finally, delete the Alloca instruction AI->getParent()->getInstList().erase(AI); NumReplaced++; } return Changed; } /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an /// aggregate allocation. /// bool SROA::isSafeUseOfAllocation(Instruction *User) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst> if (GEPI->getNumOperands() <= 2 || GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) || !isa<Constant>(GEPI->getOperand(2)) || isa<ConstantExpr>(GEPI->getOperand(2))) return false; } else { return false; } return true; } /// isSafeElementUse - Check to see if this use is an allowed use for a /// getelementptr instruction of an array aggregate allocation. /// bool SROA::isSafeElementUse(Value *Ptr) { for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); switch (User->getOpcode()) { case Instruction::Load: return true; case Instruction::Store: return User->getOperand(0) != Ptr; case Instruction::GetElementPtr: { GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); if (GEP->getNumOperands() > 1) { if (!isa<Constant>(GEP->getOperand(1)) || !cast<Constant>(GEP->getOperand(1))->isNullValue()) return false; // Using pointer arithmetic to navigate the array... } return isSafeElementUse(GEP); } default: DEBUG(std::cerr << " Transformation preventing inst: " << *User); return false; } } return true; // All users look ok :) } /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) { // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { if (!isSafeUseOfAllocation(cast<Instruction>(*I))) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << *I); return false; } // Pedantic check to avoid breaking broken programs... if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I)) if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI)) return false; } return true; } /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); int64_t NumElements = AT->getNumElements(); // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. Array allocas have extra constraints to // meet though. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (!isSafeUseOfAllocation(User)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); return false; } // Check to make sure that getelementptr follow the extra rules for arrays: if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // Check to make sure that index falls within the array. If not, // something funny is going on, so we won't do the optimization. // if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements) return false; // Check to make sure that the only thing that uses the resultant pointer // is safe for an array access. For example, code that looks like: // P = &A[0]; P = P + 1 // is legal, and should prevent promotion. // if (!isSafeElementUse(GEPI)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to uses of user: " << *GEPI); return false; } } } return true; } <commit_msg>Apostrophes are only used for possession and quoting.<commit_after>//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// // // This transformation implements the well known scalar replacement of // aggregates transformation. This xform breaks up alloca instructions of // aggregate type (structure or array) into individual alloca instructions for // each member (if possible). Then, if possible, it transforms the individual // alloca instructions into nice clean scalar SSA form. // // This combines a simple SRoA algorithm with the Mem2Reg algorithm because // often interact, especially for C++ programs. As such, iterating between // SRoA, then Mem2Reg until we run out of things to promote works well. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/iMemory.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/PromoteMemToReg.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include "Support/StringExtras.h" namespace { Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up"); Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted"); struct SROA : public FunctionPass { bool runOnFunction(Function &F); bool performScalarRepl(Function &F); bool performPromotion(Function &F); // getAnalysisUsage - This pass does not require any passes, but we know it // will not alter the CFG, so say so. virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<DominanceFrontier>(); AU.addRequired<TargetData>(); AU.setPreservesCFG(); } private: bool isSafeElementUse(Value *Ptr); bool isSafeUseOfAllocation(Instruction *User); bool isSafeStructAllocaToPromote(AllocationInst *AI); bool isSafeArrayAllocaToPromote(AllocationInst *AI); AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); }; RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); } Pass *createScalarReplAggregatesPass() { return new SROA(); } bool SROA::runOnFunction(Function &F) { bool Changed = false, LocalChange; do { LocalChange = performScalarRepl(F); LocalChange |= performPromotion(F); Changed |= LocalChange; } while (LocalChange); return Changed; } bool SROA::performPromotion(Function &F) { std::vector<AllocaInst*> Allocas; const TargetData &TD = getAnalysis<TargetData>(); BasicBlock &BB = F.getEntryNode(); // Get the entry node for the function bool Changed = false; while (1) { Allocas.clear(); // Find allocas that are safe to promote, by looking at all instructions in // the entry node for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca? if (isAllocaPromotable(AI, TD)) Allocas.push_back(AI); if (Allocas.empty()) break; PromoteMemToReg(Allocas, getAnalysis<DominanceFrontier>(), TD); NumPromoted += Allocas.size(); Changed = true; } return Changed; } // performScalarRepl - This algorithm is a simple worklist driven algorithm, // which runs on all of the malloc/alloca instructions in the function, removing // them if they are only used by getelementptr instructions. // bool SROA::performScalarRepl(Function &F) { std::vector<AllocationInst*> WorkList; // Scan the entry basic block, adding any alloca's and mallocs to the worklist BasicBlock &BB = F.getEntryNode(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (AllocationInst *A = dyn_cast<AllocationInst>(I)) WorkList.push_back(A); // Process the worklist bool Changed = false; while (!WorkList.empty()) { AllocationInst *AI = WorkList.back(); WorkList.pop_back(); // We cannot transform the allocation instruction if it is an array // allocation (allocations OF arrays are ok though), and an allocation of a // scalar value cannot be decomposed at all. // if (AI->isArrayAllocation() || (!isa<StructType>(AI->getAllocatedType()) && !isa<ArrayType>(AI->getAllocatedType()))) continue; // Check that all of the users of the allocation are capable of being // transformed. if (isa<StructType>(AI->getAllocatedType())) { if (!isSafeStructAllocaToPromote(AI)) continue; } else if (!isSafeArrayAllocaToPromote(AI)) continue; DEBUG(std::cerr << "Found inst to xform: " << *AI); Changed = true; std::vector<AllocaInst*> ElementAllocas; if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { ElementAllocas.reserve(ST->getNumContainedTypes()); for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } else { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); ElementAllocas.reserve(AT->getNumElements()); const Type *ElTy = AT->getElementType(); for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } // Now that we have created the alloca instructions that we want to use, // expand the getelementptr instructions to use them. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue(); assert(Idx < ElementAllocas.size() && "Index out of range?"); AllocaInst *AllocaToUse = ElementAllocas[Idx]; Value *RepValue; if (GEPI->getNumOperands() == 3) { // Do not insert a new getelementptr instruction with zero indices, // only to have it optimized out later. RepValue = AllocaToUse; } else { // We are indexing deeply into the structure, so we still need a // getelement ptr instruction to finish the indexing. This may be // expanded itself once the worklist is rerun. // std::string OldName = GEPI->getName(); // Steal the old name... std::vector<Value*> NewArgs; NewArgs.push_back(Constant::getNullValue(Type::LongTy)); NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end()); GEPI->setName(""); RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI); } // Move all of the users over to the new GEP. GEPI->replaceAllUsesWith(RepValue); // Delete the old GEP GEPI->getParent()->getInstList().erase(GEPI); } else { assert(0 && "Unexpected instruction type!"); } } // Finally, delete the Alloca instruction AI->getParent()->getInstList().erase(AI); NumReplaced++; } return Changed; } /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an /// aggregate allocation. /// bool SROA::isSafeUseOfAllocation(Instruction *User) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst> if (GEPI->getNumOperands() <= 2 || GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) || !isa<Constant>(GEPI->getOperand(2)) || isa<ConstantExpr>(GEPI->getOperand(2))) return false; } else { return false; } return true; } /// isSafeElementUse - Check to see if this use is an allowed use for a /// getelementptr instruction of an array aggregate allocation. /// bool SROA::isSafeElementUse(Value *Ptr) { for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); switch (User->getOpcode()) { case Instruction::Load: return true; case Instruction::Store: return User->getOperand(0) != Ptr; case Instruction::GetElementPtr: { GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); if (GEP->getNumOperands() > 1) { if (!isa<Constant>(GEP->getOperand(1)) || !cast<Constant>(GEP->getOperand(1))->isNullValue()) return false; // Using pointer arithmetic to navigate the array... } return isSafeElementUse(GEP); } default: DEBUG(std::cerr << " Transformation preventing inst: " << *User); return false; } } return true; // All users look ok :) } /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) { // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { if (!isSafeUseOfAllocation(cast<Instruction>(*I))) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << *I); return false; } // Pedantic check to avoid breaking broken programs... if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I)) if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI)) return false; } return true; } /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); int64_t NumElements = AT->getNumElements(); // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. Array allocas have extra constraints to // meet though. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (!isSafeUseOfAllocation(User)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); return false; } // Check to make sure that getelementptr follow the extra rules for arrays: if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // Check to make sure that index falls within the array. If not, // something funny is going on, so we won't do the optimization. // if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements) return false; // Check to make sure that the only thing that uses the resultant pointer // is safe for an array access. For example, code that looks like: // P = &A[0]; P = P + 1 // is legal, and should prevent promotion. // if (!isSafeElementUse(GEPI)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to uses of user: " << *GEPI); return false; } } } return true; } <|endoftext|>
<commit_before>#ifndef SG_PLATFORM_HPP_INCLUDED #define SG_PLATFORM_HPP_INCLUDED #include <cstdlib> #include <string> #ifdef _WIN32 #define SG_INLINE __forceinline #else #define SG_INLINE __attribute__((always_inline)) #endif std::string sg_getenv(const char *env) { #ifdef _WIN32 char *buf; size_t len; errno_t err = _dupenv_s(&buf, &len, env); if (err || buf == NULL) return ""; std::string ret(buf); free(buf); return ret; #else const char *ret = getenv(env); return ret ? ret : ""; #endif } #endif // SG_PLATFORM_HPP_INCLUDED <commit_msg>Added SG_TLS macro for defining thread local variables.<commit_after>#ifndef SG_PLATFORM_HPP_INCLUDED #define SG_PLATFORM_HPP_INCLUDED #include <cstdlib> #include <string> #ifdef _WIN32 #define SG_INLINE __forceinline #else #define SG_INLINE __attribute__((always_inline)) #endif #if defined(_MSC_VER) #define SG_TLS __declspec( thread ) #else #define SG_TLS __thread #endif std::string sg_getenv(const char *env) { #ifdef _WIN32 char *buf; size_t len; errno_t err = _dupenv_s(&buf, &len, env); if (err || buf == NULL) return ""; std::string ret(buf); free(buf); return ret; #else const char *ret = getenv(env); return ret ? ret : ""; #endif } #endif // SG_PLATFORM_HPP_INCLUDED <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #if !defined(NAMESPACESCOPE_HPP) #define NAMESPACESCOPE_HPP #include <util/XercesDefs.hpp> #include <util/StringPool.hpp> // // NamespaceScope provides a data structure for mapping namespace prefixes // to their URI's. The mapping accurately reflects the scoping of namespaces // at a particular instant in time. // class VALIDATORS_EXPORT NamespaceScope { public : // ----------------------------------------------------------------------- // Class specific data types // // These really should be private, but some of the compilers we have to // support are too dumb to deal with that. // // PrefMapElem // fURIId is the id of the URI from the validator's URI map. The // fPrefId is the id of the prefix from our own prefix pool. The // namespace stack consists of these elements. // // StackElem // The fMapCapacity is how large fMap has grown so far. fMapCount // is how many of them are valid right now. // ----------------------------------------------------------------------- struct PrefMapElem { unsigned int fPrefId; unsigned int fURIId; }; struct StackElem { PrefMapElem* fMap; unsigned int fMapCapacity; unsigned int fMapCount; }; // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- NamespaceScope(); ~NamespaceScope(); // ----------------------------------------------------------------------- // Stack access // ----------------------------------------------------------------------- unsigned int increaseDepth(); unsigned int decreaseDepth(); // ----------------------------------------------------------------------- // Prefix map methods // ----------------------------------------------------------------------- void addPrefix(const XMLCh* const prefixToAdd, const unsigned int uriId); unsigned int getNamespaceForPrefix(const XMLCh* const prefixToMap) const; unsigned int getNamespaceForPrefix(const XMLCh* const prefixToMap, int depthLevel) const; // ----------------------------------------------------------------------- // Miscellaneous methods // ----------------------------------------------------------------------- bool isEmpty() const; void reset(const unsigned int emptyId); private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- NamespaceScope(const NamespaceScope&); void operator=(const NamespaceScope&); // ----------------------------------------------------------------------- // Private helper methods // ----------------------------------------------------------------------- void expandMap(StackElem* const toExpand); void expandStack(); // ----------------------------------------------------------------------- // Data members // // fEmptyNamespaceId // This is the special URI id for the "" namespace, which is magic // because of the xmlns="" operation. // // fPrefixPool // This is the prefix pool where prefixes are hashed and given unique // ids. These ids are used to track prefixes in the element stack. // // fStack // fStackCapacity // fStackTop // This the stack array. Its an array of pointers to StackElem // structures. The capacity is the current high water mark of the // stack. The top is the current top of stack (i.e. the part of it // being used.) // ----------------------------------------------------------------------- unsigned int fEmptyNamespaceId; unsigned int fStackCapacity; unsigned int fStackTop; XMLStringPool fPrefixPool; StackElem** fStack; }; // --------------------------------------------------------------------------- // NamespaceScope: Stack access // --------------------------------------------------------------------------- inline unsigned int NamespaceScope::getNamespaceForPrefix(const XMLCh* const prefixToMap) const { return getNamespaceForPrefix(prefixToMap, (int)(fStackTop - 1)); } // --------------------------------------------------------------------------- // NamespaceScope: Miscellaneous methods // --------------------------------------------------------------------------- inline bool NamespaceScope::isEmpty() const { return (fStackTop == 0); } #endif /** * End of file NameSpaceScope.hpp */ <commit_msg>compilation fix.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #if !defined(NAMESPACESCOPE_HPP) #define NAMESPACESCOPE_HPP #include <util/XercesDefs.hpp> #include <util/StringPool.hpp> // // NamespaceScope provides a data structure for mapping namespace prefixes // to their URI's. The mapping accurately reflects the scoping of namespaces // at a particular instant in time. // class VALIDATORS_EXPORT NamespaceScope { public : // ----------------------------------------------------------------------- // Class specific data types // // These really should be private, but some of the compilers we have to // support are too dumb to deal with that. // // PrefMapElem // fURIId is the id of the URI from the validator's URI map. The // fPrefId is the id of the prefix from our own prefix pool. The // namespace stack consists of these elements. // // StackElem // The fMapCapacity is how large fMap has grown so far. fMapCount // is how many of them are valid right now. // ----------------------------------------------------------------------- struct PrefMapElem { unsigned int fPrefId; unsigned int fURIId; }; struct StackElem { PrefMapElem* fMap; unsigned int fMapCapacity; unsigned int fMapCount; }; // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- NamespaceScope(); ~NamespaceScope(); // ----------------------------------------------------------------------- // Stack access // ----------------------------------------------------------------------- unsigned int increaseDepth(); unsigned int decreaseDepth(); // ----------------------------------------------------------------------- // Prefix map methods // ----------------------------------------------------------------------- void addPrefix(const XMLCh* const prefixToAdd, const unsigned int uriId); unsigned int getNamespaceForPrefix(const XMLCh* const prefixToMap) const; unsigned int getNamespaceForPrefix(const XMLCh* const prefixToMap, const int depthLevel) const; // ----------------------------------------------------------------------- // Miscellaneous methods // ----------------------------------------------------------------------- bool isEmpty() const; void reset(const unsigned int emptyId); private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- NamespaceScope(const NamespaceScope&); void operator=(const NamespaceScope&); // ----------------------------------------------------------------------- // Private helper methods // ----------------------------------------------------------------------- void expandMap(StackElem* const toExpand); void expandStack(); // ----------------------------------------------------------------------- // Data members // // fEmptyNamespaceId // This is the special URI id for the "" namespace, which is magic // because of the xmlns="" operation. // // fPrefixPool // This is the prefix pool where prefixes are hashed and given unique // ids. These ids are used to track prefixes in the element stack. // // fStack // fStackCapacity // fStackTop // This the stack array. Its an array of pointers to StackElem // structures. The capacity is the current high water mark of the // stack. The top is the current top of stack (i.e. the part of it // being used.) // ----------------------------------------------------------------------- unsigned int fEmptyNamespaceId; unsigned int fStackCapacity; unsigned int fStackTop; XMLStringPool fPrefixPool; StackElem** fStack; }; // --------------------------------------------------------------------------- // NamespaceScope: Stack access // --------------------------------------------------------------------------- inline unsigned int NamespaceScope::getNamespaceForPrefix(const XMLCh* const prefixToMap) const { return getNamespaceForPrefix(prefixToMap, (int)(fStackTop - 1)); } // --------------------------------------------------------------------------- // NamespaceScope: Miscellaneous methods // --------------------------------------------------------------------------- inline bool NamespaceScope::isEmpty() const { return (fStackTop == 0); } #endif /** * End of file NameSpaceScope.hpp */ <|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. */ //The dlopen calls were not adding to OS X until 10.3 #ifdef __APPLE__ #include <AvailabilityMacros.h> #if !defined(MAC_OS_X_VERSION_10_3) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3) #define APPLE_PRE_10_3 #endif #endif #if defined(WIN32) && !defined(__CYGWIN__) #include <io.h> #include <windows.h> #include <winbase.h> #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) #include <mach-o/dyld.h> #else // all other unix #include <unistd.h> #ifdef __hpux // Although HP-UX has dlopen() it is broken! We therefore need to stick // to shl_load()/shl_unload()/shl_findsym() #include <dl.h> #include <errno.h> #else #include <dlfcn.h> #endif #endif #include <osg/Notify> #include <osg/GLExtensions> #include <osgDB/DynamicLibrary> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/ConvertUTF> using namespace osgDB; DynamicLibrary::DynamicLibrary(const std::string& name, HANDLE handle) { _name = name; _handle = handle; OSG_INFO<<"Opened DynamicLibrary "<<_name<<std::endl; } DynamicLibrary::~DynamicLibrary() { if (_handle) { OSG_INFO<<"Closing DynamicLibrary "<<_name<<std::endl; #if defined(WIN32) && !defined(__CYGWIN__) FreeLibrary((HMODULE)_handle); #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) NSUnLinkModule(static_cast<NSModule>(_handle), FALSE); #elif defined(__hpux) // fortunately, shl_t is a pointer shl_unload (static_cast<shl_t>(_handle)); #else // other unix dlclose(_handle); #endif } } DynamicLibrary* DynamicLibrary::loadLibrary(const std::string& libraryName) { HANDLE handle = NULL; std::string fullLibraryName = osgDB::findLibraryFile(libraryName); if (!fullLibraryName.empty()) handle = getLibraryHandle( fullLibraryName ); // try the lib we have found else handle = getLibraryHandle( libraryName ); // haven't found a lib ourselves, see if the OS can find it simply from the library name. if (handle) return new DynamicLibrary(libraryName,handle); // else no lib found so report errors. OSG_INFO << "DynamicLibrary::failed loading \""<<libraryName<<"\""<<std::endl; return NULL; } DynamicLibrary::HANDLE DynamicLibrary::getLibraryHandle( const std::string& libraryName) { HANDLE handle = NULL; #if defined(WIN32) && !defined(__CYGWIN__) #ifdef OSG_USE_UTF8_FILENAME handle = LoadLibraryW( convertUTF8toUTF16(libraryName).c_str() ); #else handle = LoadLibrary( libraryName.c_str() ); #endif #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) NSObjectFileImage image; // NSModule os_handle = NULL; if (NSCreateObjectFileImageFromFile(libraryName.c_str(), &image) == NSObjectFileImageSuccess) { // os_handle = NSLinkModule(image, libraryName.c_str(), TRUE); handle = NSLinkModule(image, libraryName.c_str(), TRUE); NSDestroyObjectFileImage(image); } #elif defined(__hpux) // BIND_FIRST is necessary for some reason handle = shl_load ( libraryName.c_str(), BIND_DEFERRED|BIND_FIRST|BIND_VERBOSE, 0); return handle; #else // other unix // dlopen will not work with files in the current directory unless // they are prefaced with './' (DB - Nov 5, 2003). std::string localLibraryName; if( libraryName == osgDB::getSimpleFileName( libraryName ) ) localLibraryName = "./" + libraryName; else localLibraryName = libraryName; handle = dlopen( localLibraryName.c_str(), RTLD_LAZY | RTLD_GLOBAL); if( handle == NULL ) { if (fileExists(localLibraryName)) { OSG_WARN << "Warning: dynamic library '" << libraryName << "' exists, but an error occurred while trying to open it:" << std::endl; OSG_WARN << dlerror() << std::endl; } else { OSG_INFO << "Warning: dynamic library '" << libraryName << "' does not exist (or isn't readable):" << std::endl; OSG_INFO << dlerror() << std::endl; } } #endif return handle; } DynamicLibrary::PROC_ADDRESS DynamicLibrary::getProcAddress(const std::string& procName) { if (_handle==NULL) return NULL; #if defined(WIN32) && !defined(__CYGWIN__) return osg::convertPointerType<DynamicLibrary::PROC_ADDRESS, FARPROC>( GetProcAddress( (HMODULE)_handle, procName.c_str() ) ); #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) std::string temp("_"); NSSymbol symbol; temp += procName; // Mac OS X prepends an underscore on function names symbol = NSLookupSymbolInModule(static_cast<NSModule>(_handle), temp.c_str()); return NSAddressOfSymbol(symbol); #elif defined(__hpux) void* result = NULL; if (shl_findsym (reinterpret_cast<shl_t*>(&_handle), procName.c_str(), TYPE_PROCEDURE, result) == 0) { return result; } else { OSG_WARN << "DynamicLibrary::failed looking up " << procName << std::endl; OSG_WARN << "DynamicLibrary::error " << strerror(errno) << std::endl; return NULL; } #else // other unix void* sym = dlsym( _handle, procName.c_str() ); if (!sym) { OSG_WARN << "DynamicLibrary::failed looking up " << procName << std::endl; OSG_WARN << "DynamicLibrary::error " << dlerror() << std::endl; } return sym; #endif } <commit_msg>Debugging: Hint to debug LoadLibrary issues<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. */ //The dlopen calls were not adding to OS X until 10.3 #ifdef __APPLE__ #include <AvailabilityMacros.h> #if !defined(MAC_OS_X_VERSION_10_3) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3) #define APPLE_PRE_10_3 #endif #endif #if defined(WIN32) && !defined(__CYGWIN__) #include <io.h> #include <windows.h> #include <winbase.h> #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) #include <mach-o/dyld.h> #else // all other unix #include <unistd.h> #ifdef __hpux // Although HP-UX has dlopen() it is broken! We therefore need to stick // to shl_load()/shl_unload()/shl_findsym() #include <dl.h> #include <errno.h> #else #include <dlfcn.h> #endif #endif #include <osg/Notify> #include <osg/GLExtensions> #include <osgDB/DynamicLibrary> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/ConvertUTF> using namespace osgDB; DynamicLibrary::DynamicLibrary(const std::string& name, HANDLE handle) { _name = name; _handle = handle; OSG_INFO<<"Opened DynamicLibrary "<<_name<<std::endl; } DynamicLibrary::~DynamicLibrary() { if (_handle) { OSG_INFO<<"Closing DynamicLibrary "<<_name<<std::endl; #if defined(WIN32) && !defined(__CYGWIN__) FreeLibrary((HMODULE)_handle); #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) NSUnLinkModule(static_cast<NSModule>(_handle), FALSE); #elif defined(__hpux) // fortunately, shl_t is a pointer shl_unload (static_cast<shl_t>(_handle)); #else // other unix dlclose(_handle); #endif } } DynamicLibrary* DynamicLibrary::loadLibrary(const std::string& libraryName) { HANDLE handle = NULL; OSG_DEBUG << "DynamicLibrary::try to load library \"" << libraryName << "\"" << std::endl; std::string fullLibraryName = osgDB::findLibraryFile(libraryName); if (!fullLibraryName.empty()) handle = getLibraryHandle( fullLibraryName ); // try the lib we have found else handle = getLibraryHandle( libraryName ); // haven't found a lib ourselves, see if the OS can find it simply from the library name. if (handle) return new DynamicLibrary(libraryName,handle); // else no lib found so report errors. OSG_INFO << "DynamicLibrary::failed loading \""<<libraryName<<"\""<<std::endl; return NULL; } DynamicLibrary::HANDLE DynamicLibrary::getLibraryHandle( const std::string& libraryName) { HANDLE handle = NULL; #if defined(WIN32) && !defined(__CYGWIN__) #ifdef OSG_USE_UTF8_FILENAME handle = LoadLibraryW( convertUTF8toUTF16(libraryName).c_str() ); #else handle = LoadLibrary( libraryName.c_str() ); #endif #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) NSObjectFileImage image; // NSModule os_handle = NULL; if (NSCreateObjectFileImageFromFile(libraryName.c_str(), &image) == NSObjectFileImageSuccess) { // os_handle = NSLinkModule(image, libraryName.c_str(), TRUE); handle = NSLinkModule(image, libraryName.c_str(), TRUE); NSDestroyObjectFileImage(image); } #elif defined(__hpux) // BIND_FIRST is necessary for some reason handle = shl_load ( libraryName.c_str(), BIND_DEFERRED|BIND_FIRST|BIND_VERBOSE, 0); return handle; #else // other unix // dlopen will not work with files in the current directory unless // they are prefaced with './' (DB - Nov 5, 2003). std::string localLibraryName; if( libraryName == osgDB::getSimpleFileName( libraryName ) ) localLibraryName = "./" + libraryName; else localLibraryName = libraryName; handle = dlopen( localLibraryName.c_str(), RTLD_LAZY | RTLD_GLOBAL); if( handle == NULL ) { if (fileExists(localLibraryName)) { OSG_WARN << "Warning: dynamic library '" << libraryName << "' exists, but an error occurred while trying to open it:" << std::endl; OSG_WARN << dlerror() << std::endl; } else { OSG_INFO << "Warning: dynamic library '" << libraryName << "' does not exist (or isn't readable):" << std::endl; OSG_INFO << dlerror() << std::endl; } } #endif return handle; } DynamicLibrary::PROC_ADDRESS DynamicLibrary::getProcAddress(const std::string& procName) { if (_handle==NULL) return NULL; #if defined(WIN32) && !defined(__CYGWIN__) return osg::convertPointerType<DynamicLibrary::PROC_ADDRESS, FARPROC>( GetProcAddress( (HMODULE)_handle, procName.c_str() ) ); #elif defined(__APPLE__) && defined(APPLE_PRE_10_3) std::string temp("_"); NSSymbol symbol; temp += procName; // Mac OS X prepends an underscore on function names symbol = NSLookupSymbolInModule(static_cast<NSModule>(_handle), temp.c_str()); return NSAddressOfSymbol(symbol); #elif defined(__hpux) void* result = NULL; if (shl_findsym (reinterpret_cast<shl_t*>(&_handle), procName.c_str(), TYPE_PROCEDURE, result) == 0) { return result; } else { OSG_WARN << "DynamicLibrary::failed looking up " << procName << std::endl; OSG_WARN << "DynamicLibrary::error " << strerror(errno) << std::endl; return NULL; } #else // other unix void* sym = dlsym( _handle, procName.c_str() ); if (!sym) { OSG_WARN << "DynamicLibrary::failed looking up " << procName << std::endl; OSG_WARN << "DynamicLibrary::error " << dlerror() << std::endl; } return sym; #endif } <|endoftext|>
<commit_before>//============================================================================ // vSMC/include/vsmc/internal/config.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_INTERNAL_CONFIG_HPP #define VSMC_INTERNAL_CONFIG_HPP #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <vsmc/internal/compiler.hpp> #ifndef VSMC_NO_STATIC_ASSERT #define VSMC_NO_STATIC_ASSERT 0 #endif #ifndef VSMC_NO_RUNTIME_ASSERT #ifndef NDEBUG #define VSMC_NO_RUNTIME_ASSERT 0 #else #define VSMC_NO_RUNTIME_ASSERT 1 #endif #endif #ifndef VSMC_NO_RUNTIME_WARNING #ifndef NDEBUG #define VSMC_NO_RUNTIME_WARNING 0 #else #define VSMC_NO_RUNTIME_WARNING 1 #endif #endif /// \brief Turn vSMC runtime assertions into exceptions /// \ingroup Config #ifndef VSMC_RUNTIME_ASSERT_AS_EXCEPTION #define VSMC_RUNTIME_ASSERT_AS_EXCEPTION 0 #endif /// \brief Turn vSMC runtime warnings into exceptions /// \ingroup Config #ifndef VSMC_RUNTIME_WARNING_AS_EXCEPTION #define VSMC_RUNTIME_WARNING_AS_EXCEPTION 0 #endif // Parallelization features #ifndef VSMC_HAS_CILK #define VSMC_HAS_CILK 0 #endif #ifndef VSMC_HAS_GCD #define VSMC_HAS_GCD 0 #endif #ifndef VSMC_HAS_OMP #define VSMC_HAS_OMP 0 #endif #ifndef VSMC_HAS_PPL #define VSMC_HAS_PPL 0 #endif #ifndef VSMC_HAS_TBB #define VSMC_HAS_TBB 0 #endif #ifndef VSMC_HAS_MPI #define VSMC_HAS_MPI 0 #endif #ifndef VSMC_HAS_OPENCL #define VSMC_HAS_OPENCL 0 #endif // Optional libraries #ifndef VSMC_HAS_GSL #define VSMC_HAS_GSL 0 #endif #ifndef VSMC_HAS_HDF5 #define VSMC_HAS_HDF5 0 #endif #ifndef VSMC_HAS_JEMALLOC #define VSMC_HAS_JEMALLOC 0 #endif #ifndef VSMC_HAS_JEMALLOC_STDAPI #define VSMC_HAS_JEMALLOC_STDAPI 0 #endif #ifndef VSMC_HAS_MKL #define VSMC_HAS_MKL 0 #endif #ifndef VSMC_USE_MKL_CBLAS #define VSMC_USE_MKL_CBLAS VSMC_HAS_MKL #endif #ifndef VSMC_USE_MKL_VML #define VSMC_USE_MKL_VML VSMC_HAS_MKL #endif #ifndef VSMC_USE_MKL_VSL #define VSMC_USE_MKL_VSL VSMC_HAS_MKL #endif #ifndef VSMC_HAS_ACCELERATE #define VSMC_HAS_ACCELERATE 0 #endif #ifndef VSMC_USE_ACCELERATE_CBLAS #define VSMC_USE_ACCELERATE_CBLAS VSMC_HAS_ACCELERATE #endif #ifndef VSMC_USE_ACCELERATE_VFORCE #define VSMC_USE_ACCELERATE_VFORCE VSMC_HAS_ACCELERATE #endif #ifndef VSMC_HAS_TBB_MALLOC #define VSMC_HAS_TBB_MALLOC VSMC_HAS_TBB #endif #endif // VSMC_INTERNAL_CONFIG_HPP <commit_msg>Add USE_TBB config macro<commit_after>//============================================================================ // vSMC/include/vsmc/internal/config.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_INTERNAL_CONFIG_HPP #define VSMC_INTERNAL_CONFIG_HPP #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <vsmc/internal/compiler.hpp> #ifndef VSMC_NO_STATIC_ASSERT #define VSMC_NO_STATIC_ASSERT 0 #endif #ifndef VSMC_NO_RUNTIME_ASSERT #ifndef NDEBUG #define VSMC_NO_RUNTIME_ASSERT 0 #else #define VSMC_NO_RUNTIME_ASSERT 1 #endif #endif #ifndef VSMC_NO_RUNTIME_WARNING #ifndef NDEBUG #define VSMC_NO_RUNTIME_WARNING 0 #else #define VSMC_NO_RUNTIME_WARNING 1 #endif #endif /// \brief Turn vSMC runtime assertions into exceptions /// \ingroup Config #ifndef VSMC_RUNTIME_ASSERT_AS_EXCEPTION #define VSMC_RUNTIME_ASSERT_AS_EXCEPTION 0 #endif /// \brief Turn vSMC runtime warnings into exceptions /// \ingroup Config #ifndef VSMC_RUNTIME_WARNING_AS_EXCEPTION #define VSMC_RUNTIME_WARNING_AS_EXCEPTION 0 #endif // Parallelization features #ifndef VSMC_HAS_CILK #define VSMC_HAS_CILK 0 #endif #ifndef VSMC_HAS_GCD #define VSMC_HAS_GCD 0 #endif #ifndef VSMC_HAS_OMP #define VSMC_HAS_OMP 0 #endif #ifndef VSMC_HAS_PPL #define VSMC_HAS_PPL 0 #endif #ifndef VSMC_HAS_TBB #define VSMC_HAS_TBB 0 #endif #ifndef VSMC_USE_TBB #define VSMC_USE_TBB VSMC_HAS_TBB #endif #ifndef VSMC_HAS_MPI #define VSMC_HAS_MPI 0 #endif #ifndef VSMC_HAS_OPENCL #define VSMC_HAS_OPENCL 0 #endif // Optional libraries #ifndef VSMC_HAS_GSL #define VSMC_HAS_GSL 0 #endif #ifndef VSMC_HAS_HDF5 #define VSMC_HAS_HDF5 0 #endif #ifndef VSMC_HAS_JEMALLOC #define VSMC_HAS_JEMALLOC 0 #endif #ifndef VSMC_HAS_JEMALLOC_STDAPI #define VSMC_HAS_JEMALLOC_STDAPI 0 #endif #ifndef VSMC_HAS_MKL #define VSMC_HAS_MKL 0 #endif #ifndef VSMC_USE_MKL_CBLAS #define VSMC_USE_MKL_CBLAS VSMC_HAS_MKL #endif #ifndef VSMC_USE_MKL_VML #define VSMC_USE_MKL_VML VSMC_HAS_MKL #endif #ifndef VSMC_USE_MKL_VSL #define VSMC_USE_MKL_VSL VSMC_HAS_MKL #endif #ifndef VSMC_HAS_ACCELERATE #define VSMC_HAS_ACCELERATE 0 #endif #ifndef VSMC_USE_ACCELERATE_CBLAS #define VSMC_USE_ACCELERATE_CBLAS VSMC_HAS_ACCELERATE #endif #ifndef VSMC_USE_ACCELERATE_VFORCE #define VSMC_USE_ACCELERATE_VFORCE VSMC_HAS_ACCELERATE #endif #ifndef VSMC_HAS_TBB_MALLOC #define VSMC_HAS_TBB_MALLOC VSMC_HAS_TBB #endif #endif // VSMC_INTERNAL_CONFIG_HPP <|endoftext|>
<commit_before>//============================================================================ // include/vsmc/rng/intrin.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_INTERNAL_INTRIN_HPP #define VSMC_INTERNAL_INTRIN_HPP #include <vsmc/internal/config.hpp> #ifdef _MSC_VER #include <intrin.h> #elif VSMC_HAS_INTRINSIC_FUNCTION #include <x86intrin.h> #else #error x86 intrinsic function is not supported #endif #endif // VSMC_INTERNAL_INTRIN_HPP <commit_msg>remvoe intrin.hpp<commit_after><|endoftext|>
<commit_before>#ifndef VSMC_MPI_BACKEND_MPI_HPP #define VSMC_MPI_BACKEND_MPI_HPP #include <vsmc/internal/common.hpp> #include <vsmc/core/weight.hpp> #include <boost/mpi.hpp> namespace vsmc { /// \brief MPI Communicator /// \ingroup MPI /// /// \details /// Use specialization of the singleton to configure different StateMPI template <typename ID> class MPICommunicator { public : static MPICommunicator<ID> &instance () { static MPICommunicator<ID> comm; return comm; } const MPI_Comm &get () const {return comm_;} void set (const MPI_Comm &comm) {comm_ = comm;} private : MPI_Comm comm_; MPICommunicator () : comm_(MPI_COMM_WORLD) {}; MPICommunicator (const MPICommunicator<ID> &other); MPICommunicator<ID> &operator= (const MPICommunicator<ID> &other); }; // class MPICommunicator /// \brief Particle::weight_set_type subtype using MPI /// \ingroup MPI template <typename BaseState, typename ID> class WeightSetMPI : public WeightSet<BaseState> { public : typedef typename traits::SizeTypeTrait<BaseState>::type size_type; explicit WeightSetMPI (size_type N) : WeightSet<BaseState>(N), world_(MPICommunicator<ID>::instance().get(), boost::mpi::comm_duplicate), ess_(static_cast<double>(N) * world_.size()) {} size_type resample_size () const {return this->size() * world_.size();} template <typename OutputIter> OutputIter read_resample_weight (OutputIter first) const { world_.barrier(); boost::mpi::all_gather(world_, this->weight_vec(), weight_gather_); for (int r = 0; r != world_.size(); ++r) for (size_type i = 0; i != this->size(); ++i, ++first) *first = weight_gather_[r][i]; world_.barrier(); return first; } template <typename RandomIter> RandomIter read_resample_weight (RandomIter first, int stride) const { world_.barrier(); boost::mpi::all_gather(world_, this->weight_vec(), weight_gather_); for (int r = 0; r != world_.size(); ++r) for (size_type i = 0; i != this->size(); ++i, first += stride) *first = weight_gather_[r][i]; world_.barrier(); return first; } void set_equal_weight () { world_.barrier(); ess_ = static_cast<double>(this->size()) * world_.size(); double ew = 1 / ess_; std::vector<double> &weight = this->weight_vec(); std::vector<double> &log_weight = this->log_weight_vec(); for (size_type i = 0; i != this->size(); ++i) { weight[i] = ew; log_weight[i] = 0; } world_.barrier(); } double ess () const {return ess_;} private : boost::mpi::communicator world_; double ess_; mutable std::vector<std::vector<double> > weight_gather_; void normalize_weight () { world_.barrier(); std::vector<double> &weight = this->weight_vec(); double lcoeff = 0; for (size_type i = 0; i != this->size(); ++i) lcoeff += weight[i]; double gcoeff = 0; boost::mpi::all_reduce(world_, lcoeff, gcoeff, std::plus<double>()); gcoeff = 1 / gcoeff; for (size_type i = 0; i != this->size(); ++i) weight[i] *= gcoeff; double less = 0; for (size_type i = 0; i != this->size(); ++i) less += weight[i] * weight[i]; double gess = 0; boost::mpi::all_reduce(world_, less, gess, std::plus<double>()); gess = 1 / gess; ess_ = gess; world_.barrier(); } }; // class WeightSetMPI /// \brief Particle::value_type subtype using MPI /// \ingroup MPI template <typename BaseState, typename ID> class StateMPI : public BaseState { public : typedef typename traits::SizeTypeTrait<BaseState>::type size_type; typedef WeightSetMPI<BaseState, ID> weight_set_type; explicit StateMPI (size_type N) : BaseState(N), world_(MPICommunicator<ID>::instance().get(), boost::mpi::comm_duplicate), offset_(N * static_cast<size_type>(world_.rank())), copy_tag_(boost::mpi::environment::max_tag()) {} /// \brief Copy particles /// /// \details /// The tag `boost::mpi::environment::max_tag()` is reserved by vSMC for /// copy particles. template <typename IntType> void copy (size_type N, const IntType *copy_from) { VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH_MPI; world_.barrier(); copy_from_.resize(N); if (world_.rank() == 0) { for (size_type i = 0; i != N; ++i) copy_from_[i] = copy_from[i]; } boost::mpi::broadcast(world_, copy_from_, 0); copy_recv_.clear(); copy_send_.clear(); int rank_this = world_.rank(); for (size_type to = 0; to != N; ++to) { size_type from = copy_from_[to]; int rank_recv = rank(to); int rank_send = rank(from); size_type id_recv = local_id(to); size_type id_send = local_id(from); if (rank_this == rank_recv && rank_this == rank_send) { this->copy_particle(id_send, id_recv); } else if (rank_this == rank_recv) { copy_recv_.push_back(std::make_pair(rank_send, id_recv)); } else if (rank_this == rank_send) { copy_send_.push_back(std::make_pair(rank_recv, id_send)); } } for (int r = 0; r != world_.size(); ++r) { if (rank_this == r) { for (std::size_t i = 0; i != copy_recv_.size(); ++i) { typename BaseState::state_pack_type pack; world_.recv(copy_recv_[i].first, copy_tag_, pack); this->state_unpack(copy_recv_[i].second, pack); } } else { for (std::size_t i = 0; i != copy_send_.size(); ++i) { if (copy_send_[i].first == r) { world_.send(copy_send_[i].first, copy_tag_, this->state_pack(copy_send_[i].second)); } } } world_.barrier(); } world_.barrier(); } /// \brief A duplicated MPI communicator for this object const boost::mpi::communicator &world () const {return world_;} protected : size_type offset () const {return offset_;} int rank (size_type global_id) const {return static_cast<int>(global_id / this->size());} bool is_local (size_type global_id) const {return global_id >= offset_ && global_id < this->size() + offset_;} size_type local_id (size_type global_id) const {return global_id - this->size() * rank(global_id);} private : boost::mpi::communicator world_; size_type offset_; int copy_tag_; std::vector<size_type> copy_from_; std::vector<std::pair<int, size_type> > copy_recv_; std::vector<std::pair<int, size_type> > copy_send_; }; // class StateMPI } // namespace vsmc #endif // VSMC_MPI_BACKEND_MPI_HPP <commit_msg>modulize StateMPI::copy<commit_after>#ifndef VSMC_MPI_BACKEND_MPI_HPP #define VSMC_MPI_BACKEND_MPI_HPP #include <vsmc/internal/common.hpp> #include <vsmc/core/weight.hpp> #include <boost/mpi.hpp> namespace vsmc { /// \brief MPI Communicator /// \ingroup MPI /// /// \details /// Use specialization of the singleton to configure different StateMPI template <typename ID> class MPICommunicator { public : static MPICommunicator<ID> &instance () { static MPICommunicator<ID> comm; return comm; } const MPI_Comm &get () const {return comm_;} void set (const MPI_Comm &comm) {comm_ = comm;} private : MPI_Comm comm_; MPICommunicator () : comm_(MPI_COMM_WORLD) {}; MPICommunicator (const MPICommunicator<ID> &other); MPICommunicator<ID> &operator= (const MPICommunicator<ID> &other); }; // class MPICommunicator /// \brief Particle::weight_set_type subtype using MPI /// \ingroup MPI template <typename BaseState, typename ID> class WeightSetMPI : public WeightSet<BaseState> { public : typedef typename traits::SizeTypeTrait<BaseState>::type size_type; explicit WeightSetMPI (size_type N) : WeightSet<BaseState>(N), world_(MPICommunicator<ID>::instance().get(), boost::mpi::comm_duplicate), ess_(static_cast<double>(N) * world_.size()) {} size_type resample_size () const {return this->size() * world_.size();} template <typename OutputIter> OutputIter read_resample_weight (OutputIter first) const { world_.barrier(); boost::mpi::all_gather(world_, this->weight_vec(), weight_gather_); for (int r = 0; r != world_.size(); ++r) for (size_type i = 0; i != this->size(); ++i, ++first) *first = weight_gather_[r][i]; world_.barrier(); return first; } template <typename RandomIter> RandomIter read_resample_weight (RandomIter first, int stride) const { world_.barrier(); boost::mpi::all_gather(world_, this->weight_vec(), weight_gather_); for (int r = 0; r != world_.size(); ++r) for (size_type i = 0; i != this->size(); ++i, first += stride) *first = weight_gather_[r][i]; world_.barrier(); return first; } void set_equal_weight () { world_.barrier(); ess_ = static_cast<double>(this->size()) * world_.size(); double ew = 1 / ess_; std::vector<double> &weight = this->weight_vec(); std::vector<double> &log_weight = this->log_weight_vec(); for (size_type i = 0; i != this->size(); ++i) { weight[i] = ew; log_weight[i] = 0; } world_.barrier(); } double ess () const {return ess_;} private : boost::mpi::communicator world_; double ess_; mutable std::vector<std::vector<double> > weight_gather_; void normalize_weight () { world_.barrier(); std::vector<double> &weight = this->weight_vec(); double lcoeff = 0; for (size_type i = 0; i != this->size(); ++i) lcoeff += weight[i]; double gcoeff = 0; boost::mpi::all_reduce(world_, lcoeff, gcoeff, std::plus<double>()); gcoeff = 1 / gcoeff; for (size_type i = 0; i != this->size(); ++i) weight[i] *= gcoeff; double less = 0; for (size_type i = 0; i != this->size(); ++i) less += weight[i] * weight[i]; double gess = 0; boost::mpi::all_reduce(world_, less, gess, std::plus<double>()); gess = 1 / gess; ess_ = gess; world_.barrier(); } }; // class WeightSetMPI /// \brief Particle::value_type subtype using MPI /// \ingroup MPI template <typename BaseState, typename ID> class StateMPI : public BaseState { public : typedef typename traits::SizeTypeTrait<BaseState>::type size_type; typedef WeightSetMPI<BaseState, ID> weight_set_type; explicit StateMPI (size_type N) : BaseState(N), world_(MPICommunicator<ID>::instance().get(), boost::mpi::comm_duplicate), offset_(N * static_cast<size_type>(world_.rank())), copy_tag_(boost::mpi::environment::max_tag()) {} /// \brief Copy particles /// /// \param N The number of particles on all nodes /// \param copy_from A vector of length `N`, for each particle with global /// id `to`, `copy_from[to]` is the global id of the particle it shall /// copy. /// /// \details /// The `BaseState` type is required to have the following members /// - `state_pack_type`: A type that used to pack state values. It shall be /// serializable. That is, a `state_pack_type` object is acceptable by /// `boost::mpi::communicator::send` etc. Both /// `StateMatrix::state_pack_type` and `StateTuple::state_pack_type` /// satisfy this requirement if their template type parameter types are /// serializable. For user defined types, see document of Boost.Serialize /// of how to serialize a class object. /// - `state_pack` /// \code /// state_pack_type state_pack (size_type id) const; /// \endcode /// Given a local particle id on this node, pack the state values into a /// `state_pack_type` object. /// - `state_unpack` /// \code /// void state_unpack (size_type id, const state_pack_type &pack); /// \endcode /// Given a local particle id and a `state_pack_type` object, unpack it /// into the given position on this node. /// /// In vSMC, the resampling algorithms generate the number of replications /// of each particle. Particles with replication zero need to copy other /// particles. The vector of the number of replications is transfered to /// `copy_from` by `Particle::resample`, and it is generated in such a way /// that each particle will copy from somewhere close to itself. Therefore, /// transferring between nodes is minimized. /// /// This default implementation perform three stages of copy. /// - Stage one: Generate a local duplicate of `copy_from` on node `0` and /// broadcast it to all nodes. /// - Stage two: Perform local copy, copy those particles where the /// destination and source are both on this node. This is performed in /// parallel on each node. /// - Stage three: copy particles that need message passing between nodes. /// /// A derived class can override this `copy` method. For the following /// possible reasons, /// - Stage one is not needed or too expansive /// - Stage three is too expansive. The default implementation assumes /// `this->state_pack(id)` is not too expansive, and inter-node copy is /// rare anyway. If this is not the case, then it can be a performance /// bottle neck. template <typename IntType> void copy (size_type N, const IntType *copy_from) { VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH_MPI; world_.barrier(); copy_from_.resize(N); if (world_.rank() == 0) { for (size_type i = 0; i != N; ++i) copy_from_[i] = copy_from[i]; } boost::mpi::broadcast(world_, copy_from_, 0); copy_this_node(N, &copy_from_[0], copy_recv_, copy_send_); world_.barrier(); copy_inter_node(copy_recv_, copy_send_); world_.barrier(); } /// \brief A duplicated MPI communicator for this object const boost::mpi::communicator &world () const {return world_;} /// \brief The number of particles on all nodes size_type global_size () const {return this->size() * static_cast<size_type>(world_.size());} /// \brief The number of particles on nodes with ranks less than the rank /// of this node. size_type offset () const {return offset_;} /// \brief Given a global particle id return the rank of the node it /// belongs int rank (size_type global_id) const {return static_cast<int>(global_id / this->size());} /// \brief Given a global particle id check if it is on this `node` bool is_local (size_type global_id) const {return global_id >= offset_ && global_id < this->size() + offset_;} /// \brief Transfer a global particle id into a local particle id size_type local_id (size_type global_id) const {return global_id - this->size() * rank(global_id);} protected : /// \brief The MPI recv/send tag used by `copy_inter_node` int copy_tag () const {return copy_tag_;} /// \brief Perform local copy /// /// \param N The number of particles on all nodes /// \param copy_from_first The first iterator of the copy_from vector /// \param copy_recv All particles that shall be received at this node /// \param copy_send All particles that shall be send from this node /// /// \details /// `copy_from_first` can be a one-pass input iterator used to access a /// vector of size `N`, say `copy_from`. /// For each `to` in the range `0` to `N - 1` /// - If both `to` and `from = copy_from[to]` are particles on this node, /// invoke `copy_particle` to copy the parties. Otherwise, /// - If `to` is a particle on this node, insert a pair into `copy_recv`, /// whose values are the rank of the node from which this node shall /// receive the particle and the particle id *on this node* where the /// particle received shall be unpacked. Otherwise, /// - If `from = copy_from[to]` is a particle on this node, insert a pair /// into `copy_send`, whose values are the rank of the node to which this /// node shall send the particle and the particle id *on this node* where /// the particle sent shall be packed. Otherwise do nothing. /// /// \note /// It is important the the vector access through `copy_from_first` is the /// same for all nodes. Otherwise the behavior is undefined. template <typename InputIter> void copy_this_node (size_type N, InputIter copy_from_first, std::vector<std::pair<int, size_type> > &copy_recv, std::vector<std::pair<int, size_type> > &copy_send) { copy_recv.clear(); copy_send.clear(); int rank_this = world_.rank(); for (size_type to = 0; to != N; ++to, ++copy_from_first) { size_type from = *copy_from_first; int rank_recv = rank(to); int rank_send = rank(from); size_type id_recv = local_id(to); size_type id_send = local_id(from); if (rank_this == rank_recv && rank_this == rank_send) { this->copy_particle(id_send, id_recv); } else if (rank_this == rank_recv) { copy_recv.push_back(std::make_pair(rank_send, id_recv)); } else if (rank_this == rank_send) { copy_send.push_back(std::make_pair(rank_recv, id_send)); } } } /// \brief Perform global copy /// /// \param copy_recv The output vector `copy_recv` from `copy_this_node` /// \param copy_send The output vector `copy_send` from `copy_this_node` void copy_inter_node ( const std::vector<std::pair<int, size_type> > &copy_recv, const std::vector<std::pair<int, size_type> > &copy_send) { int rank_this = world_.rank(); for (int r = 0; r != world_.size(); ++r) { if (rank_this == r) { for (std::size_t i = 0; i != copy_recv.size(); ++i) { typename BaseState::state_pack_type pack; world_.recv(copy_recv_[i].first, copy_tag_, pack); this->state_unpack(copy_recv[i].second, pack); } } else { for (std::size_t i = 0; i != copy_send.size(); ++i) { if (copy_send_[i].first == r) { world_.send(copy_send_[i].first, copy_tag_, this->state_pack(copy_send[i].second)); } } } } } private : boost::mpi::communicator world_; size_type offset_; int copy_tag_; std::vector<size_type> copy_from_; std::vector<std::pair<int, size_type> > copy_recv_; std::vector<std::pair<int, size_type> > copy_send_; }; // class StateMPI } // namespace vsmc #endif // VSMC_MPI_BACKEND_MPI_HPP <|endoftext|>
<commit_before>// 01.01.2017 Султан Xottab_DUTY Урамаев // Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим. #include <iostream> #include <thread> #include <GLFW/glfw3.h> #include <dynlib/Dynlib.hpp> #include "xdCore.hpp" #include "Console.hpp" #include "ConsoleCommand.hpp" #include "xdEngine.hpp" #include "Debug/QuantMS.hpp" void InitializeConsole() { ConsoleCommands = new CC_Container; Console = new xdConsole; Console->Initialize(); } void destroyConsole() { ConsoleCommands->Execute("config_save"); ConsoleCommands->Destroy(); delete ConsoleCommands; Console->CloseLog(); delete Console; } void HelpCmdArgs() { Console->Log("\nUse parameters with values only with quotes(-param \"value\")\n"\ "-param value will return \"alue\"\n"\ "-param \"value\" will return \"value\"\n\n"\ "Available parameters:\n"\ "-name - Specifies AppName, default is \"X-Day Engine\" \n"\ "-game - Specifies game library to be attached, default is \"xdGame\";\n" "-datapath - Specifies path of application data folder, default is \"*WorkingDirectory*/appdata\"\n"\ "-respath - Specifies path of resources folder, default is \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Specifies path and name of main config file (path/name.extension), default is \"*DataPath*/main.config\" \n"\ "-mainlog - Specifies path and name of main log file (path/name.extension), default is \"*DataPath*/main.log\"\n"\ "-nolog - Completely disables engine log. May increase performance\n"\ "-nologflush - Disables log flushing. Useless if -nolog defined\n"); Console->Log("\nИспользуйте параметры только с кавычками(-параметр \"значение\")\n"\ "-параметр значение вернёт \"начени\"\n"\ "-параметр \"значение\" вернёт \"значение\"\n"\ "\nДоступные параметры:\n"\ "-name - Задаёт AppName, по умолчанию: \"X-Day Engine\" \n"\ "-game - Задаёт игровую библиотеку для подключения, по умолчанию: \"xdGame\";\n" "-datapath - Задаёт путь до папки с настройками, по умолчанию: \"*WorkingDirectory*/appdata\"\n"\ "-respath - Задаёт путь до папки с ресурсами, по умолчанию: \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Задаёт путь и имя главного файла настроек (путь/имя.расширение), по умолчанию: \"*DataPath*/main.config\" \n"\ "-mainlog - Задаёт путь и имя главного лог файла (путь/имя.расширение), по умолчанию: \"*DataPath*/main.log\"\n"\ "-nolog - Полностью выключает лог движка. Может повысить производительность\n"\ "-nologflush - Выключает сброс лога в файл. Не имеет смысла если задан -nolog\n", false); } void threadedConsole() { while (!glfwWindowShouldClose(Engine.window)) { std::string input; std::getline(std::cin, input); ConsoleCommands->Execute(input); } } void Startup() { while (!glfwWindowShouldClose(Engine.window)) { if (ConsoleCommands->GetBool("r_fullscreen")) glfwSetWindowMonitor(Engine.window, Engine.CurrentMonitor, 0, 0, Engine.CurrentMode->width, Engine.CurrentMode->height, Engine.CurrentMode->refreshRate); else glfwSetWindowMonitor(Engine.window, nullptr, 0, 0, Engine.CurrentMode->width-256, Engine.CurrentMode->height-256, Engine.CurrentMode->refreshRate); glfwPollEvents(); } } int main(int argc, char* argv[]) { QuantMS(); #ifdef WINDOWS system("chcp 65001"); #endif Core.Initialize("X-Day Engine", **argv); InitializeConsole(); Console->Log(Core.GetGLFWVersionString()); Console->Log(Core.GetBuildString()); Console->Log("Core.Params: " + Core.Params); Console->Log("Девиз: Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим.", false); Console->Log("Slogan: It's more interesting to shoot your feet, than catch arrows by your knee. Let's continue."); HelpCmdArgs(); ConsoleCommands->ExecuteConfig(Console->ConfigFile.string()); glfwInit(); Console->Log("GLFW initialized."); Engine.Initialize(); Engine.xdCreateWindow(); auto xdSoundModule = Dynlib::open(Core.GetModuleName("xdSound").c_str()); if (xdSoundModule) { Console->Log("Module loaded successfully"); } auto impFunc = (FunctionPointer)Dynlib::load(xdSoundModule, "funcToExport"); if (impFunc) impFunc(); else Console->Log("Failed to import function"); if (Dynlib::close(xdSoundModule)) { Console->Log("Module unloaded successfully"); } std::thread WatchConsole(threadedConsole); WatchConsole.detach(); Startup(); glfwTerminate(); Console->Log("GLFW terminated."); auto TotalTimer = QuantMS(); ConsoleMsg("Total time: {} seconds", TotalTimer/1000000); destroyConsole(); system("pause"); return 0; } <commit_msg>"Fix" GLFW initialization "check"<commit_after>// 01.01.2017 Султан Xottab_DUTY Урамаев // Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим. #include <iostream> #include <thread> #include <GLFW/glfw3.h> #include <dynlib/Dynlib.hpp> #include "xdCore.hpp" #include "Console.hpp" #include "ConsoleCommand.hpp" #include "xdEngine.hpp" #include "Debug/QuantMS.hpp" void InitializeConsole() { ConsoleCommands = new CC_Container; Console = new xdConsole; Console->Initialize(); } void destroyConsole() { ConsoleCommands->Execute("config_save"); ConsoleCommands->Destroy(); delete ConsoleCommands; Console->CloseLog(); delete Console; } void HelpCmdArgs() { Console->Log("\nUse parameters with values only with quotes(-param \"value\")\n"\ "-param value will return \"alue\"\n"\ "-param \"value\" will return \"value\"\n\n"\ "Available parameters:\n"\ "-name - Specifies AppName, default is \"X-Day Engine\" \n"\ "-game - Specifies game library to be attached, default is \"xdGame\";\n" "-datapath - Specifies path of application data folder, default is \"*WorkingDirectory*/appdata\"\n"\ "-respath - Specifies path of resources folder, default is \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Specifies path and name of main config file (path/name.extension), default is \"*DataPath*/main.config\" \n"\ "-mainlog - Specifies path and name of main log file (path/name.extension), default is \"*DataPath*/main.log\"\n"\ "-nolog - Completely disables engine log. May increase performance\n"\ "-nologflush - Disables log flushing. Useless if -nolog defined\n"); Console->Log("\nИспользуйте параметры только с кавычками(-параметр \"значение\")\n"\ "-параметр значение вернёт \"начени\"\n"\ "-параметр \"значение\" вернёт \"значение\"\n"\ "\nДоступные параметры:\n"\ "-name - Задаёт AppName, по умолчанию: \"X-Day Engine\" \n"\ "-game - Задаёт игровую библиотеку для подключения, по умолчанию: \"xdGame\";\n" "-datapath - Задаёт путь до папки с настройками, по умолчанию: \"*WorkingDirectory*/appdata\"\n"\ "-respath - Задаёт путь до папки с ресурсами, по умолчанию: \"*WorkingDirectory*/res\"\n"\ "-mainconfig - Задаёт путь и имя главного файла настроек (путь/имя.расширение), по умолчанию: \"*DataPath*/main.config\" \n"\ "-mainlog - Задаёт путь и имя главного лог файла (путь/имя.расширение), по умолчанию: \"*DataPath*/main.log\"\n"\ "-nolog - Полностью выключает лог движка. Может повысить производительность\n"\ "-nologflush - Выключает сброс лога в файл. Не имеет смысла если задан -nolog\n", false); } void threadedConsole() { while (!glfwWindowShouldClose(Engine.window)) { std::string input; std::getline(std::cin, input); ConsoleCommands->Execute(input); } } void Startup() { while (!glfwWindowShouldClose(Engine.window)) { if (ConsoleCommands->GetBool("r_fullscreen")) glfwSetWindowMonitor(Engine.window, Engine.CurrentMonitor, 0, 0, Engine.CurrentMode->width, Engine.CurrentMode->height, Engine.CurrentMode->refreshRate); else glfwSetWindowMonitor(Engine.window, nullptr, 0, 0, Engine.CurrentMode->width-256, Engine.CurrentMode->height-256, Engine.CurrentMode->refreshRate); glfwPollEvents(); } } int main(int argc, char* argv[]) { QuantMS(); #ifdef WINDOWS system("chcp 65001"); #endif Core.Initialize("X-Day Engine", **argv); InitializeConsole(); Console->Log(Core.GetGLFWVersionString()); Console->Log(Core.GetBuildString()); Console->Log("Core.Params: " + Core.Params); Console->Log("Девиз: Чем стрелы коленом ловить, гораздо интереснее отстреливать свои ноги. Продолжим.", false); Console->Log("Slogan: It's more interesting to shoot your feet, than catch arrows by your knee. Let's continue."); HelpCmdArgs(); ConsoleCommands->ExecuteConfig(Console->ConfigFile.string()); if (glfwInit()) Console->Log("GLFW initialized."); else Console->Log("GLFW not initialized."); Engine.Initialize(); Engine.xdCreateWindow(); auto xdSoundModule = Dynlib::open(Core.GetModuleName("xdSound").c_str()); if (xdSoundModule) { Console->Log("Module loaded successfully"); } auto impFunc = (FunctionPointer)Dynlib::load(xdSoundModule, "funcToExport"); if (impFunc) impFunc(); else Console->Log("Failed to import function"); if (Dynlib::close(xdSoundModule)) { Console->Log("Module unloaded successfully"); } std::thread WatchConsole(threadedConsole); WatchConsole.detach(); Startup(); glfwTerminate(); Console->Log("GLFW terminated."); auto TotalTimer = QuantMS(); ConsoleMsg("Total time: {} seconds", TotalTimer/1000000); destroyConsole(); system("pause"); return 0; } <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2012-2014 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // N-Dimensional Simplex Point Generation #ifndef INCLUDED_NDSIMPLEX #define INCLUDED_NDSIMPLEX #include "libgibbs/include/optimizer/halton.hpp" #include "libgibbs/include/utils/primes.hpp" #include <boost/assert.hpp> #include <boost/math/special_functions/factorials.hpp> #include <vector> #include <algorithm> struct NDSimplex { // Reference: Chasalow and Brand, 1995, "Algorithm AS 299: Generation of Simplex Lattice Points" template <typename Func> static inline void lattice ( const std::size_t point_dimension, const std::size_t grid_points_per_major_axis, const Func &func ) { BOOST_ASSERT(grid_points_per_major_axis >= 2); BOOST_ASSERT(point_dimension >= 1); typedef std::vector<double> PointType; const double lattice_spacing = 1.0 / (double)grid_points_per_major_axis; const PointType::value_type lower_limit = 0; const PointType::value_type upper_limit = 1; PointType point; // Contains current point PointType::iterator coord_find; // corresponds to 'j' in Chasalow and Brand // Special case: 1 component; only valid point is {1} if (point_dimension == 1) { point.push_back(1); func(point); return; } // Initialize algorithm point.resize(point_dimension, lower_limit); // Fill with smallest value (0) const PointType::iterator last_coord = --point.end(); coord_find = point.begin(); *coord_find = upper_limit; // point should now be {1,0,0,0....} do { func(point); *coord_find -= lattice_spacing; if (*coord_find < lattice_spacing/2) *coord_find = lower_limit; // workaround for floating point issues if (std::distance(coord_find,point.end()) > 2) { ++coord_find; *coord_find = lattice_spacing + *last_coord; *last_coord = lower_limit; } else { *last_coord += lattice_spacing; while (*coord_find == lower_limit) --coord_find; } } while (*last_coord < upper_limit); func(point); // should be {0,0,...1} } static inline std::vector<std::vector<double>> lattice_complex( const std::vector<std::size_t> &components_in_sublattices, const std::size_t grid_points_per_major_axis ) { using boost::math::factorial; typedef std::vector<double> PointType; typedef std::vector<PointType> PointCollection; std::vector<PointCollection> point_lattices; // Simplex lattices for each sublattice std::vector<PointType> points; // The final return points (combination of all simplex lattices) std::size_t expected_points = 1; std::size_t point_dimension = 0; // TODO: Is there a way to do this without all the copying? for (auto i = components_in_sublattices.cbegin(); i != components_in_sublattices.cend(); ++i) { PointCollection simplex_points; // all points for this simplex const unsigned int q = *i; // number of components point_dimension += q; const unsigned int m = grid_points_per_major_axis - 2; // number of evenly spaced values _between_ 0 and 1 auto point_add = [&simplex_points] (PointType &address) { simplex_points.push_back(address); std::cout << "point_add: ["; for (auto u = address.begin(); u != address.end(); ++u) std::cout << *u << ","; std::cout << "]" << std::endl; }; lattice(q, grid_points_per_major_axis, point_add); expected_points *= simplex_points.size(); point_lattices.push_back(simplex_points); // push points for each simplex } std::cout << "expected_points: " << expected_points << std::endl; points.reserve(expected_points); for (auto p = 0; p < expected_points; ++p) { PointType point; std::size_t dividend = p; point.reserve(point_dimension); std::cout << "p : " << p << " indices: ["; for (auto r = point_lattices.rbegin(); r != point_lattices.rend(); ++r) { std::cout << dividend % r->size() << ","; point.insert(point.end(),(*r)[dividend % r->size()].begin(),(*r)[dividend % r->size()].end()); dividend = dividend / r->size(); } std::cout << "]" << std::endl; std::reverse(point.begin(),point.end()); points.push_back(point); } return points; } // Reference for Halton sequence: Hess and Polak, 2003. // Reference for uniformly sampling the simplex: Any text on the Dirichlet distribution template <typename Func> static inline void quasirandom_sample ( const std::size_t point_dimension, const std::size_t number_of_points, const Func &func ) { BOOST_ASSERT(point_dimension < primes_size()); // No realistic problem should ever violate this // TODO: Add the shuffling part to the Halton sequence. This will help with correlation problems for large N // TODO: Default-add the end-members (vertices) of the N-simplex for (auto sequence_pos = 1; sequence_pos <= number_of_points; ++sequence_pos) { std::vector<double> point; double point_sum = 0; for (auto i = 0; i < point_dimension; ++i) { // Draw the coordinate from an exponential distribution // N samples from the exponential distribution, when normalized to 1, will be distributed uniformly // on a facet of the N-simplex. // If X is uniformly distributed, then -LN(X) is exponentially distributed. // Since the Halton sequence is a low-discrepancy sequence over [0,1], we substitute it for the uniform distribution // This makes this algorithm deterministic and may also provide some domain coverage advantages over a // psuedo-random sample. double value = -log(halton(sequence_pos,primes[i])); point_sum += value; point.push_back(value); } for (auto i = point.begin(); i != point.end(); ++i) *i /= point_sum; // Normalize point to sum to 1 func(point); if (point_dimension == 1) break; // no need to generate additional points; only one feasible point exists for 0-simplex } } }; #endif <commit_msg>Remove some debug code<commit_after>/*============================================================================= Copyright (c) 2012-2014 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // N-Dimensional Simplex Point Generation #ifndef INCLUDED_NDSIMPLEX #define INCLUDED_NDSIMPLEX #include "libgibbs/include/optimizer/halton.hpp" #include "libgibbs/include/utils/primes.hpp" #include <boost/assert.hpp> #include <boost/math/special_functions/factorials.hpp> #include <vector> #include <algorithm> struct NDSimplex { // Reference: Chasalow and Brand, 1995, "Algorithm AS 299: Generation of Simplex Lattice Points" template <typename Func> static inline void lattice ( const std::size_t point_dimension, const std::size_t grid_points_per_major_axis, const Func &func ) { BOOST_ASSERT(grid_points_per_major_axis >= 2); BOOST_ASSERT(point_dimension >= 1); typedef std::vector<double> PointType; const double lattice_spacing = 1.0 / (double)grid_points_per_major_axis; const PointType::value_type lower_limit = 0; const PointType::value_type upper_limit = 1; PointType point; // Contains current point PointType::iterator coord_find; // corresponds to 'j' in Chasalow and Brand // Special case: 1 component; only valid point is {1} if (point_dimension == 1) { point.push_back(1); func(point); return; } // Initialize algorithm point.resize(point_dimension, lower_limit); // Fill with smallest value (0) const PointType::iterator last_coord = --point.end(); coord_find = point.begin(); *coord_find = upper_limit; // point should now be {1,0,0,0....} do { func(point); *coord_find -= lattice_spacing; if (*coord_find < lattice_spacing/2) *coord_find = lower_limit; // workaround for floating point issues if (std::distance(coord_find,point.end()) > 2) { ++coord_find; *coord_find = lattice_spacing + *last_coord; *last_coord = lower_limit; } else { *last_coord += lattice_spacing; while (*coord_find == lower_limit) --coord_find; } } while (*last_coord < upper_limit); func(point); // should be {0,0,...1} } static inline std::vector<std::vector<double>> lattice_complex( const std::vector<std::size_t> &components_in_sublattices, const std::size_t grid_points_per_major_axis ) { using boost::math::factorial; typedef std::vector<double> PointType; typedef std::vector<PointType> PointCollection; std::vector<PointCollection> point_lattices; // Simplex lattices for each sublattice std::vector<PointType> points; // The final return points (combination of all simplex lattices) std::size_t expected_points = 1; std::size_t point_dimension = 0; // TODO: Is there a way to do this without all the copying? for (auto i = components_in_sublattices.cbegin(); i != components_in_sublattices.cend(); ++i) { PointCollection simplex_points; // all points for this simplex const unsigned int q = *i; // number of components point_dimension += q; const unsigned int m = grid_points_per_major_axis - 2; // number of evenly spaced values _between_ 0 and 1 auto point_add = [&simplex_points] (PointType &address) { simplex_points.push_back(address); }; lattice(q, grid_points_per_major_axis, point_add); expected_points *= simplex_points.size(); point_lattices.push_back(simplex_points); // push points for each simplex } points.reserve(expected_points); for (auto p = 0; p < expected_points; ++p) { PointType point; std::size_t dividend = p; point.reserve(point_dimension); std::cout << "p : " << p << " indices: ["; for (auto r = point_lattices.rbegin(); r != point_lattices.rend(); ++r) { std::cout << dividend % r->size() << ","; point.insert(point.end(),(*r)[dividend % r->size()].begin(),(*r)[dividend % r->size()].end()); dividend = dividend / r->size(); } std::cout << "]" << std::endl; std::reverse(point.begin(),point.end()); points.push_back(point); } return points; } // Reference for Halton sequence: Hess and Polak, 2003. // Reference for uniformly sampling the simplex: Any text on the Dirichlet distribution template <typename Func> static inline void quasirandom_sample ( const std::size_t point_dimension, const std::size_t number_of_points, const Func &func ) { BOOST_ASSERT(point_dimension < primes_size()); // No realistic problem should ever violate this // TODO: Add the shuffling part to the Halton sequence. This will help with correlation problems for large N // TODO: Default-add the end-members (vertices) of the N-simplex for (auto sequence_pos = 1; sequence_pos <= number_of_points; ++sequence_pos) { std::vector<double> point; double point_sum = 0; for (auto i = 0; i < point_dimension; ++i) { // Draw the coordinate from an exponential distribution // N samples from the exponential distribution, when normalized to 1, will be distributed uniformly // on a facet of the N-simplex. // If X is uniformly distributed, then -LN(X) is exponentially distributed. // Since the Halton sequence is a low-discrepancy sequence over [0,1], we substitute it for the uniform distribution // This makes this algorithm deterministic and may also provide some domain coverage advantages over a // psuedo-random sample. double value = -log(halton(sequence_pos,primes[i])); point_sum += value; point.push_back(value); } for (auto i = point.begin(); i != point.end(); ++i) *i /= point_sum; // Normalize point to sum to 1 func(point); if (point_dimension == 1) break; // no need to generate additional points; only one feasible point exists for 0-simplex } } }; #endif <|endoftext|>
<commit_before>/* GRANULATE - granulation of sound stored in a table Any parameter marked with '*' can receive updates from a real-time control source. p0 = output start time * p1 = input start time (will be constrained to window, p5-6) NOTE: Unlike other instruments, this applies to a table, not to an input sound file. p2 = total duration * p3 = amplitude multiplier p4 = input sound table (e.g., maketable("sndfile", ...)) p5 = number of channels in sample table * p6 = input channel of sample table * p7 = input window start time * p8 = input window end time * p9 = wraparound (see below) The "input window" refers to the portion of the input sound table read by the granulator. When the granulator reaches the end of the window, it wraps around to the beginning, unless p9 (wraparound) is false (0). In that case, please note that any data coming from time-varying tables (such as p3), may not span the entire table. It's best to arrange for the window start to be a little after the sound table start, and for the window end to be a little before the table end. * p10 = traversal rate The granulator moves through the input window at the "traversal rate." Here are some sample values: 0 no movement 1 move forward at normal rate 2.5 move forward at a rate that is 2.5 times normal -1 move backward at normal rate The following parameters determine the character of individual grains. p11 = grain envelope table * p12 = grain hop time (time between successive grains). This is the inverse of grain density (grains per second); you can use makeconverter(..., "inverse") to convert a table or real-time control source from density to hop time. * p13 = grain input time jitter Maximum randomly determined amount to add or subtract from the input start time for a grain. * p14 = grain output time jitter Maximum randomly determined amount to add or subtract from the output start time for a grain, which is controlled by p12 (grain hop time). * p15 = grain duration minimum * p16 = grain duration maximum * p17 = grain amplitude multiplier minimum * p18 = grain amplitude multiplier maximum * p19 = grain transposition (in linear octaves, relative to 0) [optional; if missing, no transposition] p20 = grain transposition collection If this is a table, it contains a list of transpositions (in oct.pc) from which to select randomly. If it's not a table, it's ignored. The table cannot be updated dynamically. The value of p19 (transposition) affects the collection. [optional] * p21 = grain transposition jitter Maximum randomly determined amount to add or subtract from the current transposition value. If p20 (transposition collection) is active, then jitter controls how much of the collection to choose from. In this case, jitter is an oct.pc value. For example, if the collection is [0.00, 0.02, 0.05, 0.07], then a jitter value of 0.05 will cause only the first 3 pitches to be chosen, whereas a jitter value of 0.07 would cause all 4 to be chosen. [optional; if missing, no transposition jitter] p22 = random seed (integer) [optional; if missing, uses system clock] * p23 = grain pan minimum (pctleft: 0-1) * p24 = grain pan maximum [optional, ignored if mono output; if both missing, min = 0 and min = 1; if max missing, max = min] p25 = use 3rd-order interpolation, instead of 2nd-order, when transposing. This is more CPU-intensive, and often doesn't make a noticeable difference. (0: use 2nd-order, 1: use 3rd-order) [optional; 2nd-order interp is the default] John Gibson <johgibso at indiana dot edu>, 1/29/05 */ #include <stdio.h> #include <stdlib.h> #include <float.h> #include <assert.h> #include <ugens.h> #include <Instrument.h> #include <PField.h> #include <rt.h> #include <rtdefs.h> #include "GRANULATE.h" #include "grainstream.h" //#define DEBUG //#define NDEBUG // disable asserts #define PRESERVE_GRAIN_DURATION true // regardless of transposition #define USAGE_MESSAGE \ "Usage:\n" \ " GRANULATE(start, inskip, dur, amp, sound_table, num_chans, input_chan,\n" \ " window_start_time, window_end_time, wraparound, traversal_rate,\n" \ " grain_env, grain_hoptime, grain_input_jitter, grain_output_jitter,\n" \ " grain_dur_min, grain_dur_max, grain_amp_min, grain_amp_max,\n" \ " grain_transposition, grain_transposition_collection,\n" \ " grain_transposition_jitter, random_seed, grain_pan_min, grain_pan_max\n" GRANULATE::GRANULATE() : Instrument() { _stream = NULL; _branch = 0; _curwinstart = -DBL_MAX; _curwinend = -DBL_MAX; _block = NULL; _keepgoing = true; _stopped = false; } GRANULATE::~GRANULATE() { delete _stream; delete [] _block; } int GRANULATE::init(double p[], int n_args) { _nargs = n_args; if (_nargs < 19) return die("GRANULATE", USAGE_MESSAGE); const double outskip = p[0]; const double dur = p[2]; const int numinchans = int(p[5]); const int seed = _nargs > 22 ? int(p[22]) : 0; const bool use3rdOrderInterp = _nargs > 25 ? bool(p[25]) : false; if (rtsetoutput(outskip, dur, this) == -1) return DONT_SCHEDULE; if (outputChannels() > 2) return die("GRANULATE", "You can have only mono or stereo output."); _stereoOut = (outputChannels() == 2); int length; double *table = (double *) getPFieldTable(4, &length); if (table == NULL) return die("GRANULATE", "You must create a table containing the sound " "to granulate."); _stream = new GrainStream(SR, table, length, numinchans, outputChannels(), PRESERVE_GRAIN_DURATION, seed, use3rdOrderInterp); table = (double *) getPFieldTable(11, &length); if (table == NULL) return die("GRANULATE", "You must create a table containing the grain " "envelope."); _stream->setGrainEnvelopeTable(table, length); if (_nargs > 20) { table = (double *) getPFieldTable(20, &length); if (table != NULL) _stream->setGrainTranspositionCollection(table, length); } _skip = (int) (SR / (float) resetval); return nSamps(); } void GRANULATE::doupdate() { double p[_nargs]; update(p, _nargs, kInskip | kAmp | kInChan | kWinStart | kWinEnd | kWrap | kTraversal | kHopTime | kInJitter | kOutJitter | kMinDur | kMaxDur | kMinAmp | kMaxAmp | kTransp | kTranspJitter | kMinPan | kMaxPan); _amp = p[3]; _stream->setInputChan(int(p[6])); if (p[7] != _curwinstart || p[8] != _curwinend) { _stream->setWindow(p[7], p[8]); _curwinstart = p[7]; _curwinend = p[8]; } _stream->setInskip(p[1]); // do this after setting window _stream->setWraparound(bool(p[9])); _stream->setTraversalRateAndGrainHop(p[10], p[12]); _stream->setInputJitter(p[13]); _stream->setOutputJitter(p[14]); _stream->setGrainDuration(p[15], p[16]); _stream->setGrainAmp(p[17], p[18]); if (_nargs > 19) _stream->setGrainTransposition(p[19]); if (_nargs > 21) _stream->setGrainTranspositionJitter(p[21]); if (_nargs > 23 && _stereoOut) { const double min = p[23]; const double max = _nargs > 24 ? p[24] : min; _stream->setGrainPan(min, max); } } int GRANULATE::configure() { _block = new float [RTBUFSAMPS * outputChannels()]; return _block ? 0 : -1; } inline const int min(const int a, const int b) { return a < b ? a : b; } #if 0 // shows how to do single-frame I/O, but we use block I/O instead. int GRANULATE::run() { const int frames = framesToRun(); const int outchans = outputChannels(); int i; for (i = 0; i < frames; i++) { if (--_branch <= 0) { doupdate(); _branch = _skip; } // If we're not in wrap mode, this returns false when it's time to stop. _keepgoing = _stream->prepare(); float out[outchans]; if (outchans == 2) { out[0] = _stream->lastL() * _amp; out[1] = _stream->lastR() * _amp; } else out[0] = _stream->lastL() * _amp; rtaddout(out); increment(); if (!_keepgoing) { // FIXME: how do we remove note from RTcmix queue? break; } } return i; } #else int GRANULATE::run() { // NOTE: Without a lot more code, we can't guarantee that doupdate will // be called exactly every _skip samples, the way we can when not doing // block I/O. But this seems worth sacrificing for the clear performance // improvement that block I/O offers. const int frames = framesToRun(); int blockframes = min(frames, _skip); int framesdone = 0; while (1) { if (_branch <= 0) { doupdate(); _branch = _skip; } _branch -= blockframes; // If we're not in wrap mode, this returns false when it's time to stop. if (_keepgoing) _keepgoing = _stream->processBlock(_block, blockframes, _amp); rtbaddout(_block, blockframes); increment(blockframes); if (!_keepgoing && !_stopped) { // FIXME: how do we remove note from RTcmix queue? const int samps = RTBUFSAMPS * outputChannels(); for (int i = 0; i < samps; i++) _block[i] = 0.0f; advise("GRANULATE", "Reached end in non-wrap mode; stopping output."); _stopped = true; } framesdone += blockframes; if (framesdone == frames) break; assert(framesdone < frames); const int remaining = frames - framesdone; if (remaining < blockframes) blockframes = remaining; } return frames; } #endif Instrument *makeGRANULATE() { GRANULATE *inst; inst = new GRANULATE(); inst->set_bus_config("GRANULATE"); return inst; } void rtprofile() { RT_INTRO("GRANULATE", makeGRANULATE); } <commit_msg>Fix usage comment.<commit_after>/* GRANULATE - granulation of sound stored in a table Any parameter marked with '*' can receive updates from a real-time control source. p0 = output start time * p1 = input start time (will be constrained to window, p5-6) NOTE: Unlike other instruments, this applies to a table, not to an input sound file. p2 = total duration * p3 = amplitude multiplier p4 = input sound table (e.g., maketable("soundfile", ...)) p5 = number of channels in sample table * p6 = input channel of sample table * p7 = input window start time * p8 = input window end time * p9 = wraparound (see below) The "input window" refers to the portion of the input sound table read by the granulator. When the granulator reaches the end of the window, it wraps around to the beginning, unless p9 (wraparound) is false (0). In that case, please note that any data coming from time-varying tables (such as p3), may not span the entire table. It's best to arrange for the window start to be a little after the sound table start, and for the window end to be a little before the table end. * p10 = traversal rate The granulator moves through the input window at the "traversal rate." Here are some sample values: 0 no movement 1 move forward at normal rate 2.5 move forward at a rate that is 2.5 times normal -1 move backward at normal rate The following parameters determine the character of individual grains. p11 = grain envelope table * p12 = grain hop time (time between successive grains). This is the inverse of grain density (grains per second); you can use makeconverter(..., "inverse") to convert a table or real-time control source from density to hop time. * p13 = grain input time jitter Maximum randomly determined amount to add or subtract from the input start time for a grain. * p14 = grain output time jitter Maximum randomly determined amount to add or subtract from the output start time for a grain, which is controlled by p12 (grain hop time). * p15 = grain duration minimum * p16 = grain duration maximum * p17 = grain amplitude multiplier minimum * p18 = grain amplitude multiplier maximum * p19 = grain transposition (in linear octaves, relative to 0) [optional; if missing, no transposition] p20 = grain transposition collection If this is a table, it contains a list of transpositions (in oct.pc) from which to select randomly. If it's not a table, it's ignored. The table cannot be updated dynamically. The value of p19 (transposition) affects the collection. [optional] * p21 = grain transposition jitter Maximum randomly determined amount to add or subtract from the current transposition value. If p20 (transposition collection) is active, then jitter controls how much of the collection to choose from. In this case, jitter is an oct.pc value. For example, if the collection is [0.00, 0.02, 0.05, 0.07], then a jitter value of 0.05 will cause only the first 3 pitches to be chosen, whereas a jitter value of 0.07 would cause all 4 to be chosen. [optional; if missing, no transposition jitter] p22 = random seed (integer) [optional; if missing, uses system clock] * p23 = grain pan minimum (pctleft: 0-1) * p24 = grain pan maximum [optional, ignored if mono output; if both missing, min = 0 and min = 1; if max missing, max = min] p25 = use 3rd-order interpolation, instead of 2nd-order, when transposing. This is more CPU-intensive, and often doesn't make a noticeable difference. (0: use 2nd-order, 1: use 3rd-order) [optional; 2nd-order interp is the default] John Gibson <johgibso at indiana dot edu>, 1/29/05 */ #include <stdio.h> #include <stdlib.h> #include <float.h> #include <assert.h> #include <ugens.h> #include <Instrument.h> #include <PField.h> #include <rt.h> #include <rtdefs.h> #include "GRANULATE.h" #include "grainstream.h" //#define DEBUG //#define NDEBUG // disable asserts #define PRESERVE_GRAIN_DURATION true // regardless of transposition #define USAGE_MESSAGE \ "Usage:\n" \ " GRANULATE(start, inskip, dur, amp, sound_table, num_chans, input_chan,\n" \ " window_start_time, window_end_time, wraparound, traversal_rate,\n" \ " grain_env, grain_hoptime, grain_input_jitter, grain_output_jitter,\n" \ " grain_dur_min, grain_dur_max, grain_amp_min, grain_amp_max,\n" \ " grain_transposition, grain_transposition_collection,\n" \ " grain_transposition_jitter, random_seed, grain_pan_min, grain_pan_max\n" GRANULATE::GRANULATE() : Instrument() { _stream = NULL; _branch = 0; _curwinstart = -DBL_MAX; _curwinend = -DBL_MAX; _block = NULL; _keepgoing = true; _stopped = false; } GRANULATE::~GRANULATE() { delete _stream; delete [] _block; } int GRANULATE::init(double p[], int n_args) { _nargs = n_args; if (_nargs < 19) return die("GRANULATE", USAGE_MESSAGE); const double outskip = p[0]; const double dur = p[2]; const int numinchans = int(p[5]); const int seed = _nargs > 22 ? int(p[22]) : 0; const bool use3rdOrderInterp = _nargs > 25 ? bool(p[25]) : false; if (rtsetoutput(outskip, dur, this) == -1) return DONT_SCHEDULE; if (outputChannels() > 2) return die("GRANULATE", "You can have only mono or stereo output."); _stereoOut = (outputChannels() == 2); int length; double *table = (double *) getPFieldTable(4, &length); if (table == NULL) return die("GRANULATE", "You must create a table containing the sound " "to granulate."); _stream = new GrainStream(SR, table, length, numinchans, outputChannels(), PRESERVE_GRAIN_DURATION, seed, use3rdOrderInterp); table = (double *) getPFieldTable(11, &length); if (table == NULL) return die("GRANULATE", "You must create a table containing the grain " "envelope."); _stream->setGrainEnvelopeTable(table, length); if (_nargs > 20) { table = (double *) getPFieldTable(20, &length); if (table != NULL) _stream->setGrainTranspositionCollection(table, length); } _skip = (int) (SR / (float) resetval); return nSamps(); } void GRANULATE::doupdate() { double p[_nargs]; update(p, _nargs, kInskip | kAmp | kInChan | kWinStart | kWinEnd | kWrap | kTraversal | kHopTime | kInJitter | kOutJitter | kMinDur | kMaxDur | kMinAmp | kMaxAmp | kTransp | kTranspJitter | kMinPan | kMaxPan); _amp = p[3]; _stream->setInputChan(int(p[6])); if (p[7] != _curwinstart || p[8] != _curwinend) { _stream->setWindow(p[7], p[8]); _curwinstart = p[7]; _curwinend = p[8]; } _stream->setInskip(p[1]); // do this after setting window _stream->setWraparound(bool(p[9])); _stream->setTraversalRateAndGrainHop(p[10], p[12]); _stream->setInputJitter(p[13]); _stream->setOutputJitter(p[14]); _stream->setGrainDuration(p[15], p[16]); _stream->setGrainAmp(p[17], p[18]); if (_nargs > 19) _stream->setGrainTransposition(p[19]); if (_nargs > 21) _stream->setGrainTranspositionJitter(p[21]); if (_nargs > 23 && _stereoOut) { const double min = p[23]; const double max = _nargs > 24 ? p[24] : min; _stream->setGrainPan(min, max); } } int GRANULATE::configure() { _block = new float [RTBUFSAMPS * outputChannels()]; return _block ? 0 : -1; } inline const int min(const int a, const int b) { return a < b ? a : b; } #if 0 // shows how to do single-frame I/O, but we use block I/O instead. int GRANULATE::run() { const int frames = framesToRun(); const int outchans = outputChannels(); int i; for (i = 0; i < frames; i++) { if (--_branch <= 0) { doupdate(); _branch = _skip; } // If we're not in wrap mode, this returns false when it's time to stop. _keepgoing = _stream->prepare(); float out[outchans]; if (outchans == 2) { out[0] = _stream->lastL() * _amp; out[1] = _stream->lastR() * _amp; } else out[0] = _stream->lastL() * _amp; rtaddout(out); increment(); if (!_keepgoing) { // FIXME: how do we remove note from RTcmix queue? break; } } return i; } #else int GRANULATE::run() { // NOTE: Without a lot more code, we can't guarantee that doupdate will // be called exactly every _skip samples, the way we can when not doing // block I/O. But this seems worth sacrificing for the clear performance // improvement that block I/O offers. const int frames = framesToRun(); int blockframes = min(frames, _skip); int framesdone = 0; while (1) { if (_branch <= 0) { doupdate(); _branch = _skip; } _branch -= blockframes; // If we're not in wrap mode, this returns false when it's time to stop. if (_keepgoing) _keepgoing = _stream->processBlock(_block, blockframes, _amp); rtbaddout(_block, blockframes); increment(blockframes); if (!_keepgoing && !_stopped) { // FIXME: how do we remove note from RTcmix queue? const int samps = RTBUFSAMPS * outputChannels(); for (int i = 0; i < samps; i++) _block[i] = 0.0f; advise("GRANULATE", "Reached end in non-wrap mode; stopping output."); _stopped = true; } framesdone += blockframes; if (framesdone == frames) break; assert(framesdone < frames); const int remaining = frames - framesdone; if (remaining < blockframes) blockframes = remaining; } return frames; } #endif Instrument *makeGRANULATE() { GRANULATE *inst; inst = new GRANULATE(); inst->set_bus_config("GRANULATE"); return inst; } void rtprofile() { RT_INTRO("GRANULATE", makeGRANULATE); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File: CollectionOptimisation.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Collection top class definition // /////////////////////////////////////////////////////////////////////////////// #include <Collections/CollectionOptimisation.h> #include <LibUtilities/BasicUtils/ParseUtils.hpp> namespace Nektar { namespace Collections { // static manager for Operator ImplementationMap map<OpImpTimingKey,OperatorImpMap> CollectionOptimisation::m_opImpMap; CollectionOptimisation::CollectionOptimisation( LibUtilities::SessionReaderSharedPtr pSession, ImplementationType defaultType) { int i; map<ElmtOrder, ImplementationType> defaults; map<ElmtOrder, ImplementationType>::iterator it; bool verbose = (pSession.get()) && (pSession->DefinesCmdLineArgument("verbose")) && (pSession->GetComm()->GetRank() == 0); m_setByXml = false; m_autotune = false; m_maxCollSize = 0; m_defaultType = defaultType == eNoImpType ? eIterPerExp : defaultType; map<string, LibUtilities::ShapeType> elTypes; map<string, LibUtilities::ShapeType>::iterator it2; elTypes["S"] = LibUtilities::eSegment; elTypes["T"] = LibUtilities::eTriangle; elTypes["Q"] = LibUtilities::eQuadrilateral; elTypes["A"] = LibUtilities::eTetrahedron; elTypes["P"] = LibUtilities::ePyramid; elTypes["R"] = LibUtilities::ePrism; elTypes["H"] = LibUtilities::eHexahedron; // Set defaults for all element types. for (it2 = elTypes.begin(); it2 != elTypes.end(); ++it2) { defaults[ElmtOrder(it2->second, -1)] = m_defaultType; } if (defaultType == eNoImpType) { for (it2 = elTypes.begin(); it2 != elTypes.end(); ++it2) { for (int i = 1; i < 5; ++i) { defaults[ElmtOrder(it2->second, i)] = eStdMat; } } } map<string, OperatorType> opTypes; for (i = 0; i < SIZE_OperatorType; ++i) { opTypes[OperatorTypeMap[i]] = (OperatorType)i; m_global[(OperatorType)i] = defaults; } map<string, ImplementationType> impTypes; for (i = 0; i < SIZE_ImplementationType; ++i) { impTypes[ImplementationTypeMap[i]] = (ImplementationType)i; } if(pSession.get()) // turn off file reader if dummy pointer is given { TiXmlDocument &doc = pSession->GetDocument(); TiXmlHandle docHandle(&doc); TiXmlElement *master = docHandle.FirstChildElement("NEKTAR").Element(); ASSERTL0(master, "Unable to find NEKTAR tag in file."); TiXmlElement *xmlCol = master->FirstChildElement("COLLECTIONS"); // Check if user has specified some options if (xmlCol) { // Set the maxsize and default implementation type if provided const char *maxSize = xmlCol->Attribute("MAXSIZE"); m_maxCollSize = (maxSize ? atoi(maxSize) : 0); const char *defaultImpl = xmlCol->Attribute("DEFAULT"); m_defaultType = defaultType; // If user has specified a default impl type, autotuning // and set this default across all operators. if (defaultType == eNoImpType && defaultImpl) { const std::string collinfo = string(defaultImpl); m_autotune = boost::iequals(collinfo, "auto"); if (!m_autotune) { for(i = 1; i < Collections::SIZE_ImplementationType; ++i) { if(boost::iequals(collinfo, Collections::ImplementationTypeMap[i])) { m_defaultType = (Collections::ImplementationType) i; break; } } ASSERTL0(i != Collections::SIZE_ImplementationType, "Unknown default collection scheme: "+collinfo); // Override default types for (it2 = elTypes.begin(); it2 != elTypes.end(); ++it2) { defaults[ElmtOrder(it2->second, -1)] = m_defaultType; } for (i = 0; i < SIZE_OperatorType; ++i) { m_global[(OperatorType)i] = defaults; } } } // Now process operator-specific implementation selections TiXmlElement *elmt = xmlCol->FirstChildElement(); while (elmt) { m_setByXml = true; string tagname = elmt->ValueStr(); ASSERTL0(boost::iequals(tagname, "OPERATOR"), "Only OPERATOR tags are supported inside the " "COLLECTIONS tag."); const char *attr = elmt->Attribute("TYPE"); ASSERTL0(attr, "Missing TYPE in OPERATOR tag."); string opType(attr); ASSERTL0(opTypes.count(opType) > 0, "Unknown OPERATOR type " + opType + "."); OperatorType ot = opTypes[opType]; TiXmlElement *elmt2 = elmt->FirstChildElement(); while (elmt2) { string tagname = elmt2->ValueStr(); ASSERTL0(boost::iequals(tagname, "ELEMENT"), "Only ELEMENT tags are supported inside the " "OPERATOR tag."); const char *attr = elmt2->Attribute("TYPE"); ASSERTL0(attr, "Missing TYPE in ELEMENT tag."); string elType(attr); it2 = elTypes.find(elType); ASSERTL0(it2 != elTypes.end(), "Unknown element type "+elType+" in ELEMENT " "tag"); const char *attr2 = elmt2->Attribute("IMPTYPE"); ASSERTL0(attr2, "Missing IMPTYPE in ELEMENT tag."); string impType(attr2); ASSERTL0(impTypes.count(impType) > 0, "Unknown IMPTYPE type " + impType + "."); const char *attr3 = elmt2->Attribute("ORDER"); ASSERTL0(attr3, "Missing ORDER in ELEMENT tag."); string order(attr3); if (order == "*") { m_global[ot][ElmtOrder(it2->second, -1)] = impTypes[impType]; } else { vector<unsigned int> orders; ParseUtils::GenerateSeqVector(order.c_str(), orders); for (int i = 0; i < orders.size(); ++i) { m_global[ot][ElmtOrder(it2->second, orders[i])] = impTypes[impType]; } } elmt2 = elmt2->NextSiblingElement(); } elmt = elmt->NextSiblingElement(); } // Print out operator map if (verbose) { if (!m_setByXml && !m_autotune) { cout << "Setting Collection optimisation using: " << Collections::ImplementationTypeMap[m_defaultType] << endl; } if (m_setByXml) { map<OperatorType, map<ElmtOrder, ImplementationType> >::iterator mIt; map<ElmtOrder, ImplementationType>::iterator eIt; for (mIt = m_global.begin(); mIt != m_global.end(); mIt++) { cout << "Operator " << OperatorTypeMap[mIt->first] << ":" << endl; for (eIt = mIt->second.begin(); eIt != mIt->second.end(); eIt++) { cout << "- " << LibUtilities::ShapeTypeMap[eIt->first.first] << " order " << eIt->first.second << " -> " << ImplementationTypeMap[eIt->second] << endl; } } } } } } } OperatorImpMap CollectionOptimisation::GetOperatorImpMap( StdRegions::StdExpansionSharedPtr pExp) { map<OperatorType, map<ElmtOrder, ImplementationType> >::iterator it; map<ElmtOrder, ImplementationType>::iterator it2; OperatorImpMap ret; ElmtOrder searchKey(pExp->DetShapeType(), pExp->GetBasisNumModes(0)); ElmtOrder defSearch(pExp->DetShapeType(), -1); for (it = m_global.begin(); it != m_global.end(); ++it) { ImplementationType impType; it2 = it->second.find(searchKey); if (it2 == it->second.end()) { it2 = it->second.find(defSearch); if (it2 == it->second.end()) { // Shouldn't be able to reach here. impType = eNoCollection; } else { impType = it2->second; } } else { impType = it2->second; } ret[it->first] = impType; } return ret; } OperatorImpMap CollectionOptimisation::SetWithTimings( vector<StdRegions::StdExpansionSharedPtr> pCollExp, OperatorImpMap &impTypes, bool verbose ) { OperatorImpMap ret; StdRegions::StdExpansionSharedPtr pExp = pCollExp[0]; // check to see if already defined for this expansion OpImpTimingKey OpKey(pExp,pCollExp.size(),pExp->GetNumBases()); if(m_opImpMap.count(OpKey) != 0) { ret = m_opImpMap[OpKey]; return ret; } int maxsize = pCollExp.size()*max(pExp->GetNcoeffs(),pExp->GetTotPoints()); Array<OneD, NekDouble> inarray(maxsize,1.0); Array<OneD, NekDouble> outarray1(maxsize); Array<OneD, NekDouble> outarray2(maxsize); Array<OneD, NekDouble> outarray3(maxsize); Timer t; if(verbose) { cout << "Collection Implemenation for " << LibUtilities::ShapeTypeMap[pExp->DetShapeType()] << " ( "; for(int i = 0; i < pExp->GetNumBases(); ++i) { cout << pExp->GetBasis(i)->GetNumModes() <<" "; } cout << ")" << " for ngeoms = " << pCollExp.size() << endl; } // set up an array of collections CollectionVector coll; for(int imp = 1; imp < SIZE_ImplementationType; ++imp) { ImplementationType impType = (ImplementationType)imp; OperatorImpMap impTypes; for (int i = 0; i < SIZE_OperatorType; ++i) { OperatorType opType = (OperatorType)i; OperatorKey opKey(pCollExp[0]->DetShapeType(), opType, impType, pCollExp[0]->IsNodalNonTensorialExp()); if (GetOperatorFactory().ModuleExists(opKey)) { impTypes[opType] = impType; } else { cout << "Note: Implementation does not exist: " << opKey << endl; } } Collection collloc(pCollExp,impTypes); coll.push_back(collloc); } // Determine the number of tests to do in one second Array<OneD, int> Ntest(SIZE_OperatorType); for(int i = 0; i < SIZE_OperatorType; ++i) { OperatorType OpType = (OperatorType)i; t.Start(); coll[0].ApplyOperator(OpType, inarray, outarray1, outarray2, outarray3); t.Stop(); NekDouble oneTest = t.TimePerTest(1); Ntest[i] = max((int)(0.25/oneTest),1); } Array<OneD, NekDouble> timing(SIZE_ImplementationType); // loop over all operators and determine fastest implementation for(int i = 0; i < SIZE_OperatorType; ++i) { OperatorType OpType = (OperatorType)i; // call collection implementation in thorugh ExpList. for (int imp = 0; imp < coll.size(); ++imp) { if (coll[imp].HasOperator(OpType)) { t.Start(); for(int n = 0; n < Ntest[i]; ++n) { coll[imp].ApplyOperator(OpType, inarray, outarray1, outarray2, outarray3); } t.Stop(); timing[imp] = t.TimePerTest(Ntest[i]); } else { timing[imp] = 1000.0; } } // determine optimal implementation. Note +1 to // remove NoImplementationType flag int minImp = Vmath::Imin(coll.size(),timing,1)+1; if(verbose) { cout << "\t " << OperatorTypeMap[i] << ": " << ImplementationTypeMap[minImp] << "\t ("; for(int j = 0; j < coll.size(); ++j) { if (timing[j] > 999.0) { cout << "-"; } else { cout << timing[j] ; } if(j != coll.size()-1) { cout <<", "; } } cout << ")" <<endl; } // could reset global map if reusing method? //m_global[OpType][pExp->DetShapeType()] = (ImplementationType)minImp; // set up new map ret[OpType] = (ImplementationType)minImp; } // store map for use by another expansion. m_opImpMap[OpKey] = ret; return ret; } } } <commit_msg>Added specific default implementation choices for PhysDeriv op.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File: CollectionOptimisation.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Collection top class definition // /////////////////////////////////////////////////////////////////////////////// #include <Collections/CollectionOptimisation.h> #include <LibUtilities/BasicUtils/ParseUtils.hpp> namespace Nektar { namespace Collections { // static manager for Operator ImplementationMap map<OpImpTimingKey,OperatorImpMap> CollectionOptimisation::m_opImpMap; CollectionOptimisation::CollectionOptimisation( LibUtilities::SessionReaderSharedPtr pSession, ImplementationType defaultType) { int i; map<ElmtOrder, ImplementationType> defaults; map<ElmtOrder, ImplementationType> defaultsPhysDeriv; map<ElmtOrder, ImplementationType>::iterator it; bool verbose = (pSession.get()) && (pSession->DefinesCmdLineArgument("verbose")) && (pSession->GetComm()->GetRank() == 0); m_setByXml = false; m_autotune = false; m_maxCollSize = 0; m_defaultType = defaultType == eNoImpType ? eIterPerExp : defaultType; map<string, LibUtilities::ShapeType> elTypes; map<string, LibUtilities::ShapeType>::iterator it2; elTypes["S"] = LibUtilities::eSegment; elTypes["T"] = LibUtilities::eTriangle; elTypes["Q"] = LibUtilities::eQuadrilateral; elTypes["A"] = LibUtilities::eTetrahedron; elTypes["P"] = LibUtilities::ePyramid; elTypes["R"] = LibUtilities::ePrism; elTypes["H"] = LibUtilities::eHexahedron; // Set defaults for all element types. for (it2 = elTypes.begin(); it2 != elTypes.end(); ++it2) { defaults [ElmtOrder(it2->second, -1)] = m_defaultType; defaultsPhysDeriv [ElmtOrder(it2->second, -1)] = m_defaultType; } if (defaultType == eNoImpType) { for (it2 = elTypes.begin(); it2 != elTypes.end(); ++it2) { defaultsPhysDeriv [ElmtOrder(it2->second, -1)] = eNoCollection; for (int i = 1; i < 5; ++i) { defaults[ElmtOrder(it2->second, i)] = eStdMat; } for (int i = 1; i < 3; ++i) { defaultsPhysDeriv[ElmtOrder(it2->second, i)] = eSumFac; } } } map<string, OperatorType> opTypes; for (i = 0; i < SIZE_OperatorType; ++i) { opTypes[OperatorTypeMap[i]] = (OperatorType)i; switch ((OperatorType)i) { case ePhysDeriv: m_global[(OperatorType)i] = defaultsPhysDeriv; break; default: m_global[(OperatorType)i] = defaults; } } map<string, ImplementationType> impTypes; for (i = 0; i < SIZE_ImplementationType; ++i) { impTypes[ImplementationTypeMap[i]] = (ImplementationType)i; } if(pSession.get()) // turn off file reader if dummy pointer is given { TiXmlDocument &doc = pSession->GetDocument(); TiXmlHandle docHandle(&doc); TiXmlElement *master = docHandle.FirstChildElement("NEKTAR").Element(); ASSERTL0(master, "Unable to find NEKTAR tag in file."); TiXmlElement *xmlCol = master->FirstChildElement("COLLECTIONS"); // Check if user has specified some options if (xmlCol) { // Set the maxsize and default implementation type if provided const char *maxSize = xmlCol->Attribute("MAXSIZE"); m_maxCollSize = (maxSize ? atoi(maxSize) : 0); const char *defaultImpl = xmlCol->Attribute("DEFAULT"); m_defaultType = defaultType; // If user has specified a default impl type, autotuning // and set this default across all operators. if (defaultType == eNoImpType && defaultImpl) { const std::string collinfo = string(defaultImpl); m_autotune = boost::iequals(collinfo, "auto"); if (!m_autotune) { for(i = 1; i < Collections::SIZE_ImplementationType; ++i) { if(boost::iequals(collinfo, Collections::ImplementationTypeMap[i])) { m_defaultType = (Collections::ImplementationType) i; break; } } ASSERTL0(i != Collections::SIZE_ImplementationType, "Unknown default collection scheme: "+collinfo); // Override default types for (it2 = elTypes.begin(); it2 != elTypes.end(); ++it2) { defaults[ElmtOrder(it2->second, -1)] = m_defaultType; } for (i = 0; i < SIZE_OperatorType; ++i) { m_global[(OperatorType)i] = defaults; } } } // Now process operator-specific implementation selections TiXmlElement *elmt = xmlCol->FirstChildElement(); while (elmt) { m_setByXml = true; string tagname = elmt->ValueStr(); ASSERTL0(boost::iequals(tagname, "OPERATOR"), "Only OPERATOR tags are supported inside the " "COLLECTIONS tag."); const char *attr = elmt->Attribute("TYPE"); ASSERTL0(attr, "Missing TYPE in OPERATOR tag."); string opType(attr); ASSERTL0(opTypes.count(opType) > 0, "Unknown OPERATOR type " + opType + "."); OperatorType ot = opTypes[opType]; TiXmlElement *elmt2 = elmt->FirstChildElement(); while (elmt2) { string tagname = elmt2->ValueStr(); ASSERTL0(boost::iequals(tagname, "ELEMENT"), "Only ELEMENT tags are supported inside the " "OPERATOR tag."); const char *attr = elmt2->Attribute("TYPE"); ASSERTL0(attr, "Missing TYPE in ELEMENT tag."); string elType(attr); it2 = elTypes.find(elType); ASSERTL0(it2 != elTypes.end(), "Unknown element type "+elType+" in ELEMENT " "tag"); const char *attr2 = elmt2->Attribute("IMPTYPE"); ASSERTL0(attr2, "Missing IMPTYPE in ELEMENT tag."); string impType(attr2); ASSERTL0(impTypes.count(impType) > 0, "Unknown IMPTYPE type " + impType + "."); const char *attr3 = elmt2->Attribute("ORDER"); ASSERTL0(attr3, "Missing ORDER in ELEMENT tag."); string order(attr3); if (order == "*") { m_global[ot][ElmtOrder(it2->second, -1)] = impTypes[impType]; } else { vector<unsigned int> orders; ParseUtils::GenerateSeqVector(order.c_str(), orders); for (int i = 0; i < orders.size(); ++i) { m_global[ot][ElmtOrder(it2->second, orders[i])] = impTypes[impType]; } } elmt2 = elmt2->NextSiblingElement(); } elmt = elmt->NextSiblingElement(); } // Print out operator map if (verbose) { if (!m_setByXml && !m_autotune) { cout << "Setting Collection optimisation using: " << Collections::ImplementationTypeMap[m_defaultType] << endl; } if (m_setByXml) { map<OperatorType, map<ElmtOrder, ImplementationType> >::iterator mIt; map<ElmtOrder, ImplementationType>::iterator eIt; for (mIt = m_global.begin(); mIt != m_global.end(); mIt++) { cout << "Operator " << OperatorTypeMap[mIt->first] << ":" << endl; for (eIt = mIt->second.begin(); eIt != mIt->second.end(); eIt++) { cout << "- " << LibUtilities::ShapeTypeMap[eIt->first.first] << " order " << eIt->first.second << " -> " << ImplementationTypeMap[eIt->second] << endl; } } } } } } } OperatorImpMap CollectionOptimisation::GetOperatorImpMap( StdRegions::StdExpansionSharedPtr pExp) { map<OperatorType, map<ElmtOrder, ImplementationType> >::iterator it; map<ElmtOrder, ImplementationType>::iterator it2; OperatorImpMap ret; ElmtOrder searchKey(pExp->DetShapeType(), pExp->GetBasisNumModes(0)); ElmtOrder defSearch(pExp->DetShapeType(), -1); for (it = m_global.begin(); it != m_global.end(); ++it) { ImplementationType impType; it2 = it->second.find(searchKey); if (it2 == it->second.end()) { it2 = it->second.find(defSearch); if (it2 == it->second.end()) { // Shouldn't be able to reach here. impType = eNoCollection; } else { impType = it2->second; } } else { impType = it2->second; } ret[it->first] = impType; } return ret; } OperatorImpMap CollectionOptimisation::SetWithTimings( vector<StdRegions::StdExpansionSharedPtr> pCollExp, OperatorImpMap &impTypes, bool verbose ) { OperatorImpMap ret; StdRegions::StdExpansionSharedPtr pExp = pCollExp[0]; // check to see if already defined for this expansion OpImpTimingKey OpKey(pExp,pCollExp.size(),pExp->GetNumBases()); if(m_opImpMap.count(OpKey) != 0) { ret = m_opImpMap[OpKey]; return ret; } int maxsize = pCollExp.size()*max(pExp->GetNcoeffs(),pExp->GetTotPoints()); Array<OneD, NekDouble> inarray(maxsize,1.0); Array<OneD, NekDouble> outarray1(maxsize); Array<OneD, NekDouble> outarray2(maxsize); Array<OneD, NekDouble> outarray3(maxsize); Timer t; if(verbose) { cout << "Collection Implemenation for " << LibUtilities::ShapeTypeMap[pExp->DetShapeType()] << " ( "; for(int i = 0; i < pExp->GetNumBases(); ++i) { cout << pExp->GetBasis(i)->GetNumModes() <<" "; } cout << ")" << " for ngeoms = " << pCollExp.size() << endl; } // set up an array of collections CollectionVector coll; for(int imp = 1; imp < SIZE_ImplementationType; ++imp) { ImplementationType impType = (ImplementationType)imp; OperatorImpMap impTypes; for (int i = 0; i < SIZE_OperatorType; ++i) { OperatorType opType = (OperatorType)i; OperatorKey opKey(pCollExp[0]->DetShapeType(), opType, impType, pCollExp[0]->IsNodalNonTensorialExp()); if (GetOperatorFactory().ModuleExists(opKey)) { impTypes[opType] = impType; } else { cout << "Note: Implementation does not exist: " << opKey << endl; } } Collection collloc(pCollExp,impTypes); coll.push_back(collloc); } // Determine the number of tests to do in one second Array<OneD, int> Ntest(SIZE_OperatorType); for(int i = 0; i < SIZE_OperatorType; ++i) { OperatorType OpType = (OperatorType)i; t.Start(); coll[0].ApplyOperator(OpType, inarray, outarray1, outarray2, outarray3); t.Stop(); NekDouble oneTest = t.TimePerTest(1); Ntest[i] = max((int)(0.25/oneTest),1); } Array<OneD, NekDouble> timing(SIZE_ImplementationType); // loop over all operators and determine fastest implementation for(int i = 0; i < SIZE_OperatorType; ++i) { OperatorType OpType = (OperatorType)i; // call collection implementation in thorugh ExpList. for (int imp = 0; imp < coll.size(); ++imp) { if (coll[imp].HasOperator(OpType)) { t.Start(); for(int n = 0; n < Ntest[i]; ++n) { coll[imp].ApplyOperator(OpType, inarray, outarray1, outarray2, outarray3); } t.Stop(); timing[imp] = t.TimePerTest(Ntest[i]); } else { timing[imp] = 1000.0; } } // determine optimal implementation. Note +1 to // remove NoImplementationType flag int minImp = Vmath::Imin(coll.size(),timing,1)+1; if(verbose) { cout << "\t " << OperatorTypeMap[i] << ": " << ImplementationTypeMap[minImp] << "\t ("; for(int j = 0; j < coll.size(); ++j) { if (timing[j] > 999.0) { cout << "-"; } else { cout << timing[j] ; } if(j != coll.size()-1) { cout <<", "; } } cout << ")" <<endl; } // could reset global map if reusing method? //m_global[OpType][pExp->DetShapeType()] = (ImplementationType)minImp; // set up new map ret[OpType] = (ImplementationType)minImp; } // store map for use by another expansion. m_opImpMap[OpKey] = ret; return ret; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: viewcontactofe3dscene.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-11-24 16:26:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SDR_CONTACT_VIEWCONTACTOFE3DSCENE_HXX #define _SDR_CONTACT_VIEWCONTACTOFE3DSCENE_HXX #ifndef _SDR_CONTACT_VIEWCONTACTOFSDROBJ_HXX #include <svx/sdr/contact/viewcontactofsdrobj.hxx> #endif ////////////////////////////////////////////////////////////////////////////// // predeclarations class E3dScene; ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { class ViewContactOfE3dScene : public ViewContactOfSdrObj { protected: // internal access to SdrObject E3dScene& GetE3dScene() const { return (E3dScene&)GetSdrObject(); } // method to recalculate the PaintRectangle if the validity flag shows that // it is invalid. The flag is set from GetPaintRectangle, thus the implementation // only needs to refresh maPaintRectangle itself. virtual void CalcPaintRectangle(); public: // basic constructor, used from SdrObject. ViewContactOfE3dScene(E3dScene& rScene); // The destructor. When PrepareDelete() was not called before (see there) // warnings will be generated in debug version if there are still contacts // existing. virtual ~ViewContactOfE3dScene(); // When ShouldPaintObject() returns sal_True, the object itself is painted and // PaintObject() is called. virtual sal_Bool ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC); // These methods decide which parts of the objects will be painted: // When ShouldPaintDrawHierarchy() returns sal_True, the DrawHierarchy of the object is painted. // Else, the flags and rectangles of the VOCs of the sub-hierarchy are set to the values of the // object's VOC. virtual sal_Bool ShouldPaintDrawHierarchy(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC); // Paint this object. This is before evtl. SubObjects get painted. It needs to return // sal_True when something was pained and the paint output rectangle in rPaintRectangle. virtual sal_Bool PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC); }; } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif //_SDR_CONTACT_VIEWCONTACTOFE3DSCENE_HXX // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.2.1096); FILE MERGED 2005/09/05 14:18:23 rt 1.2.1096.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontactofe3dscene.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:58:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDR_CONTACT_VIEWCONTACTOFE3DSCENE_HXX #define _SDR_CONTACT_VIEWCONTACTOFE3DSCENE_HXX #ifndef _SDR_CONTACT_VIEWCONTACTOFSDROBJ_HXX #include <svx/sdr/contact/viewcontactofsdrobj.hxx> #endif ////////////////////////////////////////////////////////////////////////////// // predeclarations class E3dScene; ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { class ViewContactOfE3dScene : public ViewContactOfSdrObj { protected: // internal access to SdrObject E3dScene& GetE3dScene() const { return (E3dScene&)GetSdrObject(); } // method to recalculate the PaintRectangle if the validity flag shows that // it is invalid. The flag is set from GetPaintRectangle, thus the implementation // only needs to refresh maPaintRectangle itself. virtual void CalcPaintRectangle(); public: // basic constructor, used from SdrObject. ViewContactOfE3dScene(E3dScene& rScene); // The destructor. When PrepareDelete() was not called before (see there) // warnings will be generated in debug version if there are still contacts // existing. virtual ~ViewContactOfE3dScene(); // When ShouldPaintObject() returns sal_True, the object itself is painted and // PaintObject() is called. virtual sal_Bool ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC); // These methods decide which parts of the objects will be painted: // When ShouldPaintDrawHierarchy() returns sal_True, the DrawHierarchy of the object is painted. // Else, the flags and rectangles of the VOCs of the sub-hierarchy are set to the values of the // object's VOC. virtual sal_Bool ShouldPaintDrawHierarchy(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC); // Paint this object. This is before evtl. SubObjects get painted. It needs to return // sal_True when something was pained and the paint output rectangle in rPaintRectangle. virtual sal_Bool PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC); }; } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif //_SDR_CONTACT_VIEWCONTACTOFE3DSCENE_HXX // eof <|endoftext|>
<commit_before>#include "singletons.h" #include "config.h" #include "logging.h" #include <exception> #include "files.h" #include <iostream> using namespace std; //TODO: remove MainConfig::MainConfig() { auto search_envs = init_home_path(); auto config_json = (home/"config"/"config.json").string(); // This causes some redundant copies, but assures windows support try { find_or_create_config_files(); if(home.empty()) { std::string searched_envs = "["; for(auto &env : search_envs) searched_envs+=env+", "; searched_envs.erase(searched_envs.end()-2, searched_envs.end()); searched_envs+="]"; throw std::runtime_error("One of these environment variables needs to point to a writable directory to save configuration: " + searched_envs); } boost::property_tree::json_parser::read_json(config_json, cfg); update_config_file(); retrieve_config(); } catch(const std::exception &e) { std::stringstream ss; ss << configjson; boost::property_tree::read_json(ss, cfg); retrieve_config(); JERROR("Error reading "+ config_json + ": "+e.what()+"\n"); // logs will print to cerr when init_log haven't been run yet } } void MainConfig::find_or_create_config_files() { auto config_dir = home/"config"; auto config_json = config_dir/"config.json"; auto plugins_py = config_dir/"plugins.py"; boost::filesystem::create_directories(config_dir); // io exp captured by calling method if (!boost::filesystem::exists(config_json)) filesystem::write(config_json, configjson); // vars configjson and pluginspy if (!boost::filesystem::exists(plugins_py)) // live in files.h filesystem::write(plugins_py, pluginspy); auto juci_style_path = home/"styles"; boost::filesystem::create_directories(juci_style_path); // io exp captured by calling method juci_style_path/="juci-light.xml"; if(!boost::filesystem::exists(juci_style_path)) filesystem::write(juci_style_path, juci_light_style); juci_style_path=juci_style_path.parent_path(); juci_style_path/="juci-dark.xml"; if(!boost::filesystem::exists(juci_style_path)) filesystem::write(juci_style_path, juci_dark_style); juci_style_path=juci_style_path.parent_path(); juci_style_path/="juci-dark-blue.xml"; if(!boost::filesystem::exists(juci_style_path)) filesystem::write(juci_style_path, juci_dark_blue_style); } void MainConfig::retrieve_config() { Singleton::Config::window()->keybindings = cfg.get_child("keybindings"); GenerateSource(); GenerateDirectoryFilter(); Singleton::Config::window()->theme_name=cfg.get<std::string>("gtk_theme.name"); Singleton::Config::window()->theme_variant=cfg.get<std::string>("gtk_theme.variant"); Singleton::Config::window()->version = cfg.get<std::string>("version"); Singleton::Config::window()->default_size = {cfg.get<int>("default_window_size.width"), cfg.get<int>("default_window_size.height")}; Singleton::Config::terminal()->make_command=cfg.get<std::string>("project.make_command"); Singleton::Config::terminal()->cmake_command=cfg.get<std::string>("project.cmake_command"); Singleton::Config::terminal()->history_size=cfg.get<int>("terminal_history_size"); } bool MainConfig::check_config_file(const boost::property_tree::ptree &default_cfg, std::string parent_path) { if(parent_path.size()>0) parent_path+="."; bool exists=true; for(auto &node: default_cfg) { auto path=parent_path+node.first; try { cfg.get<std::string>(path); } catch(const std::exception &e) { cfg.add(path, node.second.data()); exists=false; } try { exists&=check_config_file(node.second, path); } catch(const std::exception &e) { } } return exists; } void MainConfig::update_config_file() { boost::property_tree::ptree default_cfg; bool cfg_ok=true; try { if(cfg.get<std::string>("version")!=JUCI_VERSION) { std::stringstream ss; ss << configjson; boost::property_tree::read_json(ss, default_cfg); cfg_ok=false; if(cfg.count("version")>0) cfg.find("version")->second.data()=default_cfg.get<std::string>("version"); } else return; } catch(const std::exception &e) { std::cerr << "Error reading json-file: " << e.what() << std::endl; cfg_ok=false; } cfg_ok&=check_config_file(default_cfg); if(!cfg_ok) { boost::property_tree::write_json((home/"config"/"config.json").string(), cfg); } } void MainConfig::GenerateSource() { auto source_cfg = Singleton::Config::source(); auto source_json = cfg.get_child("source"); Singleton::Config::source()->style=source_json.get<std::string>("style"); source_cfg->font=source_json.get<std::string>("font"); source_cfg->show_map = source_json.get<bool>("show_map"); source_cfg->map_font_size = source_json.get<std::string>("map_font_size"); source_cfg->spellcheck_language = source_json.get<std::string>("spellcheck_language"); source_cfg->default_tab_char = source_json.get<char>("default_tab_char"); source_cfg->default_tab_size = source_json.get<unsigned>("default_tab_size"); source_cfg->auto_tab_char_and_size = source_json.get<bool>("auto_tab_char_and_size"); source_cfg->wrap_lines = source_json.get<bool>("wrap_lines"); source_cfg->highlight_current_line = source_json.get<bool>("highlight_current_line"); source_cfg->show_line_numbers = source_json.get<bool>("show_line_numbers"); for (auto &i : source_json.get_child("clang_types")) source_cfg->clang_types[i.first] = i.second.get_value<std::string>(); auto pt_doc_search=cfg.get_child("documentation_searches"); for(auto &pt_doc_search_lang: pt_doc_search) { source_cfg->documentation_searches[pt_doc_search_lang.first].separator=pt_doc_search_lang.second.get<std::string>("separator"); auto &queries=source_cfg->documentation_searches.find(pt_doc_search_lang.first)->second.queries; for(auto &i: pt_doc_search_lang.second.get_child("queries")) { queries[i.first]=i.second.get_value<std::string>(); } } } void MainConfig::GenerateDirectoryFilter() { auto dir_cfg=Singleton::Config::directories(); boost::property_tree::ptree dir_json = cfg.get_child("directoryfilter"); boost::property_tree::ptree ignore_json = dir_json.get_child("ignore"); boost::property_tree::ptree except_json = dir_json.get_child("exceptions"); for ( auto &i : except_json ) dir_cfg->exceptions.emplace_back(i.second.get_value<std::string>()); for ( auto &i : ignore_json ) dir_cfg->ignored.emplace_back(i.second.get_value<std::string>()); } std::vector<std::string> MainConfig::init_home_path(){ std::vector<std::string> locations = JUCI_ENV_SEARCH_LOCATIONS; char *ptr = nullptr; for (auto &env : locations) { ptr=std::getenv(env.c_str()); if (ptr==nullptr) continue; else if (boost::filesystem::exists(ptr)) { home /= ptr; home /= ".juci"; return locations; } } home=""; return locations; } <commit_msg>Clear the propterty tree after assigning to singleton configuration<commit_after>#include "singletons.h" #include "config.h" #include "logging.h" #include <exception> #include "files.h" #include <iostream> using namespace std; //TODO: remove MainConfig::MainConfig() { auto search_envs = init_home_path(); auto config_json = (home/"config"/"config.json").string(); // This causes some redundant copies, but assures windows support try { find_or_create_config_files(); if(home.empty()) { std::string searched_envs = "["; for(auto &env : search_envs) searched_envs+=env+", "; searched_envs.erase(searched_envs.end()-2, searched_envs.end()); searched_envs+="]"; throw std::runtime_error("One of these environment variables needs to point to a writable directory to save configuration: " + searched_envs); } boost::property_tree::json_parser::read_json(config_json, cfg); update_config_file(); retrieve_config(); } catch(const std::exception &e) { std::stringstream ss; ss << configjson; boost::property_tree::read_json(ss, cfg); retrieve_config(); JERROR("Error reading "+ config_json + ": "+e.what()+"\n"); // logs will print to cerr when init_log haven't been run yet } cfg.clear(); } void MainConfig::find_or_create_config_files() { auto config_dir = home/"config"; auto config_json = config_dir/"config.json"; auto plugins_py = config_dir/"plugins.py"; boost::filesystem::create_directories(config_dir); // io exp captured by calling method if (!boost::filesystem::exists(config_json)) filesystem::write(config_json, configjson); // vars configjson and pluginspy if (!boost::filesystem::exists(plugins_py)) // live in files.h filesystem::write(plugins_py, pluginspy); auto juci_style_path = home/"styles"; boost::filesystem::create_directories(juci_style_path); // io exp captured by calling method juci_style_path/="juci-light.xml"; if(!boost::filesystem::exists(juci_style_path)) filesystem::write(juci_style_path, juci_light_style); juci_style_path=juci_style_path.parent_path(); juci_style_path/="juci-dark.xml"; if(!boost::filesystem::exists(juci_style_path)) filesystem::write(juci_style_path, juci_dark_style); juci_style_path=juci_style_path.parent_path(); juci_style_path/="juci-dark-blue.xml"; if(!boost::filesystem::exists(juci_style_path)) filesystem::write(juci_style_path, juci_dark_blue_style); } void MainConfig::retrieve_config() { Singleton::Config::window()->keybindings = cfg.get_child("keybindings"); GenerateSource(); GenerateDirectoryFilter(); Singleton::Config::window()->theme_name=cfg.get<std::string>("gtk_theme.name"); Singleton::Config::window()->theme_variant=cfg.get<std::string>("gtk_theme.variant"); Singleton::Config::window()->version = cfg.get<std::string>("version"); Singleton::Config::window()->default_size = {cfg.get<int>("default_window_size.width"), cfg.get<int>("default_window_size.height")}; Singleton::Config::terminal()->make_command=cfg.get<std::string>("project.make_command"); Singleton::Config::terminal()->cmake_command=cfg.get<std::string>("project.cmake_command"); Singleton::Config::terminal()->history_size=cfg.get<int>("terminal_history_size"); } bool MainConfig::check_config_file(const boost::property_tree::ptree &default_cfg, std::string parent_path) { if(parent_path.size()>0) parent_path+="."; bool exists=true; for(auto &node: default_cfg) { auto path=parent_path+node.first; try { cfg.get<std::string>(path); } catch(const std::exception &e) { cfg.add(path, node.second.data()); exists=false; } try { exists&=check_config_file(node.second, path); } catch(const std::exception &e) { } } return exists; } void MainConfig::update_config_file() { boost::property_tree::ptree default_cfg; bool cfg_ok=true; try { if(cfg.get<std::string>("version")!=JUCI_VERSION) { std::stringstream ss; ss << configjson; boost::property_tree::read_json(ss, default_cfg); cfg_ok=false; if(cfg.count("version")>0) cfg.find("version")->second.data()=default_cfg.get<std::string>("version"); } else return; } catch(const std::exception &e) { std::cerr << "Error reading json-file: " << e.what() << std::endl; cfg_ok=false; } cfg_ok&=check_config_file(default_cfg); if(!cfg_ok) { boost::property_tree::write_json((home/"config"/"config.json").string(), cfg); } } void MainConfig::GenerateSource() { auto source_cfg = Singleton::Config::source(); auto source_json = cfg.get_child("source"); Singleton::Config::source()->style=source_json.get<std::string>("style"); source_cfg->font=source_json.get<std::string>("font"); source_cfg->show_map = source_json.get<bool>("show_map"); source_cfg->map_font_size = source_json.get<std::string>("map_font_size"); source_cfg->spellcheck_language = source_json.get<std::string>("spellcheck_language"); source_cfg->default_tab_char = source_json.get<char>("default_tab_char"); source_cfg->default_tab_size = source_json.get<unsigned>("default_tab_size"); source_cfg->auto_tab_char_and_size = source_json.get<bool>("auto_tab_char_and_size"); source_cfg->wrap_lines = source_json.get<bool>("wrap_lines"); source_cfg->highlight_current_line = source_json.get<bool>("highlight_current_line"); source_cfg->show_line_numbers = source_json.get<bool>("show_line_numbers"); for (auto &i : source_json.get_child("clang_types")) source_cfg->clang_types[i.first] = i.second.get_value<std::string>(); auto pt_doc_search=cfg.get_child("documentation_searches"); for(auto &pt_doc_search_lang: pt_doc_search) { source_cfg->documentation_searches[pt_doc_search_lang.first].separator=pt_doc_search_lang.second.get<std::string>("separator"); auto &queries=source_cfg->documentation_searches.find(pt_doc_search_lang.first)->second.queries; for(auto &i: pt_doc_search_lang.second.get_child("queries")) { queries[i.first]=i.second.get_value<std::string>(); } } } void MainConfig::GenerateDirectoryFilter() { auto dir_cfg=Singleton::Config::directories(); boost::property_tree::ptree dir_json = cfg.get_child("directoryfilter"); boost::property_tree::ptree ignore_json = dir_json.get_child("ignore"); boost::property_tree::ptree except_json = dir_json.get_child("exceptions"); for ( auto &i : except_json ) dir_cfg->exceptions.emplace_back(i.second.get_value<std::string>()); for ( auto &i : ignore_json ) dir_cfg->ignored.emplace_back(i.second.get_value<std::string>()); } std::vector<std::string> MainConfig::init_home_path(){ std::vector<std::string> locations = JUCI_ENV_SEARCH_LOCATIONS; char *ptr = nullptr; for (auto &env : locations) { ptr=std::getenv(env.c_str()); if (ptr==nullptr) continue; else if (boost::filesystem::exists(ptr)) { home /= ptr; home /= ".juci"; return locations; } } home=""; return locations; } <|endoftext|>
<commit_before>#pragma once /* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ // This class is the parts of java.util.UUID that we need #include <stdint.h> #include <cassert> #include <array> #include <iosfwd> #include <seastar/core/sstring.hh> #include <seastar/core/print.hh> #include <seastar/net/byteorder.hh> #include "bytes.hh" #include "hashing.hh" #include "utils/serialization.hh" namespace utils { class UUID { private: int64_t most_sig_bits; int64_t least_sig_bits; public: UUID() : most_sig_bits(0), least_sig_bits(0) {} UUID(int64_t most_sig_bits, int64_t least_sig_bits) : most_sig_bits(most_sig_bits), least_sig_bits(least_sig_bits) {} explicit UUID(const sstring& uuid_string) : UUID(sstring_view(uuid_string)) { } explicit UUID(const char * s) : UUID(sstring_view(s)) {} explicit UUID(sstring_view uuid_string); int64_t get_most_significant_bits() const { return most_sig_bits; } int64_t get_least_significant_bits() const { return least_sig_bits; } int version() const { return (most_sig_bits >> 12) & 0xf; } bool is_timestamp() const { return version() == 1; } int64_t timestamp() const { //if (version() != 1) { // throw new UnsupportedOperationException("Not a time-based UUID"); //} assert(is_timestamp()); return ((most_sig_bits & 0xFFF) << 48) | (((most_sig_bits >> 16) & 0xFFFF) << 32) | (((uint64_t)most_sig_bits) >> 32); } // This matches Java's UUID.toString() actual implementation. Note that // that method's documentation suggest something completely different! sstring to_sstring() const { return format("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", ((uint64_t)most_sig_bits >> 32), ((uint64_t)most_sig_bits >> 16 & 0xffff), ((uint64_t)most_sig_bits & 0xffff), ((uint64_t)least_sig_bits >> 48 & 0xffff), ((uint64_t)least_sig_bits & 0xffffffffffffLL)); } friend std::ostream& operator<<(std::ostream& out, const UUID& uuid); bool operator==(const UUID& v) const { return most_sig_bits == v.most_sig_bits && least_sig_bits == v.least_sig_bits ; } bool operator!=(const UUID& v) const { return !(*this == v); } bool operator<(const UUID& v) const { if (most_sig_bits != v.most_sig_bits) { return uint64_t(most_sig_bits) < uint64_t(v.most_sig_bits); } else { return uint64_t(least_sig_bits) < uint64_t(v.least_sig_bits); } } bool operator>(const UUID& v) const { return v < *this; } bool operator<=(const UUID& v) const { return !(*this > v); } bool operator>=(const UUID& v) const { return !(*this < v); } bytes serialize() const { bytes b(bytes::initialized_later(), serialized_size()); auto i = b.begin(); serialize(i); return b; } static size_t serialized_size() noexcept { return 16; } template <typename CharOutputIterator> void serialize(CharOutputIterator& out) const { serialize_int64(out, most_sig_bits); serialize_int64(out, least_sig_bits); } }; UUID make_random_uuid(); } template<> struct appending_hash<utils::UUID> { template<typename Hasher> void operator()(Hasher& h, const utils::UUID& id) const { feed_hash(h, id.get_most_significant_bits()); feed_hash(h, id.get_least_significant_bits()); } }; namespace std { template<> struct hash<utils::UUID> { size_t operator()(const utils::UUID& id) const { auto hilo = id.get_most_significant_bits() ^ id.get_least_significant_bits(); return size_t((hilo >> 32) ^ hilo); } }; } <commit_msg>uuid: implement optimized timeuuid compare<commit_after>#pragma once /* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ // This class is the parts of java.util.UUID that we need #include <stdint.h> #include <cassert> #include <array> #include <iosfwd> #include <seastar/core/sstring.hh> #include <seastar/core/print.hh> #include <seastar/net/byteorder.hh> #include "bytes.hh" #include "hashing.hh" #include "utils/serialization.hh" namespace utils { class UUID { private: int64_t most_sig_bits; int64_t least_sig_bits; public: UUID() : most_sig_bits(0), least_sig_bits(0) {} UUID(int64_t most_sig_bits, int64_t least_sig_bits) : most_sig_bits(most_sig_bits), least_sig_bits(least_sig_bits) {} explicit UUID(const sstring& uuid_string) : UUID(sstring_view(uuid_string)) { } explicit UUID(const char * s) : UUID(sstring_view(s)) {} explicit UUID(sstring_view uuid_string); int64_t get_most_significant_bits() const { return most_sig_bits; } int64_t get_least_significant_bits() const { return least_sig_bits; } int version() const { return (most_sig_bits >> 12) & 0xf; } bool is_timestamp() const { return version() == 1; } int64_t timestamp() const { //if (version() != 1) { // throw new UnsupportedOperationException("Not a time-based UUID"); //} assert(is_timestamp()); return ((most_sig_bits & 0xFFF) << 48) | (((most_sig_bits >> 16) & 0xFFFF) << 32) | (((uint64_t)most_sig_bits) >> 32); } // This matches Java's UUID.toString() actual implementation. Note that // that method's documentation suggest something completely different! sstring to_sstring() const { return format("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", ((uint64_t)most_sig_bits >> 32), ((uint64_t)most_sig_bits >> 16 & 0xffff), ((uint64_t)most_sig_bits & 0xffff), ((uint64_t)least_sig_bits >> 48 & 0xffff), ((uint64_t)least_sig_bits & 0xffffffffffffLL)); } friend std::ostream& operator<<(std::ostream& out, const UUID& uuid); bool operator==(const UUID& v) const { return most_sig_bits == v.most_sig_bits && least_sig_bits == v.least_sig_bits ; } bool operator!=(const UUID& v) const { return !(*this == v); } bool operator<(const UUID& v) const { if (most_sig_bits != v.most_sig_bits) { return uint64_t(most_sig_bits) < uint64_t(v.most_sig_bits); } else { return uint64_t(least_sig_bits) < uint64_t(v.least_sig_bits); } } bool operator>(const UUID& v) const { return v < *this; } bool operator<=(const UUID& v) const { return !(*this > v); } bool operator>=(const UUID& v) const { return !(*this < v); } bytes serialize() const { bytes b(bytes::initialized_later(), serialized_size()); auto i = b.begin(); serialize(i); return b; } static size_t serialized_size() noexcept { return 16; } template <typename CharOutputIterator> void serialize(CharOutputIterator& out) const { serialize_int64(out, most_sig_bits); serialize_int64(out, least_sig_bits); } }; UUID make_random_uuid(); inline int uint64_t_tri_compare(uint64_t a, uint64_t b) { return a < b ? -1 : a > b; } // Read 8 most significant bytes of timeuuid from serialized bytes inline uint64_t timeuuid_read_msb(const int8_t *b) { // cast to unsigned to avoid sign-compliment during shift. auto u64 = [](uint8_t i) -> uint64_t { return i; }; // Scylla and Cassandra use a standard UUID memory layout for MSB: // 4 bytes 2 bytes 2 bytes // time_low - time_mid - time_hi_and_version // // The storage format uses network byte order. // Reorder bytes to allow for an integer compare. return u64(b[6] & 0xf) << 56 | u64(b[7]) << 48 | u64(b[4]) << 40 | u64(b[5]) << 32 | u64(b[0]) << 24 | u64(b[1]) << 16 | u64(b[2]) << 8 | u64(b[3]); } inline uint64_t uuid_read_lsb(const int8_t *b) { auto u64 = [](uint8_t i) -> uint64_t { return i; }; return u64(b[8]) << 56 | u64(b[9]) << 48 | u64(b[10]) << 40 | u64(b[11]) << 32 | u64(b[12]) << 24 | u64(b[13]) << 16 | u64(b[14]) << 8 | u64(b[15]); } // Compare two values of timeuuid type. // Cassandra legacy requires: // - using signed compare for least significant bits. // - masking off UUID version during compare, to // treat possible non-version-1 UUID the same way as UUID. // // To avoid breaking ordering in existing sstables, Scylla preserves // Cassandra compare order. // inline int timeuuid_tri_compare(bytes_view o1, bytes_view o2) { auto timeuuid_read_lsb = [](bytes_view o) -> uint64_t { return uuid_read_lsb(o.begin()) ^ 0x8080808080808080; }; int res = uint64_t_tri_compare(timeuuid_read_msb(o1.begin()), timeuuid_read_msb(o2.begin())); if (res == 0) { res = uint64_t_tri_compare(timeuuid_read_lsb(o1), timeuuid_read_lsb(o2)); } return res; } // Compare two values of UUID type, if they happen to be // both of Version 1 (timeuuids). // // This function uses memory order for least significant bits, // which is both faster and monotonic, so should be preferred // to @timeuuid_tri_compare() used for all new features. // inline int uuid_tri_compare_timeuuid(bytes_view o1, bytes_view o2) { int res = uint64_t_tri_compare(timeuuid_read_msb(o1.begin()), timeuuid_read_msb(o2.begin())); if (res == 0) { res = uint64_t_tri_compare(uuid_read_lsb(o1.begin()), uuid_read_lsb(o2.begin())); } return res; } } template<> struct appending_hash<utils::UUID> { template<typename Hasher> void operator()(Hasher& h, const utils::UUID& id) const { feed_hash(h, id.get_most_significant_bits()); feed_hash(h, id.get_least_significant_bits()); } }; namespace std { template<> struct hash<utils::UUID> { size_t operator()(const utils::UUID& id) const { auto hilo = id.get_most_significant_bits() ^ id.get_least_significant_bits(); return size_t((hilo >> 32) ^ hilo); } }; } <|endoftext|>
<commit_before>#pragma once /* * Copyright 2015 Cloudius Systems. */ // This class is the parts of java.util.UUID that we need #include <stdint.h> #include <cassert> #include "core/sstring.hh" #include "core/print.hh" namespace utils { class UUID { private: int64_t most_sig_bits; int64_t least_sig_bits; public: UUID(int64_t most_sig_bits, int64_t least_sig_bits) : most_sig_bits(most_sig_bits), least_sig_bits(least_sig_bits) {} int64_t get_most_significant_bits() const { return most_sig_bits; } int64_t get_least_significant_bits() const { return least_sig_bits; } int version() const { return (most_sig_bits >> 12) & 0xf; } int64_t timestamp() const { //if (version() != 1) { // throw new UnsupportedOperationException("Not a time-based UUID"); //} assert(version() == 1); return ((most_sig_bits & 0xFFF) << 48) | (((most_sig_bits >> 16) & 0xFFFF) << 32) | (((uint64_t)most_sig_bits) >> 32); } // This matches Java's UUID.toString() actual implementation. Note that // that method's documentation suggest something completely different! sstring to_sstring() const { return sprint("%08x-%04x-%04x-%04x-%012x", ((uint64_t)most_sig_bits >> 32), ((uint64_t)most_sig_bits >> 16 & 0xffff), ((uint64_t)most_sig_bits & 0xffff), ((uint64_t)least_sig_bits >> 48 & 0xffff), ((uint64_t)least_sig_bits & 0xffffffffffffLL)); } }; UUID make_random_uuid(); } <commit_msg>Add hash function to UUID.<commit_after>#pragma once /* * Copyright 2015 Cloudius Systems. */ // This class is the parts of java.util.UUID that we need #include <stdint.h> #include <cassert> #include "core/sstring.hh" #include "core/print.hh" namespace utils { class UUID { private: int64_t most_sig_bits; int64_t least_sig_bits; public: UUID(int64_t most_sig_bits, int64_t least_sig_bits) : most_sig_bits(most_sig_bits), least_sig_bits(least_sig_bits) {} int64_t get_most_significant_bits() const { return most_sig_bits; } int64_t get_least_significant_bits() const { return least_sig_bits; } int version() const { return (most_sig_bits >> 12) & 0xf; } int64_t timestamp() const { //if (version() != 1) { // throw new UnsupportedOperationException("Not a time-based UUID"); //} assert(version() == 1); return ((most_sig_bits & 0xFFF) << 48) | (((most_sig_bits >> 16) & 0xFFFF) << 32) | (((uint64_t)most_sig_bits) >> 32); } // This matches Java's UUID.toString() actual implementation. Note that // that method's documentation suggest something completely different! sstring to_sstring() const { return sprint("%08x-%04x-%04x-%04x-%012x", ((uint64_t)most_sig_bits >> 32), ((uint64_t)most_sig_bits >> 16 & 0xffff), ((uint64_t)most_sig_bits & 0xffff), ((uint64_t)least_sig_bits >> 48 & 0xffff), ((uint64_t)least_sig_bits & 0xffffffffffffLL)); } bool operator==(const UUID& v) const { return most_sig_bits == v.most_sig_bits && least_sig_bits == v.least_sig_bits ; } }; UUID make_random_uuid(); } namespace std { template<> struct hash<utils::UUID> { size_t operator()(const utils::UUID& id) const { auto hilo = id.get_most_significant_bits() ^ id.get_least_significant_bits(); return size_t((hilo >> 32) ^ hilo); } }; } <|endoftext|>
<commit_before>#include "openmc/dagmc.h" #include "openmc/cell.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/string_utils.h" #include "openmc/settings.h" #include "openmc/geometry.h" #include <string> #include <sstream> #include <algorithm> #include <fstream> namespace openmc { #ifdef DAGMC const bool dagmc_enabled = true; #else const bool dagmc_enabled = false; #endif } #ifdef DAGMC #include "uwuw.hpp" #include "dagmcmetadata.hpp" const std::string DAGMC_FILENAME = "dagmc.h5m"; namespace openmc { namespace model { moab::DagMC* DAG; } // namespace model bool get_uwuw_materials_xml(std::string& s) { UWUW uwuw(DAGMC_FILENAME.c_str()); std::stringstream ss; bool uwuw_mats_present = false; if (uwuw.material_library.size() != 0) { uwuw_mats_present = true; // write header ss << "<?xml version=\"1.0\"?>\n"; ss << "<materials>\n"; std::map<std::string, pyne::Material> ml = uwuw.material_library; std::map<std::string, pyne::Material>::iterator it; // write materials for (it = ml.begin(); it != ml.end(); it++) { ss << it->second.openmc("atom"); } // write footer ss << "</materials>"; s = ss.str(); } return uwuw_mats_present; } pugi::xml_document* read_uwuw_materials() { pugi::xml_document* doc = NULL; std::string s; bool found_uwuw_mats = get_uwuw_materials_xml(s); if(found_uwuw_mats) { doc = new pugi::xml_document(); pugi::xml_parse_result result = doc->load_string(s.c_str()); } return doc; } bool write_uwuw_materials_xml() { std::string s; bool found_uwuw_mats = get_uwuw_materials_xml(s); // if there is a material library in the file if (found_uwuw_mats) { // write a material.xml file std::ofstream mats_xml("materials.xml"); mats_xml << s; mats_xml.close(); } return found_uwuw_mats; } void load_dagmc_geometry() { if (!model::DAG) { model::DAG = new moab::DagMC(); } /// Materials \\\ // create uwuw instance UWUW uwuw(DAGMC_FILENAME.c_str()); // check for uwuw material definitions bool using_uwuw = (uwuw.material_library.size() == 0) ? false : true; // notify user if UWUW materials are going to be used if (using_uwuw) { std::cout << "Found UWUW Materials in the DAGMC geometry file." << std::endl; } int32_t dagmc_univ_id = 0; // universe is always 0 for DAGMC runs // load the DAGMC geometry moab::ErrorCode rval = model::DAG->load_file(DAGMC_FILENAME.c_str()); MB_CHK_ERR_CONT(rval); // initialize acceleration data structures rval = model::DAG->init_OBBTree(); MB_CHK_ERR_CONT(rval); // parse model metadata dagmcMetaData DMD(model::DAG); if (using_uwuw) { DMD.load_property_data(); } std::vector<std::string> keywords; keywords.push_back("mat"); keywords.push_back("density"); keywords.push_back("boundary"); std::map<std::string, std::string> dum; std::string delimiters = ":/"; rval = model::DAG->parse_properties(keywords, dum, delimiters.c_str()); /// Cells (Volumes) \\\ // initialize cell objects model::n_cells = model::DAG->num_entities(3); for (int i = 0; i < model::n_cells; i++) { moab::EntityHandle vol_handle = model::DAG->entity_by_index(3, i+1); // set cell ids using global IDs DAGCell* c = new DAGCell(); c->id_ = model::DAG->id_by_index(3, i+1); c->dagmc_ptr_ = model::DAG; c->universe_ = dagmc_univ_id; // set to zero for now c->fill_ = C_NONE; // no fill, single universe model::cells.push_back(c); model::cell_map[c->id_] = i; // Populate the Universe vector and dict auto it = model::universe_map.find(dagmc_univ_id); if (it == model::universe_map.end()) { model::universes.push_back(new Universe()); model::universes.back()-> id_ = dagmc_univ_id; model::universes.back()->cells_.push_back(i); model::universe_map[dagmc_univ_id] = model::universes.size() - 1; } else { model::universes[it->second]->cells_.push_back(i); } if (model::DAG->is_implicit_complement(vol_handle)) { // assuming implicit complement is always void c->material_.push_back(MATERIAL_VOID); continue; } // determine volume material assignment std::string mat_value; if (model::DAG->has_prop(vol_handle, "mat")) { rval = model::DAG->prop_value(vol_handle, "mat", mat_value); MB_CHK_ERR_CONT(rval); } else { std::stringstream err_msg; err_msg << "Volume " << c->id_ << " has no material assignment."; fatal_error(err_msg.str()); } std::string cmp_str = mat_value; to_lower(cmp_str); // material void checks if (cmp_str.find("void") != std::string::npos || cmp_str.find("vacuum") != std::string::npos || cmp_str.find("graveyard") != std::string::npos) { c->material_.push_back(MATERIAL_VOID); } else { if (using_uwuw) { // lookup material in uwuw if the were present std::string uwuw_mat = DMD.volume_material_property_data_eh[vol_handle]; if (uwuw.material_library.count(uwuw_mat) != 0) { int matnumber = uwuw.material_library[uwuw_mat].metadata["mat_number"].asInt(); c->material_.push_back(matnumber); } else { std::stringstream err_msg; err_msg << "Material with value " << mat_value << " not found "; err_msg << "in the material library"; fatal_error(err_msg.str()); } } else { // if not using UWUW materials, we'll find this material // later in the materials.xml c->material_.push_back(std::stoi(mat_value)); } } } // allocate the cell overlap count if necessary if (settings::check_overlaps) { model::overlap_check_count.resize(model::cells.size(), 0); } /// Surfaces \\\ // initialize surface objects int n_surfaces = model::DAG->num_entities(2); model::surfaces.resize(n_surfaces); for (int i = 0; i < n_surfaces; i++) { moab::EntityHandle surf_handle = model::DAG->entity_by_index(2, i+1); // set cell ids using global IDs DAGSurface* s = new DAGSurface(); s->id_ = model::DAG->id_by_index(2, i+1); s->dagmc_ptr_ = model::DAG; // set BCs std::string bc_value; if (model::DAG->has_prop(surf_handle, "boundary")) { rval = model::DAG->prop_value(surf_handle, "boundary", bc_value); MB_CHK_ERR_CONT(rval); to_lower(bc_value); if (bc_value == "transmit" || bc_value == "transmission") { s->bc_ = BC_TRANSMIT; } else if (bc_value == "vacuum") { s->bc_ = BC_VACUUM; } else if (bc_value == "reflective" || bc_value == "reflect" || bc_value == "reflecting") { s->bc_ = BC_REFLECT; } else if (bc_value == "periodic") { fatal_error("Periodic boundary condition not supported in DAGMC."); } else { std::stringstream err_msg; err_msg << "Unknown boundary condition \"" << s->bc_ << "\" specified on surface " << s->id_; fatal_error(err_msg); } } else { // if no condition is found, set to transmit s->bc_ = BC_TRANSMIT; } // add to global array and map model::surfaces[i] = s; model::surface_map[s->id_] = s->id_; } return; } void free_memory_dagmc() { delete model::DAG; } } #endif <commit_msg>Adding volume-based temperature reading from DagMC models.<commit_after>#include "openmc/dagmc.h" #include "openmc/cell.h" #include "openmc/constants.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/string_utils.h" #include "openmc/settings.h" #include "openmc/geometry.h" #include <string> #include <sstream> #include <algorithm> #include <fstream> namespace openmc { #ifdef DAGMC const bool dagmc_enabled = true; #else const bool dagmc_enabled = false; #endif } #ifdef DAGMC #include "uwuw.hpp" #include "dagmcmetadata.hpp" const std::string DAGMC_FILENAME = "dagmc.h5m"; namespace openmc { namespace model { moab::DagMC* DAG; } // namespace model bool get_uwuw_materials_xml(std::string& s) { UWUW uwuw(DAGMC_FILENAME.c_str()); std::stringstream ss; bool uwuw_mats_present = false; if (uwuw.material_library.size() != 0) { uwuw_mats_present = true; // write header ss << "<?xml version=\"1.0\"?>\n"; ss << "<materials>\n"; std::map<std::string, pyne::Material> ml = uwuw.material_library; std::map<std::string, pyne::Material>::iterator it; // write materials for (it = ml.begin(); it != ml.end(); it++) { ss << it->second.openmc("atom"); } // write footer ss << "</materials>"; s = ss.str(); } return uwuw_mats_present; } pugi::xml_document* read_uwuw_materials() { pugi::xml_document* doc = NULL; std::string s; bool found_uwuw_mats = get_uwuw_materials_xml(s); if(found_uwuw_mats) { doc = new pugi::xml_document(); pugi::xml_parse_result result = doc->load_string(s.c_str()); } return doc; } bool write_uwuw_materials_xml() { std::string s; bool found_uwuw_mats = get_uwuw_materials_xml(s); // if there is a material library in the file if (found_uwuw_mats) { // write a material.xml file std::ofstream mats_xml("materials.xml"); mats_xml << s; mats_xml.close(); } return found_uwuw_mats; } void load_dagmc_geometry() { if (!model::DAG) { model::DAG = new moab::DagMC(); } /// Materials \\\ // create uwuw instance UWUW uwuw(DAGMC_FILENAME.c_str()); // check for uwuw material definitions bool using_uwuw = (uwuw.material_library.size() == 0) ? false : true; // notify user if UWUW materials are going to be used if (using_uwuw) { std::cout << "Found UWUW Materials in the DAGMC geometry file." << std::endl; } int32_t dagmc_univ_id = 0; // universe is always 0 for DAGMC runs // load the DAGMC geometry moab::ErrorCode rval = model::DAG->load_file(DAGMC_FILENAME.c_str()); MB_CHK_ERR_CONT(rval); // initialize acceleration data structures rval = model::DAG->init_OBBTree(); MB_CHK_ERR_CONT(rval); // parse model metadata dagmcMetaData DMD(model::DAG); if (using_uwuw) { DMD.load_property_data(); } std::vector<std::string> keywords; keywords.push_back("temp"); keywords.push_back("mat"); keywords.push_back("density"); keywords.push_back("boundary"); std::map<std::string, std::string> dum; std::string delimiters = ":/"; rval = model::DAG->parse_properties(keywords, dum, delimiters.c_str()); /// Cells (Volumes) \\\ // initialize cell objects model::n_cells = model::DAG->num_entities(3); for (int i = 0; i < model::n_cells; i++) { moab::EntityHandle vol_handle = model::DAG->entity_by_index(3, i+1); // set cell ids using global IDs DAGCell* c = new DAGCell(); c->id_ = model::DAG->id_by_index(3, i+1); c->dagmc_ptr_ = model::DAG; c->universe_ = dagmc_univ_id; // set to zero for now c->fill_ = C_NONE; // no fill, single universe model::cells.push_back(c); model::cell_map[c->id_] = i; // Populate the Universe vector and dict auto it = model::universe_map.find(dagmc_univ_id); if (it == model::universe_map.end()) { model::universes.push_back(new Universe()); model::universes.back()-> id_ = dagmc_univ_id; model::universes.back()->cells_.push_back(i); model::universe_map[dagmc_univ_id] = model::universes.size() - 1; } else { model::universes[it->second]->cells_.push_back(i); } if (model::DAG->is_implicit_complement(vol_handle)) { // assuming implicit complement is always void c->material_.push_back(MATERIAL_VOID); continue; } // check for temperature assignment std::string temp_value; if (model::DAG->has_prop(vol_handle, "temp")) { rval = model::DAG->prop_value(vol_handle, "temp", temp_value); MB_CHK_ERR_CONT(rval); double temp = std::stod(temp_value); c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * temp)); } else { c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * settings::temperature_default)); } // determine volume material assignment std::string mat_value; if (model::DAG->has_prop(vol_handle, "mat")) { rval = model::DAG->prop_value(vol_handle, "mat", mat_value); MB_CHK_ERR_CONT(rval); } else { std::stringstream err_msg; err_msg << "Volume " << c->id_ << " has no material assignment."; fatal_error(err_msg.str()); } std::string cmp_str = mat_value; to_lower(cmp_str); // material void checks if (cmp_str.find("void") != std::string::npos || cmp_str.find("vacuum") != std::string::npos || cmp_str.find("graveyard") != std::string::npos) { c->material_.push_back(MATERIAL_VOID); } else { if (using_uwuw) { // lookup material in uwuw if the were present std::string uwuw_mat = DMD.volume_material_property_data_eh[vol_handle]; if (uwuw.material_library.count(uwuw_mat) != 0) { int matnumber = uwuw.material_library[uwuw_mat].metadata["mat_number"].asInt(); c->material_.push_back(matnumber); } else { std::stringstream err_msg; err_msg << "Material with value " << mat_value << " not found "; err_msg << "in the material library"; fatal_error(err_msg.str()); } } else { // if not using UWUW materials, we'll find this material // later in the materials.xml c->material_.push_back(std::stoi(mat_value)); } } } // allocate the cell overlap count if necessary if (settings::check_overlaps) { model::overlap_check_count.resize(model::cells.size(), 0); } /// Surfaces \\\ // initialize surface objects int n_surfaces = model::DAG->num_entities(2); model::surfaces.resize(n_surfaces); for (int i = 0; i < n_surfaces; i++) { moab::EntityHandle surf_handle = model::DAG->entity_by_index(2, i+1); // set cell ids using global IDs DAGSurface* s = new DAGSurface(); s->id_ = model::DAG->id_by_index(2, i+1); s->dagmc_ptr_ = model::DAG; // set BCs std::string bc_value; if (model::DAG->has_prop(surf_handle, "boundary")) { rval = model::DAG->prop_value(surf_handle, "boundary", bc_value); MB_CHK_ERR_CONT(rval); to_lower(bc_value); if (bc_value == "transmit" || bc_value == "transmission") { s->bc_ = BC_TRANSMIT; } else if (bc_value == "vacuum") { s->bc_ = BC_VACUUM; } else if (bc_value == "reflective" || bc_value == "reflect" || bc_value == "reflecting") { s->bc_ = BC_REFLECT; } else if (bc_value == "periodic") { fatal_error("Periodic boundary condition not supported in DAGMC."); } else { std::stringstream err_msg; err_msg << "Unknown boundary condition \"" << s->bc_ << "\" specified on surface " << s->id_; fatal_error(err_msg); } } else { // if no condition is found, set to transmit s->bc_ = BC_TRANSMIT; } // add to global array and map model::surfaces[i] = s; model::surface_map[s->id_] = s->id_; } return; } void free_memory_dagmc() { delete model::DAG; } } #endif <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of DO-CV, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2015 David Ok <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <gtest/gtest.h> #include <unordered_set> #include <DO/Sara/DisjointSets/AdjacencyList.hpp> #include <DO/Sara/DisjointSets/DisjointSets.hpp> #include "../AssertHelpers.hpp" using namespace std; using namespace DO::Sara; TEST(TestDisjointSets, test_on_image) { auto regions = Image<int>{ 5, 5 }; regions.matrix() << // 0 1 2 3 4 0, 0, 1, 2, 3, // 5 6 7 8 9 0, 1, 1, 2, 3, // 10 11 12 13 14 0, 2, 2, 2, 2, // 15 16 17 18 19 4, 4, 2, 2, 2, // 20 21 22 23 24 4, 4, 2, 2, 5; // Compute the adjacency list using the 4-connectivity. auto adjacency_list = compute_adjacency_list_2d(regions); auto disjoint_sets = DisjointSets{ regions.size(), adjacency_list }; disjoint_sets.compute_connected_components(); auto components = disjoint_sets.get_connected_components(); // Robustify the test because the components are enumerated in a peculiar way. auto true_components = vector<vector<size_t>>{ { 24 }, { 15, 16, 20, 21 }, { 4, 9 }, { 3, 8, 11, 12, 13, 14, 17, 18, 19, 22, 23 }, { 2, 6, 7 }, { 0, 1, 5, 10 }, }; EXPECT_EQ(components.size(), true_components.size()); for (size_t i = 0; i < components.size(); ++i) ASSERT_ITEMS_EQ(true_components[i], components[i]); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>MAINT: robustify the unit test.<commit_after>// ========================================================================== // // This file is part of DO-CV, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2015 David Ok <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <gtest/gtest.h> #include <unordered_set> #include <DO/Sara/DisjointSets/AdjacencyList.hpp> #include <DO/Sara/DisjointSets/DisjointSets.hpp> #include "../AssertHelpers.hpp" using namespace std; using namespace DO::Sara; TEST(TestDisjointSets, test_on_image) { auto regions = Image<int>{ 5, 5 }; regions.matrix() << // 0 1 2 3 4 0, 0, 1, 2, 3, // 5 6 7 8 9 0, 1, 1, 2, 3, // 10 11 12 13 14 0, 2, 2, 2, 2, // 15 16 17 18 19 4, 4, 2, 2, 2, // 20 21 22 23 24 4, 4, 2, 2, 5; // Compute the adjacency list using the 4-connectivity. auto adjacency_list = compute_adjacency_list_2d(regions); auto disjoint_sets = DisjointSets{ regions.size(), adjacency_list }; disjoint_sets.compute_connected_components(); auto components = disjoint_sets.get_connected_components(); for (auto& component : components) sort(component.begin(), component.end()); auto true_components = vector<vector<size_t>>{ { 0, 1, 5, 10 }, { 2, 6, 7 }, { 3, 8, 11, 12, 13, 14, 17, 18, 19, 22, 23 }, { 4, 9 }, { 15, 16, 20, 21 }, { 24 }, }; EXPECT_EQ(components.size(), true_components.size()); for (size_t i = 0; i < components.size(); ++i) EXPECT_NE(components.end(), find(components.begin(), components.end(), true_components[i])); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// RUN: %clangxx_asan -O %s -o %t // RUN: not %run %t crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t crash // // Test crash due to __sanitizer_annotate_contiguous_container. #include <assert.h> #include <string.h> extern "C" { void __sanitizer_annotate_contiguous_container(const void *beg, const void *end, const void *old_mid, const void *new_mid); } // extern "C" static volatile int one = 1; int TestCrash() { long t[100]; t[60] = 0; __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 100, &t[0] + 50); // CHECK-CRASH: AddressSanitizer: container-overflow // CHECK-CRASH: if you don't care about these errors you may set ASAN_OPTIONS=detect_container_overflow=0 return (int)t[60 * one]; // Touches the poisoned memory. } void BadBounds() { long t[100]; // CHECK-BAD-BOUNDS: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 101, &t[0] + 50); } void BadAlignment() { int t[100]; // CHECK-BAD-ALIGNMENT: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container // CHECK-BAD-ALIGNMENT: ERROR: beg is not aligned by 8 __sanitizer_annotate_contiguous_container(&t[1], &t[0] + 100, &t[1] + 10, &t[0] + 50); } int main(int argc, char **argv) { assert(argc == 2); if (!strcmp(argv[1], "crash")) return TestCrash(); else if (!strcmp(argv[1], "bad-bounds")) BadBounds(); else if (!strcmp(argv[1], "bad-alignment")) BadAlignment(); } <commit_msg>[ThinLTO] Ensure sanitizer passes are run<commit_after>// RUN: %clangxx_asan -O %s -o %t // RUN: not %run %t crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t crash // // RUN: %clangxx_asan -flto=thin -O %s -o %t.thinlto // RUN: not %run %t.thinlto crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t.thinlto bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t.thinlto bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t.thinlto crash // // Test crash due to __sanitizer_annotate_contiguous_container. #include <assert.h> #include <string.h> extern "C" { void __sanitizer_annotate_contiguous_container(const void *beg, const void *end, const void *old_mid, const void *new_mid); } // extern "C" static volatile int one = 1; int TestCrash() { long t[100]; t[60] = 0; __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 100, &t[0] + 50); // CHECK-CRASH: AddressSanitizer: container-overflow // CHECK-CRASH: if you don't care about these errors you may set ASAN_OPTIONS=detect_container_overflow=0 return (int)t[60 * one]; // Touches the poisoned memory. } void BadBounds() { long t[100]; // CHECK-BAD-BOUNDS: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 101, &t[0] + 50); } void BadAlignment() { int t[100]; // CHECK-BAD-ALIGNMENT: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container // CHECK-BAD-ALIGNMENT: ERROR: beg is not aligned by 8 __sanitizer_annotate_contiguous_container(&t[1], &t[0] + 100, &t[1] + 10, &t[0] + 50); } int main(int argc, char **argv) { assert(argc == 2); if (!strcmp(argv[1], "crash")) return TestCrash(); else if (!strcmp(argv[1], "bad-bounds")) BadBounds(); else if (!strcmp(argv[1], "bad-alignment")) BadAlignment(); } <|endoftext|>
<commit_before>/* * Copyright 2010-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause */ #include <bx/debug.h> #include <bx/string.h> // isPrint #include <inttypes.h> // PRIx* #if BX_PLATFORM_ANDROID # include <android/log.h> #elif BX_PLATFORM_WINDOWS || BX_PLATFORM_WINRT || BX_PLATFORM_XBOX360 || BX_PLATFORM_XBOXONE extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char* _str); #elif BX_PLATFORM_IOS || BX_PLATFORM_OSX # if defined(__OBJC__) # import <Foundation/NSObjCRuntime.h> # else # include <CoreFoundation/CFString.h> extern "C" void NSLog(CFStringRef _format, ...); # endif // defined(__OBJC__) #elif 0 // BX_PLATFORM_EMSCRIPTEN # include <emscripten.h> #else # include <stdio.h> // fputs, fflush #endif // BX_PLATFORM_WINDOWS namespace bx { void debugBreak() { #if BX_COMPILER_MSVC __debugbreak(); #elif BX_CPU_ARM __builtin_trap(); // asm("bkpt 0"); #elif !BX_PLATFORM_NACL && BX_CPU_X86 && (BX_COMPILER_GCC || BX_COMPILER_CLANG) // NaCl doesn't like int 3: // NativeClient: NaCl module load failed: Validation failure. File violates Native Client safety rules. __asm__ ("int $3"); #else // cross platform implementation int* int3 = (int*)3L; *int3 = 3; #endif // BX } void debugOutput(const char* _out) { #if BX_PLATFORM_ANDROID # ifndef BX_ANDROID_LOG_TAG # define BX_ANDROID_LOG_TAG "" # endif // BX_ANDROID_LOG_TAG __android_log_write(ANDROID_LOG_DEBUG, BX_ANDROID_LOG_TAG, _out); #elif BX_PLATFORM_WINDOWS || BX_PLATFORM_WINRT || BX_PLATFORM_XBOX360 || BX_PLATFORM_XBOXONE OutputDebugStringA(_out); #elif BX_PLATFORM_IOS || BX_PLATFORM_OSX # if defined(__OBJC__) NSLog(@"%s", _out); # else NSLog(__CFStringMakeConstantString("%s"), _out); # endif // defined(__OBJC__) #elif 0 // BX_PLATFORM_EMSCRIPTEN emscripten_log(EM_LOG_CONSOLE, "%s", _out); #else fputs(_out, stdout); fflush(stdout); #endif // BX_PLATFORM_ } void debugPrintfVargs(const char* _format, va_list _argList) { char temp[8192]; char* out = temp; int32_t len = vsnprintf(out, sizeof(temp), _format, _argList); if ( (int32_t)sizeof(temp) < len) { out = (char*)alloca(len+1); len = vsnprintf(out, len, _format, _argList); } out[len] = '\0'; debugOutput(out); } void debugPrintf(const char* _format, ...) { va_list argList; va_start(argList, _format); debugPrintfVargs(_format, argList); va_end(argList); } #define DBG_ADDRESS "%" PRIxPTR void debugPrintfData(const void* _data, uint32_t _size, const char* _format, ...) { #define HEX_DUMP_WIDTH 16 #define HEX_DUMP_SPACE_WIDTH 48 #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s" va_list argList; va_start(argList, _format); debugPrintfVargs(_format, argList); va_end(argList); debugPrintf("\ndata: " DBG_ADDRESS ", size: %d\n", _data, _size); if (NULL != _data) { const uint8_t* data = reinterpret_cast<const uint8_t*>(_data); char hex[HEX_DUMP_WIDTH*3+1]; char ascii[HEX_DUMP_WIDTH+1]; uint32_t hexPos = 0; uint32_t asciiPos = 0; for (uint32_t ii = 0; ii < _size; ++ii) { snprintf(&hex[hexPos], sizeof(hex)-hexPos, "%02x ", data[asciiPos]); hexPos += 3; ascii[asciiPos] = isPrint(data[asciiPos]) ? data[asciiPos] : '.'; asciiPos++; if (HEX_DUMP_WIDTH == asciiPos) { ascii[asciiPos] = '\0'; debugPrintf("\t" DBG_ADDRESS "\t" HEX_DUMP_FORMAT "\t%s\n", data, hex, ascii); data += asciiPos; hexPos = 0; asciiPos = 0; } } if (0 != asciiPos) { ascii[asciiPos] = '\0'; debugPrintf("\t" DBG_ADDRESS "\t" HEX_DUMP_FORMAT "\t%s\n", data, hex, ascii); } } #undef HEX_DUMP_WIDTH #undef HEX_DUMP_SPACE_WIDTH #undef HEX_DUMP_FORMAT } } // namespace bx <commit_msg>Cleanup.<commit_after>/* * Copyright 2010-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause */ #include <bx/debug.h> #include <bx/string.h> // isPrint #include <inttypes.h> // PRIx* #if BX_PLATFORM_ANDROID # include <android/log.h> #elif BX_PLATFORM_WINDOWS || BX_PLATFORM_WINRT || BX_PLATFORM_XBOX360 || BX_PLATFORM_XBOXONE extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char* _str); #elif BX_PLATFORM_IOS || BX_PLATFORM_OSX # if defined(__OBJC__) # import <Foundation/NSObjCRuntime.h> # else # include <CoreFoundation/CFString.h> extern "C" void NSLog(CFStringRef _format, ...); # endif // defined(__OBJC__) #elif 0 // BX_PLATFORM_EMSCRIPTEN # include <emscripten.h> #else # include <stdio.h> // fputs, fflush #endif // BX_PLATFORM_WINDOWS namespace bx { void debugBreak() { #if BX_COMPILER_MSVC __debugbreak(); #elif BX_CPU_ARM __builtin_trap(); // asm("bkpt 0"); #elif !BX_PLATFORM_NACL && BX_CPU_X86 && (BX_COMPILER_GCC || BX_COMPILER_CLANG) // NaCl doesn't like int 3: // NativeClient: NaCl module load failed: Validation failure. File violates Native Client safety rules. __asm__ ("int $3"); #else // cross platform implementation int* int3 = (int*)3L; *int3 = 3; #endif // BX } void debugOutput(const char* _out) { #if BX_PLATFORM_ANDROID # ifndef BX_ANDROID_LOG_TAG # define BX_ANDROID_LOG_TAG "" # endif // BX_ANDROID_LOG_TAG __android_log_write(ANDROID_LOG_DEBUG, BX_ANDROID_LOG_TAG, _out); #elif BX_PLATFORM_WINDOWS || BX_PLATFORM_WINRT || BX_PLATFORM_XBOX360 || BX_PLATFORM_XBOXONE OutputDebugStringA(_out); #elif BX_PLATFORM_IOS || BX_PLATFORM_OSX # if defined(__OBJC__) NSLog(@"%s", _out); # else NSLog(__CFStringMakeConstantString("%s"), _out); # endif // defined(__OBJC__) #elif 0 // BX_PLATFORM_EMSCRIPTEN emscripten_log(EM_LOG_CONSOLE, "%s", _out); #elif !BX_CRT_NONE fputs(_out, stdout); fflush(stdout); #else BX_UNUSED(_out); #endif // BX_PLATFORM_ } void debugPrintfVargs(const char* _format, va_list _argList) { char temp[8192]; char* out = temp; int32_t len = vsnprintf(out, sizeof(temp), _format, _argList); if ( (int32_t)sizeof(temp) < len) { out = (char*)alloca(len+1); len = vsnprintf(out, len, _format, _argList); } out[len] = '\0'; debugOutput(out); } void debugPrintf(const char* _format, ...) { va_list argList; va_start(argList, _format); debugPrintfVargs(_format, argList); va_end(argList); } #define DBG_ADDRESS "%" PRIxPTR void debugPrintfData(const void* _data, uint32_t _size, const char* _format, ...) { #define HEX_DUMP_WIDTH 16 #define HEX_DUMP_SPACE_WIDTH 48 #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s" va_list argList; va_start(argList, _format); debugPrintfVargs(_format, argList); va_end(argList); debugPrintf("\ndata: " DBG_ADDRESS ", size: %d\n", _data, _size); if (NULL != _data) { const uint8_t* data = reinterpret_cast<const uint8_t*>(_data); char hex[HEX_DUMP_WIDTH*3+1]; char ascii[HEX_DUMP_WIDTH+1]; uint32_t hexPos = 0; uint32_t asciiPos = 0; for (uint32_t ii = 0; ii < _size; ++ii) { snprintf(&hex[hexPos], sizeof(hex)-hexPos, "%02x ", data[asciiPos]); hexPos += 3; ascii[asciiPos] = isPrint(data[asciiPos]) ? data[asciiPos] : '.'; asciiPos++; if (HEX_DUMP_WIDTH == asciiPos) { ascii[asciiPos] = '\0'; debugPrintf("\t" DBG_ADDRESS "\t" HEX_DUMP_FORMAT "\t%s\n", data, hex, ascii); data += asciiPos; hexPos = 0; asciiPos = 0; } } if (0 != asciiPos) { ascii[asciiPos] = '\0'; debugPrintf("\t" DBG_ADDRESS "\t" HEX_DUMP_FORMAT "\t%s\n", data, hex, ascii); } } #undef HEX_DUMP_WIDTH #undef HEX_DUMP_SPACE_WIDTH #undef HEX_DUMP_FORMAT } } // namespace bx <|endoftext|>
<commit_before>#include "index/StringTable.hpp" #include <boost/test/unit_test.hpp> using namespace utymap::index; struct Index_StringTableFixture { Index_StringTableFixture() : indexPath("index.idx"), stringPath("strings.dat"), table(*new StringTable(indexPath, stringPath)) { BOOST_TEST_MESSAGE("setup fixture"); } ~Index_StringTableFixture() { BOOST_TEST_MESSAGE("teardown fixture"); delete &table; std::remove(indexPath.c_str()); std::remove(stringPath.c_str()); } std::string indexPath; std::string stringPath; StringTable& table; }; BOOST_FIXTURE_TEST_SUITE( Index_StringTable, Index_StringTableFixture ) BOOST_AUTO_TEST_CASE( GivenNonPresentString_WhenGetIdFirstTime_ThenReturnZero ) { uint32_t id = table.getId("some_string"); BOOST_CHECK( id == 0 ); } BOOST_AUTO_TEST_CASE( GivenTable_WhenInsertMultiple_ThenReturnSequentialId ) { uint32_t id1 = table.getId("string1"); uint32_t id2 = table.getId("string2"); uint32_t id3 = table.getId("string3"); BOOST_CHECK( id1 == 0 ); BOOST_CHECK( id2 == 1 ); BOOST_CHECK( id3 == 2 ); } BOOST_AUTO_TEST_CASE( GivenThreeStrings_WhenGetIdOfSecond_ThenReturnValidId ) { uint32_t id = table.getId("string1"); id = table.getId("string2"); id = table.getId("string3"); id = table.getId("string2"); BOOST_CHECK( id == 1 ); } BOOST_AUTO_TEST_CASE( GivenThreeStrings_WhenGetStringOfSecond_ThenReturnValidString ) { uint32_t id = table.getId("string1"); table.getId("string2"); table.getId("string3"); std::string str = table.getString(1); BOOST_CHECK( str == "string2" ); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>cross platform: add missing include<commit_after>#include "index/StringTable.hpp" #include <boost/test/unit_test.hpp> #include <cstdio> using namespace utymap::index; struct Index_StringTableFixture { Index_StringTableFixture() : indexPath("index.idx"), stringPath("strings.dat"), table(*new StringTable(indexPath, stringPath)) { BOOST_TEST_MESSAGE("setup fixture"); } ~Index_StringTableFixture() { BOOST_TEST_MESSAGE("teardown fixture"); delete &table; std::remove(indexPath.c_str()); std::remove(stringPath.c_str()); } std::string indexPath; std::string stringPath; StringTable& table; }; BOOST_FIXTURE_TEST_SUITE( Index_StringTable, Index_StringTableFixture ) BOOST_AUTO_TEST_CASE( GivenNonPresentString_WhenGetIdFirstTime_ThenReturnZero ) { uint32_t id = table.getId("some_string"); BOOST_CHECK( id == 0 ); } BOOST_AUTO_TEST_CASE( GivenTable_WhenInsertMultiple_ThenReturnSequentialId ) { uint32_t id1 = table.getId("string1"); uint32_t id2 = table.getId("string2"); uint32_t id3 = table.getId("string3"); BOOST_CHECK( id1 == 0 ); BOOST_CHECK( id2 == 1 ); BOOST_CHECK( id3 == 2 ); } BOOST_AUTO_TEST_CASE( GivenThreeStrings_WhenGetIdOfSecond_ThenReturnValidId ) { uint32_t id = table.getId("string1"); id = table.getId("string2"); id = table.getId("string3"); id = table.getId("string2"); BOOST_CHECK( id == 1 ); } BOOST_AUTO_TEST_CASE( GivenThreeStrings_WhenGetStringOfSecond_ThenReturnValidString ) { uint32_t id = table.getId("string1"); table.getId("string2"); table.getId("string3"); std::string str = table.getString(1); BOOST_CHECK( str == "string2" ); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <map> #include <llvm/IR/Value.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Constants.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Module.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/raw_ostream.h> #include "llvm/LLVMNode.h" #include "llvm/LLVMDependenceGraph.h" #include "llvm/llvm-util.h" #include "llvm/analysis/PointsTo/PointsTo.h" #include "ReachingDefinitions/ReachingDefinitions.h" #include "DefUse.h" #include "analysis/PointsTo/PointerSubgraph.h" #include "analysis/DFS.h" using dg::analysis::rd::LLVMReachingDefinitions; using dg::analysis::rd::RDNode; using namespace llvm; /// -------------------------------------------------- // Add def-use edges /// -------------------------------------------------- namespace dg { static void handleInstruction(const Instruction *Inst, LLVMNode *node) { LLVMDependenceGraph *dg = node->getDG(); for (auto I = Inst->op_begin(), E = Inst->op_end(); I != E; ++I) { LLVMNode *op = dg->getNode(*I); if (op) op->addDataDependence(node); } } static void addReturnEdge(LLVMNode *callNode, LLVMDependenceGraph *subgraph) { // FIXME we may loose some accuracy here and // this edges causes that we'll go into subprocedure // even with summary edges if (!callNode->isVoidTy()) subgraph->getExit()->addDataDependence(callNode); } LLVMDefUseAnalysis::LLVMDefUseAnalysis(LLVMDependenceGraph *dg, LLVMReachingDefinitions *rd, LLVMPointerAnalysis *pta) : analysis::DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), analysis::DATAFLOW_INTERPROCEDURAL), dg(dg), RD(rd), PTA(pta), DL(new DataLayout(dg->getModule())) { assert(PTA && "Need points-to information"); assert(RD && "Need reaching definitions"); } void LLVMDefUseAnalysis::handleInlineAsm(LLVMNode *callNode) { CallInst *CI = cast<CallInst>(callNode->getValue()); LLVMDependenceGraph *dg = callNode->getDG(); // the last operand is the asm itself, so iterate only to e - 1 for (unsigned i = 0, e = CI->getNumOperands(); i < e - 1; ++i) { Value *opVal = CI->getOperand(i); if (!opVal->getType()->isPointerTy()) continue; LLVMNode *opNode = dg->getNode(opVal->stripInBoundsOffsets()); if (!opNode) { // FIXME: ConstantExpr llvmutil::printerr("WARN: unhandled inline asm operand: ", opVal); continue; } assert(opNode && "Do not have an operand for inline asm"); // if nothing else, this call at least uses the operands opNode->addDataDependence(callNode); } } void LLVMDefUseAnalysis::handleIntrinsicCall(LLVMNode *callNode, CallInst *CI) { IntrinsicInst *I = cast<IntrinsicInst>(CI); Value *dest, *src = nullptr; switch (I->getIntrinsicID()) { case Intrinsic::memmove: case Intrinsic::memcpy: dest = I->getOperand(0); src = I->getOperand(1); break; case Intrinsic::memset: dest = I->getOperand(0); break; case Intrinsic::vastart: dest = I->getOperand(0); break; default: //assert(0 && "DEF-USE: Unhandled intrinsic call"); //handleUndefinedCall(callNode, CI); return; } // we must have dest set assert(dest); // these functions touch the memory of the pointers addDataDependence(callNode, CI, dest, UNKNOWN_OFFSET /* FIXME */); if (src) addDataDependence(callNode, CI, src, UNKNOWN_OFFSET /* FIXME */); } void LLVMDefUseAnalysis::handleCallInst(LLVMNode *node) { CallInst *CI = cast<CallInst>(node->getKey()); if (CI->isInlineAsm()) { handleInlineAsm(node); return; } Function *func = dyn_cast<Function>(CI->getCalledValue()->stripPointerCasts()); if (func) { if (func->isIntrinsic() && !isa<DbgValueInst>(CI)) { handleIntrinsicCall(node, CI); return; } // for realloc, we need to make it data dependent on the // memory it reallocates, since that is the memory it copies if (strcmp(func->getName().data(), "realloc") == 0) addDataDependence(node, CI, CI->getOperand(0), UNKNOWN_OFFSET /* FIXME */); } /* if (func && func->size() == 0) { handleUndefinedCall(node); return; } */ // add edges from the return nodes of subprocedure // to the call (if the call returns something) for (LLVMDependenceGraph *subgraph : node->getSubgraphs()) addReturnEdge(node, subgraph); } // Add data dependence edges from all memory location that may write // to memory pointed by 'pts' to 'node' void LLVMDefUseAnalysis::addUnknownDataDependence(LLVMNode *node, PSNode *pts) { // iterate over all nodes from ReachingDefinitions Subgraph. It is faster than // going over all llvm nodes and querying the pointer to analysis for (auto it : RD->getNodesMap()) { RDNode *rdnode = it.second; // only STORE may be a definition site if (rdnode->getType() != analysis::rd::STORE) continue; llvm::Value *rdVal = rdnode->getUserData<llvm::Value>(); // artificial node? if (!rdVal) continue; // does this store define some value that is in pts? for (const analysis::rd::DefSite& ds : rdnode->getDefines()) { llvm::Value *llvmVal = ds.target->getUserData<llvm::Value>(); // is this an artificial node? if (!llvmVal) continue; // if these two sets have an over-lap, we must add the data dependence for (const auto& ptr : pts->pointsTo) if (ptr.target->getUserData<llvm::Value>() == llvmVal) { addDataDependence(node, rdVal); } } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, llvm::Value *rdval) { LLVMNode *rdnode = dg->getNode(rdval); if (!rdnode) { // that means that the value is not from this graph. // We need to add interprocedural edge llvm::Function *F = llvm::cast<llvm::Instruction>(rdval)->getParent()->getParent(); LLVMNode *entryNode = dg->getGlobalNode(F); assert(entryNode && "Don't have built function"); // get the graph where the node lives LLVMDependenceGraph *graph = entryNode->getDG(); assert(graph != dg && "Cannot find a node"); rdnode = graph->getNode(rdval); if (!rdnode) { llvmutil::printerr("ERROR: DG has not val: ", rdval); return; } } assert(rdnode); rdnode->addDataDependence(node); } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, RDNode *rd) { llvm::Value *rdval = rd->getUserData<llvm::Value>(); assert(rdval && "RDNode has not set the coresponding value"); addDataDependence(node, rdval); } // \param mem current reaching definitions point void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, PSNode *pts, RDNode *mem, uint64_t size) { using namespace dg::analysis; for (const pta::Pointer& ptr : pts->pointsTo) { if (!ptr.isValid()) continue; llvm::Value *llvmVal = ptr.target->getUserData<llvm::Value>(); assert(llvmVal && "Don't have Value in PSNode"); RDNode *val = RD->getNode(llvmVal); if(!val) { llvmutil::printerr("Don't have mapping:\n ", llvmVal); continue; } std::set<RDNode *> defs; // Get even reaching definitions for UNKNOWN_MEMORY. // Since those can be ours definitions, we must add them always mem->getReachingDefinitions(rd::UNKNOWN_MEMORY, UNKNOWN_OFFSET, UNKNOWN_OFFSET, defs); if (!defs.empty()) { for (RDNode *rd : defs) { assert(!rd->isUnknown() && "Unknown memory defined at unknown location?"); addDataDependence(node, rd); } defs.clear(); } mem->getReachingDefinitions(val, ptr.offset, size, defs); if (defs.empty()) { llvm::GlobalVariable *GV = llvm::dyn_cast<llvm::GlobalVariable>(llvmVal); if (!GV || !GV->hasInitializer()) llvm::errs() << "No reaching definition for: " << *llvmVal << " off: " << *ptr.offset << "\n"; continue; } // add data dependence for (RDNode *rd : defs) { if (rd->isUnknown()) { // we don't know what definitions reach this node, // se we must add data dependence to all possible // write to this memory addUnknownDataDependence(node, pts); // we can bail out, since we have added all break; } addDataDependence(node, rd); } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, const llvm::Value *where, /* in CFG */ const llvm::Value *ptrOp, uint64_t size) { using namespace dg::analysis; // get points-to information for the operand pta::PSNode *pts = PTA->getPointsTo(ptrOp); //assert(pts && "Don't have points-to information for LoadInst"); if (!pts) { llvmutil::printerr("ERROR: No points-to: ", ptrOp); return; } // get the node from reaching definition where we have // all the reaching definitions RDNode *mem = RD->getMapping(where); if(!mem) { llvmutil::printerr("ERROR: Don't have mapping: ", where); return; } // take every memory the load inst can use and get the // reaching definition addDataDependence(node, pts, mem, size); } static uint64_t getAllocatedSize(llvm::Type *Ty, const llvm::DataLayout *DL) { // Type can be i8 *null or similar if (!Ty->isSized()) return UNKNOWN_OFFSET; return DL->getTypeAllocSize(Ty); } void LLVMDefUseAnalysis::handleLoadInst(llvm::LoadInst *Inst, LLVMNode *node) { using namespace dg::analysis; uint64_t size = getAllocatedSize(Inst->getType(), DL); addDataDependence(node, Inst, Inst->getPointerOperand(), size); } bool LLVMDefUseAnalysis::runOnNode(LLVMNode *node, LLVMNode *prev) { Value *val = node->getKey(); (void) prev; if (LoadInst *Inst = dyn_cast<LoadInst>(val)) { handleLoadInst(Inst, node); } else if (isa<CallInst>(val)) { handleCallInst(node); /*} else if (StoreInst *Inst = dyn_cast<StoreInst>(val)) { handleStoreInst(Inst, node);*/ } /* just add direct def-use edges to every instruction */ if (Instruction *Inst = dyn_cast<Instruction>(val)) handleInstruction(Inst, node); // we will run only once return false; } } // namespace dg <commit_msg>print warning about missing RD only once<commit_after>#include <map> #include <llvm/IR/Value.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Constants.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Module.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/raw_ostream.h> #include "llvm/LLVMNode.h" #include "llvm/LLVMDependenceGraph.h" #include "llvm/llvm-util.h" #include "llvm/analysis/PointsTo/PointsTo.h" #include "ReachingDefinitions/ReachingDefinitions.h" #include "DefUse.h" #include "analysis/PointsTo/PointerSubgraph.h" #include "analysis/DFS.h" using dg::analysis::rd::LLVMReachingDefinitions; using dg::analysis::rd::RDNode; using namespace llvm; /// -------------------------------------------------- // Add def-use edges /// -------------------------------------------------- namespace dg { static void handleInstruction(const Instruction *Inst, LLVMNode *node) { LLVMDependenceGraph *dg = node->getDG(); for (auto I = Inst->op_begin(), E = Inst->op_end(); I != E; ++I) { LLVMNode *op = dg->getNode(*I); if (op) op->addDataDependence(node); } } static void addReturnEdge(LLVMNode *callNode, LLVMDependenceGraph *subgraph) { // FIXME we may loose some accuracy here and // this edges causes that we'll go into subprocedure // even with summary edges if (!callNode->isVoidTy()) subgraph->getExit()->addDataDependence(callNode); } LLVMDefUseAnalysis::LLVMDefUseAnalysis(LLVMDependenceGraph *dg, LLVMReachingDefinitions *rd, LLVMPointerAnalysis *pta) : analysis::DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), analysis::DATAFLOW_INTERPROCEDURAL), dg(dg), RD(rd), PTA(pta), DL(new DataLayout(dg->getModule())) { assert(PTA && "Need points-to information"); assert(RD && "Need reaching definitions"); } void LLVMDefUseAnalysis::handleInlineAsm(LLVMNode *callNode) { CallInst *CI = cast<CallInst>(callNode->getValue()); LLVMDependenceGraph *dg = callNode->getDG(); // the last operand is the asm itself, so iterate only to e - 1 for (unsigned i = 0, e = CI->getNumOperands(); i < e - 1; ++i) { Value *opVal = CI->getOperand(i); if (!opVal->getType()->isPointerTy()) continue; LLVMNode *opNode = dg->getNode(opVal->stripInBoundsOffsets()); if (!opNode) { // FIXME: ConstantExpr llvmutil::printerr("WARN: unhandled inline asm operand: ", opVal); continue; } assert(opNode && "Do not have an operand for inline asm"); // if nothing else, this call at least uses the operands opNode->addDataDependence(callNode); } } void LLVMDefUseAnalysis::handleIntrinsicCall(LLVMNode *callNode, CallInst *CI) { IntrinsicInst *I = cast<IntrinsicInst>(CI); Value *dest, *src = nullptr; switch (I->getIntrinsicID()) { case Intrinsic::memmove: case Intrinsic::memcpy: dest = I->getOperand(0); src = I->getOperand(1); break; case Intrinsic::memset: dest = I->getOperand(0); break; case Intrinsic::vastart: dest = I->getOperand(0); break; default: //assert(0 && "DEF-USE: Unhandled intrinsic call"); //handleUndefinedCall(callNode, CI); return; } // we must have dest set assert(dest); // these functions touch the memory of the pointers addDataDependence(callNode, CI, dest, UNKNOWN_OFFSET /* FIXME */); if (src) addDataDependence(callNode, CI, src, UNKNOWN_OFFSET /* FIXME */); } void LLVMDefUseAnalysis::handleCallInst(LLVMNode *node) { CallInst *CI = cast<CallInst>(node->getKey()); if (CI->isInlineAsm()) { handleInlineAsm(node); return; } Function *func = dyn_cast<Function>(CI->getCalledValue()->stripPointerCasts()); if (func) { if (func->isIntrinsic() && !isa<DbgValueInst>(CI)) { handleIntrinsicCall(node, CI); return; } // for realloc, we need to make it data dependent on the // memory it reallocates, since that is the memory it copies if (strcmp(func->getName().data(), "realloc") == 0) addDataDependence(node, CI, CI->getOperand(0), UNKNOWN_OFFSET /* FIXME */); } /* if (func && func->size() == 0) { handleUndefinedCall(node); return; } */ // add edges from the return nodes of subprocedure // to the call (if the call returns something) for (LLVMDependenceGraph *subgraph : node->getSubgraphs()) addReturnEdge(node, subgraph); } // Add data dependence edges from all memory location that may write // to memory pointed by 'pts' to 'node' void LLVMDefUseAnalysis::addUnknownDataDependence(LLVMNode *node, PSNode *pts) { // iterate over all nodes from ReachingDefinitions Subgraph. It is faster than // going over all llvm nodes and querying the pointer to analysis for (auto it : RD->getNodesMap()) { RDNode *rdnode = it.second; // only STORE may be a definition site if (rdnode->getType() != analysis::rd::STORE) continue; llvm::Value *rdVal = rdnode->getUserData<llvm::Value>(); // artificial node? if (!rdVal) continue; // does this store define some value that is in pts? for (const analysis::rd::DefSite& ds : rdnode->getDefines()) { llvm::Value *llvmVal = ds.target->getUserData<llvm::Value>(); // is this an artificial node? if (!llvmVal) continue; // if these two sets have an over-lap, we must add the data dependence for (const auto& ptr : pts->pointsTo) if (ptr.target->getUserData<llvm::Value>() == llvmVal) { addDataDependence(node, rdVal); } } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, llvm::Value *rdval) { LLVMNode *rdnode = dg->getNode(rdval); if (!rdnode) { // that means that the value is not from this graph. // We need to add interprocedural edge llvm::Function *F = llvm::cast<llvm::Instruction>(rdval)->getParent()->getParent(); LLVMNode *entryNode = dg->getGlobalNode(F); assert(entryNode && "Don't have built function"); // get the graph where the node lives LLVMDependenceGraph *graph = entryNode->getDG(); assert(graph != dg && "Cannot find a node"); rdnode = graph->getNode(rdval); if (!rdnode) { llvmutil::printerr("ERROR: DG has not val: ", rdval); return; } } assert(rdnode); rdnode->addDataDependence(node); } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, RDNode *rd) { llvm::Value *rdval = rd->getUserData<llvm::Value>(); assert(rdval && "RDNode has not set the coresponding value"); addDataDependence(node, rdval); } // \param mem current reaching definitions point void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, PSNode *pts, RDNode *mem, uint64_t size) { using namespace dg::analysis; for (const pta::Pointer& ptr : pts->pointsTo) { if (!ptr.isValid()) continue; llvm::Value *llvmVal = ptr.target->getUserData<llvm::Value>(); assert(llvmVal && "Don't have Value in PSNode"); RDNode *val = RD->getNode(llvmVal); if(!val) { llvmutil::printerr("Don't have mapping:\n ", llvmVal); continue; } std::set<RDNode *> defs; // Get even reaching definitions for UNKNOWN_MEMORY. // Since those can be ours definitions, we must add them always mem->getReachingDefinitions(rd::UNKNOWN_MEMORY, UNKNOWN_OFFSET, UNKNOWN_OFFSET, defs); if (!defs.empty()) { for (RDNode *rd : defs) { assert(!rd->isUnknown() && "Unknown memory defined at unknown location?"); addDataDependence(node, rd); } defs.clear(); } mem->getReachingDefinitions(val, ptr.offset, size, defs); if (defs.empty()) { llvm::GlobalVariable *GV = llvm::dyn_cast<llvm::GlobalVariable>(llvmVal); if (!GV || !GV->hasInitializer()) { static std::set<const llvm::Value *> reported; if (reported.insert(llvmVal).second) { llvm::errs() << "No reaching definition for: " << *llvmVal << " off: " << *ptr.offset << "\n"; } } continue; } // add data dependence for (RDNode *rd : defs) { if (rd->isUnknown()) { // we don't know what definitions reach this node, // se we must add data dependence to all possible // write to this memory addUnknownDataDependence(node, pts); // we can bail out, since we have added all break; } addDataDependence(node, rd); } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, const llvm::Value *where, /* in CFG */ const llvm::Value *ptrOp, uint64_t size) { using namespace dg::analysis; // get points-to information for the operand pta::PSNode *pts = PTA->getPointsTo(ptrOp); //assert(pts && "Don't have points-to information for LoadInst"); if (!pts) { llvmutil::printerr("ERROR: No points-to: ", ptrOp); return; } // get the node from reaching definition where we have // all the reaching definitions RDNode *mem = RD->getMapping(where); if(!mem) { llvmutil::printerr("ERROR: Don't have mapping: ", where); return; } // take every memory the load inst can use and get the // reaching definition addDataDependence(node, pts, mem, size); } static uint64_t getAllocatedSize(llvm::Type *Ty, const llvm::DataLayout *DL) { // Type can be i8 *null or similar if (!Ty->isSized()) return UNKNOWN_OFFSET; return DL->getTypeAllocSize(Ty); } void LLVMDefUseAnalysis::handleLoadInst(llvm::LoadInst *Inst, LLVMNode *node) { using namespace dg::analysis; uint64_t size = getAllocatedSize(Inst->getType(), DL); addDataDependence(node, Inst, Inst->getPointerOperand(), size); } bool LLVMDefUseAnalysis::runOnNode(LLVMNode *node, LLVMNode *prev) { Value *val = node->getKey(); (void) prev; if (LoadInst *Inst = dyn_cast<LoadInst>(val)) { handleLoadInst(Inst, node); } else if (isa<CallInst>(val)) { handleCallInst(node); /*} else if (StoreInst *Inst = dyn_cast<StoreInst>(val)) { handleStoreInst(Inst, node);*/ } /* just add direct def-use edges to every instruction */ if (Instruction *Inst = dyn_cast<Instruction>(val)) handleInstruction(Inst, node); // we will run only once return false; } } // namespace dg <|endoftext|>
<commit_before>// --------------------------------------------------------------------- // // Copyright (C) 2009 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/base/config.h> #ifdef DEAL_II_WITH_P4EST #include <deal.II/lac/vector.h> #include <deal.II/lac/block_vector.h> #include <deal.II/lac/parallel_vector.h> #include <deal.II/lac/parallel_block_vector.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/distributed/solution_transfer.h> #include <deal.II/distributed/tria.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/dofs/dof_accessor.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/base/std_cxx11/bind.h> DEAL_II_NAMESPACE_OPEN namespace parallel { namespace distributed { template<int dim, typename VECTOR, class DH> SolutionTransfer<dim, VECTOR, DH>::SolutionTransfer(const DH &dof) : dof_handler(&dof, typeid(*this).name()) {} template<int dim, typename VECTOR, class DH> SolutionTransfer<dim, VECTOR, DH>::~SolutionTransfer() {} template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_for_coarsening_and_refinement (const std::vector<const VECTOR *> &all_in) { input_vectors = all_in; register_data_attach( get_data_size() * input_vectors.size() ); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: register_data_attach(const std::size_t size) { Assert(size > 0, ExcMessage("Please transfer at least one vector!")); //TODO: casting away constness is bad parallel::distributed::Triangulation<dim> *tria = (dynamic_cast<parallel::distributed::Triangulation<dim>*> (const_cast<dealii::Triangulation<dim>*> (&dof_handler->get_tria()))); Assert (tria != 0, ExcInternalError()); offset = tria->register_data_attach(size, std_cxx11::bind(&SolutionTransfer<dim, VECTOR, DH>::pack_callback, this, std_cxx11::_1, std_cxx11::_2, std_cxx11::_3)); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_for_coarsening_and_refinement (const VECTOR &in) { std::vector<const VECTOR *> all_in(1, &in); prepare_for_coarsening_and_refinement(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_serialization(const VECTOR &in) { std::vector<const VECTOR *> all_in(1, &in); prepare_serialization(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_serialization(const std::vector<const VECTOR *> &all_in) { prepare_for_coarsening_and_refinement (all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: deserialize(VECTOR &in) { std::vector<VECTOR *> all_in(1, &in); deserialize(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: deserialize(std::vector<VECTOR *> &all_in) { register_data_attach( get_data_size() * all_in.size() ); // this makes interpolate() happy input_vectors.resize(all_in.size()); interpolate(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: interpolate (std::vector<VECTOR *> &all_out) { Assert(input_vectors.size()==all_out.size(), ExcDimensionMismatch(input_vectors.size(), all_out.size()) ); //TODO: casting away constness is bad parallel::distributed::Triangulation<dim> *tria = (dynamic_cast<parallel::distributed::Triangulation<dim>*> (const_cast<dealii::Triangulation<dim>*> (&dof_handler->get_tria()))); Assert (tria != 0, ExcInternalError()); tria->notify_ready_to_unpack(offset, std_cxx11::bind(&SolutionTransfer<dim, VECTOR, DH>::unpack_callback, this, std_cxx11::_1, std_cxx11::_2, std_cxx11::_3, std_cxx11::ref(all_out))); for (typename std::vector<VECTOR *>::iterator it=all_out.begin(); it !=all_out.end(); ++it) (*it)->compress(::dealii::VectorOperation::insert); input_vectors.clear(); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: interpolate (VECTOR &out) { std::vector<VECTOR *> all_out(1, &out); interpolate(all_out); } template<int dim, typename VECTOR, class DH> unsigned int SolutionTransfer<dim, VECTOR, DH>:: get_data_size() const { return sizeof(double)* DoFTools::max_dofs_per_cell(*dof_handler); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: pack_callback(const typename Triangulation<dim,dim>::cell_iterator &cell_, const typename Triangulation<dim,dim>::CellStatus /*status*/, void *data) { double *data_store = reinterpret_cast<double *>(data); typename DH::cell_iterator cell(*cell_, dof_handler); const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell; ::dealii::Vector<double> dofvalues(dofs_per_cell); for (typename std::vector<const VECTOR *>::iterator it=input_vectors.begin(); it !=input_vectors.end(); ++it) { cell->get_interpolated_dof_values(*(*it), dofvalues); std::memcpy(data_store, &dofvalues(0), sizeof(double)*dofs_per_cell); data_store += dofs_per_cell; } } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: unpack_callback(const typename Triangulation<dim,dim>::cell_iterator &cell_, const typename Triangulation<dim,dim>::CellStatus /*status*/, const void *data, std::vector<VECTOR *> &all_out) { typename DH::cell_iterator cell(*cell_, dof_handler); const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell; ::dealii::Vector<double> dofvalues(dofs_per_cell); const double *data_store = reinterpret_cast<const double *>(data); for (typename std::vector<VECTOR *>::iterator it = all_out.begin(); it != all_out.end(); ++it) { std::memcpy(&dofvalues(0), data_store, sizeof(double)*dofs_per_cell); cell->set_dof_values_by_interpolation(dofvalues, *(*it)); data_store += dofs_per_cell; } } } } // explicit instantiations #include "solution_transfer.inst" DEAL_II_NAMESPACE_CLOSE #endif <commit_msg>improve SolutionTransfer exception<commit_after>// --------------------------------------------------------------------- // // Copyright (C) 2009 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/base/config.h> #ifdef DEAL_II_WITH_P4EST #include <deal.II/lac/vector.h> #include <deal.II/lac/block_vector.h> #include <deal.II/lac/parallel_vector.h> #include <deal.II/lac/parallel_block_vector.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/distributed/solution_transfer.h> #include <deal.II/distributed/tria.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/dofs/dof_accessor.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/base/std_cxx11/bind.h> DEAL_II_NAMESPACE_OPEN namespace parallel { namespace distributed { template<int dim, typename VECTOR, class DH> SolutionTransfer<dim, VECTOR, DH>::SolutionTransfer(const DH &dof) : dof_handler(&dof, typeid(*this).name()) { parallel::distributed::Triangulation<dim> *tria = (dynamic_cast<parallel::distributed::Triangulation<dim>*> (const_cast<dealii::Triangulation<dim>*> (&dof_handler->get_tria()))); Assert (tria != 0, ExcMessage("parallel::distributed::SolutionTransfer requires a parallel::distributed::Triangulation object.")); } template<int dim, typename VECTOR, class DH> SolutionTransfer<dim, VECTOR, DH>::~SolutionTransfer() {} template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_for_coarsening_and_refinement (const std::vector<const VECTOR *> &all_in) { input_vectors = all_in; register_data_attach( get_data_size() * input_vectors.size() ); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: register_data_attach(const std::size_t size) { Assert(size > 0, ExcMessage("Please transfer at least one vector!")); //TODO: casting away constness is bad parallel::distributed::Triangulation<dim> *tria = (dynamic_cast<parallel::distributed::Triangulation<dim>*> (const_cast<dealii::Triangulation<dim>*> (&dof_handler->get_tria()))); Assert (tria != 0, ExcInternalError()); offset = tria->register_data_attach(size, std_cxx11::bind(&SolutionTransfer<dim, VECTOR, DH>::pack_callback, this, std_cxx11::_1, std_cxx11::_2, std_cxx11::_3)); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_for_coarsening_and_refinement (const VECTOR &in) { std::vector<const VECTOR *> all_in(1, &in); prepare_for_coarsening_and_refinement(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_serialization(const VECTOR &in) { std::vector<const VECTOR *> all_in(1, &in); prepare_serialization(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: prepare_serialization(const std::vector<const VECTOR *> &all_in) { prepare_for_coarsening_and_refinement (all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: deserialize(VECTOR &in) { std::vector<VECTOR *> all_in(1, &in); deserialize(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: deserialize(std::vector<VECTOR *> &all_in) { register_data_attach( get_data_size() * all_in.size() ); // this makes interpolate() happy input_vectors.resize(all_in.size()); interpolate(all_in); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: interpolate (std::vector<VECTOR *> &all_out) { Assert(input_vectors.size()==all_out.size(), ExcDimensionMismatch(input_vectors.size(), all_out.size()) ); //TODO: casting away constness is bad parallel::distributed::Triangulation<dim> *tria = (dynamic_cast<parallel::distributed::Triangulation<dim>*> (const_cast<dealii::Triangulation<dim>*> (&dof_handler->get_tria()))); Assert (tria != 0, ExcInternalError()); tria->notify_ready_to_unpack(offset, std_cxx11::bind(&SolutionTransfer<dim, VECTOR, DH>::unpack_callback, this, std_cxx11::_1, std_cxx11::_2, std_cxx11::_3, std_cxx11::ref(all_out))); for (typename std::vector<VECTOR *>::iterator it=all_out.begin(); it !=all_out.end(); ++it) (*it)->compress(::dealii::VectorOperation::insert); input_vectors.clear(); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: interpolate (VECTOR &out) { std::vector<VECTOR *> all_out(1, &out); interpolate(all_out); } template<int dim, typename VECTOR, class DH> unsigned int SolutionTransfer<dim, VECTOR, DH>:: get_data_size() const { return sizeof(double)* DoFTools::max_dofs_per_cell(*dof_handler); } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: pack_callback(const typename Triangulation<dim,dim>::cell_iterator &cell_, const typename Triangulation<dim,dim>::CellStatus /*status*/, void *data) { double *data_store = reinterpret_cast<double *>(data); typename DH::cell_iterator cell(*cell_, dof_handler); const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell; ::dealii::Vector<double> dofvalues(dofs_per_cell); for (typename std::vector<const VECTOR *>::iterator it=input_vectors.begin(); it !=input_vectors.end(); ++it) { cell->get_interpolated_dof_values(*(*it), dofvalues); std::memcpy(data_store, &dofvalues(0), sizeof(double)*dofs_per_cell); data_store += dofs_per_cell; } } template<int dim, typename VECTOR, class DH> void SolutionTransfer<dim, VECTOR, DH>:: unpack_callback(const typename Triangulation<dim,dim>::cell_iterator &cell_, const typename Triangulation<dim,dim>::CellStatus /*status*/, const void *data, std::vector<VECTOR *> &all_out) { typename DH::cell_iterator cell(*cell_, dof_handler); const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell; ::dealii::Vector<double> dofvalues(dofs_per_cell); const double *data_store = reinterpret_cast<const double *>(data); for (typename std::vector<VECTOR *>::iterator it = all_out.begin(); it != all_out.end(); ++it) { std::memcpy(&dofvalues(0), data_store, sizeof(double)*dofs_per_cell); cell->set_dof_values_by_interpolation(dofvalues, *(*it)); data_store += dofs_per_cell; } } } } // explicit instantiations #include "solution_transfer.inst" DEAL_II_NAMESPACE_CLOSE #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Archive.h" #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <utilities/StaticString.h> #include <panic.h> #include <Log.h> Archive::Archive(uint8_t *pPhys, size_t sSize) : m_Region("Archive") { if ((reinterpret_cast<physical_uintptr_t>(pPhys) & (PhysicalMemoryManager::getPageSize() - 1)) != 0) panic("Archive: Alignment issues"); if (PhysicalMemoryManager::instance().allocateRegion(m_Region, (sSize + PhysicalMemoryManager::getPageSize() - 1) / PhysicalMemoryManager::getPageSize(), PhysicalMemoryManager::continuous, VirtualAddressSpace::KernelMode, reinterpret_cast<physical_uintptr_t>(pPhys)) == false) { ERROR("Archive: allocateRegion failed."); } } Archive::~Archive() { // TODO destroy all pages. } size_t Archive::getNumFiles() { size_t i = 0; File *pFile = getFirst(); while (pFile != 0) { i++; pFile = getNext(pFile); } return i; } size_t Archive::getFileSize(size_t n) { File *pFile = get(n); NormalStaticString str(pFile->size); return str.intValue(8); // Octal } char *Archive::getFileName(size_t n) { return get(n)->name; } uintptr_t *Archive::getFile(size_t n) { return reinterpret_cast<uintptr_t*>(reinterpret_cast<uintptr_t>(get(n)) + 512); } Archive::File *Archive::getFirst() { return reinterpret_cast<File*> (m_Region.virtualAddress()); } Archive::File *Archive::getNext(File *pFile) { NormalStaticString str(pFile->size); size_t size = str.intValue(8); // Octal. size_t nBlocks = (size + 511) / 512; pFile = adjust_pointer(pFile, 512 * (nBlocks + 1)); if (pFile->name[0] == '\0')return 0; return pFile; } Archive::File *Archive::get(size_t n) { File *pFile = getFirst(); for (size_t i = 0;i < n;i++) pFile = getNext(pFile); return pFile; } <commit_msg>kernel: free used memory in Archive destructor<commit_after>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Archive.h" #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <utilities/StaticString.h> #include <panic.h> #include <Log.h> Archive::Archive(uint8_t *pPhys, size_t sSize) : m_Region("Archive") { if ((reinterpret_cast<physical_uintptr_t>(pPhys) & (PhysicalMemoryManager::getPageSize() - 1)) != 0) panic("Archive: Alignment issues"); if (PhysicalMemoryManager::instance().allocateRegion(m_Region, (sSize + PhysicalMemoryManager::getPageSize() - 1) / PhysicalMemoryManager::getPageSize(), PhysicalMemoryManager::continuous, VirtualAddressSpace::KernelMode, reinterpret_cast<physical_uintptr_t>(pPhys)) == false) { ERROR("Archive: allocateRegion failed."); } } Archive::~Archive() { m_Region.free(); } size_t Archive::getNumFiles() { size_t i = 0; File *pFile = getFirst(); while (pFile != 0) { i++; pFile = getNext(pFile); } return i; } size_t Archive::getFileSize(size_t n) { File *pFile = get(n); NormalStaticString str(pFile->size); return str.intValue(8); // Octal } char *Archive::getFileName(size_t n) { return get(n)->name; } uintptr_t *Archive::getFile(size_t n) { return reinterpret_cast<uintptr_t*>(reinterpret_cast<uintptr_t>(get(n)) + 512); } Archive::File *Archive::getFirst() { return reinterpret_cast<File*> (m_Region.virtualAddress()); } Archive::File *Archive::getNext(File *pFile) { NormalStaticString str(pFile->size); size_t size = str.intValue(8); // Octal. size_t nBlocks = (size + 511) / 512; pFile = adjust_pointer(pFile, 512 * (nBlocks + 1)); if (pFile->name[0] == '\0')return 0; return pFile; } Archive::File *Archive::get(size_t n) { File *pFile = getFirst(); for (size_t i = 0;i < n;i++) pFile = getNext(pFile); return pFile; } <|endoftext|>
<commit_before>#include <cmath> #include <omp.h> #include "galaxy.h" void cela::newp1(double dt) { p1 = p + v * dt + a * dt * dt / 2; } void cela::flush(double dt) { v += a * dt; p = p1; } galaxy::galaxy(int n, cela* stars, double step, double G, double t, int r, double o, bool aplfx):n(n), dt(step), G(G), t(t), recurdepth(r), omega(o), applyenergyfix(aplfx) { celas = new cela[n]; int i; for (i=0;i<n;i++) { celas[i] = stars[i]; } this->calculateEnergy(); e0 = ek + ep; } galaxy::~galaxy() { delete [] celas; } void galaxy::setGravity(double gc) { G = gc; } void galaxy::setTimeStep(double step) { dt = step; } bool galaxy::togglefix() { if (applyenergyfix) { applyenergyfix = false; } else { applyenergyfix = true; } return applyenergyfix; } int galaxy::getCelaNum() { return n; } double galaxy::getTime() { return t; } int galaxy::getRecDpt() { return recurdepth; } double galaxy::getOmega() { return omega; } double galaxy::getG() { return G; } double galaxy::getStep() { return dt; } bool galaxy::appliedfix() { return applyenergyfix; } cela* galaxy::output(){ return celas; } void galaxy::setacc(int i) { int j; vector r; //vector distance double d; //distance vector acc(0,0,0); vector epi; // unit vector in direction of p[j]-p[i] vector dvi,dvj; //if (celas[i].c) { //Collided with another cela. acceleration already calculated // return; //} for (j=0;j<n;j++) { // cela[j]'s gravity on cela[i] if (j != i) { //Not myself r = celas[j].p - celas[i].p; d = r.mag(); epi = r / d; if (d <= (celas[i].r + celas[j].r)) { if (!celas[j].c && !celas[i].c) { //Collision with uncollided one celas[i].c = true; celas[j].c = true; dvj = 2 * celas[i].m / (celas[j].m + celas[i].m) * (celas[i].v - celas[j].v) * epi * epi; dvi = 2 * celas[j].m / (celas[j].m + celas[i].m) * (celas[j].v - celas[i].v) * epi * epi; celas[i].v += dvi; celas[j].v += dvj; } acc += G * celas[j].m * epi / ((celas[i].r + celas[j].r) * (celas[i].r + celas[j].r)); } else { acc += G * celas[j].m * epi / (d * d); } } } celas[i].a = acc; return; } vector galaxy::getacc1(int i) { int j; vector r; //vector distance double d; //distance vector acc(0,0,0); vector epi; // unit vector in direction of p[j]-p[i] if (celas[i].c) { //Collided in this stepi return celas[i].a; } for (j=0;j<n;j++) { // cela[j]'s gravity on cela[i] if (j != i) { //Not myself r = celas[j].p1 - celas[i].p1; d = r.mag(); epi = r / d; if (d <= (celas[i].r + celas[j].r)) { acc += G * celas[j].m * epi / ((celas[i].r + celas[j].r) * (celas[i].r + celas[j].r)); } else { acc += G * celas[j].m * epi / (d * d); } } } return acc; } void galaxy::calculateEnergy() { int i,j; ek = 0; ep = 0; for (i=0;i<n;i++) { ek += celas[i].m * (celas[i].v * celas[i].v) / 2; for (j=0;j<i;j++) { ep -= G * celas[i].m * celas[j].m / (celas[j].p - celas[i].p).mag(); } } } double galaxy::getEnergy() { if (applyenergyfix) { return e0; } this->calculateEnergy(); return ek + ep; } void galaxy::run() { int i,rec; double co; // fix coefficient for (i=0;i<n;i++) { celas[i].c = false; } for (i=0;i<n;i++) { setacc(i); } for (rec=0;rec<recurdepth;rec++) { //Recursive calculation for (i=0;i<n;i++) { celas[i].newp1(dt); } for (i=0;i<n;i++) { celas[i].a = celas[i].a * (1 - omega) + getacc1(i) * omega; } } for (i=0;i<n;i++) { //Flush back celas[i].newp1(dt); celas[i].flush(dt); } if (applyenergyfix) { // Fix system energy this->calculateEnergy(); co = sqrt((e0 - ep) / ek); for (i=0;i<n;i++) { celas[i].v *= co; } } t += dt; } <commit_msg>Updated comments<commit_after>#include <cmath> #include <omp.h> #include "galaxy.h" void cela::newp1(double dt) { p1 = p + v * dt + a * dt * dt / 2; } void cela::flush(double dt) { v += a * dt; p = p1; } galaxy::galaxy(int n, cela* stars, double step, double G, double t, int r, double o, bool aplfx):n(n), dt(step), G(G), t(t), recurdepth(r), omega(o), applyenergyfix(aplfx) { celas = new cela[n]; int i; for (i=0;i<n;i++) { celas[i] = stars[i]; } this->calculateEnergy(); e0 = ek + ep; } galaxy::~galaxy() { delete [] celas; } void galaxy::setGravity(double gc) { G = gc; } void galaxy::setTimeStep(double step) { dt = step; } bool galaxy::togglefix() { if (applyenergyfix) { applyenergyfix = false; } else { applyenergyfix = true; } return applyenergyfix; } int galaxy::getCelaNum() { return n; } double galaxy::getTime() { return t; } int galaxy::getRecDpt() { return recurdepth; } double galaxy::getOmega() { return omega; } double galaxy::getG() { return G; } double galaxy::getStep() { return dt; } bool galaxy::appliedfix() { return applyenergyfix; } cela* galaxy::output(){ return celas; } void galaxy::setacc(int i) { int j; vector r; //vector distance double d; //distance vector acc(0,0,0); vector epi; // unit vector in direction of p[j]-p[i] vector dvi,dvj; for (j=0;j<n;j++) { // cela[j]'s gravity on cela[i] if (j != i) { //Not myself r = celas[j].p - celas[i].p; d = r.mag(); epi = r / d; if (d <= (celas[i].r + celas[j].r)) { if (!celas[j].c && !celas[i].c) { //Collision with uncollided one celas[i].c = true; celas[j].c = true; dvj = 2 * celas[i].m / (celas[j].m + celas[i].m) * (celas[i].v - celas[j].v) * epi * epi; dvi = 2 * celas[j].m / (celas[j].m + celas[i].m) * (celas[j].v - celas[i].v) * epi * epi; celas[i].v += dvi; celas[j].v += dvj; } acc += G * celas[j].m * epi / ((celas[i].r + celas[j].r) * (celas[i].r + celas[j].r)); } else { acc += G * celas[j].m * epi / (d * d); } } } celas[i].a = acc; return; } vector galaxy::getacc1(int i) { int j; vector r; //vector distance double d; //distance vector acc(0,0,0); vector epi; // unit vector in direction of p[j]-p[i] if (celas[i].c) { //Collided in this step return celas[i].a; } for (j=0;j<n;j++) { // cela[j]'s gravity on cela[i] if (j != i) { //Not myself r = celas[j].p1 - celas[i].p1; d = r.mag(); epi = r / d; if (d <= (celas[i].r + celas[j].r)) { acc += G * celas[j].m * epi / ((celas[i].r + celas[j].r) * (celas[i].r + celas[j].r)); } else { acc += G * celas[j].m * epi / (d * d); } } } return acc; } void galaxy::calculateEnergy() { int i,j; ek = 0; ep = 0; for (i=0;i<n;i++) { ek += celas[i].m * (celas[i].v * celas[i].v) / 2; for (j=0;j<i;j++) { ep -= G * celas[i].m * celas[j].m / (celas[j].p - celas[i].p).mag(); } } } double galaxy::getEnergy() { if (applyenergyfix) { return e0; } this->calculateEnergy(); return ek + ep; } void galaxy::run() { int i,rec; double co; // fix coefficient for (i=0;i<n;i++) { celas[i].c = false; } for (i=0;i<n;i++) { setacc(i); } for (rec=0;rec<recurdepth;rec++) { //Recursive calculation for (i=0;i<n;i++) { celas[i].newp1(dt); } for (i=0;i<n;i++) { celas[i].a = celas[i].a * (1 - omega) + getacc1(i) * omega; } } for (i=0;i<n;i++) { //Flush back celas[i].newp1(dt); celas[i].flush(dt); } if (applyenergyfix) { // Fix system energy this->calculateEnergy(); co = sqrt((e0 - ep) / ek); for (i=0;i<n;i++) { celas[i].v *= co; } } t += dt; } <|endoftext|>
<commit_before>#include "../common/init.h" #include "util/debug.h" #include "util/bitmap.h" #include "util/timedifference.h" #include <stdlib.h> #include <math.h> #include <string> using std::string; static void test(Graphics::Bitmap input, string size, int increase){ Graphics::Bitmap output(input.getWidth() * increase, input.getWidth() * increase); for (int i = 1; i < 4; i++){ TimeDifference timer; int max = pow(10, i); timer.startTime(); for (int x = 0; x < max; x++){ input.StretchHqx(output); } timer.endTime(); Global::debug(0) << timer.printAverageTime(size, max) << std::endl; } } static void run(string path){ Graphics::Bitmap image(path); test(image, "2x", 2); test(image, "3x", 3); test(image, "4x", 4); } int main(int argc, char ** argv){ Screen::realInit(); atexit(Screen::realFinish); Global::setDebug(0); if (argc > 1){ run(argv[1]); } else { run("src/test/hqx/test.png"); } return 0; } <commit_msg>add xbr performance test. only do filters if the dimensions match exactly<commit_after>#include "../common/init.h" #include "util/debug.h" #include "util/bitmap.h" #include "util/timedifference.h" #include <stdlib.h> #include <math.h> #include <string> using std::string; static void testhqx(Graphics::Bitmap input, string size, int increase){ Graphics::Bitmap output(input.getWidth() * increase, input.getHeight() * increase); for (int i = 1; i < 4; i++){ TimeDifference timer; int max = pow(10, i); timer.startTime(); for (int x = 0; x < max; x++){ input.StretchHqx(output); } timer.endTime(); Global::debug(0) << timer.printAverageTime(size, max) << std::endl; } } static void testxbr(Graphics::Bitmap input, string size, int increase){ Graphics::Bitmap output(input.getWidth() * increase, input.getHeight() * increase); for (int i = 1; i < 4; i++){ TimeDifference timer; int max = pow(10, i); timer.startTime(); for (int x = 0; x < max; x++){ input.StretchXbr(output); } timer.endTime(); Global::debug(0) << timer.printAverageTime(size, max) << std::endl; } } static void run(string path){ Graphics::Bitmap image(path); testhqx(image, "hq2x", 2); testhqx(image, "hq3x", 3); testhqx(image, "hq4x", 4); testxbr(image, "2xbr", 2); testxbr(image, "3xbr", 3); testxbr(image, "4xbr", 4); } int main(int argc, char ** argv){ Screen::realInit(); atexit(Screen::realFinish); Global::setDebug(0); if (argc > 1){ run(argv[1]); } else { run("src/test/hqx/test.png"); } return 0; } <|endoftext|>
<commit_before>#include "rice/Array.hpp" #include "rice/Constructor.hpp" #include "rice/Object.hpp" #include "config.h" #include "generator.h" #include "question.h" #include "topic.h" using namespace ailab; template<> question_t from_ruby<question_t>(Rice::Object obj) { size_t qid = from_ruby<size_t>(obj.call("question_id")); size_t tid = from_ruby<size_t>(obj.call("topic_id")); size_t d = from_ruby<size_t>(obj.call("difficulty")); std::string t = from_ruby<std::string>(obj.call("text")); return question_t(qid, tid, d, t); } template<> Rice::Object to_ruby(question_t const &q) { return Rice::Data_Object<question_t>(new question_t(q)); } template<> std::vector<question_t> from_ruby<std::vector<question_t>>(Rice::Object obj) { Rice::Array arr(obj); std::vector<question_t> res; res.reserve(arr.size()); for (Rice::Object o : arr) res.push_back(from_ruby<question_t>(o)); return res; } template<> Rice::Object to_ruby(std::vector<question_t> const &questions) { Rice::Array arr; for (question_t const &q : questions) arr.push(to_ruby(q)); return arr; } template<> topic_t from_ruby<topic_t>(Rice::Object obj) { size_t id = from_ruby<size_t>(obj.call("topic_id")); size_t pid = from_ruby<size_t>(obj.call("parent_id")); std::string text = from_ruby<std::string>(obj.call("text")); return topic_t(id, pid, text); } template<> Rice::Object to_ruby<topic_t>(topic_t const &th) { return Rice::Data_Object<topic_t>(new topic_t(th)); } template<> std::vector<topic_t> from_ruby<std::vector<topic_t>>(Rice::Object obj) { Rice::Array arr(obj); std::vector<topic_t> topics; topics.reserve(arr.size()); for (Rice::Object obj : arr) topics.push_back(from_ruby<topic_t>(obj)); return topics; } void set_life_time(Rice::Object obj, size_t life_time) { Rice::Data_Object<config_t>(obj)->life_time = life_time; } size_t get_life_time(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->life_time; } void set_mutation_chance(Rice::Object obj, double mutation_chance) { Rice::Data_Object<config_t>(obj)->mutation_chance = mutation_chance; } double get_mutation_chance(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->mutation_chance; } void set_population_size(Rice::Object obj, size_t population_size) { Rice::Data_Object<config_t>(obj)->population_size = population_size; } size_t get_population_size(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->population_size; } void set_variants_count(Rice::Object obj, size_t variants_count) { Rice::Data_Object<config_t>(obj)->variants_count = variants_count; } size_t get_variants_count(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->variants_count; } void set_questions_count(Rice::Object obj, size_t questions_count) { Rice::Data_Object<config_t>(obj)->questions_count = questions_count; } size_t get_questions_count(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->questions_count; } void set_topics(Rice::Object obj, Rice::Array topics) { std::vector<size_t> th = from_ruby<std::vector<size_t>>(topics); Rice::Data_Object<config_t>(obj)->topics = std::move(th); } Rice::Array get_topics(Rice::Object obj) { std::vector<size_t> const &topics = Rice::Data_Object<config_t>(obj)->topics; Rice::Array arr; for (size_t t : topics) arr.push(to_ruby<size_t>(t)); return arr; } template<> config_t from_ruby<config_t>(Rice::Object obj) { config_t result; result.life_time = from_ruby<size_t>(obj.call("life_time")); result.mutation_chance = from_ruby<double>(obj.call("mutation_chance")); result.population_size = from_ruby<size_t>(obj.call("population_size")); result.variants_count = from_ruby<size_t>(obj.call("variants_count")); result.questions_count = from_ruby<size_t>(obj.call("questions_count")); result.topics = from_ruby<std::vector<size_t>>(obj.call("topics")); return result; } template<> Rice::Object to_ruby<config_t>(config_t const &cnf) { return Rice::Data_Object<config_t>(new config_t(cnf)); } template<> generator_t from_ruby<generator_t>(Rice::Object obj) { config_t config = from_ruby<config_t>(obj.call("config")); std::vector<topic_t> topics = from_ruby<std::vector<topic_t>>(obj.call("topics")); std::vector<question_t> questions = from_ruby<std::vector<question_t>>(obj.call("questions")); return generator_t(std::move(config), std::move(topics), std::move(questions)); } template<> Rice::Object to_ruby(generator_t const &t) { return Rice::Data_Object<generator_t>(new generator_t(t)); } template<> Rice::Object to_ruby<variants_t>(variants_t const &ans) { std::vector<std::vector<question_t>> const &questions = ans.get_questions(); Rice::Array result; for (std::vector<question_t> const &arr : questions) { Rice::Array buffer; for (question_t const &q : arr) buffer.push(to_ruby<question_t>(q)); result.push(buffer); } return result; } extern "C" void Init_tasks_generator() { Rice::Module rb_mTasksGenerator = Rice::define_module("TasksGenerator"); Rice::Data_Type<config_t> rb_cConfig = Rice::define_class_under<config_t>(rb_mTasksGenerator, "Config") .define_constructor(Rice::Constructor<config_t, size_t, size_t>(), (Rice::Arg("variants_count") = 8, Rice::Arg("questions_count") = 8)) .define_method("life_time=", &set_life_time) .define_method("mutation_chance=", &set_mutation_chance) .define_method("population_size=", &set_population_size) .define_method("variants_count=", &set_variants_count) .define_method("questions_count=", &set_questions_count) .define_method("life_time", &get_life_time) .define_method("mutation_chance", &get_mutation_chance) .define_method("population_size", &get_population_size) .define_method("variants_count", &get_variants_count) .define_method("questions_count", &get_questions_count) .define_method("topics", &get_topics) .define_method("topics=", &set_topics); Rice::Data_Type<topic_t> rb_ctopic = Rice::define_class_under<topic_t>(rb_mTasksGenerator, "Topic") .define_constructor(Rice::Constructor<topic_t, size_t, size_t, std::string>(), (Rice::Arg("id"), Rice::Arg("pid"), Rice::Arg("text"))) .define_method("topic_id", &topic_t::get_topic_id) .define_method("parent_id", &topic_t::get_parent_id) .define_method("text", &topic_t::get_text); Rice::Data_Type<question_t> rb_cQuestion = Rice::define_class_under<question_t>(rb_mTasksGenerator, "Question") .define_constructor(Rice::Constructor<question_t, size_t, size_t, size_t, std::string>(), (Rice::Arg("id"), Rice::Arg("tid"), Rice::Arg("difficulty"), Rice::Arg("text"))) .define_method("question_id", &question_t::get_question_id) .define_method("topic_id", &question_t::get_topic_id) .define_method("difficulty", &question_t::get_difficulty) .define_method("text", &question_t::get_text); Rice::Data_Type<generator_t> rb_cGenerator = Rice::define_class_under<generator_t>(rb_mTasksGenerator, "Generator") .define_constructor(Rice::Constructor<generator_t, config_t, std::vector<topic_t>, std::vector<question_t>>(), (Rice::Arg("cnf"), Rice::Arg("topics"), Rice::Arg("questions"))) .define_method("generate", &generator_t::generate); } <commit_msg>added ruby binding for vector<size_t><commit_after>#include "rice/Array.hpp" #include "rice/Constructor.hpp" #include "rice/Object.hpp" #include "config.h" #include "generator.h" #include "question.h" #include "topic.h" using namespace ailab; template<> question_t from_ruby<question_t>(Rice::Object obj) { size_t qid = from_ruby<size_t>(obj.call("question_id")); size_t tid = from_ruby<size_t>(obj.call("topic_id")); size_t d = from_ruby<size_t>(obj.call("difficulty")); std::string t = from_ruby<std::string>(obj.call("text")); return question_t(qid, tid, d, t); } template<> Rice::Object to_ruby(question_t const &q) { return Rice::Data_Object<question_t>(new question_t(q)); } template<> std::vector<question_t> from_ruby<std::vector<question_t>>(Rice::Object obj) { Rice::Array arr(obj); std::vector<question_t> res; res.reserve(arr.size()); for (Rice::Object o : arr) res.push_back(from_ruby<question_t>(o)); return res; } template<> Rice::Object to_ruby(std::vector<question_t> const &questions) { Rice::Array arr; for (question_t const &q : questions) arr.push(to_ruby(q)); return arr; } template<> topic_t from_ruby<topic_t>(Rice::Object obj) { size_t id = from_ruby<size_t>(obj.call("topic_id")); size_t pid = from_ruby<size_t>(obj.call("parent_id")); std::string text = from_ruby<std::string>(obj.call("text")); return topic_t(id, pid, text); } template<> Rice::Object to_ruby<topic_t>(topic_t const &th) { return Rice::Data_Object<topic_t>(new topic_t(th)); } template<> std::vector<topic_t> from_ruby<std::vector<topic_t>>(Rice::Object obj) { Rice::Array arr(obj); std::vector<topic_t> topics; topics.reserve(arr.size()); for (Rice::Object obj : arr) topics.push_back(from_ruby<topic_t>(obj)); return topics; } template<> Rice::Object to_ruby<std::vector<size_t>>(std::vector<size_t> const &v) { return Rice::Data_Object<std::vector<size_t>>(new std::vector<size_t>(v)); } template<> std::vector<size_t> from_ruby<std::vector<size_t>>(Rice::Object obj) { Rice::Array arr(obj); std::vector<size_t> result; result.reserve(arr.size()); for (Rice::Object obj : arr) result.push_back(from_ruby<size_t>(obj)); return result; } void set_life_time(Rice::Object obj, size_t life_time) { Rice::Data_Object<config_t>(obj)->life_time = life_time; } size_t get_life_time(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->life_time; } void set_mutation_chance(Rice::Object obj, double mutation_chance) { Rice::Data_Object<config_t>(obj)->mutation_chance = mutation_chance; } double get_mutation_chance(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->mutation_chance; } void set_population_size(Rice::Object obj, size_t population_size) { Rice::Data_Object<config_t>(obj)->population_size = population_size; } size_t get_population_size(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->population_size; } void set_variants_count(Rice::Object obj, size_t variants_count) { Rice::Data_Object<config_t>(obj)->variants_count = variants_count; } size_t get_variants_count(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->variants_count; } void set_questions_count(Rice::Object obj, size_t questions_count) { Rice::Data_Object<config_t>(obj)->questions_count = questions_count; } size_t get_questions_count(Rice::Object obj) { return Rice::Data_Object<config_t>(obj)->questions_count; } void set_topics(Rice::Object obj, Rice::Array topics) { std::vector<size_t> th = from_ruby<std::vector<size_t>>(topics); Rice::Data_Object<config_t>(obj)->topics = std::move(th); } Rice::Array get_topics(Rice::Object obj) { std::vector<size_t> const &topics = Rice::Data_Object<config_t>(obj)->topics; Rice::Array arr; for (size_t t : topics) arr.push(to_ruby<size_t>(t)); return arr; } template<> config_t from_ruby<config_t>(Rice::Object obj) { config_t result; result.life_time = from_ruby<size_t>(obj.call("life_time")); result.mutation_chance = from_ruby<double>(obj.call("mutation_chance")); result.population_size = from_ruby<size_t>(obj.call("population_size")); result.variants_count = from_ruby<size_t>(obj.call("variants_count")); result.questions_count = from_ruby<size_t>(obj.call("questions_count")); result.topics = from_ruby<std::vector<size_t>>(obj.call("topics")); return result; } template<> Rice::Object to_ruby<config_t>(config_t const &cnf) { return Rice::Data_Object<config_t>(new config_t(cnf)); } template<> generator_t from_ruby<generator_t>(Rice::Object obj) { config_t config = from_ruby<config_t>(obj.call("config")); std::vector<topic_t> topics = from_ruby<std::vector<topic_t>>(obj.call("topics")); std::vector<question_t> questions = from_ruby<std::vector<question_t>>(obj.call("questions")); return generator_t(std::move(config), std::move(topics), std::move(questions)); } template<> Rice::Object to_ruby(generator_t const &t) { return Rice::Data_Object<generator_t>(new generator_t(t)); } template<> Rice::Object to_ruby<variants_t>(variants_t const &ans) { std::vector<std::vector<question_t>> const &questions = ans.get_questions(); Rice::Array result; for (std::vector<question_t> const &arr : questions) { Rice::Array buffer; for (question_t const &q : arr) buffer.push(to_ruby<question_t>(q)); result.push(buffer); } return result; } extern "C" void Init_tasks_generator() { Rice::Module rb_mTasksGenerator = Rice::define_module("TasksGenerator"); Rice::Data_Type<config_t> rb_cConfig = Rice::define_class_under<config_t>(rb_mTasksGenerator, "Config") .define_constructor(Rice::Constructor<config_t, size_t, size_t>(), (Rice::Arg("variants_count") = 8, Rice::Arg("questions_count") = 8)) .define_method("life_time=", &set_life_time) .define_method("mutation_chance=", &set_mutation_chance) .define_method("population_size=", &set_population_size) .define_method("variants_count=", &set_variants_count) .define_method("questions_count=", &set_questions_count) .define_method("life_time", &get_life_time) .define_method("mutation_chance", &get_mutation_chance) .define_method("population_size", &get_population_size) .define_method("variants_count", &get_variants_count) .define_method("questions_count", &get_questions_count) .define_method("topics", &get_topics) .define_method("topics=", &set_topics); Rice::Data_Type<topic_t> rb_ctopic = Rice::define_class_under<topic_t>(rb_mTasksGenerator, "Topic") .define_constructor(Rice::Constructor<topic_t, size_t, size_t, std::string>(), (Rice::Arg("id"), Rice::Arg("pid"), Rice::Arg("text"))) .define_method("topic_id", &topic_t::get_topic_id) .define_method("parent_id", &topic_t::get_parent_id) .define_method("text", &topic_t::get_text); Rice::Data_Type<question_t> rb_cQuestion = Rice::define_class_under<question_t>(rb_mTasksGenerator, "Question") .define_constructor(Rice::Constructor<question_t, size_t, size_t, size_t, std::string>(), (Rice::Arg("id"), Rice::Arg("tid"), Rice::Arg("difficulty"), Rice::Arg("text"))) .define_method("question_id", &question_t::get_question_id) .define_method("topic_id", &question_t::get_topic_id) .define_method("difficulty", &question_t::get_difficulty) .define_method("text", &question_t::get_text); Rice::Data_Type<generator_t> rb_cGenerator = Rice::define_class_under<generator_t>(rb_mTasksGenerator, "Generator") .define_constructor(Rice::Constructor<generator_t, config_t, std::vector<topic_t>, std::vector<question_t>>(), (Rice::Arg("cnf"), Rice::Arg("topics"), Rice::Arg("questions"))) .define_method("generate", &generator_t::generate); } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <vector> #include "prevector.h" #include "random.h" #include "serialize.h" #include "streams.h" #include "test/test_dash.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup) template<unsigned int N, typename T> class prevector_tester { typedef std::vector<T> realtype; realtype real_vector; realtype real_vector_alt; typedef prevector<N, T> pretype; pretype pre_vector; pretype pre_vector_alt; typedef typename pretype::size_type Size; void test() { const pretype& const_pre_vector = pre_vector; BOOST_CHECK_EQUAL(real_vector.size(), pre_vector.size()); BOOST_CHECK_EQUAL(real_vector.empty(), pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { BOOST_CHECK(real_vector[s] == pre_vector[s]); BOOST_CHECK(&(pre_vector[s]) == &(pre_vector.begin()[s])); BOOST_CHECK(&(pre_vector[s]) == &*(pre_vector.begin() + s)); BOOST_CHECK(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // BOOST_CHECK(realtype(pre_vector) == real_vector); BOOST_CHECK(pretype(real_vector.begin(), real_vector.end()) == pre_vector); BOOST_CHECK(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; BOOST_FOREACH(const T& v, pre_vector) { BOOST_CHECK(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, pre_vector) { BOOST_CHECK(v == real_vector[--pos]); } BOOST_FOREACH(const T& v, const_pre_vector) { BOOST_CHECK(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) { BOOST_CHECK(v == real_vector[--pos]); } CDataStream ss1(SER_DISK, 0); CDataStream ss2(SER_DISK, 0); ss1 << real_vector; ss2 << pre_vector; BOOST_CHECK_EQUAL(ss1.size(), ss2.size()); for (Size s = 0; s < ss1.size(); s++) { BOOST_CHECK_EQUAL(ss1[s], ss2[s]); } } public: void resize(Size s) { real_vector.resize(s); BOOST_CHECK_EQUAL(real_vector.size(), s); pre_vector.resize(s); BOOST_CHECK_EQUAL(pre_vector.size(), s); test(); } void reserve(Size s) { real_vector.reserve(s); BOOST_CHECK(real_vector.capacity() >= s); pre_vector.reserve(s); BOOST_CHECK(pre_vector.capacity() >= s); test(); } void insert(Size position, const T& value) { real_vector.insert(real_vector.begin() + position, value); pre_vector.insert(pre_vector.begin() + position, value); test(); } void insert(Size position, Size count, const T& value) { real_vector.insert(real_vector.begin() + position, count, value); pre_vector.insert(pre_vector.begin() + position, count, value); test(); } template<typename I> void insert_range(Size position, I first, I last) { real_vector.insert(real_vector.begin() + position, first, last); pre_vector.insert(pre_vector.begin() + position, first, last); test(); } void erase(Size position) { real_vector.erase(real_vector.begin() + position); pre_vector.erase(pre_vector.begin() + position); test(); } void erase(Size first, Size last) { real_vector.erase(real_vector.begin() + first, real_vector.begin() + last); pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last); test(); } void update(Size pos, const T& value) { real_vector[pos] = value; pre_vector[pos] = value; test(); } void push_back(const T& value) { real_vector.push_back(value); pre_vector.push_back(value); test(); } void pop_back() { real_vector.pop_back(); pre_vector.pop_back(); test(); } void clear() { real_vector.clear(); pre_vector.clear(); } void assign(Size n, const T& value) { real_vector.assign(n, value); pre_vector.assign(n, value); } Size size() { return real_vector.size(); } Size capacity() { return pre_vector.capacity(); } void shrink_to_fit() { pre_vector.shrink_to_fit(); test(); } void swap() { real_vector.swap(real_vector_alt); pre_vector.swap(pre_vector_alt); test(); } }; BOOST_AUTO_TEST_CASE(PrevectorTestInt) { for (int j = 0; j < 64; j++) { prevector_tester<8, int> test; for (int i = 0; i < 2048; i++) { int r = insecure_rand(); if ((r % 4) == 0) { test.insert(insecure_rand() % (test.size() + 1), insecure_rand()); } if (test.size() > 0 && ((r >> 2) % 4) == 1) { test.erase(insecure_rand() % test.size()); } if (((r >> 4) % 8) == 2) { int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2)); test.resize(new_size); } if (((r >> 7) % 8) == 3) { test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand()); } if (((r >> 10) % 8) == 4) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } if (((r >> 13) % 16) == 5) { test.push_back(insecure_rand()); } if (test.size() > 0 && ((r >> 17) % 16) == 6) { test.pop_back(); } if (((r >> 21) % 32) == 7) { int values[4]; int num = 1 + (insecure_rand() % 4); for (int i = 0; i < num; i++) { values[i] = insecure_rand(); } test.insert_range(insecure_rand() % (test.size() + 1), values, values + num); } if (((r >> 26) % 32) == 8) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } r = insecure_rand(); if (r % 32 == 9) { test.reserve(insecure_rand() % 32); } if ((r >> 5) % 64 == 10) { test.shrink_to_fit(); } if (test.size() > 0) { test.update(insecure_rand() % test.size(), insecure_rand()); } if (((r >> 11) % 1024) == 11) { test.clear(); } if (((r >> 21) % 512) == 12) { test.assign(insecure_rand() % 32, insecure_rand()); } if (((r >> 15) % 64) == 3) { test.swap(); } } } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Minimal fix to slow prevector tests as stopgap measure<commit_after>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <vector> #include "prevector.h" #include "random.h" #include "serialize.h" #include "streams.h" #include "test/test_dash.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup) template<unsigned int N, typename T> class prevector_tester { typedef std::vector<T> realtype; realtype real_vector; realtype real_vector_alt; typedef prevector<N, T> pretype; pretype pre_vector; pretype pre_vector_alt; typedef typename pretype::size_type Size; bool passed = true; uint32_t insecure_rand_Rz_cache; uint32_t insecure_rand_Rw_cache; template <typename A, typename B> void local_check_equal(A a, B b) { local_check(a == b); } void local_check(bool b) { passed &= b; } void test() { const pretype& const_pre_vector = pre_vector; local_check_equal(real_vector.size(), pre_vector.size()); local_check_equal(real_vector.empty(), pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { local_check(real_vector[s] == pre_vector[s]); local_check(&(pre_vector[s]) == &(pre_vector.begin()[s])); local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s)); local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // local_check(realtype(pre_vector) == real_vector); local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector); local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; BOOST_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[--pos]); } BOOST_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[--pos]); } CDataStream ss1(SER_DISK, 0); CDataStream ss2(SER_DISK, 0); ss1 << real_vector; ss2 << pre_vector; local_check_equal(ss1.size(), ss2.size()); for (Size s = 0; s < ss1.size(); s++) { local_check_equal(ss1[s], ss2[s]); } } public: void resize(Size s) { real_vector.resize(s); local_check_equal(real_vector.size(), s); pre_vector.resize(s); local_check_equal(pre_vector.size(), s); test(); } void reserve(Size s) { real_vector.reserve(s); local_check(real_vector.capacity() >= s); pre_vector.reserve(s); local_check(pre_vector.capacity() >= s); test(); } void insert(Size position, const T& value) { real_vector.insert(real_vector.begin() + position, value); pre_vector.insert(pre_vector.begin() + position, value); test(); } void insert(Size position, Size count, const T& value) { real_vector.insert(real_vector.begin() + position, count, value); pre_vector.insert(pre_vector.begin() + position, count, value); test(); } template<typename I> void insert_range(Size position, I first, I last) { real_vector.insert(real_vector.begin() + position, first, last); pre_vector.insert(pre_vector.begin() + position, first, last); test(); } void erase(Size position) { real_vector.erase(real_vector.begin() + position); pre_vector.erase(pre_vector.begin() + position); test(); } void erase(Size first, Size last) { real_vector.erase(real_vector.begin() + first, real_vector.begin() + last); pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last); test(); } void update(Size pos, const T& value) { real_vector[pos] = value; pre_vector[pos] = value; test(); } void push_back(const T& value) { real_vector.push_back(value); pre_vector.push_back(value); test(); } void pop_back() { real_vector.pop_back(); pre_vector.pop_back(); test(); } void clear() { real_vector.clear(); pre_vector.clear(); } void assign(Size n, const T& value) { real_vector.assign(n, value); pre_vector.assign(n, value); } Size size() { return real_vector.size(); } Size capacity() { return pre_vector.capacity(); } void shrink_to_fit() { pre_vector.shrink_to_fit(); test(); } void swap() { real_vector.swap(real_vector_alt); pre_vector.swap(pre_vector_alt); test(); } ~prevector_tester() { BOOST_CHECK_MESSAGE(passed, "insecure_rand_Rz: " << insecure_rand_Rz_cache << ", insecure_rand_Rw: " << insecure_rand_Rw_cache); } prevector_tester() { seed_insecure_rand(); insecure_rand_Rz_cache = insecure_rand_Rz; insecure_rand_Rw_cache = insecure_rand_Rw; } }; BOOST_AUTO_TEST_CASE(PrevectorTestInt) { for (int j = 0; j < 64; j++) { prevector_tester<8, int> test; for (int i = 0; i < 2048; i++) { int r = insecure_rand(); if ((r % 4) == 0) { test.insert(insecure_rand() % (test.size() + 1), insecure_rand()); } if (test.size() > 0 && ((r >> 2) % 4) == 1) { test.erase(insecure_rand() % test.size()); } if (((r >> 4) % 8) == 2) { int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2)); test.resize(new_size); } if (((r >> 7) % 8) == 3) { test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand()); } if (((r >> 10) % 8) == 4) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } if (((r >> 13) % 16) == 5) { test.push_back(insecure_rand()); } if (test.size() > 0 && ((r >> 17) % 16) == 6) { test.pop_back(); } if (((r >> 21) % 32) == 7) { int values[4]; int num = 1 + (insecure_rand() % 4); for (int i = 0; i < num; i++) { values[i] = insecure_rand(); } test.insert_range(insecure_rand() % (test.size() + 1), values, values + num); } if (((r >> 26) % 32) == 8) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } r = insecure_rand(); if (r % 32 == 9) { test.reserve(insecure_rand() % 32); } if ((r >> 5) % 64 == 10) { test.shrink_to_fit(); } if (test.size() > 0) { test.update(insecure_rand() % test.size(), insecure_rand()); } if (((r >> 11) % 1024) == 11) { test.clear(); } if (((r >> 21) % 512) == 12) { test.assign(insecure_rand() % 32, insecure_rand()); } if (((r >> 15) % 64) == 3) { test.swap(); } } } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #define MATH_BULLET_INTEROP #include "DebugOperatorNew.h" #include "btBulletDynamicsCommon.h" #include "PhysicsModule.h" #include "PhysicsWorld.h" #include "PhysicsUtils.h" #include "Profiler.h" #include "Scene.h" #include "OgreWorld.h" #include "EC_RigidBody.h" #include "LoggingFunctions.h" #include "Geometry/LineSegment.h" #include <Ogre.h> #include "MemoryLeakCheck.h" namespace Physics { void TickCallback(btDynamicsWorld *world, btScalar timeStep) { static_cast<Physics::PhysicsWorld*>(world->getWorldUserInfo())->ProcessPostTick(timeStep); } PhysicsWorld::PhysicsWorld(ScenePtr scene, bool isClient) : scene_(scene), collisionConfiguration_(0), collisionDispatcher_(0), broadphase_(0), solver_(0), world_(0), physicsUpdatePeriod_(1.0f / 60.0f), maxSubSteps_(6), // If fps is below 10, we start to slow down physics isClient_(isClient), runPhysics_(true), drawDebugGeometry_(false), drawDebugManuallySet_(false), debugDrawMode_(0), cachedOgreWorld_(0) { collisionConfiguration_ = new btDefaultCollisionConfiguration(); collisionDispatcher_ = new btCollisionDispatcher(collisionConfiguration_); broadphase_ = new btDbvtBroadphase(); solver_ = new btSequentialImpulseConstraintSolver(); world_ = new btDiscreteDynamicsWorld(collisionDispatcher_, broadphase_, solver_, collisionConfiguration_); world_->setDebugDrawer(this); world_->setInternalTickCallback(TickCallback, (void*)this, false); } PhysicsWorld::~PhysicsWorld() { SAFE_DELETE(world_); SAFE_DELETE(solver_); SAFE_DELETE(broadphase_); SAFE_DELETE(collisionDispatcher_); SAFE_DELETE(collisionConfiguration_); } void PhysicsWorld::SetPhysicsUpdatePeriod(float updatePeriod) { // Allow max.1000 fps if (updatePeriod <= 0.001f) updatePeriod = 0.001f; physicsUpdatePeriod_ = updatePeriod; } void PhysicsWorld::SetMaxSubSteps(int steps) { if (steps > 0) maxSubSteps_ = steps; } void PhysicsWorld::SetGravity(const float3& gravity) { world_->setGravity(gravity); } float3 PhysicsWorld::Gravity() const { return world_->getGravity(); } btDiscreteDynamicsWorld* PhysicsWorld::BulletWorld() const { return world_; } void PhysicsWorld::Simulate(f64 frametime) { if (!runPhysics_) return; PROFILE(PhysicsWorld_Simulate); emit AboutToUpdate((float)frametime); { PROFILE(Bullet_stepSimulation); ///\note Do not delete or rename this PROFILE() block. The DebugStats profiler uses this string as a label to know where to inject the Bullet internal profiling data. world_->stepSimulation((float)frametime, maxSubSteps_, physicsUpdatePeriod_); } // Automatically enable debug geometry if at least one debug-enabled rigidbody. Automatically disable if no debug-enabled rigidbodies // However, do not do this if user has used the physicsdebug console command if (!drawDebugManuallySet_) { if ((!drawDebugGeometry_) && (!debugRigidBodies_.empty())) SetDebugGeometryEnabled(true); if ((drawDebugGeometry_) && (debugRigidBodies_.empty())) SetDebugGeometryEnabled(false); } if (drawDebugGeometry_) DrawDebugGeometry(); } void PhysicsWorld::ProcessPostTick(float substeptime) { PROFILE(PhysicsWorld_ProcessPostTick); // Check contacts and send collision signals for them int numManifolds = collisionDispatcher_->getNumManifolds(); std::set<std::pair<btCollisionObject*, btCollisionObject*> > currentCollisions; if (numManifolds > 0) { PROFILE(PhysicsWorld_SendCollisions); for(int i = 0; i < numManifolds; ++i) { btPersistentManifold* contactManifold = collisionDispatcher_->getManifoldByIndexInternal(i); int numContacts = contactManifold->getNumContacts(); if (numContacts == 0) continue; btCollisionObject* objectA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* objectB = static_cast<btCollisionObject*>(contactManifold->getBody1()); std::pair<btCollisionObject*, btCollisionObject*> objectPair; if (objectA < objectB) objectPair = std::make_pair(objectA, objectB); else objectPair = std::make_pair(objectB, objectA); EC_RigidBody* bodyA = static_cast<EC_RigidBody*>(objectA->getUserPointer()); EC_RigidBody* bodyB = static_cast<EC_RigidBody*>(objectB->getUserPointer()); // We are only interested in collisions where both EC_RigidBody components are known if (!bodyA || !bodyB) { LogError("Inconsistent Bullet physics scene state! An object exists in the physics scene which does not have an associated EC_RigidBody!"); continue; } // Also, both bodies should have valid parent entities Entity* entityA = bodyA->ParentEntity(); Entity* entityB = bodyB->ParentEntity(); if (!entityA || !entityB) { LogError("Inconsistent Bullet physics scene state! A parentless EC_RigidBody exists in the physics scene!"); continue; } // Check that at least one of the bodies is active if (!objectA->isActive() && !objectB->isActive()) continue; bool newCollision = previousCollisions_.find(objectPair) == previousCollisions_.end(); for(int j = 0; j < numContacts; ++j) { btManifoldPoint& point = contactManifold->getContactPoint(j); float3 position = point.m_positionWorldOnB; float3 normal = point.m_normalWorldOnB; float distance = point.m_distance1; float impulse = point.m_appliedImpulse; { PROFILE(PhysicsWorld_emit_PhysicsCollision); emit PhysicsCollision(entityA, entityB, position, normal, distance, impulse, newCollision); } bodyA->EmitPhysicsCollision(entityB, position, normal, distance, impulse, newCollision); bodyB->EmitPhysicsCollision(entityA, position, normal, distance, impulse, newCollision); // Report newCollision = true only for the first contact, in case there are several contacts, and application does some logic depending on it // (for example play a sound -> avoid multiple sounds being played) newCollision = false; } currentCollisions.insert(objectPair); } } previousCollisions_ = currentCollisions; { PROFILE(PhysicsWorld_ProcessPostTick_Updated); emit Updated(substeptime); } } PhysicsRaycastResult* PhysicsWorld::Raycast(const float3& origin, const float3& direction, float maxdistance, int collisiongroup, int collisionmask) { PROFILE(PhysicsWorld_Raycast); static PhysicsRaycastResult result; float3 normalizedDir = direction.Normalized(); btCollisionWorld::ClosestRayResultCallback rayCallback(origin, origin + maxdistance * normalizedDir); rayCallback.m_collisionFilterGroup = collisiongroup; rayCallback.m_collisionFilterMask = collisionmask; world_->rayTest(rayCallback.m_rayFromWorld, rayCallback.m_rayToWorld, rayCallback); result.entity = 0; result.distance = 0; if (rayCallback.hasHit()) { result.pos = rayCallback.m_hitPointWorld; result.normal = rayCallback.m_hitNormalWorld; result.distance = (result.pos - origin).Length(); if (rayCallback.m_collisionObject) { EC_RigidBody* body = static_cast<EC_RigidBody*>(rayCallback.m_collisionObject->getUserPointer()); if (body) result.entity = body->ParentEntity(); } } return &result; } void PhysicsWorld::SetDebugGeometryEnabled(bool enable) { if (scene_.expired() || !scene_.lock()->ViewEnabled() || drawDebugGeometry_ == enable) return; drawDebugGeometry_ = enable; if (!enable) setDebugMode(0); else setDebugMode(btIDebugDraw::DBG_DrawWireframe); } void PhysicsWorld::DrawDebugGeometry() { if (!drawDebugGeometry_) return; PROFILE(PhysicsModule_DrawDebugGeometry); // Draw debug only for the active (visible) scene OgreWorldPtr ogreWorld = scene_.lock()->GetWorld<OgreWorld>(); cachedOgreWorld_ = ogreWorld.get(); if (!ogreWorld) return; if (!ogreWorld->IsActive()) return; // Get all lines of the physics world world_->debugDrawWorld(); } void PhysicsWorld::reportErrorWarning(const char* warningString) { LogWarning("Physics: " + std::string(warningString)); } void PhysicsWorld::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) { if (drawDebugGeometry_ && cachedOgreWorld_) cachedOgreWorld_->DebugDrawLine(from, to, color.x(), color.y(), color.z()); } } // ~Physics <commit_msg>Fixed crash in PhysicsWorld collision signal emit functions that occurred if scripts changed physics world state in a collision signal handler.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #define MATH_BULLET_INTEROP #include "DebugOperatorNew.h" #include "btBulletDynamicsCommon.h" #include "PhysicsModule.h" #include "PhysicsWorld.h" #include "PhysicsUtils.h" #include "Profiler.h" #include "Scene.h" #include "OgreWorld.h" #include "EC_RigidBody.h" #include "LoggingFunctions.h" #include "Geometry/LineSegment.h" #include <Ogre.h> #include "MemoryLeakCheck.h" namespace Physics { void TickCallback(btDynamicsWorld *world, btScalar timeStep) { static_cast<Physics::PhysicsWorld*>(world->getWorldUserInfo())->ProcessPostTick(timeStep); } PhysicsWorld::PhysicsWorld(ScenePtr scene, bool isClient) : scene_(scene), collisionConfiguration_(0), collisionDispatcher_(0), broadphase_(0), solver_(0), world_(0), physicsUpdatePeriod_(1.0f / 60.0f), maxSubSteps_(6), // If fps is below 10, we start to slow down physics isClient_(isClient), runPhysics_(true), drawDebugGeometry_(false), drawDebugManuallySet_(false), debugDrawMode_(0), cachedOgreWorld_(0) { collisionConfiguration_ = new btDefaultCollisionConfiguration(); collisionDispatcher_ = new btCollisionDispatcher(collisionConfiguration_); broadphase_ = new btDbvtBroadphase(); solver_ = new btSequentialImpulseConstraintSolver(); world_ = new btDiscreteDynamicsWorld(collisionDispatcher_, broadphase_, solver_, collisionConfiguration_); world_->setDebugDrawer(this); world_->setInternalTickCallback(TickCallback, (void*)this, false); } PhysicsWorld::~PhysicsWorld() { SAFE_DELETE(world_); SAFE_DELETE(solver_); SAFE_DELETE(broadphase_); SAFE_DELETE(collisionDispatcher_); SAFE_DELETE(collisionConfiguration_); } void PhysicsWorld::SetPhysicsUpdatePeriod(float updatePeriod) { // Allow max.1000 fps if (updatePeriod <= 0.001f) updatePeriod = 0.001f; physicsUpdatePeriod_ = updatePeriod; } void PhysicsWorld::SetMaxSubSteps(int steps) { if (steps > 0) maxSubSteps_ = steps; } void PhysicsWorld::SetGravity(const float3& gravity) { world_->setGravity(gravity); } float3 PhysicsWorld::Gravity() const { return world_->getGravity(); } btDiscreteDynamicsWorld* PhysicsWorld::BulletWorld() const { return world_; } void PhysicsWorld::Simulate(f64 frametime) { if (!runPhysics_) return; PROFILE(PhysicsWorld_Simulate); emit AboutToUpdate((float)frametime); { PROFILE(Bullet_stepSimulation); ///\note Do not delete or rename this PROFILE() block. The DebugStats profiler uses this string as a label to know where to inject the Bullet internal profiling data. world_->stepSimulation((float)frametime, maxSubSteps_, physicsUpdatePeriod_); } // Automatically enable debug geometry if at least one debug-enabled rigidbody. Automatically disable if no debug-enabled rigidbodies // However, do not do this if user has used the physicsdebug console command if (!drawDebugManuallySet_) { if ((!drawDebugGeometry_) && (!debugRigidBodies_.empty())) SetDebugGeometryEnabled(true); if ((drawDebugGeometry_) && (debugRigidBodies_.empty())) SetDebugGeometryEnabled(false); } if (drawDebugGeometry_) DrawDebugGeometry(); } void PhysicsWorld::ProcessPostTick(float substeptime) { PROFILE(PhysicsWorld_ProcessPostTick); // Check contacts and send collision signals for them int numManifolds = collisionDispatcher_->getNumManifolds(); std::set<std::pair<btCollisionObject*, btCollisionObject*> > currentCollisions; // Collect all collision signals to a list before emitting any of them, in case a collision // handler changes physics state before the loop below is over (which would lead into catastrophic // consequences) struct CollisionSignal { EC_RigidBody *bodyA; EC_RigidBody *bodyB; float3 position; float3 normal; float distance; float impulse; bool newCollision; }; std::vector<CollisionSignal> collisions; collisions.reserve(numManifolds * 3); // Guess some initial memory size for the collision list. if (numManifolds > 0) { PROFILE(PhysicsWorld_SendCollisions); for(int i = 0; i < numManifolds; ++i) { btPersistentManifold* contactManifold = collisionDispatcher_->getManifoldByIndexInternal(i); int numContacts = contactManifold->getNumContacts(); if (numContacts == 0) continue; btCollisionObject* objectA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* objectB = static_cast<btCollisionObject*>(contactManifold->getBody1()); std::pair<btCollisionObject*, btCollisionObject*> objectPair; if (objectA < objectB) objectPair = std::make_pair(objectA, objectB); else objectPair = std::make_pair(objectB, objectA); EC_RigidBody* bodyA = static_cast<EC_RigidBody*>(objectA->getUserPointer()); EC_RigidBody* bodyB = static_cast<EC_RigidBody*>(objectB->getUserPointer()); // We are only interested in collisions where both EC_RigidBody components are known if (!bodyA || !bodyB) { LogError("Inconsistent Bullet physics scene state! An object exists in the physics scene which does not have an associated EC_RigidBody!"); continue; } // Also, both bodies should have valid parent entities Entity* entityA = bodyA->ParentEntity(); Entity* entityB = bodyB->ParentEntity(); if (!entityA || !entityB) { LogError("Inconsistent Bullet physics scene state! A parentless EC_RigidBody exists in the physics scene!"); continue; } // Check that at least one of the bodies is active if (!objectA->isActive() && !objectB->isActive()) continue; bool newCollision = previousCollisions_.find(objectPair) == previousCollisions_.end(); for(int j = 0; j < numContacts; ++j) { btManifoldPoint& point = contactManifold->getContactPoint(j); CollisionSignal s; s.bodyA = bodyA; s.bodyB = bodyB; s.position = point.m_positionWorldOnB; s.normal = point.m_normalWorldOnB; s.distance = point.m_distance1; s.impulse = point.m_appliedImpulse; s.newCollision = newCollision; collisions.push_back(s); // Report newCollision = true only for the first contact, in case there are several contacts, and application does some logic depending on it // (for example play a sound -> avoid multiple sounds being played) newCollision = false; } currentCollisions.insert(objectPair); } } // Now fire all collision signals. { PROFILE(PhysicsWorld_emit_PhysicsCollisions); for(size_t i = 0; i < collisions.size(); ++i) { emit PhysicsCollision(collisions[i].bodyA->ParentEntity(), collisions[i].bodyB->ParentEntity(), collisions[i].position, collisions[i].normal, collisions[i].distance, collisions[i].impulse, collisions[i].newCollision); collisions[i].bodyA->EmitPhysicsCollision(collisions[i].bodyB->ParentEntity(), collisions[i].position, collisions[i].normal, collisions[i].distance, collisions[i].impulse, collisions[i].newCollision); collisions[i].bodyB->EmitPhysicsCollision(collisions[i].bodyA->ParentEntity(), collisions[i].position, collisions[i].normal, collisions[i].distance, collisions[i].impulse, collisions[i].newCollision); } } previousCollisions_ = currentCollisions; { PROFILE(PhysicsWorld_ProcessPostTick_Updated); emit Updated(substeptime); } } PhysicsRaycastResult* PhysicsWorld::Raycast(const float3& origin, const float3& direction, float maxdistance, int collisiongroup, int collisionmask) { PROFILE(PhysicsWorld_Raycast); static PhysicsRaycastResult result; float3 normalizedDir = direction.Normalized(); btCollisionWorld::ClosestRayResultCallback rayCallback(origin, origin + maxdistance * normalizedDir); rayCallback.m_collisionFilterGroup = collisiongroup; rayCallback.m_collisionFilterMask = collisionmask; world_->rayTest(rayCallback.m_rayFromWorld, rayCallback.m_rayToWorld, rayCallback); result.entity = 0; result.distance = 0; if (rayCallback.hasHit()) { result.pos = rayCallback.m_hitPointWorld; result.normal = rayCallback.m_hitNormalWorld; result.distance = (result.pos - origin).Length(); if (rayCallback.m_collisionObject) { EC_RigidBody* body = static_cast<EC_RigidBody*>(rayCallback.m_collisionObject->getUserPointer()); if (body) result.entity = body->ParentEntity(); } } return &result; } void PhysicsWorld::SetDebugGeometryEnabled(bool enable) { if (scene_.expired() || !scene_.lock()->ViewEnabled() || drawDebugGeometry_ == enable) return; drawDebugGeometry_ = enable; if (!enable) setDebugMode(0); else setDebugMode(btIDebugDraw::DBG_DrawWireframe); } void PhysicsWorld::DrawDebugGeometry() { if (!drawDebugGeometry_) return; PROFILE(PhysicsModule_DrawDebugGeometry); // Draw debug only for the active (visible) scene OgreWorldPtr ogreWorld = scene_.lock()->GetWorld<OgreWorld>(); cachedOgreWorld_ = ogreWorld.get(); if (!ogreWorld) return; if (!ogreWorld->IsActive()) return; // Get all lines of the physics world world_->debugDrawWorld(); } void PhysicsWorld::reportErrorWarning(const char* warningString) { LogWarning("Physics: " + std::string(warningString)); } void PhysicsWorld::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) { if (drawDebugGeometry_ && cachedOgreWorld_) cachedOgreWorld_->DebugDrawLine(from, to, color.x(), color.y(), color.z()); } } // ~Physics <|endoftext|>
<commit_before>// Copyright (c) 2012-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <random.h> #include <scheduler.h> #include <test/test_chaincoin.h> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(scheduler_tests) static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime) { { boost::unique_lock<boost::mutex> lock(mutex); counter += delta; } boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min(); if (rescheduleTime != noTime) { CScheduler::Function f = boost::bind(&microTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime); s.schedule(f, rescheduleTime); } } static void MicroSleep(uint64_t n) { #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::microseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::microseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } BOOST_AUTO_TEST_CASE(manythreads) { // Stress test: hundreds of microsecond-scheduled tasks, // serviced by 10 threads. // // So... ten shared counters, which if all the tasks execute // properly will sum to the number of tasks done. // Each task adds or subtracts a random amount from one of the // counters, and then schedules another task 0-1000 // microseconds in the future to subtract or add from // the counter -random_amount+1, so in the end the shared // counters should sum to the number of initial tasks performed. CScheduler microTasks; boost::mutex counterMutex[10]; int counter[10] = { 0 }; FastRandomContext rng(42); auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; // [0, 9] auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + (int)rc.randrange(1012); }; // [-11, 1000] auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + (int)rc.randrange(2001); }; // [-1000, 1000] boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); boost::chrono::system_clock::time_point now = start; boost::chrono::system_clock::time_point first, last; size_t nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 0); for (int i = 0; i < 100; ++i) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 100); BOOST_CHECK(first < last); BOOST_CHECK(last > now); // As soon as these are created they will start running and servicing the queue boost::thread_group microThreads; for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); MicroSleep(600); now = boost::chrono::system_clock::now(); // More threads and more tasks: for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); for (int i = 0; i < 100; i++) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } // Drain the task queue then exit threads microTasks.stop(true); microThreads.join_all(); // ... wait until all the threads are done int counterSum = 0; for (int i = 0; i < 10; i++) { BOOST_CHECK(counter[i] != 0); counterSum += counter[i]; } BOOST_CHECK_EQUAL(counterSum, 200); } BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered) { CScheduler scheduler; // each queue should be well ordered with respect to itself but not other queues SingleThreadedSchedulerClient queue1(&scheduler); SingleThreadedSchedulerClient queue2(&scheduler); // create more threads than queues // if the queues only permit execution of one task at once then // the extra threads should effectively be doing nothing // if they don't we'll get out of order behaviour boost::thread_group threads; for (int i = 0; i < 5; ++i) { threads.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler)); } // these are not atomic, if SinglethreadedSchedulerClient prevents // parallel execution at the queue level no synchronization should be required here int counter1 = 0; int counter2 = 0; // just simply count up on each queue - if execution is properly ordered then // the callbacks should run in exactly the order in which they were enqueued for (int i = 0; i < 100; ++i) { queue1.AddToProcessQueue([i, &counter1]() { BOOST_CHECK_EQUAL(i, counter1++); }); queue2.AddToProcessQueue([i, &counter2]() { BOOST_CHECK_EQUAL(i, counter2++); }); } // finish up scheduler.stop(true); threads.join_all(); BOOST_CHECK_EQUAL(counter1, 100); BOOST_CHECK_EQUAL(counter2, 100); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Use assert when running from multithreaded code as BOOST_CHECK_* are not thread safe<commit_after>// Copyright (c) 2012-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <random.h> #include <scheduler.h> #include <test/test_chaincoin.h> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(scheduler_tests) static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime) { { boost::unique_lock<boost::mutex> lock(mutex); counter += delta; } boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min(); if (rescheduleTime != noTime) { CScheduler::Function f = boost::bind(&microTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime); s.schedule(f, rescheduleTime); } } static void MicroSleep(uint64_t n) { #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::microseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::microseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } BOOST_AUTO_TEST_CASE(manythreads) { // Stress test: hundreds of microsecond-scheduled tasks, // serviced by 10 threads. // // So... ten shared counters, which if all the tasks execute // properly will sum to the number of tasks done. // Each task adds or subtracts a random amount from one of the // counters, and then schedules another task 0-1000 // microseconds in the future to subtract or add from // the counter -random_amount+1, so in the end the shared // counters should sum to the number of initial tasks performed. CScheduler microTasks; boost::mutex counterMutex[10]; int counter[10] = { 0 }; FastRandomContext rng(42); auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; // [0, 9] auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + (int)rc.randrange(1012); }; // [-11, 1000] auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + (int)rc.randrange(2001); }; // [-1000, 1000] boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); boost::chrono::system_clock::time_point now = start; boost::chrono::system_clock::time_point first, last; size_t nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 0); for (int i = 0; i < 100; ++i) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 100); BOOST_CHECK(first < last); BOOST_CHECK(last > now); // As soon as these are created they will start running and servicing the queue boost::thread_group microThreads; for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); MicroSleep(600); now = boost::chrono::system_clock::now(); // More threads and more tasks: for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); for (int i = 0; i < 100; i++) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } // Drain the task queue then exit threads microTasks.stop(true); microThreads.join_all(); // ... wait until all the threads are done int counterSum = 0; for (int i = 0; i < 10; i++) { BOOST_CHECK(counter[i] != 0); counterSum += counter[i]; } BOOST_CHECK_EQUAL(counterSum, 200); } BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered) { CScheduler scheduler; // each queue should be well ordered with respect to itself but not other queues SingleThreadedSchedulerClient queue1(&scheduler); SingleThreadedSchedulerClient queue2(&scheduler); // create more threads than queues // if the queues only permit execution of one task at once then // the extra threads should effectively be doing nothing // if they don't we'll get out of order behaviour boost::thread_group threads; for (int i = 0; i < 5; ++i) { threads.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler)); } // these are not atomic, if SinglethreadedSchedulerClient prevents // parallel execution at the queue level no synchronization should be required here int counter1 = 0; int counter2 = 0; // just simply count up on each queue - if execution is properly ordered then // the callbacks should run in exactly the order in which they were enqueued for (int i = 0; i < 100; ++i) { queue1.AddToProcessQueue([i, &counter1]() { assert(i == counter1++); }); queue2.AddToProcessQueue([i, &counter2]() { assert(i == counter2++); }); } // finish up scheduler.stop(true); threads.join_all(); BOOST_CHECK_EQUAL(counter1, 100); BOOST_CHECK_EQUAL(counter2, 100); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015, 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015, 2016 Sensics, Inc. // // 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. // Internal Includes #include "PoseEstimator_RANSAC.h" #include "LED.h" #include "CameraParameters.h" #include "cvToEigen.h" // Library/third-party includes #include <opencv2/core/core.hpp> #include <opencv2/calib3d/calib3d.hpp> // Standard includes #include <algorithm> namespace osvr { namespace vbtracker { bool RANSACPoseEstimator::operator()(CameraParameters const &camParams, LedPtrList const &leds, BeaconStateVec const &beacons, std::vector<BeaconData> &beaconDebug, Eigen::Vector3d &outXlate, Eigen::Quaterniond &outQuat) { // We need to get a pair of matched vectors of points: 2D locations // with in the image and 3D locations in model space. There needs to // be a correspondence between the points in these vectors, such that // the ith element in one matches the ith element in the other. We // make these by looking up the locations of LEDs with known identifiers // and pushing both onto the vectors at the same time. std::vector<cv::Point3f> objectPoints; std::vector<cv::Point2f> imagePoints; std::vector<ZeroBasedBeaconId> beaconIds; for (auto const &led : leds) { auto id = makeZeroBased(led->getID()); auto index = asIndex(id); beaconDebug[index].variance = -1; beaconDebug[index].measurement = led->getLocationForTracking(); beaconIds.push_back(id); /// Effectively invert the image points here so we get the output of /// a coordinate system we want. imagePoints.push_back(led->getLocationForTracking()); objectPoints.push_back( vec3dToCVPoint3f(beacons[index]->stateVector())); } // Make sure we have enough points to do our estimation. if (objectPoints.size() < m_permittedOutliers + m_requiredInliers) { return false; } // Produce an estimate of the translation and rotation needed to take // points from model space into camera space. We allow for at most // m_permittedOutliers outliers. Even in simulation data, we sometimes // find duplicate IDs for LEDs, indicating that we are getting // mis-identified ones sometimes. // We tried using the previous guess to reduce the amount of computation // being done, but this got us stuck in infinite locations. We seem to // do okay without using it, so leaving it out. // @todo Make number of iterations into a parameter. bool usePreviousGuess = false; int iterationsCount = 5; cv::Mat inlierIndices; cv::Mat rvec; cv::Mat tvec; #if CV_MAJOR_VERSION == 2 cv::solvePnPRansac( objectPoints, imagePoints, camParams.cameraMatrix, camParams.distortionParameters, rvec, tvec, usePreviousGuess, iterationsCount, 8.0f, static_cast<int>(objectPoints.size() - m_permittedOutliers), inlierIndices); #elif CV_MAJOR_VERSION == 3 // parameter added to the OpenCV 3.0 interface in place of the number of // inliers /// @todo how to determine this requested confidence from the data we're /// given? double confidence = 0.99; auto ransacResult = cv::solvePnPRansac( objectPoints, imagePoints, camParams.cameraMatrix, camParams.distortionParameters, rvec, tvec, usePreviousGuess, iterationsCount, 8.0f, confidence, inlierIndices); if (!ransacResult) { return false; } #else #error "Unrecognized OpenCV version!" #endif //========================================================================== // Make sure we got all the inliers we needed. Otherwise, reject this // pose. if (inlierIndices.rows < static_cast<int>(m_requiredInliers)) { return false; } //========================================================================== // Reproject the inliers into the image and make sure they are actually // close to the expected location; otherwise, we have a bad pose. const double pixelReprojectionErrorForSingleAxisMax = 4; if (inlierIndices.rows > 0) { std::vector<cv::Point3f> inlierObjectPoints; std::vector<cv::Point2f> inlierImagePoints; std::vector<ZeroBasedBeaconId> inlierBeaconIds; for (int i = 0; i < inlierIndices.rows; i++) { inlierObjectPoints.push_back(objectPoints[i]); inlierImagePoints.push_back(imagePoints[i]); inlierBeaconIds.push_back(beaconIds[i]); } std::vector<cv::Point2f> reprojectedPoints; cv::projectPoints( inlierObjectPoints, rvec, tvec, camParams.cameraMatrix, camParams.distortionParameters, reprojectedPoints); for (size_t i = 0; i < reprojectedPoints.size(); i++) { if (reprojectedPoints[i].x - inlierImagePoints[i].x > pixelReprojectionErrorForSingleAxisMax) { return false; } if (reprojectedPoints[i].y - inlierImagePoints[i].y > pixelReprojectionErrorForSingleAxisMax) { return false; } } /// Now, we will sort that vector of inlier beacon IDs so we can /// rapidly binary search it to flag the LEDs we used. // Need a custom comparator for the ID type. auto idComparator = [](ZeroBasedBeaconId const &lhs, ZeroBasedBeaconId const &rhs) { return lhs.value() < rhs.value(); }; std::sort(begin(inlierBeaconIds), end(inlierBeaconIds), idComparator); // This lambda wraps binary_search to do what it says: check to see // if a given beacon ID is in the list of inlier beacons. auto isAnInlierBeacon = [&inlierBeaconIds, &idComparator]( ZeroBasedBeaconId const &needle) { return std::binary_search(begin(inlierBeaconIds), end(inlierBeaconIds), needle, idComparator); }; for (auto &led : leds) { if (isAnInlierBeacon(led->getID())) { led->markAsUsed(); } } } //========================================================================== // Convert this into an OSVR representation of the transformation that // gives the pose of the HDK origin in the camera coordinate system, // switching units to meters and encoding the angle in a unit // quaternion. // The matrix described by rvec and tvec takes points in model space // (the space where the LEDs are defined, which is in mm away from an // implied origin) into a coordinate system where the center is at the // camera's origin, with X to the right, Y down, and Z in the direction // that the camera is facing (but still in the original units of mm): // |Xc| |r11 r12 r13 t1| |Xm| // |Yc| = |r21 r22 r23 t2|*|Ym| // |Zc| |r31 r32 r33 t3| |Zm| // |1 | // That is, it rotates into the camera coordinate system and then adds // the translation, which is in the camera coordinate system. // This is the transformation we want, since it reports the sensor's // position and orientation in camera space, except that we want to // convert // the units into meters and the orientation into a Quaternion. // NOTE: This is a right-handed coordinate system with X pointing // towards the right from the camera center of projection, Y pointing // down, and Z pointing along the camera viewing direction, if the input // points are not inverted. outXlate = cvToVector3d(tvec); outQuat = cvRotVecToQuat(rvec); return true; } /// Variance in Meters^2 static const double InitialPositionStateError = 0.; /// Variance in Radians^2 static const double InitialOrientationStateError = 0.5; static const double InitialVelocityStateError = 0.; static const double InitialAngVelStateError = 0.; static const double InitialStateError[] = { InitialPositionStateError, InitialPositionStateError, InitialPositionStateError, InitialOrientationStateError, InitialOrientationStateError, InitialOrientationStateError, InitialVelocityStateError, InitialVelocityStateError, InitialVelocityStateError, InitialAngVelStateError, InitialAngVelStateError, InitialAngVelStateError}; bool RANSACPoseEstimator::operator()(EstimatorInOutParams const &p, LedPtrList const &leds) { Eigen::Vector3d xlate; Eigen::Quaterniond quat; /// Call the main pose estimation to get the vector and quat. { auto ret = (*this)(p.camParams, leds, p.beacons, p.beaconDebug, xlate, quat); if (!ret) { return false; } } /// OK, so if we're here, estimation succeeded and we have valid data in /// xlate and quat. p.state.position() = xlate; p.state.setQuaternion(quat); /// Zero things we can't measure. #if 1 p.state.incrementalOrientation() = Eigen::Vector3d::Zero(); p.state.velocity() = Eigen::Vector3d::Zero(); p.state.angularVelocity() = Eigen::Vector3d::Zero(); #endif using StateVec = kalman::types::DimVector<BodyState>; using StateSquareMatrix = kalman::types::DimSquareMatrix<BodyState>; StateSquareMatrix covariance = StateVec(InitialStateError).asDiagonal(); /// @todo Copy the existing angular velocity error covariance /* covariance.bottomRightCorner<3, 3>() = p.state.errorCovariance().bottomRightCorner<3, 3>(); */ p.state.setErrorCovariance(covariance); return true; } } // namespace vbtracker } // namespace osvr <commit_msg>Pull out and name the max reprojection error.<commit_after>/** @file @brief Implementation @date 2015, 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015, 2016 Sensics, Inc. // // 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. // Internal Includes #include "PoseEstimator_RANSAC.h" #include "LED.h" #include "CameraParameters.h" #include "cvToEigen.h" // Library/third-party includes #include <opencv2/core/core.hpp> #include <opencv2/calib3d/calib3d.hpp> // Standard includes #include <algorithm> namespace osvr { namespace vbtracker { bool RANSACPoseEstimator::operator()(CameraParameters const &camParams, LedPtrList const &leds, BeaconStateVec const &beacons, std::vector<BeaconData> &beaconDebug, Eigen::Vector3d &outXlate, Eigen::Quaterniond &outQuat) { // We need to get a pair of matched vectors of points: 2D locations // with in the image and 3D locations in model space. There needs to // be a correspondence between the points in these vectors, such that // the ith element in one matches the ith element in the other. We // make these by looking up the locations of LEDs with known identifiers // and pushing both onto the vectors at the same time. std::vector<cv::Point3f> objectPoints; std::vector<cv::Point2f> imagePoints; std::vector<ZeroBasedBeaconId> beaconIds; for (auto const &led : leds) { auto id = makeZeroBased(led->getID()); auto index = asIndex(id); beaconDebug[index].variance = -1; beaconDebug[index].measurement = led->getLocationForTracking(); beaconIds.push_back(id); /// Effectively invert the image points here so we get the output of /// a coordinate system we want. imagePoints.push_back(led->getLocationForTracking()); objectPoints.push_back( vec3dToCVPoint3f(beacons[index]->stateVector())); } // Make sure we have enough points to do our estimation. if (objectPoints.size() < m_permittedOutliers + m_requiredInliers) { return false; } // Produce an estimate of the translation and rotation needed to take // points from model space into camera space. We allow for at most // m_permittedOutliers outliers. Even in simulation data, we sometimes // find duplicate IDs for LEDs, indicating that we are getting // mis-identified ones sometimes. // We tried using the previous guess to reduce the amount of computation // being done, but this got us stuck in infinite locations. We seem to // do okay without using it, so leaving it out. // @todo Make number of iterations into a parameter. bool usePreviousGuess = false; int iterationsCount = 5; float maxReprojectionError = 6.f; cv::Mat inlierIndices; cv::Mat rvec; cv::Mat tvec; #if CV_MAJOR_VERSION == 2 cv::solvePnPRansac( objectPoints, imagePoints, camParams.cameraMatrix, camParams.distortionParameters, rvec, tvec, usePreviousGuess, iterationsCount, maxReprojectionError, static_cast<int>(objectPoints.size() - m_permittedOutliers), inlierIndices); #elif CV_MAJOR_VERSION == 3 // parameter added to the OpenCV 3.0 interface in place of the number of // inliers /// @todo how to determine this requested confidence from the data we're /// given? double confidence = 0.99; auto ransacResult = cv::solvePnPRansac( objectPoints, imagePoints, camParams.cameraMatrix, camParams.distortionParameters, rvec, tvec, usePreviousGuess, iterationsCount, maxReprojectionError, confidence, inlierIndices); if (!ransacResult) { return false; } #else #error "Unrecognized OpenCV version!" #endif //========================================================================== // Make sure we got all the inliers we needed. Otherwise, reject this // pose. if (inlierIndices.rows < static_cast<int>(m_requiredInliers)) { return false; } //========================================================================== // Reproject the inliers into the image and make sure they are actually // close to the expected location; otherwise, we have a bad pose. const double pixelReprojectionErrorForSingleAxisMax = 4; if (inlierIndices.rows > 0) { std::vector<cv::Point3f> inlierObjectPoints; std::vector<cv::Point2f> inlierImagePoints; std::vector<ZeroBasedBeaconId> inlierBeaconIds; for (int i = 0; i < inlierIndices.rows; i++) { inlierObjectPoints.push_back(objectPoints[i]); inlierImagePoints.push_back(imagePoints[i]); inlierBeaconIds.push_back(beaconIds[i]); } std::vector<cv::Point2f> reprojectedPoints; cv::projectPoints( inlierObjectPoints, rvec, tvec, camParams.cameraMatrix, camParams.distortionParameters, reprojectedPoints); for (size_t i = 0; i < reprojectedPoints.size(); i++) { if (reprojectedPoints[i].x - inlierImagePoints[i].x > pixelReprojectionErrorForSingleAxisMax) { return false; } if (reprojectedPoints[i].y - inlierImagePoints[i].y > pixelReprojectionErrorForSingleAxisMax) { return false; } } /// Now, we will sort that vector of inlier beacon IDs so we can /// rapidly binary search it to flag the LEDs we used. // Need a custom comparator for the ID type. auto idComparator = [](ZeroBasedBeaconId const &lhs, ZeroBasedBeaconId const &rhs) { return lhs.value() < rhs.value(); }; std::sort(begin(inlierBeaconIds), end(inlierBeaconIds), idComparator); // This lambda wraps binary_search to do what it says: check to see // if a given beacon ID is in the list of inlier beacons. auto isAnInlierBeacon = [&inlierBeaconIds, &idComparator]( ZeroBasedBeaconId const &needle) { return std::binary_search(begin(inlierBeaconIds), end(inlierBeaconIds), needle, idComparator); }; for (auto &led : leds) { if (isAnInlierBeacon(led->getID())) { led->markAsUsed(); } } } //========================================================================== // Convert this into an OSVR representation of the transformation that // gives the pose of the HDK origin in the camera coordinate system, // switching units to meters and encoding the angle in a unit // quaternion. // The matrix described by rvec and tvec takes points in model space // (the space where the LEDs are defined, which is in mm away from an // implied origin) into a coordinate system where the center is at the // camera's origin, with X to the right, Y down, and Z in the direction // that the camera is facing (but still in the original units of mm): // |Xc| |r11 r12 r13 t1| |Xm| // |Yc| = |r21 r22 r23 t2|*|Ym| // |Zc| |r31 r32 r33 t3| |Zm| // |1 | // That is, it rotates into the camera coordinate system and then adds // the translation, which is in the camera coordinate system. // This is the transformation we want, since it reports the sensor's // position and orientation in camera space, except that we want to // convert // the units into meters and the orientation into a Quaternion. // NOTE: This is a right-handed coordinate system with X pointing // towards the right from the camera center of projection, Y pointing // down, and Z pointing along the camera viewing direction, if the input // points are not inverted. outXlate = cvToVector3d(tvec); outQuat = cvRotVecToQuat(rvec); return true; } /// Variance in Meters^2 static const double InitialPositionStateError = 0.; /// Variance in Radians^2 static const double InitialOrientationStateError = 0.5; static const double InitialVelocityStateError = 0.; static const double InitialAngVelStateError = 0.; static const double InitialStateError[] = { InitialPositionStateError, InitialPositionStateError, InitialPositionStateError, InitialOrientationStateError, InitialOrientationStateError, InitialOrientationStateError, InitialVelocityStateError, InitialVelocityStateError, InitialVelocityStateError, InitialAngVelStateError, InitialAngVelStateError, InitialAngVelStateError}; bool RANSACPoseEstimator::operator()(EstimatorInOutParams const &p, LedPtrList const &leds) { Eigen::Vector3d xlate; Eigen::Quaterniond quat; /// Call the main pose estimation to get the vector and quat. { auto ret = (*this)(p.camParams, leds, p.beacons, p.beaconDebug, xlate, quat); if (!ret) { return false; } } /// OK, so if we're here, estimation succeeded and we have valid data in /// xlate and quat. p.state.position() = xlate; p.state.setQuaternion(quat); /// Zero things we can't measure. #if 1 p.state.incrementalOrientation() = Eigen::Vector3d::Zero(); p.state.velocity() = Eigen::Vector3d::Zero(); p.state.angularVelocity() = Eigen::Vector3d::Zero(); #endif using StateVec = kalman::types::DimVector<BodyState>; using StateSquareMatrix = kalman::types::DimSquareMatrix<BodyState>; StateSquareMatrix covariance = StateVec(InitialStateError).asDiagonal(); /// @todo Copy the existing angular velocity error covariance /* covariance.bottomRightCorner<3, 3>() = p.state.errorCovariance().bottomRightCorner<3, 3>(); */ p.state.setErrorCovariance(covariance); return true; } } // namespace vbtracker } // namespace osvr <|endoftext|>
<commit_before>#include "libpixel/graphics/device/device.h" #include "libpixel/graphics/render/primitive/primitiveRenderer.h" namespace libpixel { PrimitiveRenderer::PrimitiveRenderer() { } PrimitiveRenderer::~PrimitiveRenderer() { } void PrimitiveRenderer::RenderEllipse(Vec2 position, Vec2 size, Vec3 rotation, Vec4 color, int segments) { glEnable(GL_BLEND); glPushMatrix(); glTranslatef(position[0], position[1], 0.f); glScalef(size[0], size[1], 1.f); glRotatef(rotation[0], 1, 0, 0); glRotatef(rotation[1], 0, 1, 0); glRotatef(rotation[2], 0, 0, 1); glColor4f(color[0], color[1], color[2], color[3]); GLfloat glVertices[segments*2]; float angle = 0; for (int i=0; i<segments*2; i+=2) { angle += M_PI/(segments/2); glVertices[i] = cos(angle); glVertices[i+1] = sin(angle); } glVertexPointer(2, GL_FLOAT, 0, glVertices); glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_LINE_LOOP, 0, segments); glPopMatrix(); glDisable(GL_BLEND); } void PrimitiveRenderer::RenderLine(Vec2 start, Vec2 end, Vec4 color) { glEnable(GL_BLEND); glPushMatrix(); glColor4f(color[0], color[1], color[2], color[3]); GLfloat glVertices[] = { start[0], start[1], end[0], end[1] }; glVertexPointer(2, GL_FLOAT, 0, glVertices); glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_LINES, 0, 2); glColor4f(1.f, 1.f, 1.f, 1.f); glPopMatrix(); glDisable(GL_BLEND); } void PrimitiveRenderer::RenderBox(Vec2 position, Vec2 size, Vec4 color) { glEnable(GL_BLEND); glColor4f(color[0], color[1], color[2], color[3]); glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); Vec2 tl(position[0] - size[0]/2.f, position[1] - size[1]/2.f); Vec2 br(position[0] + size[0]/2.f, position[1] + size[1]/2.f); GLfloat glVertices[8] = { tl[0], br[1], tl[0], tl[1], br[0], tl[1], br[0], br[1] }; glVertexPointer(2, GL_FLOAT, 0, glVertices); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); } } <commit_msg>Fix alpha blending in primitive renderer<commit_after>#include "libpixel/graphics/device/device.h" #include "libpixel/graphics/render/primitive/primitiveRenderer.h" namespace libpixel { PrimitiveRenderer::PrimitiveRenderer() { } PrimitiveRenderer::~PrimitiveRenderer() { } void PrimitiveRenderer::RenderEllipse(Vec2 position, Vec2 size, Vec3 rotation, Vec4 color, int segments) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glTranslatef(position[0], position[1], 0.f); glScalef(size[0], size[1], 1.f); glRotatef(rotation[0], 1, 0, 0); glRotatef(rotation[1], 0, 1, 0); glRotatef(rotation[2], 0, 0, 1); glColor4f(color[0], color[1], color[2], color[3]); GLfloat glVertices[segments*2]; float angle = 0; for (int i=0; i<segments*2; i+=2) { angle += M_PI/(segments/2); glVertices[i] = cos(angle); glVertices[i+1] = sin(angle); } glVertexPointer(2, GL_FLOAT, 0, glVertices); glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_LINE_LOOP, 0, segments); glPopMatrix(); glColor4f(1.f, 1.f, 1.f, 1.f); glDisable(GL_BLEND); } void PrimitiveRenderer::RenderLine(Vec2 start, Vec2 end, Vec4 color) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glColor4f(color[0], color[1], color[2], color[3]); GLfloat glVertices[] = { start[0], start[1], end[0], end[1] }; glVertexPointer(2, GL_FLOAT, 0, glVertices); glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_LINES, 0, 2); glColor4f(1.f, 1.f, 1.f, 1.f); glPopMatrix(); glDisable(GL_BLEND); } void PrimitiveRenderer::RenderBox(Vec2 position, Vec2 size, Vec4 color) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(color[0], color[1], color[2], color[3]); glEnableClientState(GL_VERTEX_ARRAY); Vec2 tl(position[0] - size[0]/2.f, position[1] - size[1]/2.f); Vec2 br(position[0] + size[0]/2.f, position[1] + size[1]/2.f); GLfloat glVertices[8] = { tl[0], br[1], tl[0], tl[1], br[0], tl[1], br[0], br[1] }; glVertexPointer(2, GL_FLOAT, 0, glVertices); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.f, 1.f, 1.f, 1.f); glDisable(GL_BLEND); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/framework/executor.h" #include <algorithm> #include <iostream> #include <memory> #include <set> #include <vector> #include "paddle/framework/lod_tensor.h" #include "paddle/framework/op_registry.h" #include "paddle/framework/scope.h" #include <boost/range/adaptor/reversed.hpp> namespace paddle { namespace framework { const std::string kFeedOpType = "feed"; const std::string kFetchOpType = "fetch"; Executor::Executor(const std::vector<platform::Place>& places) { PADDLE_ENFORCE_GT(places.size(), 0); device_contexts_.resize(places.size()); for (size_t i = 0; i < places.size(); i++) { if (platform::is_cpu_place(places[i])) { device_contexts_[i] = new platform::CPUDeviceContext( boost::get<platform::CPUPlace>(places[i])); } else if (platform::is_gpu_place(places[i])) { #ifdef PADDLE_WITH_CUDA device_contexts_[i] = new platform::CUDADeviceContext( boost::get<platform::GPUPlace>(places[i])); #else PADDLE_THROW( "'GPUPlace' is not supported, Please re-compile with WITH_GPU " "option"); #endif } } } Executor::~Executor() { for (auto& device_context : device_contexts_) { delete device_context; } } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_GT(pdesc.blocks_size(), block_id); auto& block = pdesc.blocks(block_id); auto& device = device_contexts_[0]; // Instantiate all the vars in the global scope for (auto& var : block.vars()) { scope->NewVar(var.name()); } Scope& local_scope = scope->NewScope(); std::vector<bool> should_run = Prune(pdesc, block_id); PADDLE_ENFORCE_EQ(should_run.size(), static_cast<size_t>(block.ops_size())); for (size_t i = 0; i < should_run.size(); ++i) { if (should_run[i]) { for (auto& var : block.ops(i).outputs()) { for (auto& argu : var.arguments()) { if (local_scope.FindVar(argu) == nullptr) { local_scope.NewVar(argu); } } } auto op = paddle::framework::OpRegistry::CreateOp(block.ops(i)); op->Run(local_scope, *device); } } // TODO(tonyyang-svail): // - Destroy local_scope } std::vector<bool> Executor::Prune(const ProgramDesc& pdesc, int block_id) { // TODO(tonyyang-svail): // - will change to use multiple blocks for RNN op and Cond Op auto& block = pdesc.blocks(block_id); auto& ops = block.ops(); bool expect_feed = true; for (auto& op_desc : ops) { PADDLE_ENFORCE(op_desc.type() != kFeedOpType || expect_feed, "All FeedOps are at the beginning of the ProgramDesc"); expect_feed = (op_desc.type() == kFeedOpType); } bool expect_fetch = true; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; PADDLE_ENFORCE(op_desc.type() != kFetchOpType || expect_fetch, "All FetchOps must at the end of the ProgramDesc"); expect_fetch = (op_desc.type() == kFetchOpType); } std::set<std::string> dependent_vars; std::vector<bool> should_run; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; bool found_dependent_vars = false; for (auto& var : op_desc.outputs()) { for (auto& argu : var.arguments()) { if (dependent_vars.count(argu) != 0) { found_dependent_vars = true; } } } if (op_desc.type() == kFetchOpType || found_dependent_vars) { // erase its output to the dependency graph for (auto& var : op_desc.outputs()) { for (auto& argu : var.arguments()) { dependent_vars.erase(argu); } } // insert its input to the dependency graph for (auto& var : op_desc.inputs()) { for (auto& argu : var.arguments()) { dependent_vars.insert(argu); } } should_run.push_back(true); } else { should_run.push_back(false); } } // TODO(tonyyang-svail): // - check this after integration of Init // PADDLE_ENFORCE(dependent_vars.empty()); // since we are traversing the ProgramDesc in reverse order // we reverse the should_run vector std::reverse(should_run.begin(), should_run.end()); return should_run; } Executor::Executor(const std::vector<platform::Place>& places) { PADDLE_ENFORCE_GT(places.size(), 0); device_contexts_.resize(places.size()); for (size_t i = 0; i < places.size(); i++) { if (platform::is_cpu_place(places[i])) { device_contexts_[i] = new platform::CPUDeviceContext( boost::get<platform::CPUPlace>(places[i])); } else if (platform::is_gpu_place(places[i])) { #ifdef PADDLE_WITH_CUDA device_contexts_[i] = new platform::CUDADeviceContext( boost::get<platform::GPUPlace>(places[i])); #else PADDLE_THROW("'GPUPlace' is not supported in CPU only device."); #endif } } } Executor::~Executor() { for (auto& device_context : device_contexts_) { delete device_context; } } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_GT(pdesc.blocks_size(), block_id); auto& block = pdesc.blocks(block_id); auto& device = device_contexts_[0]; // Instantiate all the vars in the global scope for (auto& var : block.vars()) { scope->NewVar(var.name()); } Scope& local_scope = scope->NewScope(); std::vector<bool> should_run = Prune(pdesc, block_id); PADDLE_ENFORCE_EQ(should_run.size(), static_cast<size_t>(block.ops_size())); for (size_t i = 0; i < should_run.size(); ++i) { if (should_run[i]) { for (auto& var : block.ops(i).outputs()) { for (auto& argu : var.arguments()) { if (local_scope.FindVar(argu) == nullptr) { local_scope.NewVar(argu); } } } auto op = paddle::framework::OpRegistry::CreateOp(block.ops(i)); op->Run(local_scope, *device); } } // TODO(tonyyang-svail): // - Destroy local_scope } } // namespace framework } // namespace paddle <commit_msg>clean up for merge<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/framework/executor.h" #include <algorithm> #include <iostream> #include <memory> #include <set> #include <vector> #include "paddle/framework/lod_tensor.h" #include "paddle/framework/op_registry.h" #include "paddle/framework/scope.h" #include <boost/range/adaptor/reversed.hpp> namespace paddle { namespace framework { const std::string kFeedOpType = "feed"; const std::string kFetchOpType = "fetch"; Executor::Executor(const std::vector<platform::Place>& places) { PADDLE_ENFORCE_GT(places.size(), 0); device_contexts_.resize(places.size()); for (size_t i = 0; i < places.size(); i++) { if (platform::is_cpu_place(places[i])) { device_contexts_[i] = new platform::CPUDeviceContext( boost::get<platform::CPUPlace>(places[i])); } else if (platform::is_gpu_place(places[i])) { #ifdef PADDLE_WITH_CUDA device_contexts_[i] = new platform::CUDADeviceContext( boost::get<platform::GPUPlace>(places[i])); #else PADDLE_THROW( "'GPUPlace' is not supported, Please re-compile with WITH_GPU " "option"); #endif } } } Executor::~Executor() { for (auto& device_context : device_contexts_) { delete device_context; } } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_GT(pdesc.blocks_size(), block_id); auto& block = pdesc.blocks(block_id); auto& device = device_contexts_[0]; // Instantiate all the vars in the global scope for (auto& var : block.vars()) { scope->NewVar(var.name()); } Scope& local_scope = scope->NewScope(); std::vector<bool> should_run = Prune(pdesc, block_id); PADDLE_ENFORCE_EQ(should_run.size(), static_cast<size_t>(block.ops_size())); for (size_t i = 0; i < should_run.size(); ++i) { if (should_run[i]) { for (auto& var : block.ops(i).outputs()) { for (auto& argu : var.arguments()) { if (local_scope.FindVar(argu) == nullptr) { local_scope.NewVar(argu); } } } auto op = paddle::framework::OpRegistry::CreateOp(block.ops(i)); op->Run(local_scope, *device); } } // TODO(tonyyang-svail): // - Destroy local_scope } std::vector<bool> Prune(const ProgramDesc& pdesc, int block_id) { // TODO(tonyyang-svail): // - will change to use multiple blocks for RNN op and Cond Op auto& block = pdesc.blocks(block_id); auto& ops = block.ops(); bool expect_feed = true; for (auto& op_desc : ops) { PADDLE_ENFORCE(op_desc.type() != kFeedOpType || expect_feed, "All FeedOps are at the beginning of the ProgramDesc"); expect_feed = (op_desc.type() == kFeedOpType); } bool expect_fetch = true; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; PADDLE_ENFORCE(op_desc.type() != kFetchOpType || expect_fetch, "All FetchOps must at the end of the ProgramDesc"); expect_fetch = (op_desc.type() == kFetchOpType); } std::set<std::string> dependent_vars; std::vector<bool> should_run; for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) { auto& op_desc = *op_iter; bool found_dependent_vars = false; for (auto& var : op_desc.outputs()) { for (auto& argu : var.arguments()) { if (dependent_vars.count(argu) != 0) { found_dependent_vars = true; } } } if (op_desc.type() == kFetchOpType || found_dependent_vars) { // erase its output to the dependency graph for (auto& var : op_desc.outputs()) { for (auto& argu : var.arguments()) { dependent_vars.erase(argu); } } // insert its input to the dependency graph for (auto& var : op_desc.inputs()) { for (auto& argu : var.arguments()) { dependent_vars.insert(argu); } } should_run.push_back(true); } else { should_run.push_back(false); } } // TODO(tonyyang-svail): // - check this after integration of Init // PADDLE_ENFORCE(dependent_vars.empty()); // since we are traversing the ProgramDesc in reverse order // we reverse the should_run vector std::reverse(should_run.begin(), should_run.end()); return should_run; } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>#include "EntityEditor.hpp" #include <Engine/Component/Animation.hpp> #include <Engine/Component/Physics.hpp> #include <Engine/Component/Mesh.hpp> #include <Engine/Component/Lens.hpp> #include <Engine/Component/Material.hpp> #include <Engine/Component/DirectionalLight.hpp> #include <Engine/Component/PointLight.hpp> #include <Engine/Component/SpotLight.hpp> #include <Engine/Component/Listener.hpp> #include <Engine/Component/Script.hpp> #include <Engine/Component/SoundSource.hpp> #include <Engine/Component/ParticleEmitter.hpp> #include <Engine/Hymn.hpp> #include <Engine/Geometry/Model.hpp> #include <Engine/Geometry/RiggedModel.hpp> #include <Engine/Texture/Texture2D.hpp> #include <Engine/Audio/SoundBuffer.hpp> #include <Engine/Script/ScriptFile.hpp> #include <Engine/Util/FileSystem.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include "../../Util/EditorSettings.hpp" #include "../FileSelector.hpp" using namespace GUI; EntityEditor::EntityEditor() { name[0] = '\0'; AddEditor<Component::Animation>("Animation", std::bind(&EntityEditor::AnimationEditor, this, std::placeholders::_1)); AddEditor<Component::Physics>("Physics", std::bind(&EntityEditor::PhysicsEditor, this, std::placeholders::_1)); AddEditor<Component::Mesh>("Mesh", std::bind(&EntityEditor::MeshEditor, this, std::placeholders::_1)); AddEditor<Component::Lens>("Lens", std::bind(&EntityEditor::LensEditor, this, std::placeholders::_1)); AddEditor<Component::Material>("Material", std::bind(&EntityEditor::MaterialEditor, this, std::placeholders::_1)); AddEditor<Component::DirectionalLight>("Directional light", std::bind(&EntityEditor::DirectionalLightEditor, this, std::placeholders::_1)); AddEditor<Component::PointLight>("Point light", std::bind(&EntityEditor::PointLightEditor, this, std::placeholders::_1)); AddEditor<Component::SpotLight>("Spot light", std::bind(&EntityEditor::SpotLightEditor, this, std::placeholders::_1)); AddEditor<Component::Listener>("Listener", std::bind(&EntityEditor::ListenerEditor, this, std::placeholders::_1)); AddEditor<Component::Script>("Script", std::bind(&EntityEditor::ScriptEditor, this, std::placeholders::_1)); AddEditor<Component::SoundSource>("Sound source", std::bind(&EntityEditor::SoundSourceEditor, this, std::placeholders::_1)); AddEditor<Component::ParticleEmitter>("Particle emitter", std::bind(&EntityEditor::ParticleEmitterEditor, this, std::placeholders::_1)); } EntityEditor::~EntityEditor() { } void EntityEditor::Show() { if (ImGui::Begin(("Entity: " + entity->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(entity))).c_str(), &visible)) { ImGui::InputText("Name", name, 128); entity->name = name; ImGui::Text("Transform"); ImGui::Indent(); ImGui::InputFloat3("Position", &entity->position[0]); ImGui::InputFloat3("Rotation", &entity->rotation[0]); ImGui::InputFloat3("Scale", &entity->scale[0]); ImGui::Unindent(); if (!entity->IsScene()) { if (ImGui::Button("Add component")) ImGui::OpenPopup("Add component"); if (ImGui::BeginPopup("Add component")) { ImGui::Text("Components"); ImGui::Separator(); for (Editor& editor : editors) { editor.addFunction(); } ImGui::EndPopup(); } for (Editor& editor : editors) { editor.editFunction(); } } } ImGui::End(); } void EntityEditor::SetEntity(Entity* entity) { this->entity = entity; strcpy(name, entity->name.c_str()); } bool EntityEditor::ShowsEntity(Entity* entity) { return this->entity == entity; } bool EntityEditor::IsVisible() const { return visible; } void EntityEditor::SetVisible(bool visible) { this->visible = visible; } void EntityEditor::AnimationEditor(Component::Animation* animation) { ImGui::Indent(); if (ImGui::Button("Select model##Animation")) ImGui::OpenPopup("Select model##Animation"); if (ImGui::BeginPopup("Select model##Animation")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) animation->riggedModel = dynamic_cast<Geometry::RiggedModel*>(model); } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::PhysicsEditor(Component::Physics* physics) { ImGui::Text("Positional"); ImGui::Indent(); ImGui::InputFloat3("Velocity", &physics->velocity[0]); ImGui::InputFloat("Max velocity", &physics->maxVelocity); ImGui::InputFloat3("Acceleration", &physics->acceleration[0]); ImGui::InputFloat("Velocity drag factor", &physics->velocityDragFactor); ImGui::InputFloat("Gravity factor", &physics->gravityFactor); ImGui::Unindent(); ImGui::Text("Angular"); ImGui::Indent(); ImGui::InputFloat3("Angular velocity", &physics->angularVelocity[0]); ImGui::InputFloat("Max angular velocity", &physics->maxAngularVelocity); ImGui::InputFloat3("Angular acceleration", &physics->angularAcceleration[0]); ImGui::InputFloat("Angular drag factor", &physics->angularDragFactor); ImGui::InputFloat3("Moment of inertia", &physics->momentOfInertia[0]); ImGui::Unindent(); } void EntityEditor::MeshEditor(Component::Mesh* mesh) { ImGui::Indent(); if (ImGui::Button("Select model##Mesh")) ImGui::OpenPopup("Select model##Mesh"); if (ImGui::BeginPopup("Select model##Mesh")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) mesh->geometry = model; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::LensEditor(Component::Lens* lens) { ImGui::Indent(); ImGui::InputFloat("Field of view", &lens->fieldOfView); ImGui::InputFloat("Z near", &lens->zNear); ImGui::InputFloat("Z far", &lens->zFar); ImGui::Unindent(); } void EntityEditor::MaterialEditor(Component::Material* material) { // Diffuse ImGui::Text("Diffuse"); ImGui::Indent(); if (ImGui::Button("Select diffuse texture")) ImGui::OpenPopup("Select diffuse texture"); if (ImGui::BeginPopup("Select diffuse texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->diffuse = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Normal ImGui::Text("Normal"); ImGui::Indent(); if (ImGui::Button("Select normal texture")) ImGui::OpenPopup("Select normal texture"); if (ImGui::BeginPopup("Select normal texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->normal = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Specular ImGui::Text("Specular"); ImGui::Indent(); if (ImGui::Button("Select specular texture")) ImGui::OpenPopup("Select specular texture"); if (ImGui::BeginPopup("Select specular texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->specular = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Glow ImGui::Text("Glow"); ImGui::Indent(); if (ImGui::Button("Select glow texture")) ImGui::OpenPopup("Select glow texture"); if (ImGui::BeginPopup("Select glow texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->glow = texture; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::DirectionalLightEditor(Component::DirectionalLight* directionalLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &directionalLight->color[0]); ImGui::InputFloat("Ambient coefficient", &directionalLight->ambientCoefficient); ImGui::Unindent(); } void EntityEditor::PointLightEditor(Component::PointLight* pointLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &pointLight->color[0]); ImGui::InputFloat("Ambient coefficient", &pointLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &pointLight->attenuation); ImGui::InputFloat("Intensity", &pointLight->intensity); ImGui::Unindent(); } void EntityEditor::SpotLightEditor(Component::SpotLight* spotLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &spotLight->color[0]); ImGui::InputFloat("Ambient coefficient", &spotLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &spotLight->attenuation); ImGui::InputFloat("Intensity", &spotLight->intensity); ImGui::InputFloat("Cone angle", &spotLight->coneAngle); ImGui::Unindent(); } void EntityEditor::ListenerEditor(Component::Listener* listener) { } void EntityEditor::ScriptEditor(Component::Script* script) { ImGui::Indent(); if(script->scriptFile != nullptr) ImGui::Text(script->scriptFile->name.c_str()); else ImGui::Text("No script loaded"); if (ImGui::Button("Select script")) ImGui::OpenPopup("Select script"); if (ImGui::BeginPopup("Select script")) { ImGui::Text("Scripts"); ImGui::Separator(); for (ScriptFile* scriptFile : Hymn().scripts) { if (ImGui::Selectable(scriptFile->name.c_str())) script->scriptFile = scriptFile; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::SoundSourceEditor(Component::SoundSource* soundSource) { ImGui::Text("Sound"); ImGui::Indent(); if (ImGui::Button("Select sound")) ImGui::OpenPopup("Select sound"); if (ImGui::BeginPopup("Select sound")) { ImGui::Text("Sounds"); ImGui::Separator(); for (Audio::SoundBuffer* sound : Hymn().sounds) { if (ImGui::Selectable(sound->name.c_str())) soundSource->soundBuffer = sound; } ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Sound properties"); ImGui::Indent(); ImGui::InputFloat("Pitch", &soundSource->pitch); ImGui::InputFloat("Gain", &soundSource->gain); ImGui::Checkbox("Loop", &soundSource->loop); ImGui::Unindent(); } void EntityEditor::ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter) { ImGui::Text("Particle"); ImGui::Indent(); ImGui::InputInt("Texture index", &particleEmitter->particleType.textureIndex); ImGui::InputFloat3("Min velocity", &particleEmitter->particleType.minVelocity[0]); ImGui::InputFloat3("Max velocity", &particleEmitter->particleType.maxVelocity[0]); ImGui::InputFloat("Min lifetime", &particleEmitter->particleType.minLifetime); ImGui::InputFloat("Max lifetime", &particleEmitter->particleType.maxLifetime); ImGui::InputFloat2("Min size", &particleEmitter->particleType.minSize[0]); ImGui::InputFloat2("Max size", &particleEmitter->particleType.maxSize[0]); ImGui::Checkbox("Uniform scaling", &particleEmitter->particleType.uniformScaling); ImGui::InputFloat("Start alpha", &particleEmitter->particleType.startAlpha); ImGui::InputFloat("Mid alpha", &particleEmitter->particleType.midAlpha); ImGui::InputFloat("End alpha", &particleEmitter->particleType.endAlpha); ImGui::InputFloat3("Color", &particleEmitter->particleType.color[0]); ImGui::Unindent(); ImGui::Text("Emitter"); ImGui::Indent(); ImGui::InputFloat3("Size", &particleEmitter->size[0]); ImGui::InputFloat("Min emit time", &particleEmitter->minEmitTime); ImGui::InputFloat("Max emit time", &particleEmitter->maxEmitTime); if (ImGui::Button("Emitter type")) ImGui::OpenPopup("Emitter type"); if (ImGui::BeginPopup("Emitter type")) { ImGui::Text("Emitter type"); ImGui::Separator(); if (ImGui::Selectable("Point")) particleEmitter->emitterType = Component::ParticleEmitter::POINT; if (ImGui::Selectable("Cuboid")) particleEmitter->emitterType = Component::ParticleEmitter::CUBOID; ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Preview"); ImGui::Indent(); ImGui::Unindent(); } <commit_msg>Preview diffuse<commit_after>#include "EntityEditor.hpp" #include <Engine/Component/Animation.hpp> #include <Engine/Component/Physics.hpp> #include <Engine/Component/Mesh.hpp> #include <Engine/Component/Lens.hpp> #include <Engine/Component/Material.hpp> #include <Engine/Component/DirectionalLight.hpp> #include <Engine/Component/PointLight.hpp> #include <Engine/Component/SpotLight.hpp> #include <Engine/Component/Listener.hpp> #include <Engine/Component/Script.hpp> #include <Engine/Component/SoundSource.hpp> #include <Engine/Component/ParticleEmitter.hpp> #include <Engine/Hymn.hpp> #include <Engine/Geometry/Model.hpp> #include <Engine/Geometry/RiggedModel.hpp> #include <Engine/Texture/Texture2D.hpp> #include <Engine/Audio/SoundBuffer.hpp> #include <Engine/Script/ScriptFile.hpp> #include <Engine/Util/FileSystem.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include "../../Util/EditorSettings.hpp" #include "../FileSelector.hpp" using namespace GUI; EntityEditor::EntityEditor() { name[0] = '\0'; AddEditor<Component::Animation>("Animation", std::bind(&EntityEditor::AnimationEditor, this, std::placeholders::_1)); AddEditor<Component::Physics>("Physics", std::bind(&EntityEditor::PhysicsEditor, this, std::placeholders::_1)); AddEditor<Component::Mesh>("Mesh", std::bind(&EntityEditor::MeshEditor, this, std::placeholders::_1)); AddEditor<Component::Lens>("Lens", std::bind(&EntityEditor::LensEditor, this, std::placeholders::_1)); AddEditor<Component::Material>("Material", std::bind(&EntityEditor::MaterialEditor, this, std::placeholders::_1)); AddEditor<Component::DirectionalLight>("Directional light", std::bind(&EntityEditor::DirectionalLightEditor, this, std::placeholders::_1)); AddEditor<Component::PointLight>("Point light", std::bind(&EntityEditor::PointLightEditor, this, std::placeholders::_1)); AddEditor<Component::SpotLight>("Spot light", std::bind(&EntityEditor::SpotLightEditor, this, std::placeholders::_1)); AddEditor<Component::Listener>("Listener", std::bind(&EntityEditor::ListenerEditor, this, std::placeholders::_1)); AddEditor<Component::Script>("Script", std::bind(&EntityEditor::ScriptEditor, this, std::placeholders::_1)); AddEditor<Component::SoundSource>("Sound source", std::bind(&EntityEditor::SoundSourceEditor, this, std::placeholders::_1)); AddEditor<Component::ParticleEmitter>("Particle emitter", std::bind(&EntityEditor::ParticleEmitterEditor, this, std::placeholders::_1)); } EntityEditor::~EntityEditor() { } void EntityEditor::Show() { if (ImGui::Begin(("Entity: " + entity->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(entity))).c_str(), &visible)) { ImGui::InputText("Name", name, 128); entity->name = name; ImGui::Text("Transform"); ImGui::Indent(); ImGui::InputFloat3("Position", &entity->position[0]); ImGui::InputFloat3("Rotation", &entity->rotation[0]); ImGui::InputFloat3("Scale", &entity->scale[0]); ImGui::Unindent(); if (!entity->IsScene()) { if (ImGui::Button("Add component")) ImGui::OpenPopup("Add component"); if (ImGui::BeginPopup("Add component")) { ImGui::Text("Components"); ImGui::Separator(); for (Editor& editor : editors) { editor.addFunction(); } ImGui::EndPopup(); } for (Editor& editor : editors) { editor.editFunction(); } } } ImGui::End(); } void EntityEditor::SetEntity(Entity* entity) { this->entity = entity; strcpy(name, entity->name.c_str()); } bool EntityEditor::ShowsEntity(Entity* entity) { return this->entity == entity; } bool EntityEditor::IsVisible() const { return visible; } void EntityEditor::SetVisible(bool visible) { this->visible = visible; } void EntityEditor::AnimationEditor(Component::Animation* animation) { ImGui::Indent(); if (ImGui::Button("Select model##Animation")) ImGui::OpenPopup("Select model##Animation"); if (ImGui::BeginPopup("Select model##Animation")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) animation->riggedModel = dynamic_cast<Geometry::RiggedModel*>(model); } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::PhysicsEditor(Component::Physics* physics) { ImGui::Text("Positional"); ImGui::Indent(); ImGui::InputFloat3("Velocity", &physics->velocity[0]); ImGui::InputFloat("Max velocity", &physics->maxVelocity); ImGui::InputFloat3("Acceleration", &physics->acceleration[0]); ImGui::InputFloat("Velocity drag factor", &physics->velocityDragFactor); ImGui::InputFloat("Gravity factor", &physics->gravityFactor); ImGui::Unindent(); ImGui::Text("Angular"); ImGui::Indent(); ImGui::InputFloat3("Angular velocity", &physics->angularVelocity[0]); ImGui::InputFloat("Max angular velocity", &physics->maxAngularVelocity); ImGui::InputFloat3("Angular acceleration", &physics->angularAcceleration[0]); ImGui::InputFloat("Angular drag factor", &physics->angularDragFactor); ImGui::InputFloat3("Moment of inertia", &physics->momentOfInertia[0]); ImGui::Unindent(); } void EntityEditor::MeshEditor(Component::Mesh* mesh) { ImGui::Indent(); if (ImGui::Button("Select model##Mesh")) ImGui::OpenPopup("Select model##Mesh"); if (ImGui::BeginPopup("Select model##Mesh")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) mesh->geometry = model; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::LensEditor(Component::Lens* lens) { ImGui::Indent(); ImGui::InputFloat("Field of view", &lens->fieldOfView); ImGui::InputFloat("Z near", &lens->zNear); ImGui::InputFloat("Z far", &lens->zFar); ImGui::Unindent(); } void EntityEditor::MaterialEditor(Component::Material* material) { // Diffuse ImGui::Text("Diffuse"); ImGui::Indent(); if (material->diffuse->IsLoaded()) ImGui::Image((void*) material->diffuse->GetTextureID(), ImVec2(128, 128)); if (ImGui::Button("Select diffuse texture")) ImGui::OpenPopup("Select diffuse texture"); if (ImGui::BeginPopup("Select diffuse texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->diffuse = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Normal ImGui::Text("Normal"); ImGui::Indent(); if (ImGui::Button("Select normal texture")) ImGui::OpenPopup("Select normal texture"); if (ImGui::BeginPopup("Select normal texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->normal = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Specular ImGui::Text("Specular"); ImGui::Indent(); if (ImGui::Button("Select specular texture")) ImGui::OpenPopup("Select specular texture"); if (ImGui::BeginPopup("Select specular texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->specular = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Glow ImGui::Text("Glow"); ImGui::Indent(); if (ImGui::Button("Select glow texture")) ImGui::OpenPopup("Select glow texture"); if (ImGui::BeginPopup("Select glow texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->glow = texture; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::DirectionalLightEditor(Component::DirectionalLight* directionalLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &directionalLight->color[0]); ImGui::InputFloat("Ambient coefficient", &directionalLight->ambientCoefficient); ImGui::Unindent(); } void EntityEditor::PointLightEditor(Component::PointLight* pointLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &pointLight->color[0]); ImGui::InputFloat("Ambient coefficient", &pointLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &pointLight->attenuation); ImGui::InputFloat("Intensity", &pointLight->intensity); ImGui::Unindent(); } void EntityEditor::SpotLightEditor(Component::SpotLight* spotLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &spotLight->color[0]); ImGui::InputFloat("Ambient coefficient", &spotLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &spotLight->attenuation); ImGui::InputFloat("Intensity", &spotLight->intensity); ImGui::InputFloat("Cone angle", &spotLight->coneAngle); ImGui::Unindent(); } void EntityEditor::ListenerEditor(Component::Listener* listener) { } void EntityEditor::ScriptEditor(Component::Script* script) { ImGui::Indent(); if(script->scriptFile != nullptr) ImGui::Text(script->scriptFile->name.c_str()); else ImGui::Text("No script loaded"); if (ImGui::Button("Select script")) ImGui::OpenPopup("Select script"); if (ImGui::BeginPopup("Select script")) { ImGui::Text("Scripts"); ImGui::Separator(); for (ScriptFile* scriptFile : Hymn().scripts) { if (ImGui::Selectable(scriptFile->name.c_str())) script->scriptFile = scriptFile; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::SoundSourceEditor(Component::SoundSource* soundSource) { ImGui::Text("Sound"); ImGui::Indent(); if (ImGui::Button("Select sound")) ImGui::OpenPopup("Select sound"); if (ImGui::BeginPopup("Select sound")) { ImGui::Text("Sounds"); ImGui::Separator(); for (Audio::SoundBuffer* sound : Hymn().sounds) { if (ImGui::Selectable(sound->name.c_str())) soundSource->soundBuffer = sound; } ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Sound properties"); ImGui::Indent(); ImGui::InputFloat("Pitch", &soundSource->pitch); ImGui::InputFloat("Gain", &soundSource->gain); ImGui::Checkbox("Loop", &soundSource->loop); ImGui::Unindent(); } void EntityEditor::ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter) { ImGui::Text("Particle"); ImGui::Indent(); ImGui::InputInt("Texture index", &particleEmitter->particleType.textureIndex); ImGui::InputFloat3("Min velocity", &particleEmitter->particleType.minVelocity[0]); ImGui::InputFloat3("Max velocity", &particleEmitter->particleType.maxVelocity[0]); ImGui::InputFloat("Min lifetime", &particleEmitter->particleType.minLifetime); ImGui::InputFloat("Max lifetime", &particleEmitter->particleType.maxLifetime); ImGui::InputFloat2("Min size", &particleEmitter->particleType.minSize[0]); ImGui::InputFloat2("Max size", &particleEmitter->particleType.maxSize[0]); ImGui::Checkbox("Uniform scaling", &particleEmitter->particleType.uniformScaling); ImGui::InputFloat("Start alpha", &particleEmitter->particleType.startAlpha); ImGui::InputFloat("Mid alpha", &particleEmitter->particleType.midAlpha); ImGui::InputFloat("End alpha", &particleEmitter->particleType.endAlpha); ImGui::InputFloat3("Color", &particleEmitter->particleType.color[0]); ImGui::Unindent(); ImGui::Text("Emitter"); ImGui::Indent(); ImGui::InputFloat3("Size", &particleEmitter->size[0]); ImGui::InputFloat("Min emit time", &particleEmitter->minEmitTime); ImGui::InputFloat("Max emit time", &particleEmitter->maxEmitTime); if (ImGui::Button("Emitter type")) ImGui::OpenPopup("Emitter type"); if (ImGui::BeginPopup("Emitter type")) { ImGui::Text("Emitter type"); ImGui::Separator(); if (ImGui::Selectable("Point")) particleEmitter->emitterType = Component::ParticleEmitter::POINT; if (ImGui::Selectable("Cuboid")) particleEmitter->emitterType = Component::ParticleEmitter::CUBOID; ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Preview"); ImGui::Indent(); ImGui::Unindent(); } <|endoftext|>
<commit_before>/** * @file * * @brief This file contains a basic YAML to `KeySet` converter function. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <cstdio> #include <fstream> #include <iostream> #include <sstream> #include <yaep.h> #include <kdberrors.h> #include "convert.hpp" #include "error_listener.hpp" #include "lexer.hpp" #include "listener.hpp" #include "memory.hpp" #include "walk.hpp" using std::cerr; using std::cout; using std::endl; using std::ifstream; using std::string; using std::stringstream; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using ckdb::keyNew; namespace { // -- Globals ------------------------------------------------------------------------------------------------------------------------------ ErrorListener * errorListenerAdress; Lexer * lexerAddress; Memory * parserMemoryAddress; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- /** * @brief This function returns the next token produced by the lexer. * * If the lexer found the end of the input, then this function returns `-1`. * * @param attribute The parser uses this parameter to store auxiliary data for * the returned token. * * @return A number specifying the type of the first token the parser has not * emitted yet */ int nextToken (void ** attribute) { return lexerAddress->nextToken (attribute); } /** * @brief This function reacts to syntax errors reported by YAEP’s parsing * engine. * * @param errorToken This number specifies the token where the error occurred. * @param errorTokenData This variable stores the data contained in * `errorToken`. * @param ignoredToken This number specifies the first token that was ignored * during error recovery. * @param ignoredTokenData This variable stores the data contained in * `ignoredToken`. * @param recoveredToken This number specifies the first included token after * the error recovery has taken place. * @param recoveredTokenData This variable stores the data contained in * `recoveredToken`. */ void syntaxError (int errorToken, void * errorTokenData, int ignoredToken, void * ignoredTokenData, int recoveredToken, void * recoveredTokenData) { return errorListenerAdress->syntaxError (errorToken, errorTokenData, ignoredToken, ignoredTokenData, recoveredToken, recoveredTokenData); } /** * This function allocates a memory region of the given size. * * @param size This variable specifies the amount of data this method should * allocate. * * @return A pointer to a memory region of the specified size */ void * alloc (int size) { return parserMemoryAddress->allocate (size); } } // namespace /** * @brief This function converts the given YAML file to keys and adds the * result to `keySet`. * * @param keySet The function adds the converted keys to this variable. * @param parent The function uses this parent key of `keySet` to emit error * information. * @param filename This parameter stores the path of the YAML file this * function converts. * * @retval -2 if the file could not be opened for reading * @retval -1 if there was a error converting the YAML file * @retval 0 if parsing was successful and the function did not change the * given key set * @retval 1 if parsing was successful and the function did change `keySet` */ int addToKeySet (CppKeySet & keySet, CppKey & parent, string const & filename) { string const grammar = #include "yaml.h" ; yaep parser; if (parser.parse_grammar (1, grammar.c_str ()) != 0) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, parent.getKey (), "Unable to parse grammar: %s", parser.error_message ()); return -1; } Memory memory; parserMemoryAddress = &memory; ErrorListener errorListener; errorListenerAdress = &errorListener; ifstream input{ filename }; if (!input.good ()) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”", filename.c_str ()); return -2; } Lexer lexer{ input }; lexerAddress = &lexer; int ambiguousOutput; struct yaep_tree_node * root = nullptr; parser.parse (nextToken, syntaxError, alloc, nullptr, &root, &ambiguousOutput); if (ambiguousOutput) { ELEKTRA_SET_ERRORF ( ELEKTRA_ERROR_PARSE, parent.getKey (), "The content of file “%s” showed that the grammar:\n%s\nproduces ambiguous output!\n" "Please fix the grammar, to make sure it produces only one unique syntax tree for every kind of YAML input.", filename.c_str (), grammar.c_str ()); return -1; } if (errorListener.getNumberOfErrors () > 0) { ELEKTRA_SET_ERROR (ELEKTRA_ERROR_PARSE, parent.getKey (), errorListener.getErrorMessage ().c_str ()); return -1; } Listener listener{ parent }; walk (listener, root); keySet.append (listener.getKeySet ()); return listener.getKeySet ().size () > 0; } <commit_msg>YAwn: Split code of function `addToKeySet`<commit_after>/** * @file * * @brief This file contains a basic YAML to `KeySet` converter function. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <cstdio> #include <fstream> #include <iostream> #include <sstream> #include <yaep.h> #include <kdberrors.h> #include "convert.hpp" #include "error_listener.hpp" #include "lexer.hpp" #include "listener.hpp" #include "memory.hpp" #include "walk.hpp" using std::cerr; using std::cout; using std::endl; using std::ifstream; using std::string; using std::stringstream; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using ckdb::keyNew; namespace { // -- Globals ------------------------------------------------------------------------------------------------------------------------------ ErrorListener * errorListenerAdress; Lexer * lexerAddress; Memory * parserMemoryAddress; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- /** * @brief This function returns the next token produced by the lexer. * * If the lexer found the end of the input, then this function returns `-1`. * * @param attribute The parser uses this parameter to store auxiliary data for * the returned token. * * @return A number specifying the type of the first token the parser has not * emitted yet */ int nextToken (void ** attribute) { return lexerAddress->nextToken (attribute); } /** * @brief This function reacts to syntax errors reported by YAEP’s parsing * engine. * * @param errorToken This number specifies the token where the error occurred. * @param errorTokenData This variable stores the data contained in * `errorToken`. * @param ignoredToken This number specifies the first token that was ignored * during error recovery. * @param ignoredTokenData This variable stores the data contained in * `ignoredToken`. * @param recoveredToken This number specifies the first included token after * the error recovery has taken place. * @param recoveredTokenData This variable stores the data contained in * `recoveredToken`. */ void syntaxError (int errorToken, void * errorTokenData, int ignoredToken, void * ignoredTokenData, int recoveredToken, void * recoveredTokenData) { return errorListenerAdress->syntaxError (errorToken, errorTokenData, ignoredToken, ignoredTokenData, recoveredToken, recoveredTokenData); } /** * This function allocates a memory region of the given size. * * @param size This variable specifies the amount of data this method should * allocate. * * @return A pointer to a memory region of the specified size */ void * alloc (int size) { return parserMemoryAddress->allocate (size); } /** * @brief This function parses the YAML grammar contained in `yaml.bnf`. * * @param parser This variable stores the YAEP parser that uses the YAML grammar contained in `yaml.bnf` to parse input. * @param error This function stores error information in this key, if it was unable to parse the grammar. * * @return A string containing the content of `yaml.bnf`, if parsing of the grammar was successful, or an empty string otherwise */ string parseGrammar (yaep & parser, CppKey & error) { string grammar = #include "yaml.h" ; if (parser.parse_grammar (1, grammar.c_str ()) != 0) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, error.getKey (), "Unable to parse grammar: %s", parser.error_message ()); return ""; } return grammar; } /** * @brief This function creates a stream containing the content of a given file. * * @param filename This variable stores location of the file for which this function creates an input stream * @param error This function stores an error message in this key, if it was unable to access `filename`. * * @return A input stream that contains the content of `filename`, if creating the stream was successful */ ifstream openFile (string const & filename, CppKey & error) { ifstream input{ filename }; if (!input.good ()) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, error.getKey (), "Unable to open file “%s”", filename.c_str ()); } return input; } /** * @brief This function stores error information in `error`, if parsing was unsuccessful. * * @param ambiguousOutput This variable is true, when YAEP was unable to create a unique syntax tree from the given input. * @param errorListener This object stores information about errors that occurred while YAEP parsed the input. * @param filename This variable stores the location of the file YAEP parsed. * @param grammar This argument stores the YAML grammar used to parse the input. * @param error This function will use this variable to store information about errors that occurred while parsing. * * @retval -1 If there was an error parsing the last input * @retval 0 Otherwise */ int handleErrors (int const ambiguousOutput, ErrorListener const & errorListener, string const & filename, string const & grammar, CppKey & error) { if (ambiguousOutput) { ELEKTRA_SET_ERRORF ( ELEKTRA_ERROR_PARSE, error.getKey (), "The content of file “%s” showed that the grammar:\n%s\nproduces ambiguous output!\n" "Please fix the grammar, to make sure it produces only one unique syntax tree for every kind of YAML input.", filename.c_str (), grammar.c_str ()); return -1; } if (errorListener.getNumberOfErrors () > 0) { ELEKTRA_SET_ERROR (ELEKTRA_ERROR_PARSE, error.getKey (), errorListener.getErrorMessage ().c_str ()); return -1; } return 0; } } // namespace /** * @brief This function converts the given YAML file to keys and adds the * result to `keySet`. * * @param keySet The function adds the converted keys to this variable. * @param parent The function uses this parent key of `keySet` to emit error * information. * @param filename This parameter stores the path of the YAML file this * function converts. * * @retval -2 if the file could not be opened for reading * @retval -1 if there was a error converting the YAML file * @retval 0 if parsing was successful and the function did not change the * given key set * @retval 1 if parsing was successful and the function did change `keySet` */ int addToKeySet (CppKeySet & keySet, CppKey & parent, string const & filename) { yaep parser; auto grammar = parseGrammar (parser, parent); if (grammar.size () <= 0) return -1; auto input = openFile (filename, parent); if (!input.good ()) return -1; Memory memory; parserMemoryAddress = &memory; ErrorListener errorListener; errorListenerAdress = &errorListener; Lexer lexer{ input }; lexerAddress = &lexer; int ambiguousOutput; struct yaep_tree_node * root = nullptr; parser.parse (nextToken, syntaxError, alloc, nullptr, &root, &ambiguousOutput); if (handleErrors (ambiguousOutput, errorListener, filename, grammar, parent) < 0) return -1; Listener listener{ parent }; walk (listener, root); keySet.append (listener.getKeySet ()); return listener.getKeySet ().size () > 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/framework/executor.h" #include <set> #include "gflags/gflags.h" #include "paddle/framework/feed_fetch_type.h" #include "paddle/framework/lod_rank_table.h" #include "paddle/framework/lod_tensor_array.h" #include "paddle/framework/op_registry.h" DEFINE_bool(check_nan_inf, false, "Checking whether operator produce NAN/INF or not. It will be " "extremely slow so please use this flag wisely."); namespace paddle { namespace framework { const std::string kFeedOpType = "feed"; const std::string kFetchOpType = "fetch"; Executor::Executor(const platform::Place& place) : place_(place) {} static void CreateTensor(Variable* var, proto::VarDesc::VarType var_type) { if (var_type == proto::VarDesc::LOD_TENSOR) { var->GetMutable<LoDTensor>(); } else if (var_type == proto::VarDesc::SELECTED_ROWS) { var->GetMutable<SelectedRows>(); } else if (var_type == proto::VarDesc::FEED_MINIBATCH) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::FETCH_LIST) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::STEP_SCOPES) { var->GetMutable<std::vector<framework::Scope>>(); } else if (var_type == proto::VarDesc::LOD_RANK_TABLE) { var->GetMutable<LoDRankTable>(); } else if (var_type == proto::VarDesc::LOD_TENSOR_ARRAY) { var->GetMutable<LoDTensorArray>(); } else { PADDLE_THROW( "Variable type %d is not in " "[LoDTensor, SelectedRows, FEED_MINIBATCH, FETCH_LIST, LOD_RANK_TABLE]", var_type); } } static void CheckTensorNANOrInf(const std::string& name, const framework::Tensor& tensor) { if (tensor.memory_size() == 0) { return; } if (tensor.type().hash_code() != typeid(float).hash_code() && tensor.type().hash_code() != typeid(double).hash_code()) { return; } PADDLE_ENFORCE(!framework::HasInf(tensor), "Tensor %s has Inf", name); PADDLE_ENFORCE(!framework::HasNAN(tensor), "Tensor %s has NAN, %p", name, &tensor); } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id, bool create_local_scope, bool create_vars) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_LT(static_cast<size_t>(block_id), pdesc.Size()); auto& block = pdesc.Block(block_id); Scope* local_scope = scope; if (create_vars) { if (create_local_scope) { local_scope = &scope->NewScope(); for (auto& var : block.AllVars()) { if (var->Name() == framework::kEmptyVarName) { continue; } if (var->Persistable()) { auto* ptr = scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " global, which pointer is " << ptr; } else { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " locally, which pointer is " << ptr; } } } else { for (auto& var : block.AllVars()) { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create variable " << var->Name() << ", which pointer is " << ptr; } } // if (create_local_scope) } // if (create_vars) for (auto& op_desc : block.AllOps()) { auto op = paddle::framework::OpRegistry::CreateOp(*op_desc); VLOG(3) << op->DebugString(); op->Run(*local_scope, place_); if (FLAGS_check_nan_inf) { for (auto& vname : op->OutputVars(true)) { auto* var = local_scope->FindVar(vname); if (var == nullptr) continue; if (var->IsType<framework::LoDTensor>()) { CheckTensorNANOrInf(vname, var->Get<framework::LoDTensor>()); } } } } if (create_vars && create_local_scope) { scope->DeleteScope(local_scope); } } } // namespace framework } // namespace paddle <commit_msg>Remove debug codes<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/framework/executor.h" #include <set> #include "gflags/gflags.h" #include "paddle/framework/feed_fetch_type.h" #include "paddle/framework/lod_rank_table.h" #include "paddle/framework/lod_tensor_array.h" #include "paddle/framework/op_registry.h" DEFINE_bool(check_nan_inf, false, "Checking whether operator produce NAN/INF or not. It will be " "extremely slow so please use this flag wisely."); namespace paddle { namespace framework { const std::string kFeedOpType = "feed"; const std::string kFetchOpType = "fetch"; Executor::Executor(const platform::Place& place) : place_(place) {} static void CreateTensor(Variable* var, proto::VarDesc::VarType var_type) { if (var_type == proto::VarDesc::LOD_TENSOR) { var->GetMutable<LoDTensor>(); } else if (var_type == proto::VarDesc::SELECTED_ROWS) { var->GetMutable<SelectedRows>(); } else if (var_type == proto::VarDesc::FEED_MINIBATCH) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::FETCH_LIST) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::STEP_SCOPES) { var->GetMutable<std::vector<framework::Scope>>(); } else if (var_type == proto::VarDesc::LOD_RANK_TABLE) { var->GetMutable<LoDRankTable>(); } else if (var_type == proto::VarDesc::LOD_TENSOR_ARRAY) { var->GetMutable<LoDTensorArray>(); } else { PADDLE_THROW( "Variable type %d is not in " "[LoDTensor, SelectedRows, FEED_MINIBATCH, FETCH_LIST, LOD_RANK_TABLE]", var_type); } } static void CheckTensorNANOrInf(const std::string& name, const framework::Tensor& tensor) { if (tensor.memory_size() == 0) { return; } if (tensor.type().hash_code() != typeid(float).hash_code() && tensor.type().hash_code() != typeid(double).hash_code()) { return; } PADDLE_ENFORCE(!framework::HasInf(tensor), "Tensor %s has Inf", name); PADDLE_ENFORCE(!framework::HasNAN(tensor), "Tensor %s has NAN", name); } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id, bool create_local_scope, bool create_vars) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_LT(static_cast<size_t>(block_id), pdesc.Size()); auto& block = pdesc.Block(block_id); Scope* local_scope = scope; if (create_vars) { if (create_local_scope) { local_scope = &scope->NewScope(); for (auto& var : block.AllVars()) { if (var->Name() == framework::kEmptyVarName) { continue; } if (var->Persistable()) { auto* ptr = scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " global, which pointer is " << ptr; } else { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " locally, which pointer is " << ptr; } } } else { for (auto& var : block.AllVars()) { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create variable " << var->Name() << ", which pointer is " << ptr; } } // if (create_local_scope) } // if (create_vars) for (auto& op_desc : block.AllOps()) { auto op = paddle::framework::OpRegistry::CreateOp(*op_desc); VLOG(3) << op->DebugString(); op->Run(*local_scope, place_); if (FLAGS_check_nan_inf) { for (auto& vname : op->OutputVars(true)) { auto* var = local_scope->FindVar(vname); if (var == nullptr) continue; if (var->IsType<framework::LoDTensor>()) { CheckTensorNANOrInf(vname, var->Get<framework::LoDTensor>()); } } } } if (create_vars && create_local_scope) { scope->DeleteScope(local_scope); } } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: chartlock.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2007-08-03 13:07:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <vcl/svapp.hxx> #include "chartlock.hxx" #include "document.hxx" #include "drwlayer.hxx" #include <svx/svditer.hxx> #include <svx/svdoole2.hxx> using namespace com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::WeakReference; #define SC_CHARTLOCKTIMEOUT 660 // ==================================================================== namespace { std::vector< WeakReference< frame::XModel > > lcl_getAllLivingCharts( ScDocument* pDoc ) { std::vector< WeakReference< frame::XModel > > aRet; if( !pDoc ) return aRet; ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer(); if (!pDrawLayer) return aRet; for (SCTAB nTab=0; nTab<=pDoc->GetMaxTableNumber(); nTab++) { if (pDoc->HasTable(nTab)) { SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab)); DBG_ASSERT(pPage,"Page ?"); SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS ); SdrObject* pObject = aIter.Next(); while (pObject) { if( pDoc->IsChart( pObject ) ) { uno::Reference< embed::XEmbeddedObject > xIPObj = ((SdrOle2Obj*)pObject)->GetObjRef(); uno::Reference< embed::XComponentSupplier > xCompSupp( xIPObj, uno::UNO_QUERY ); if( xCompSupp.is()) { Reference< frame::XModel > xModel( xCompSupp->getComponent(), uno::UNO_QUERY ); if( xModel.is() ) aRet.push_back( xModel ); } } pObject = aIter.Next(); } } } return aRet; } }//end anonymous namespace // === ScChartLockGuard ====================================== ScChartLockGuard::ScChartLockGuard( ScDocument* pDoc ) : maChartModels( lcl_getAllLivingCharts( pDoc ) ) { std::vector< WeakReference< frame::XModel > >::const_iterator aIter = maChartModels.begin(); const std::vector< WeakReference< frame::XModel > >::const_iterator aEnd = maChartModels.end(); for( ; aIter != aEnd; ++aIter ) { try { Reference< frame::XModel > xModel( *aIter ); if( xModel.is()) xModel->lockControllers(); } catch ( uno::Exception& ) { DBG_ERROR("Unexpected exception in ScChartLockGuard"); } } } ScChartLockGuard::~ScChartLockGuard() { std::vector< WeakReference< frame::XModel > >::const_iterator aIter = maChartModels.begin(); const std::vector< WeakReference< frame::XModel > >::const_iterator aEnd = maChartModels.end(); for( ; aIter != aEnd; ++aIter ) { try { Reference< frame::XModel > xModel( *aIter ); if( xModel.is()) xModel->unlockControllers(); } catch ( uno::Exception& ) { DBG_ERROR("Unexpected exception in ScChartLockGuard"); } } } void ScChartLockGuard::AlsoLockThisChart( const Reference< frame::XModel >& xModel ) { if(!xModel.is()) return; WeakReference< frame::XModel > xWeakModel(xModel); std::vector< WeakReference< frame::XModel > >::iterator aFindIter( ::std::find( maChartModels.begin(), maChartModels.end(), xWeakModel ) ); if( aFindIter == maChartModels.end() ) { try { xModel->lockControllers(); maChartModels.push_back( xModel ); } catch ( uno::Exception& ) { DBG_ERROR("Unexpected exception in ScChartLockGuard"); } } } // === ScTemporaryChartLock ====================================== ScTemporaryChartLock::ScTemporaryChartLock( ScDocument* pDocP ) : mpDoc( pDocP ) { maTimer.SetTimeout( SC_CHARTLOCKTIMEOUT ); maTimer.SetTimeoutHdl( LINK( this, ScTemporaryChartLock, TimeoutHdl ) ); } ScTemporaryChartLock::~ScTemporaryChartLock() { mpDoc = 0; StopLocking(); } void ScTemporaryChartLock::StartOrContinueLocking() { if(!mapScChartLockGuard.get()) mapScChartLockGuard = std::auto_ptr< ScChartLockGuard >( new ScChartLockGuard(mpDoc) ); maTimer.Start(); } void ScTemporaryChartLock::StopLocking() { maTimer.Stop(); mapScChartLockGuard.reset(); } void ScTemporaryChartLock::AlsoLockThisChart( const Reference< frame::XModel >& xModel ) { if(mapScChartLockGuard.get()) mapScChartLockGuard->AlsoLockThisChart( xModel ); } IMPL_LINK( ScTemporaryChartLock, TimeoutHdl, Timer*, EMPTYARG ) { mapScChartLockGuard.reset(); return 0; } <commit_msg>INTEGRATION: CWS dr58_SRC680 (1.2.76); FILE MERGED 2008/01/11 12:45:44 dr 1.2.76.1: #i84412# set note visibility when copying cells, remove global depenencies from postit.hxx header<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: chartlock.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2008-01-29 15:21:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <vcl/svapp.hxx> #include <svx/svditer.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include "chartlock.hxx" #include "document.hxx" #include "drwlayer.hxx" using namespace com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::WeakReference; #define SC_CHARTLOCKTIMEOUT 660 // ==================================================================== namespace { std::vector< WeakReference< frame::XModel > > lcl_getAllLivingCharts( ScDocument* pDoc ) { std::vector< WeakReference< frame::XModel > > aRet; if( !pDoc ) return aRet; ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer(); if (!pDrawLayer) return aRet; for (SCTAB nTab=0; nTab<=pDoc->GetMaxTableNumber(); nTab++) { if (pDoc->HasTable(nTab)) { SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab)); DBG_ASSERT(pPage,"Page ?"); SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS ); SdrObject* pObject = aIter.Next(); while (pObject) { if( pDoc->IsChart( pObject ) ) { uno::Reference< embed::XEmbeddedObject > xIPObj = ((SdrOle2Obj*)pObject)->GetObjRef(); uno::Reference< embed::XComponentSupplier > xCompSupp( xIPObj, uno::UNO_QUERY ); if( xCompSupp.is()) { Reference< frame::XModel > xModel( xCompSupp->getComponent(), uno::UNO_QUERY ); if( xModel.is() ) aRet.push_back( xModel ); } } pObject = aIter.Next(); } } } return aRet; } }//end anonymous namespace // === ScChartLockGuard ====================================== ScChartLockGuard::ScChartLockGuard( ScDocument* pDoc ) : maChartModels( lcl_getAllLivingCharts( pDoc ) ) { std::vector< WeakReference< frame::XModel > >::const_iterator aIter = maChartModels.begin(); const std::vector< WeakReference< frame::XModel > >::const_iterator aEnd = maChartModels.end(); for( ; aIter != aEnd; ++aIter ) { try { Reference< frame::XModel > xModel( *aIter ); if( xModel.is()) xModel->lockControllers(); } catch ( uno::Exception& ) { DBG_ERROR("Unexpected exception in ScChartLockGuard"); } } } ScChartLockGuard::~ScChartLockGuard() { std::vector< WeakReference< frame::XModel > >::const_iterator aIter = maChartModels.begin(); const std::vector< WeakReference< frame::XModel > >::const_iterator aEnd = maChartModels.end(); for( ; aIter != aEnd; ++aIter ) { try { Reference< frame::XModel > xModel( *aIter ); if( xModel.is()) xModel->unlockControllers(); } catch ( uno::Exception& ) { DBG_ERROR("Unexpected exception in ScChartLockGuard"); } } } void ScChartLockGuard::AlsoLockThisChart( const Reference< frame::XModel >& xModel ) { if(!xModel.is()) return; WeakReference< frame::XModel > xWeakModel(xModel); std::vector< WeakReference< frame::XModel > >::iterator aFindIter( ::std::find( maChartModels.begin(), maChartModels.end(), xWeakModel ) ); if( aFindIter == maChartModels.end() ) { try { xModel->lockControllers(); maChartModels.push_back( xModel ); } catch ( uno::Exception& ) { DBG_ERROR("Unexpected exception in ScChartLockGuard"); } } } // === ScTemporaryChartLock ====================================== ScTemporaryChartLock::ScTemporaryChartLock( ScDocument* pDocP ) : mpDoc( pDocP ) { maTimer.SetTimeout( SC_CHARTLOCKTIMEOUT ); maTimer.SetTimeoutHdl( LINK( this, ScTemporaryChartLock, TimeoutHdl ) ); } ScTemporaryChartLock::~ScTemporaryChartLock() { mpDoc = 0; StopLocking(); } void ScTemporaryChartLock::StartOrContinueLocking() { if(!mapScChartLockGuard.get()) mapScChartLockGuard = std::auto_ptr< ScChartLockGuard >( new ScChartLockGuard(mpDoc) ); maTimer.Start(); } void ScTemporaryChartLock::StopLocking() { maTimer.Stop(); mapScChartLockGuard.reset(); } void ScTemporaryChartLock::AlsoLockThisChart( const Reference< frame::XModel >& xModel ) { if(mapScChartLockGuard.get()) mapScChartLockGuard->AlsoLockThisChart( xModel ); } IMPL_LINK( ScTemporaryChartLock, TimeoutHdl, Timer*, EMPTYARG ) { mapScChartLockGuard.reset(); return 0; } <|endoftext|>
<commit_before>/** * folderdialogquotatab_p.cpp * * Copyright (c) 2006 Till Adam <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "folderdialogquotatab_p.h" #include <qlayout.h> #include <qlabel.h> #include <qprogressbar.h> #include <qwhatsthis.h> #include <qcombobox.h> #include <math.h> #include "kmkernel.h" #include "klocale.h" #include "kconfig.h" #include "kdebug.h" #include "kdialog.h" #include "globalsettings.h" #include "quotajobs.h" using namespace KMail; struct QuotaInfo; QuotaWidget::QuotaWidget( QWidget* parent, const char* name ) :QWidget( parent ) { setObjectName( name ); QVBoxLayout *box = new QVBoxLayout(this); QWidget *stuff = new QWidget( this ); QGridLayout* layout = new QGridLayout( stuff, 3, 3, KDialog::marginHint(), KDialog::spacingHint() ); mInfoLabel = new QLabel("", stuff ); mRootLabel = new QLabel("", stuff ); mProgressBar = new QProgressBar( stuff ); layout->addWidget( new QLabel( i18n("Root:" ), stuff ), 0, 0 ); layout->addWidget( mRootLabel, 0, 1 ); layout->addWidget( new QLabel( i18n("Usage:"), stuff ), 1, 0 ); //layout->addWidget( new QLabel( i18n("Status:"), stuff ), 2, 0 ); layout->addWidget( mInfoLabel, 1, 1 ); layout->addWidget( mProgressBar, 2, 1 ); box->addWidget( stuff ); box->addStretch( 2 ); readConfig(); } void QuotaWidget::setQuotaInfo( const QuotaInfo& info ) { // we are assuming only to get STORAGE type info here, thus // casting to int is safe int current = info.current().toInt(); int max = info.max().toInt(); int factor = static_cast<int> ( pow( 1000, mFactor ) ); mProgressBar->setMaximum( max ); mProgressBar->setValue( current ); mInfoLabel->setText( i18n("%1 of %2 %3 used", current/factor, max/factor, mUnits ) ); mRootLabel->setText( info.root() ); } void QuotaWidget::readConfig() { if( GlobalSettings::self()->quotaUnit() == GlobalSettings::EnumQuotaUnit::KB ) { mUnits = QString( i18n("KB") ); mFactor = 0; } else if( GlobalSettings::self()->quotaUnit() == GlobalSettings::EnumQuotaUnit::MB ) { mUnits = QString( i18n("MB") ); mFactor = 1; } else if( GlobalSettings::self()->quotaUnit() == GlobalSettings::EnumQuotaUnit::GB ) { mUnits = QString( i18n("GB") ); mFactor = 2; } } #include "folderdialogquotatab_p.moc" <commit_msg>SVN_SILENT compile<commit_after>/** * folderdialogquotatab_p.cpp * * Copyright (c) 2006 Till Adam <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "folderdialogquotatab_p.h" #include <qlayout.h> #include <qlabel.h> #include <qprogressbar.h> #include <qwhatsthis.h> #include <qcombobox.h> #include <math.h> #include "kmkernel.h" #include "klocale.h" #include "kconfig.h" #include "kdebug.h" #include "kdialog.h" #include "globalsettings.h" #include "quotajobs.h" namespace KMail { class QuotaInfo; } using namespace KMail; QuotaWidget::QuotaWidget( QWidget* parent, const char* name ) :QWidget( parent ) { setObjectName( name ); QVBoxLayout *box = new QVBoxLayout(this); QWidget *stuff = new QWidget( this ); QGridLayout* layout = new QGridLayout( stuff, 3, 3, KDialog::marginHint(), KDialog::spacingHint() ); mInfoLabel = new QLabel("", stuff ); mRootLabel = new QLabel("", stuff ); mProgressBar = new QProgressBar( stuff ); layout->addWidget( new QLabel( i18n("Root:" ), stuff ), 0, 0 ); layout->addWidget( mRootLabel, 0, 1 ); layout->addWidget( new QLabel( i18n("Usage:"), stuff ), 1, 0 ); //layout->addWidget( new QLabel( i18n("Status:"), stuff ), 2, 0 ); layout->addWidget( mInfoLabel, 1, 1 ); layout->addWidget( mProgressBar, 2, 1 ); box->addWidget( stuff ); box->addStretch( 2 ); readConfig(); } void QuotaWidget::setQuotaInfo( const QuotaInfo& info ) { // we are assuming only to get STORAGE type info here, thus // casting to int is safe int current = info.current().toInt(); int max = info.max().toInt(); int factor = static_cast<int> ( pow( 1000, mFactor ) ); mProgressBar->setMaximum( max ); mProgressBar->setValue( current ); mInfoLabel->setText( i18n("%1 of %2 %3 used", current/factor, max/factor, mUnits ) ); mRootLabel->setText( info.root() ); } void QuotaWidget::readConfig() { if( GlobalSettings::self()->quotaUnit() == GlobalSettings::EnumQuotaUnit::KB ) { mUnits = QString( i18n("KB") ); mFactor = 0; } else if( GlobalSettings::self()->quotaUnit() == GlobalSettings::EnumQuotaUnit::MB ) { mUnits = QString( i18n("MB") ); mFactor = 1; } else if( GlobalSettings::self()->quotaUnit() == GlobalSettings::EnumQuotaUnit::GB ) { mUnits = QString( i18n("GB") ); mFactor = 2; } } #include "folderdialogquotatab_p.moc" <|endoftext|>
<commit_before>#include "EntityEditor.hpp" #include <Engine/Component/Animation.hpp> #include <Engine/Component/Physics.hpp> #include <Engine/Component/Mesh.hpp> #include <Engine/Component/Lens.hpp> #include <Engine/Component/Material.hpp> #include <Engine/Component/DirectionalLight.hpp> #include <Engine/Component/PointLight.hpp> #include <Engine/Component/SpotLight.hpp> #include <Engine/Component/Listener.hpp> #include <Engine/Component/Script.hpp> #include <Engine/Component/SoundSource.hpp> #include <Engine/Component/ParticleEmitter.hpp> #include <Engine/Hymn.hpp> #include <Engine/Geometry/Model.hpp> #include <Engine/Geometry/RiggedModel.hpp> #include <Engine/Texture/Texture2D.hpp> #include <Engine/Audio/SoundBuffer.hpp> #include <Engine/Script/ScriptFile.hpp> #include <Engine/Util/FileSystem.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include "../../Util/EditorSettings.hpp" #include "../FileSelector.hpp" using namespace GUI; EntityEditor::EntityEditor() { name[0] = '\0'; AddEditor<Component::Animation>("Animation", std::bind(&EntityEditor::AnimationEditor, this, std::placeholders::_1)); AddEditor<Component::Physics>("Physics", std::bind(&EntityEditor::PhysicsEditor, this, std::placeholders::_1)); AddEditor<Component::Mesh>("Mesh", std::bind(&EntityEditor::MeshEditor, this, std::placeholders::_1)); AddEditor<Component::Lens>("Lens", std::bind(&EntityEditor::LensEditor, this, std::placeholders::_1)); AddEditor<Component::Material>("Material", std::bind(&EntityEditor::MaterialEditor, this, std::placeholders::_1)); AddEditor<Component::DirectionalLight>("Directional light", std::bind(&EntityEditor::DirectionalLightEditor, this, std::placeholders::_1)); AddEditor<Component::PointLight>("Point light", std::bind(&EntityEditor::PointLightEditor, this, std::placeholders::_1)); AddEditor<Component::SpotLight>("Spot light", std::bind(&EntityEditor::SpotLightEditor, this, std::placeholders::_1)); AddEditor<Component::Listener>("Listener", std::bind(&EntityEditor::ListenerEditor, this, std::placeholders::_1)); AddEditor<Component::Script>("Script", std::bind(&EntityEditor::ScriptEditor, this, std::placeholders::_1)); AddEditor<Component::SoundSource>("Sound source", std::bind(&EntityEditor::SoundSourceEditor, this, std::placeholders::_1)); AddEditor<Component::ParticleEmitter>("Particle emitter", std::bind(&EntityEditor::ParticleEmitterEditor, this, std::placeholders::_1)); } EntityEditor::~EntityEditor() { } void EntityEditor::Show() { if (ImGui::Begin(("Entity: " + entity->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(entity))).c_str(), &visible)) { ImGui::InputText("Name", name, 128); entity->name = name; ImGui::Text("Transform"); ImGui::Indent(); ImGui::InputFloat3("Position", &entity->position[0]); ImGui::InputFloat3("Rotation", &entity->rotation[0]); ImGui::InputFloat3("Scale", &entity->scale[0]); ImGui::Unindent(); if (!entity->IsScene()) { if (ImGui::Button("Add component")) ImGui::OpenPopup("Add component"); if (ImGui::BeginPopup("Add component")) { ImGui::Text("Components"); ImGui::Separator(); for (Editor& editor : editors) { editor.addFunction(); } ImGui::EndPopup(); } for (Editor& editor : editors) { editor.editFunction(); } } } ImGui::End(); } void EntityEditor::SetEntity(Entity* entity) { this->entity = entity; strcpy(name, entity->name.c_str()); } bool EntityEditor::ShowsEntity(Entity* entity) { return this->entity == entity; } bool EntityEditor::IsVisible() const { return visible; } void EntityEditor::SetVisible(bool visible) { this->visible = visible; } void EntityEditor::AnimationEditor(Component::Animation* animation) { ImGui::Indent(); if (ImGui::Button("Select model##Animation")) ImGui::OpenPopup("Select model##Animation"); if (ImGui::BeginPopup("Select model##Animation")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) animation->riggedModel = dynamic_cast<Geometry::RiggedModel*>(model); } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::PhysicsEditor(Component::Physics* physics) { ImGui::Text("Positional"); ImGui::Indent(); ImGui::InputFloat3("Velocity", &physics->velocity[0]); ImGui::InputFloat("Max velocity", &physics->maxVelocity); ImGui::InputFloat3("Acceleration", &physics->acceleration[0]); ImGui::InputFloat("Velocity drag factor", &physics->velocityDragFactor); ImGui::InputFloat("Gravity factor", &physics->gravityFactor); ImGui::Unindent(); ImGui::Text("Angular"); ImGui::Indent(); ImGui::InputFloat3("Angular velocity", &physics->angularVelocity[0]); ImGui::InputFloat("Max angular velocity", &physics->maxAngularVelocity); ImGui::InputFloat3("Angular acceleration", &physics->angularAcceleration[0]); ImGui::InputFloat("Angular drag factor", &physics->angularDragFactor); ImGui::InputFloat3("Moment of inertia", &physics->momentOfInertia[0]); ImGui::Unindent(); } void EntityEditor::MeshEditor(Component::Mesh* mesh) { ImGui::Indent(); if (ImGui::Button("Select model##Mesh")) ImGui::OpenPopup("Select model##Mesh"); if (ImGui::BeginPopup("Select model##Mesh")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) mesh->geometry = model; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::LensEditor(Component::Lens* lens) { ImGui::Indent(); ImGui::InputFloat("Field of view", &lens->fieldOfView); ImGui::InputFloat("Z near", &lens->zNear); ImGui::InputFloat("Z far", &lens->zFar); ImGui::Unindent(); } void EntityEditor::MaterialEditor(Component::Material* material) { // Diffuse ImGui::Text("Diffuse"); ImGui::Indent(); if (material->diffuse->IsLoaded()) ImGui::Image((void*) material->diffuse->GetTextureID(), ImVec2(128, 128)); if (ImGui::Button("Select diffuse texture")) ImGui::OpenPopup("Select diffuse texture"); if (ImGui::BeginPopup("Select diffuse texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->diffuse = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Normal ImGui::Text("Normal"); ImGui::Indent(); if (ImGui::Button("Select normal texture")) ImGui::OpenPopup("Select normal texture"); if (ImGui::BeginPopup("Select normal texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->normal = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Specular ImGui::Text("Specular"); ImGui::Indent(); if (ImGui::Button("Select specular texture")) ImGui::OpenPopup("Select specular texture"); if (ImGui::BeginPopup("Select specular texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->specular = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Glow ImGui::Text("Glow"); ImGui::Indent(); if (ImGui::Button("Select glow texture")) ImGui::OpenPopup("Select glow texture"); if (ImGui::BeginPopup("Select glow texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->glow = texture; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::DirectionalLightEditor(Component::DirectionalLight* directionalLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &directionalLight->color[0]); ImGui::InputFloat("Ambient coefficient", &directionalLight->ambientCoefficient); ImGui::Unindent(); } void EntityEditor::PointLightEditor(Component::PointLight* pointLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &pointLight->color[0]); ImGui::InputFloat("Ambient coefficient", &pointLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &pointLight->attenuation); ImGui::InputFloat("Intensity", &pointLight->intensity); ImGui::Unindent(); } void EntityEditor::SpotLightEditor(Component::SpotLight* spotLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &spotLight->color[0]); ImGui::InputFloat("Ambient coefficient", &spotLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &spotLight->attenuation); ImGui::InputFloat("Intensity", &spotLight->intensity); ImGui::InputFloat("Cone angle", &spotLight->coneAngle); ImGui::Unindent(); } void EntityEditor::ListenerEditor(Component::Listener* listener) { } void EntityEditor::ScriptEditor(Component::Script* script) { ImGui::Indent(); if(script->scriptFile != nullptr) ImGui::Text(script->scriptFile->name.c_str()); else ImGui::Text("No script loaded"); if (ImGui::Button("Select script")) ImGui::OpenPopup("Select script"); if (ImGui::BeginPopup("Select script")) { ImGui::Text("Scripts"); ImGui::Separator(); for (ScriptFile* scriptFile : Hymn().scripts) { if (ImGui::Selectable(scriptFile->name.c_str())) script->scriptFile = scriptFile; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::SoundSourceEditor(Component::SoundSource* soundSource) { ImGui::Text("Sound"); ImGui::Indent(); if (ImGui::Button("Select sound")) ImGui::OpenPopup("Select sound"); if (ImGui::BeginPopup("Select sound")) { ImGui::Text("Sounds"); ImGui::Separator(); for (Audio::SoundBuffer* sound : Hymn().sounds) { if (ImGui::Selectable(sound->name.c_str())) soundSource->soundBuffer = sound; } ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Sound properties"); ImGui::Indent(); ImGui::InputFloat("Pitch", &soundSource->pitch); ImGui::InputFloat("Gain", &soundSource->gain); ImGui::Checkbox("Loop", &soundSource->loop); ImGui::Unindent(); } void EntityEditor::ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter) { ImGui::Text("Particle"); ImGui::Indent(); ImGui::InputInt("Texture index", &particleEmitter->particleType.textureIndex); ImGui::InputFloat3("Min velocity", &particleEmitter->particleType.minVelocity[0]); ImGui::InputFloat3("Max velocity", &particleEmitter->particleType.maxVelocity[0]); ImGui::InputFloat("Min lifetime", &particleEmitter->particleType.minLifetime); ImGui::InputFloat("Max lifetime", &particleEmitter->particleType.maxLifetime); ImGui::InputFloat2("Min size", &particleEmitter->particleType.minSize[0]); ImGui::InputFloat2("Max size", &particleEmitter->particleType.maxSize[0]); ImGui::Checkbox("Uniform scaling", &particleEmitter->particleType.uniformScaling); ImGui::InputFloat("Start alpha", &particleEmitter->particleType.startAlpha); ImGui::InputFloat("Mid alpha", &particleEmitter->particleType.midAlpha); ImGui::InputFloat("End alpha", &particleEmitter->particleType.endAlpha); ImGui::InputFloat3("Color", &particleEmitter->particleType.color[0]); ImGui::Unindent(); ImGui::Text("Emitter"); ImGui::Indent(); ImGui::InputFloat3("Size", &particleEmitter->size[0]); ImGui::InputFloat("Min emit time", &particleEmitter->minEmitTime); ImGui::InputFloat("Max emit time", &particleEmitter->maxEmitTime); if (ImGui::Button("Emitter type")) ImGui::OpenPopup("Emitter type"); if (ImGui::BeginPopup("Emitter type")) { ImGui::Text("Emitter type"); ImGui::Separator(); if (ImGui::Selectable("Point")) particleEmitter->emitterType = Component::ParticleEmitter::POINT; if (ImGui::Selectable("Cuboid")) particleEmitter->emitterType = Component::ParticleEmitter::CUBOID; ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Preview"); ImGui::Indent(); ImGui::Unindent(); } <commit_msg>Preview normal map<commit_after>#include "EntityEditor.hpp" #include <Engine/Component/Animation.hpp> #include <Engine/Component/Physics.hpp> #include <Engine/Component/Mesh.hpp> #include <Engine/Component/Lens.hpp> #include <Engine/Component/Material.hpp> #include <Engine/Component/DirectionalLight.hpp> #include <Engine/Component/PointLight.hpp> #include <Engine/Component/SpotLight.hpp> #include <Engine/Component/Listener.hpp> #include <Engine/Component/Script.hpp> #include <Engine/Component/SoundSource.hpp> #include <Engine/Component/ParticleEmitter.hpp> #include <Engine/Hymn.hpp> #include <Engine/Geometry/Model.hpp> #include <Engine/Geometry/RiggedModel.hpp> #include <Engine/Texture/Texture2D.hpp> #include <Engine/Audio/SoundBuffer.hpp> #include <Engine/Script/ScriptFile.hpp> #include <Engine/Util/FileSystem.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include "../../Util/EditorSettings.hpp" #include "../FileSelector.hpp" using namespace GUI; EntityEditor::EntityEditor() { name[0] = '\0'; AddEditor<Component::Animation>("Animation", std::bind(&EntityEditor::AnimationEditor, this, std::placeholders::_1)); AddEditor<Component::Physics>("Physics", std::bind(&EntityEditor::PhysicsEditor, this, std::placeholders::_1)); AddEditor<Component::Mesh>("Mesh", std::bind(&EntityEditor::MeshEditor, this, std::placeholders::_1)); AddEditor<Component::Lens>("Lens", std::bind(&EntityEditor::LensEditor, this, std::placeholders::_1)); AddEditor<Component::Material>("Material", std::bind(&EntityEditor::MaterialEditor, this, std::placeholders::_1)); AddEditor<Component::DirectionalLight>("Directional light", std::bind(&EntityEditor::DirectionalLightEditor, this, std::placeholders::_1)); AddEditor<Component::PointLight>("Point light", std::bind(&EntityEditor::PointLightEditor, this, std::placeholders::_1)); AddEditor<Component::SpotLight>("Spot light", std::bind(&EntityEditor::SpotLightEditor, this, std::placeholders::_1)); AddEditor<Component::Listener>("Listener", std::bind(&EntityEditor::ListenerEditor, this, std::placeholders::_1)); AddEditor<Component::Script>("Script", std::bind(&EntityEditor::ScriptEditor, this, std::placeholders::_1)); AddEditor<Component::SoundSource>("Sound source", std::bind(&EntityEditor::SoundSourceEditor, this, std::placeholders::_1)); AddEditor<Component::ParticleEmitter>("Particle emitter", std::bind(&EntityEditor::ParticleEmitterEditor, this, std::placeholders::_1)); } EntityEditor::~EntityEditor() { } void EntityEditor::Show() { if (ImGui::Begin(("Entity: " + entity->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(entity))).c_str(), &visible)) { ImGui::InputText("Name", name, 128); entity->name = name; ImGui::Text("Transform"); ImGui::Indent(); ImGui::InputFloat3("Position", &entity->position[0]); ImGui::InputFloat3("Rotation", &entity->rotation[0]); ImGui::InputFloat3("Scale", &entity->scale[0]); ImGui::Unindent(); if (!entity->IsScene()) { if (ImGui::Button("Add component")) ImGui::OpenPopup("Add component"); if (ImGui::BeginPopup("Add component")) { ImGui::Text("Components"); ImGui::Separator(); for (Editor& editor : editors) { editor.addFunction(); } ImGui::EndPopup(); } for (Editor& editor : editors) { editor.editFunction(); } } } ImGui::End(); } void EntityEditor::SetEntity(Entity* entity) { this->entity = entity; strcpy(name, entity->name.c_str()); } bool EntityEditor::ShowsEntity(Entity* entity) { return this->entity == entity; } bool EntityEditor::IsVisible() const { return visible; } void EntityEditor::SetVisible(bool visible) { this->visible = visible; } void EntityEditor::AnimationEditor(Component::Animation* animation) { ImGui::Indent(); if (ImGui::Button("Select model##Animation")) ImGui::OpenPopup("Select model##Animation"); if (ImGui::BeginPopup("Select model##Animation")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) animation->riggedModel = dynamic_cast<Geometry::RiggedModel*>(model); } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::PhysicsEditor(Component::Physics* physics) { ImGui::Text("Positional"); ImGui::Indent(); ImGui::InputFloat3("Velocity", &physics->velocity[0]); ImGui::InputFloat("Max velocity", &physics->maxVelocity); ImGui::InputFloat3("Acceleration", &physics->acceleration[0]); ImGui::InputFloat("Velocity drag factor", &physics->velocityDragFactor); ImGui::InputFloat("Gravity factor", &physics->gravityFactor); ImGui::Unindent(); ImGui::Text("Angular"); ImGui::Indent(); ImGui::InputFloat3("Angular velocity", &physics->angularVelocity[0]); ImGui::InputFloat("Max angular velocity", &physics->maxAngularVelocity); ImGui::InputFloat3("Angular acceleration", &physics->angularAcceleration[0]); ImGui::InputFloat("Angular drag factor", &physics->angularDragFactor); ImGui::InputFloat3("Moment of inertia", &physics->momentOfInertia[0]); ImGui::Unindent(); } void EntityEditor::MeshEditor(Component::Mesh* mesh) { ImGui::Indent(); if (ImGui::Button("Select model##Mesh")) ImGui::OpenPopup("Select model##Mesh"); if (ImGui::BeginPopup("Select model##Mesh")) { ImGui::Text("Models"); ImGui::Separator(); for (Geometry::Model* model : Hymn().models) { if (ImGui::Selectable(model->name.c_str())) mesh->geometry = model; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::LensEditor(Component::Lens* lens) { ImGui::Indent(); ImGui::InputFloat("Field of view", &lens->fieldOfView); ImGui::InputFloat("Z near", &lens->zNear); ImGui::InputFloat("Z far", &lens->zFar); ImGui::Unindent(); } void EntityEditor::MaterialEditor(Component::Material* material) { // Diffuse ImGui::Text("Diffuse"); ImGui::Indent(); if (material->diffuse->IsLoaded()) ImGui::Image((void*) material->diffuse->GetTextureID(), ImVec2(128, 128)); if (ImGui::Button("Select diffuse texture")) ImGui::OpenPopup("Select diffuse texture"); if (ImGui::BeginPopup("Select diffuse texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->diffuse = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Normal ImGui::Text("Normal"); ImGui::Indent(); if (material->normal->IsLoaded()) ImGui::Image((void*) material->normal->GetTextureID(), ImVec2(128, 128)); if (ImGui::Button("Select normal texture")) ImGui::OpenPopup("Select normal texture"); if (ImGui::BeginPopup("Select normal texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->normal = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Specular ImGui::Text("Specular"); ImGui::Indent(); if (ImGui::Button("Select specular texture")) ImGui::OpenPopup("Select specular texture"); if (ImGui::BeginPopup("Select specular texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->specular = texture; } ImGui::EndPopup(); } ImGui::Unindent(); // Glow ImGui::Text("Glow"); ImGui::Indent(); if (ImGui::Button("Select glow texture")) ImGui::OpenPopup("Select glow texture"); if (ImGui::BeginPopup("Select glow texture")) { ImGui::Text("Textures"); ImGui::Separator(); for (Texture2D* texture : Hymn().textures) { if (ImGui::Selectable(texture->name.c_str())) material->glow = texture; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::DirectionalLightEditor(Component::DirectionalLight* directionalLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &directionalLight->color[0]); ImGui::InputFloat("Ambient coefficient", &directionalLight->ambientCoefficient); ImGui::Unindent(); } void EntityEditor::PointLightEditor(Component::PointLight* pointLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &pointLight->color[0]); ImGui::InputFloat("Ambient coefficient", &pointLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &pointLight->attenuation); ImGui::InputFloat("Intensity", &pointLight->intensity); ImGui::Unindent(); } void EntityEditor::SpotLightEditor(Component::SpotLight* spotLight) { ImGui::Indent(); ImGui::InputFloat3("Color", &spotLight->color[0]); ImGui::InputFloat("Ambient coefficient", &spotLight->ambientCoefficient); ImGui::InputFloat("Attenuation", &spotLight->attenuation); ImGui::InputFloat("Intensity", &spotLight->intensity); ImGui::InputFloat("Cone angle", &spotLight->coneAngle); ImGui::Unindent(); } void EntityEditor::ListenerEditor(Component::Listener* listener) { } void EntityEditor::ScriptEditor(Component::Script* script) { ImGui::Indent(); if(script->scriptFile != nullptr) ImGui::Text(script->scriptFile->name.c_str()); else ImGui::Text("No script loaded"); if (ImGui::Button("Select script")) ImGui::OpenPopup("Select script"); if (ImGui::BeginPopup("Select script")) { ImGui::Text("Scripts"); ImGui::Separator(); for (ScriptFile* scriptFile : Hymn().scripts) { if (ImGui::Selectable(scriptFile->name.c_str())) script->scriptFile = scriptFile; } ImGui::EndPopup(); } ImGui::Unindent(); } void EntityEditor::SoundSourceEditor(Component::SoundSource* soundSource) { ImGui::Text("Sound"); ImGui::Indent(); if (ImGui::Button("Select sound")) ImGui::OpenPopup("Select sound"); if (ImGui::BeginPopup("Select sound")) { ImGui::Text("Sounds"); ImGui::Separator(); for (Audio::SoundBuffer* sound : Hymn().sounds) { if (ImGui::Selectable(sound->name.c_str())) soundSource->soundBuffer = sound; } ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Sound properties"); ImGui::Indent(); ImGui::InputFloat("Pitch", &soundSource->pitch); ImGui::InputFloat("Gain", &soundSource->gain); ImGui::Checkbox("Loop", &soundSource->loop); ImGui::Unindent(); } void EntityEditor::ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter) { ImGui::Text("Particle"); ImGui::Indent(); ImGui::InputInt("Texture index", &particleEmitter->particleType.textureIndex); ImGui::InputFloat3("Min velocity", &particleEmitter->particleType.minVelocity[0]); ImGui::InputFloat3("Max velocity", &particleEmitter->particleType.maxVelocity[0]); ImGui::InputFloat("Min lifetime", &particleEmitter->particleType.minLifetime); ImGui::InputFloat("Max lifetime", &particleEmitter->particleType.maxLifetime); ImGui::InputFloat2("Min size", &particleEmitter->particleType.minSize[0]); ImGui::InputFloat2("Max size", &particleEmitter->particleType.maxSize[0]); ImGui::Checkbox("Uniform scaling", &particleEmitter->particleType.uniformScaling); ImGui::InputFloat("Start alpha", &particleEmitter->particleType.startAlpha); ImGui::InputFloat("Mid alpha", &particleEmitter->particleType.midAlpha); ImGui::InputFloat("End alpha", &particleEmitter->particleType.endAlpha); ImGui::InputFloat3("Color", &particleEmitter->particleType.color[0]); ImGui::Unindent(); ImGui::Text("Emitter"); ImGui::Indent(); ImGui::InputFloat3("Size", &particleEmitter->size[0]); ImGui::InputFloat("Min emit time", &particleEmitter->minEmitTime); ImGui::InputFloat("Max emit time", &particleEmitter->maxEmitTime); if (ImGui::Button("Emitter type")) ImGui::OpenPopup("Emitter type"); if (ImGui::BeginPopup("Emitter type")) { ImGui::Text("Emitter type"); ImGui::Separator(); if (ImGui::Selectable("Point")) particleEmitter->emitterType = Component::ParticleEmitter::POINT; if (ImGui::Selectable("Cuboid")) particleEmitter->emitterType = Component::ParticleEmitter::CUBOID; ImGui::EndPopup(); } ImGui::Unindent(); ImGui::Text("Preview"); ImGui::Indent(); ImGui::Unindent(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xeescher.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-07-10 13:53:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_XEESCHER_HXX #define SC_XEESCHER_HXX #ifndef SC_XLESCHER_HXX #include "xlescher.hxx" #endif #include "xcl97rec.hxx" namespace com { namespace sun { namespace star { namespace script { struct ScriptEventDescriptor; } } } } // ============================================================================ /** Helper to manage controls linked to the sheet. */ class XclExpCtrlLinkHelper : protected XclExpRoot { public: explicit XclExpCtrlLinkHelper( const XclExpRoot& rRoot ); virtual ~XclExpCtrlLinkHelper(); /** Sets the address of the control's linked cell. */ void SetCellLink( const ScAddress& rCellLink ); /** Sets the address of the control's linked source cell range. */ void SetSourceRange( const ScRange& rSrcRange ); protected: /** Returns the Excel token array of the cell link, or 0, if no link present. */ inline const XclTokenArray* GetCellLinkTokArr() const { return mxCellLink.get(); } /** Returns the Excel token array of the source range, or 0, if no link present. */ inline const XclTokenArray* GetSourceRangeTokArr() const { return mxSrcRange.get(); } /** Returns the number of entries in the source range, or 0, if no source set. */ inline sal_uInt16 GetSourceEntryCount() const { return mnEntryCount; } /** Writes a formula with special style only valid in OBJ records. */ void WriteFormula( XclExpStream& rStrm, const XclTokenArray& rTokArr ) const; /** Writes a formula subrecord with special style only valid in OBJ records. */ void WriteFormulaSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId, const XclTokenArray& rTokArr ) const; private: XclTokenArrayRef mxCellLink; /// Formula for linked cell. XclTokenArrayRef mxSrcRange; /// Formula for source data range. sal_uInt16 mnEntryCount; /// Number of entries in source range. }; // ---------------------------------------------------------------------------- #if EXC_EXP_OCX_CTRL /** Represents an OBJ record for an OCX form control. */ class XclExpObjOcxCtrl : public XclObj, public XclExpCtrlLinkHelper { public: explicit XclExpObjOcxCtrl( const XclExpRoot& rRoot, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rxShape, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& rxCtrlModel, const String& rClassName, sal_uInt32 nStrmStart, sal_uInt32 nStrmSize ); private: virtual void WriteSubRecs( XclExpStream& rStrm ); private: String maClassName; /// Class name of the control. sal_uInt32 mnStrmStart; /// Start position in 'Ctls' stream. sal_uInt32 mnStrmSize; /// Size in 'Ctls' stream. }; #else /** Represents an OBJ record for an TBX form control. */ class XclExpObjTbxCtrl : public XclObj, public XclExpCtrlLinkHelper { public: explicit XclExpObjTbxCtrl( const XclExpRoot& rRoot, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rxShape, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& rxCtrlModel ); /** Sets the name of a macro attached to this control. @return true = The passed event descriptor was valid, macro name has been found. */ bool SetMacroLink( const ::com::sun::star::script::ScriptEventDescriptor& rEvent ); private: virtual void WriteSubRecs( XclExpStream& rStrm ); /** Writes an ftMacro subrecord containing a macro link, or nothing, if no macro present. */ void WriteMacroSubRec( XclExpStream& rStrm ); /** Writes a subrecord containing a cell link, or nothing, if no link present. */ void WriteCellLinkSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId ); /** Writes the ftSbs sub structure containing scrollbar data. */ void WriteSbs( XclExpStream& rStrm ); private: ScfInt16Vec maMultiSel; /// Indexes of all selected entries in a multi selection. XclTokenArrayRef mxMacroLink; /// Token array containing a link to an attached macro. sal_Int32 mnHeight; /// Height of the control. sal_uInt16 mnState; /// Checked/unchecked state. sal_Int16 mnLineCount; /// Combobox dropdown line count. sal_Int16 mnSelEntry; /// Selected entry in combobox (1-based). sal_Int16 mnScrollValue; /// Scrollbar: Current value. sal_Int16 mnScrollMin; /// Scrollbar: Minimum value. sal_Int16 mnScrollMax; /// Scrollbar: Maximum value. sal_Int16 mnScrollStep; /// Scrollbar: Single step. sal_Int16 mnScrollPage; /// Scrollbar: Page step. bool mbFlatButton; /// False = 3D button style; True = Flat button style. bool mbFlatBorder; /// False = 3D border style; True = Flat border style. bool mbMultiSel; /// true = Multi selection in listbox. bool mbScrollHor; /// Scrollbar: true = horizontal. }; #endif // ============================================================================ /** Represents a NOTE record containing the relevant data of a cell note. NOTE records differ significantly in various BIFF versions. This class encapsulates all needed actions for each supported BIFF version. BIFF5/BIFF7: Stores the note text and generates a single or multiple NOTE records on saving. BIFF8: Creates the Escher object containing the drawing information and the note text. */ class XclExpNote : public XclExpRecord { public: /** Constructs a NOTE record from the passed note object and/or the text. @descr The additional text will be separated from the note text with an empty line. @param rScPos The Calc cell address of the note. @param pScNote The Calc note object. May be 0 to create a note from rAddText only. @param rAddText Additional text appended to the note text. */ explicit XclExpNote( const XclExpRoot& rRoot, const ScAddress& rScPos, const ScPostIt* pScNote, const String& rAddText ); /** Writes the NOTE record, if the respective Escher object is present. */ virtual void Save( XclExpStream& rStrm ); private: /** Writes the body of the NOTE record. */ virtual void WriteBody( XclExpStream& rStrm ); private: XclExpString maAuthor; /// Name of the author. ByteString maNoteText; /// Main text of the note (<=BIFF7). ScAddress maScPos; /// Calc cell address of the note. sal_uInt16 mnObjId; /// Escher object ID (BIFF8). bool mbVisible; /// true = permanently visible. }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS dr52 (1.7.132); FILE MERGED 2007/01/05 16:06:26 dr 1.7.132.1: #i51348# load drawing object names<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xeescher.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2007-01-22 13:21:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_XEESCHER_HXX #define SC_XEESCHER_HXX #ifndef SC_XLESCHER_HXX #include "xlescher.hxx" #endif #include "xcl97rec.hxx" namespace com { namespace sun { namespace star { namespace script { struct ScriptEventDescriptor; } } } } // ============================================================================ /** Helper class for form controils to manage spreadsheet links . */ class XclExpControlObjHelper : protected XclExpRoot { public: explicit XclExpControlObjHelper( const XclExpRoot& rRoot ); virtual ~XclExpControlObjHelper(); protected: /** Tries to get spreadsheet cell link and source range link from the passed shape. */ void ConvertSheetLinks( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); /** Returns the Excel token array of the cell link, or 0, if no link present. */ inline const XclTokenArray* GetCellLinkTokArr() const { return mxCellLink.get(); } /** Returns the Excel token array of the source range, or 0, if no link present. */ inline const XclTokenArray* GetSourceRangeTokArr() const { return mxSrcRange.get(); } /** Returns the number of entries in the source range, or 0, if no source set. */ inline sal_uInt16 GetSourceEntryCount() const { return mnEntryCount; } /** Writes a formula with special style only valid in OBJ records. */ void WriteFormula( XclExpStream& rStrm, const XclTokenArray& rTokArr ) const; /** Writes a formula subrecord with special style only valid in OBJ records. */ void WriteFormulaSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId, const XclTokenArray& rTokArr ) const; private: XclTokenArrayRef mxCellLink; /// Formula for linked cell. XclTokenArrayRef mxSrcRange; /// Formula for source data range. sal_uInt16 mnEntryCount; /// Number of entries in source range. }; // ---------------------------------------------------------------------------- #if EXC_EXP_OCX_CTRL /** Represents an OBJ record for an OCX form control. */ class XclExpOcxControlObj : public XclObj, public XclExpControlObjHelper { public: explicit XclExpOcxControlObj( const XclExpRoot& rRoot, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape, const String& rClassName, sal_uInt32 nStrmStart, sal_uInt32 nStrmSize ); private: virtual void WriteSubRecs( XclExpStream& rStrm ); private: String maClassName; /// Class name of the control. sal_uInt32 mnStrmStart; /// Start position in 'Ctls' stream. sal_uInt32 mnStrmSize; /// Size in 'Ctls' stream. }; #else /** Represents an OBJ record for an TBX form control. */ class XclExpTbxControlObj : public XclObj, public XclExpControlObjHelper { public: explicit XclExpTbxControlObj( const XclExpRoot& rRoot, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); /** Sets the name of a macro attached to this control. @return true = The passed event descriptor was valid, macro name has been found. */ bool SetMacroLink( const ::com::sun::star::script::ScriptEventDescriptor& rEvent ); private: virtual void WriteSubRecs( XclExpStream& rStrm ); /** Writes an ftMacro subrecord containing a macro link, or nothing, if no macro present. */ void WriteMacroSubRec( XclExpStream& rStrm ); /** Writes a subrecord containing a cell link, or nothing, if no link present. */ void WriteCellLinkSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId ); /** Writes the ftSbs sub structure containing scrollbar data. */ void WriteSbs( XclExpStream& rStrm ); private: ScfInt16Vec maMultiSel; /// Indexes of all selected entries in a multi selection. XclTokenArrayRef mxMacroLink; /// Token array containing a link to an attached macro. sal_Int32 mnHeight; /// Height of the control. sal_uInt16 mnState; /// Checked/unchecked state. sal_Int16 mnLineCount; /// Combobox dropdown line count. sal_Int16 mnSelEntry; /// Selected entry in combobox (1-based). sal_Int16 mnScrollValue; /// Scrollbar: Current value. sal_Int16 mnScrollMin; /// Scrollbar: Minimum value. sal_Int16 mnScrollMax; /// Scrollbar: Maximum value. sal_Int16 mnScrollStep; /// Scrollbar: Single step. sal_Int16 mnScrollPage; /// Scrollbar: Page step. bool mbFlatButton; /// False = 3D button style; True = Flat button style. bool mbFlatBorder; /// False = 3D border style; True = Flat border style. bool mbMultiSel; /// true = Multi selection in listbox. bool mbScrollHor; /// Scrollbar: true = horizontal. }; #endif // ============================================================================ /** Represents a NOTE record containing the relevant data of a cell note. NOTE records differ significantly in various BIFF versions. This class encapsulates all needed actions for each supported BIFF version. BIFF5/BIFF7: Stores the note text and generates a single or multiple NOTE records on saving. BIFF8: Creates the Escher object containing the drawing information and the note text. */ class XclExpNote : public XclExpRecord { public: /** Constructs a NOTE record from the passed note object and/or the text. @descr The additional text will be separated from the note text with an empty line. @param rScPos The Calc cell address of the note. @param pScNote The Calc note object. May be 0 to create a note from rAddText only. @param rAddText Additional text appended to the note text. */ explicit XclExpNote( const XclExpRoot& rRoot, const ScAddress& rScPos, const ScPostIt* pScNote, const String& rAddText ); /** Writes the NOTE record, if the respective Escher object is present. */ virtual void Save( XclExpStream& rStrm ); private: /** Writes the body of the NOTE record. */ virtual void WriteBody( XclExpStream& rStrm ); private: XclExpString maAuthor; /// Name of the author. ByteString maNoteText; /// Main text of the note (<=BIFF7). ScAddress maScPos; /// Calc cell address of the note. sal_uInt16 mnObjId; /// Escher object ID (BIFF8). bool mbVisible; /// true = permanently visible. }; // ============================================================================ #endif <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2012 Belledonne Communications SARL. Author: Yann Diorcet 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/>. */ #include "agent.hh" #include "registrardb.hh" #include "authdb.hh" #include <sofia-sip/nua.h> #include <sofia-sip/sip_status.h> class GatewayRegister { private: typedef enum { INITIAL, REGISTRING, REGISTRED } State; State state; Agent *agent; su_home_t home; nua_handle_t *nh; sip_from_t *from; sip_to_t *to; string password; public: void sendRegister(bool authentication = false, const char *realm = NULL); GatewayRegister(Agent *ag, nua_t * nua, sip_from_t *from, sip_to_t *to); ~GatewayRegister(); void onMessage(const sip_t *sip); void onError(const char * message, ...); void start(); void end(); sip_from_t* getFrom() const { return from; } sip_to_t* getTo() const { return to; } void setPassword(const string &password) { this->password = password; } const string& getPassword() { return password; } private: // Listener class NEED to copy the shared pointer class OnAuthListener: public AuthDbListener { private: GatewayRegister *gw; public: OnAuthListener(GatewayRegister * gw) : gw(gw) { } virtual void onAsynchronousPasswordFound(const string &password) { LOGD("Found password"); gw->setPassword(password); gw->sendRegister(); delete this; } virtual void onSynchronousPasswordFound(const string &password) { LOGD("Found password"); gw->setPassword(password); gw->sendRegister(); delete this; } virtual void onError() { gw->onError("Error on password retrieval"); delete this; } }; // Listener class NEED to copy the shared pointer class OnFetchListener: public RegistrarDbListener { private: GatewayRegister *gw; public: OnFetchListener(GatewayRegister * gw) : gw(gw) { } ~OnFetchListener() { } void onRecordFound(Record *r) { if (r == NULL) { LOGD("Record doesn't exist. Fork"); OnAuthListener * listener = new OnAuthListener(gw); string password; AuthDb *mAuthDb = AuthDb::get(); AuthDbResult result = mAuthDb->password(gw->getFrom()->a_url, gw->getFrom()->a_url->url_user, password, listener); // Already a response? if (result != AuthDbResult::PENDING) { if (result == AuthDbResult::PASSWORD_FOUND) { gw->setPassword(password); gw->sendRegister(); } else { LOGE("Can't find user password. Abort."); } delete listener; } } else { LOGD("Record already exists. Not forked"); } delete this; } void onError() { gw->onError("Fetch error."); delete this; } }; }; class GatewayAdapter: public Module, public ModuleToolbox { public: GatewayAdapter(Agent *ag); ~GatewayAdapter(); virtual void onDeclare(ConfigStruct *module_config) { ConfigItemDescriptor items[] = { { String, "gateway", "A gateway uri where to send all requests", "" }, { String, "gateway-domain", "Force the domain of send all requests", "" }, config_item_end }; module_config->addChildrenValues(items); } virtual void onLoad(Agent *agent, const ConfigStruct *module_config); virtual void onRequest(std::shared_ptr<SipEvent> &ev); virtual void onResponse(std::shared_ptr<SipEvent> &ev); private: static void nua_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *_t, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]); static ModuleInfo<GatewayAdapter> sInfo; su_home_t *mHome; nua_t *mNua; }; GatewayAdapter::GatewayAdapter(Agent *ag) : Module(ag) { mHome = su_home_create(); } GatewayAdapter::~GatewayAdapter() { su_home_destroy(mHome); } void GatewayAdapter::onLoad(Agent *agent, const ConfigStruct *module_config) { std::string gateway = module_config->get<ConfigString>("gateway")->read(); mNua = nua_create(agent->getRoot(), nua_callback, NULL, NUTAG_OUTBOUND("no-validate no-natify no-options-keepalive"), NUTAG_PROXY(gateway.c_str()), TAG_END()); } void GatewayAdapter::onRequest(std::shared_ptr<SipEvent> &ev) { sip_t *sip = ev->mSip; if (sip->sip_request->rq_method == sip_method_register) { if (sip->sip_contact != NULL) { // Patch contacts sip_contact_t *contact = nta_agent_contact(getAgent()->getSofiaAgent()); if (contact == NULL) { LOGE("Can't find a valid contact for the agent"); return; } contact = sip_contact_dup(ev->getHome(), contact); contact->m_next = sip->sip_contact; sip->sip_contact = contact; GatewayRegister *gr = new GatewayRegister(getAgent(), mNua, sip->sip_from, sip->sip_to); gr->start(); } } } GatewayRegister::GatewayRegister(Agent *ag, nua_t *nua, sip_from_t *sip_from, sip_to_t *sip_to) : agent(ag) { su_home_init(&home); url_t *domain = NULL; ConfigStruct *cr = ConfigManager::get()->getRoot(); ConfigStruct *ma = cr->get<ConfigStruct>("module::GatewayAdapter"); std::string domainString = ma->get<ConfigString>("gateway-domain")->read(); if (!domainString.empty()) { domain = url_make(&home, domainString.c_str()); } from = sip_from_dup(&home, sip_from); to = sip_to_dup(&home, sip_to); // Override domains? if (domain != NULL) { from->a_url->url_host = domain->url_host; from->a_url->url_port = domain->url_port; to->a_url->url_host = domain->url_host; to->a_url->url_port = domain->url_port; } state = State::INITIAL; nh = nua_handle(nua, this, SIPTAG_FROM(from), SIPTAG_TO(to), TAG_END()); } GatewayRegister::~GatewayRegister() { nua_handle_destroy(nh); su_home_deinit(&home); } void GatewayRegister::sendRegister(bool authentication, const char *realm) { LOGD("Send REGISTER: auth %i", authentication); state = State::REGISTRING; if (!authentication) { nua_register(nh, TAG_END()); } else { char * digest; if (realm != NULL) digest = su_sprintf(&home, "Digest:%s:%s:%s", realm, from->a_url->url_user, password.c_str()); else digest = su_sprintf(&home, "Digest:\"%s\":%s:%s", from->a_url->url_host, from->a_url->url_user, password.c_str()); nua_authenticate(nh, NUTAG_AUTH(digest), TAG_END()); } } void GatewayAdapter::onResponse(std::shared_ptr<SipEvent> &ev) { } void GatewayRegister::onMessage(const sip_t *sip) { switch (state) { case State::INITIAL: onError("Can't receive message in this state"); break; case State::REGISTRING: if (sip->sip_status->st_status == 401) { sendRegister(true); } else if (sip->sip_status->st_status == 407) { // Override realm const char *realm = NULL; if (sip->sip_proxy_authenticate != NULL && sip->sip_proxy_authenticate->au_params != NULL) { realm = msg_params_find(sip->sip_proxy_authenticate->au_params, "realm="); } sendRegister(true, realm); } else if (sip->sip_status->st_status == 200) { state = State::REGISTRED; end(); // TODO: stop the dialog? } else { LOGD("not handled response:%i", sip->sip_status->st_status); } break; case State::REGISTRED: LOGD("new message %i", sip->sip_status->st_status); break; } } void GatewayRegister::onError(const char *message, ...) { va_list args; va_start(args, message); LOGE("%s", message); va_end(args); end(); } void GatewayRegister::start() { LOGD("GatewayRegister start"); OnFetchListener *listener = new OnFetchListener(this); LOGD("Fetching binding"); RegistrarDb::get(agent)->fetch(from->a_url, listener); } void GatewayRegister::end() { LOGD("GatewayRegister end"); delete this; } ModuleInfo<GatewayAdapter> GatewayAdapter::sInfo("GatewayAdapter", "..."); void GatewayAdapter::nua_callback(nua_event_t event, int status, char const *phurase, nua_t *nua, nua_magic_t *_t, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]) { GatewayRegister * gr = (GatewayRegister *) hmagic; if (gr == NULL) { LOGE("NULL GatewayRegister"); return; } if (sip != NULL) { gr->onMessage(sip); } else { LOGD("nua_callback: No sip message %d -> %s", status, phurase); } } <commit_msg>Memory leaks fix<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2012 Belledonne Communications SARL. Author: Yann Diorcet 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/>. */ #include "agent.hh" #include "registrardb.hh" #include "authdb.hh" #include <sofia-sip/nua.h> #include <sofia-sip/sip_status.h> class GatewayRegister { private: typedef enum { INITIAL, REGISTRING, REGISTRED } State; State state; Agent *agent; su_home_t home; nua_handle_t *nh; sip_from_t *from; sip_to_t *to; string password; public: void sendRegister(bool authentication = false, const char *realm = NULL); GatewayRegister(Agent *ag, nua_t * nua, sip_from_t *from, sip_to_t *to); ~GatewayRegister(); void onMessage(const sip_t *sip); void onError(const char * message, ...); void start(); void end(); sip_from_t* getFrom() const { return from; } sip_to_t* getTo() const { return to; } void setPassword(const string &password) { this->password = password; } const string& getPassword() { return password; } private: // Listener class NEED to copy the shared pointer class OnAuthListener: public AuthDbListener { private: GatewayRegister *gw; public: OnAuthListener(GatewayRegister * gw) : gw(gw) { } virtual void onAsynchronousPasswordFound(const string &password) { LOGD("Found password"); gw->setPassword(password); gw->sendRegister(); delete this; } virtual void onSynchronousPasswordFound(const string &password) { LOGD("Found password"); gw->setPassword(password); gw->sendRegister(); delete this; } virtual void onError() { gw->onError("Error on password retrieval"); delete this; } }; // Listener class NEED to copy the shared pointer class OnFetchListener: public RegistrarDbListener { private: GatewayRegister *gw; public: OnFetchListener(GatewayRegister * gw) : gw(gw) { } ~OnFetchListener() { } void onRecordFound(Record *r) { if (r == NULL) { LOGD("Record doesn't exist. Fork"); OnAuthListener * listener = new OnAuthListener(gw); string password; AuthDb *mAuthDb = AuthDb::get(); AuthDbResult result = mAuthDb->password(gw->getFrom()->a_url, gw->getFrom()->a_url->url_user, password, listener); // Already a response? if (result != AuthDbResult::PENDING) { if (result == AuthDbResult::PASSWORD_FOUND) { gw->setPassword(password); gw->sendRegister(); } else { LOGE("Can't find user password. Abort."); } delete listener; } } else { LOGD("Record already exists. Not forked"); } delete this; } void onError() { gw->onError("Fetch error."); delete this; } }; }; class GatewayAdapter: public Module, public ModuleToolbox { public: GatewayAdapter(Agent *ag); ~GatewayAdapter(); virtual void onDeclare(ConfigStruct *module_config) { ConfigItemDescriptor items[] = { { String, "gateway", "A gateway uri where to send all requests", "" }, { String, "gateway-domain", "Force the domain of send all requests", "" }, config_item_end }; module_config->addChildrenValues(items); } virtual void onLoad(Agent *agent, const ConfigStruct *module_config); virtual void onRequest(std::shared_ptr<SipEvent> &ev); virtual void onResponse(std::shared_ptr<SipEvent> &ev); private: static void nua_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *_t, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]); static ModuleInfo<GatewayAdapter> sInfo; su_home_t *mHome; nua_t *mNua; }; GatewayAdapter::GatewayAdapter(Agent *ag) : Module(ag) { mHome = su_home_create(); } GatewayAdapter::~GatewayAdapter() { su_home_destroy(mHome); if(mNua != NULL) { nua_shutdown(mNua); nua_destroy(mNua); } } void GatewayAdapter::onLoad(Agent *agent, const ConfigStruct *module_config) { std::string gateway = module_config->get<ConfigString>("gateway")->read(); mNua = nua_create(agent->getRoot(), nua_callback, NULL, NUTAG_OUTBOUND("no-validate no-natify no-options-keepalive"), NUTAG_PROXY(gateway.c_str()), TAG_END()); } void GatewayAdapter::onRequest(std::shared_ptr<SipEvent> &ev) { sip_t *sip = ev->mSip; if (sip->sip_request->rq_method == sip_method_register) { if (sip->sip_contact != NULL) { // Patch contacts sip_contact_t *contact = nta_agent_contact(getAgent()->getSofiaAgent()); if (contact == NULL) { LOGE("Can't find a valid contact for the agent"); return; } contact = sip_contact_dup(ev->getHome(), contact); contact->m_next = sip->sip_contact; sip->sip_contact = contact; GatewayRegister *gr = new GatewayRegister(getAgent(), mNua, sip->sip_from, sip->sip_to); gr->start(); } } } GatewayRegister::GatewayRegister(Agent *ag, nua_t *nua, sip_from_t *sip_from, sip_to_t *sip_to) : agent(ag) { su_home_init(&home); url_t *domain = NULL; ConfigStruct *cr = ConfigManager::get()->getRoot(); ConfigStruct *ma = cr->get<ConfigStruct>("module::GatewayAdapter"); std::string domainString = ma->get<ConfigString>("gateway-domain")->read(); if (!domainString.empty()) { domain = url_make(&home, domainString.c_str()); } from = sip_from_dup(&home, sip_from); to = sip_to_dup(&home, sip_to); // Override domains? if (domain != NULL) { from->a_url->url_host = domain->url_host; from->a_url->url_port = domain->url_port; to->a_url->url_host = domain->url_host; to->a_url->url_port = domain->url_port; } state = State::INITIAL; nh = nua_handle(nua, this, SIPTAG_FROM(from), SIPTAG_TO(to), TAG_END()); } GatewayRegister::~GatewayRegister() { nua_handle_destroy(nh); su_home_deinit(&home); } void GatewayRegister::sendRegister(bool authentication, const char *realm) { LOGD("Send REGISTER: auth %i", authentication); state = State::REGISTRING; if (!authentication) { nua_register(nh, TAG_END()); } else { char * digest; if (realm != NULL) digest = su_sprintf(&home, "Digest:%s:%s:%s", realm, from->a_url->url_user, password.c_str()); else digest = su_sprintf(&home, "Digest:\"%s\":%s:%s", from->a_url->url_host, from->a_url->url_user, password.c_str()); nua_authenticate(nh, NUTAG_AUTH(digest), TAG_END()); } } void GatewayAdapter::onResponse(std::shared_ptr<SipEvent> &ev) { } void GatewayRegister::onMessage(const sip_t *sip) { switch (state) { case State::INITIAL: onError("Can't receive message in this state"); break; case State::REGISTRING: if (sip->sip_status->st_status == 401) { sendRegister(true); } else if (sip->sip_status->st_status == 407) { // Override realm const char *realm = NULL; if (sip->sip_proxy_authenticate != NULL && sip->sip_proxy_authenticate->au_params != NULL) { realm = msg_params_find(sip->sip_proxy_authenticate->au_params, "realm="); } sendRegister(true, realm); } else if (sip->sip_status->st_status == 200) { state = State::REGISTRED; end(); // TODO: stop the dialog? } else { LOGD("not handled response:%i", sip->sip_status->st_status); } break; case State::REGISTRED: LOGD("new message %i", sip->sip_status->st_status); break; } } void GatewayRegister::onError(const char *message, ...) { va_list args; va_start(args, message); LOGE("%s", message); va_end(args); end(); } void GatewayRegister::start() { LOGD("GatewayRegister start"); OnFetchListener *listener = new OnFetchListener(this); LOGD("Fetching binding"); RegistrarDb::get(agent)->fetch(from->a_url, listener); } void GatewayRegister::end() { LOGD("GatewayRegister end"); delete this; } ModuleInfo<GatewayAdapter> GatewayAdapter::sInfo("GatewayAdapter", "..."); void GatewayAdapter::nua_callback(nua_event_t event, int status, char const *phurase, nua_t *nua, nua_magic_t *_t, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]) { GatewayRegister * gr = (GatewayRegister *) hmagic; if (gr == NULL) { LOGE("NULL GatewayRegister"); return; } if (sip != NULL) { gr->onMessage(sip); } else { LOGD("nua_callback: No sip message %d -> %s", status, phurase); } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #include <boost/bind.hpp> #include <boost/next_prior.hpp> #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { assert(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } entry::entry(const dictionary_type& v) { new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(const string_type& v) { new(data) string_type(v); m_type = string_t; } entry::entry(const list_type& v) { new(data) list_type(v); m_type = list_t; } entry::entry(const integer_type& v) { new(data) integer_type(v); m_type = int_t; } void entry::operator=(const dictionary_type& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; } void entry::operator=(const string_type& v) { destruct(); new(data) string_type(v); m_type = string_t; } void entry::operator=(const list_type& v) { destruct(); new(data) list_type(v); m_type = list_t; } void entry::operator=(const integer_type& v) { destruct(); new(data) integer_type(v); m_type = int_t; } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: assert(m_type == undefined_t); return true; } } void entry::construct(data_type t) { m_type = t; switch(m_type) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: assert(m_type == undefined_t); m_type = undefined_t; } } void entry::copy(const entry& e) { m_type = e.m_type; switch(m_type) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: m_type = undefined_t; } } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: assert(m_type == undefined_t); break; } } void entry::print(std::ostream& os, int indent) const { assert(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <commit_msg>fixed entry::print() to work correctly with binary strings<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <iomanip> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #include <boost/bind.hpp> #include <boost/next_prior.hpp> #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { assert(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } entry::entry(const dictionary_type& v) { new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(const string_type& v) { new(data) string_type(v); m_type = string_t; } entry::entry(const list_type& v) { new(data) list_type(v); m_type = list_t; } entry::entry(const integer_type& v) { new(data) integer_type(v); m_type = int_t; } void entry::operator=(const dictionary_type& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; } void entry::operator=(const string_type& v) { destruct(); new(data) string_type(v); m_type = string_t; } void entry::operator=(const list_type& v) { destruct(); new(data) list_type(v); m_type = list_t; } void entry::operator=(const integer_type& v) { destruct(); new(data) integer_type(v); m_type = int_t; } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: assert(m_type == undefined_t); return true; } } void entry::construct(data_type t) { m_type = t; switch(m_type) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: assert(m_type == undefined_t); m_type = undefined_t; } } void entry::copy(const entry& e) { m_type = e.m_type; switch(m_type) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: m_type = undefined_t; } } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: assert(m_type == undefined_t); break; } } void entry::print(std::ostream& os, int indent) const { assert(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCommunicator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkCommunicator.h" #include "vtkDataSetReader.h" #include "vtkDataSetWriter.h" #include "vtkStructuredPointsReader.h" #include "vtkStructuredPointsWriter.h" #include "vtkImageClip.h" #include "vtkCharArray.h" #include "vtkUnsignedCharArray.h" #include "vtkIntArray.h" #include "vtkUnsignedLongArray.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" template <class T> static int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self) { self->Send(data, length, handle, tag); return 1; } template <class T> static int ReceiveDataArray(T* data, int length, int handle, int tag, vtkDataArray *array) { return 1; } vtkCommunicator::vtkCommunicator() { this->MarshalString = 0; this->MarshalStringLength = 0; this->MarshalDataLength = 0; } vtkCommunicator::~vtkCommunicator() { this->DeleteAndSetMarshalString(0, 0); } void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Marshal string: "; if ( this->MarshalString ) { os << this->MarshalString << endl; } else { os << "(None)" << endl; } os << indent << "Marshal string length: " << this->MarshalStringLength << endl; os << indent << "Marshal data length: " << this->MarshalDataLength << endl; } //---------------------------------------------------------------------------- // Internal method. Assumes responsibility for deleting the string void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength) { // delete any previous string if (this->MarshalString) { delete [] this->MarshalString; this->MarshalString = 0; this->MarshalStringLength = 0; this->MarshalDataLength = 0; } this->MarshalString = str; this->MarshalStringLength = strLength; } // Need to add better error checking int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle, int tag) { if (data == NULL) { this->MarshalDataLength = 0; this->Send( &this->MarshalDataLength, 1, remoteHandle, tag); return 1; } if (this->WriteObject(data)) { this->Send( &this->MarshalDataLength, 1, remoteHandle, tag); // then send the string. this->Send( this->MarshalString, this->MarshalDataLength, remoteHandle, tag); return 1; } // could not marshal data return 0; } int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag) { if (data == NULL) { this->MarshalDataLength = 0; this->Send( &this->MarshalDataLength, 1, remoteHandle, tag); return 1; } // send array type int type = data->GetDataType(); this->Send( &type, 1, remoteHandle, tag); // send array size vtkIdType size = data->GetSize(); this->Send( &size, 1, remoteHandle, tag); // send number of components in array int numComponents = data->GetNumberOfComponents(); this->Send( &numComponents, 1, remoteHandle, tag); const char* name = data->GetName(); int len = strlen(name) + 1; // send length of name this->Send( &len, 1, remoteHandle, tag); // send name this->Send( const_cast<char*>(name), len, remoteHandle, tag); // now send the raw array switch (type) { case VTK_CHAR: return SendDataArray(static_cast<char*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); case VTK_UNSIGNED_CHAR: return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); case VTK_INT: return SendDataArray(static_cast<int*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); case VTK_UNSIGNED_LONG: return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); case VTK_FLOAT: return SendDataArray(static_cast<float*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); case VTK_DOUBLE: return SendDataArray(static_cast<double*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); case VTK_ID_TYPE: return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(type)), size, remoteHandle, tag, this); default: vtkErrorMacro(<<"Unsupported data type!"); return 0; // could not marshal data } } int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle, int tag) { int dataLength; // First receive the data length. if (!this->Receive( &dataLength, 1, remoteHandle, tag)) { vtkErrorMacro("Could not receive data!"); return 0; } if (dataLength < 0) { vtkErrorMacro("Bad data length"); return 0; } if (dataLength == 0) { // This indicates a NULL object was sent. Do nothing. return 1; } // if we cannot reuse the string, allocate a new one. if (dataLength > this->MarshalStringLength) { char *str = new char[dataLength + 10]; // maybe a little extra? this->DeleteAndSetMarshalString(str, dataLength + 10); } // Receive the string this->Receive(this->MarshalString, dataLength, remoteHandle, tag); this->MarshalDataLength = dataLength; this->ReadObject(data); // we should really look at status to determine success return 1; } int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle, int tag) { vtkIdType size; int type; int numComponents; int nameLength; char *c = 0; unsigned char *uc = 0; int *i = 0; unsigned long *ul = 0; float *f = 0; double *d = 0; vtkIdType *idt = 0; // First receive the data type. if (!this->Receive( &type, 1, remoteHandle, tag)) { vtkErrorMacro("Could not receive data!"); return 0; } // Next receive the data length. if (!this->Receive( &size, 1, remoteHandle, tag)) { vtkErrorMacro("Could not receive data!"); return 0; } // Next receive the number of components. this->Receive( &numComponents, 1, remoteHandle, tag); // Next receive the length of the name. this->Receive( &nameLength, 1, remoteHandle, tag); char *str = new char[nameLength]; // maybe a little extra? this->DeleteAndSetMarshalString(str, nameLength); // Receive the name this->Receive(this->MarshalString, nameLength, remoteHandle, tag); this->MarshalDataLength = nameLength; if (size < 0) { vtkErrorMacro("Bad data length"); return 0; } if (size == 0) { // This indicates a NULL object was sent. Do nothing. return 1; } // Receive the raw data array switch (type) { case VTK_CHAR: c = new char[size]; this->Receive(c, size, remoteHandle, tag); static_cast<vtkCharArray*>(data)->SetArray(c, size, 1); break; case VTK_UNSIGNED_CHAR: uc = new unsigned char[size]; this->Receive(uc, size, remoteHandle, tag); static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 1); break; case VTK_INT: i = new int[size]; this->Receive(i, size, remoteHandle, tag); static_cast<vtkIntArray*>(data)->SetArray(i, size, 1); break; case VTK_UNSIGNED_LONG: ul = new unsigned long[size]; this->Receive(ul, size, remoteHandle, tag); static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 1); break; case VTK_FLOAT: f = new float[size]; this->Receive(f, size, remoteHandle, tag); static_cast<vtkFloatArray*>(data)->SetArray(f, size, 1); break; case VTK_DOUBLE: d = new double[size]; this->Receive(d, size, remoteHandle, tag); static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 1); break; case VTK_ID_TYPE: idt = new vtkIdType[size]; this->Receive(idt, size, remoteHandle, tag); static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 1); break; default: vtkErrorMacro(<<"Unsupported data type!"); return 0; // could not marshal data } data->SetName(this->MarshalString); data->SetNumberOfComponents(numComponents); return 1; } int vtkCommunicator::WriteObject(vtkDataObject *data) { if (strcmp(data->GetClassName(), "vtkPolyData") == 0 || strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredPoints") == 0) { return this->WriteDataSet((vtkDataSet*)data); } if (strcmp(data->GetClassName(), "vtkImageData") == 0) { return this->WriteImageData((vtkImageData*)data); } vtkErrorMacro("Cannot marshal object of type " << data->GetClassName()); return 0; } int vtkCommunicator::ReadObject(vtkDataObject *data) { if (strcmp(data->GetClassName(), "vtkPolyData") == 0 || strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredPoints") == 0) { return this->ReadDataSet((vtkDataSet*)data); } if (strcmp(data->GetClassName(), "vtkImageData") == 0) { return this->ReadImageData((vtkImageData*)data); } vtkErrorMacro("Cannot marshal object of type " << data->GetClassName()); return 1; } int vtkCommunicator::WriteImageData(vtkImageData *data) { vtkImageClip *clip; vtkStructuredPointsWriter *writer; int size; // keep Update from propagating vtkImageData *tmp = vtkImageData::New(); tmp->ShallowCopy(data); clip = vtkImageClip::New(); clip->SetInput(tmp); clip->SetOutputWholeExtent(data->GetExtent()); writer = vtkStructuredPointsWriter::New(); writer->SetFileTypeToBinary(); writer->WriteToOutputStringOn(); writer->SetInput(clip->GetOutput()); writer->Write(); size = writer->GetOutputStringLength(); this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size); this->MarshalDataLength = size; clip->Delete(); writer->Delete(); tmp->Delete(); return 1; } int vtkCommunicator::ReadImageData(vtkImageData *object) { vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New(); if (this->MarshalString == NULL || this->MarshalStringLength <= 0) { return 0; } reader->ReadFromInputStringOn(); reader->SetInputString(this->MarshalString, this->MarshalDataLength); reader->GetOutput()->Update(); object->ShallowCopy(reader->GetOutput()); reader->Delete(); return 1; } int vtkCommunicator::WriteDataSet(vtkDataSet *data) { vtkDataSet *copy; unsigned long size; vtkDataSetWriter *writer = vtkDataSetWriter::New(); copy = (vtkDataSet*)(data->MakeObject()); copy->ShallowCopy(data); // There is a problem with binary files with no data. if (copy->GetNumberOfCells() > 0) { writer->SetFileTypeToBinary(); } writer->WriteToOutputStringOn(); writer->SetInput(copy); writer->Write(); size = writer->GetOutputStringLength(); this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size); this->MarshalDataLength = size; writer->Delete(); copy->Delete(); return 1; } int vtkCommunicator::ReadDataSet(vtkDataSet *object) { vtkDataSet *output; vtkDataSetReader *reader = vtkDataSetReader::New(); if (this->MarshalString == NULL || this->MarshalStringLength <= 0) { return 0; } reader->ReadFromInputStringOn(); reader->SetInputString(this->MarshalString, this->MarshalDataLength); output = reader->GetOutput(); output->Update(); object->ShallowCopy(output); //object->DataHasBeenGenerated(); reader->Delete(); return 1; } <commit_msg>ERR GetVoidPointer(type) should be GetVoidPointer(0)<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCommunicator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkCommunicator.h" #include "vtkDataSetReader.h" #include "vtkDataSetWriter.h" #include "vtkStructuredPointsReader.h" #include "vtkStructuredPointsWriter.h" #include "vtkImageClip.h" #include "vtkCharArray.h" #include "vtkUnsignedCharArray.h" #include "vtkIntArray.h" #include "vtkUnsignedLongArray.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" template <class T> static int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self) { self->Send(data, length, handle, tag); return 1; } template <class T> static int ReceiveDataArray(T* data, int length, int handle, int tag, vtkDataArray *array) { return 1; } vtkCommunicator::vtkCommunicator() { this->MarshalString = 0; this->MarshalStringLength = 0; this->MarshalDataLength = 0; } vtkCommunicator::~vtkCommunicator() { this->DeleteAndSetMarshalString(0, 0); } void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Marshal string: "; if ( this->MarshalString ) { os << this->MarshalString << endl; } else { os << "(None)" << endl; } os << indent << "Marshal string length: " << this->MarshalStringLength << endl; os << indent << "Marshal data length: " << this->MarshalDataLength << endl; } //---------------------------------------------------------------------------- // Internal method. Assumes responsibility for deleting the string void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength) { // delete any previous string if (this->MarshalString) { delete [] this->MarshalString; this->MarshalString = 0; this->MarshalStringLength = 0; this->MarshalDataLength = 0; } this->MarshalString = str; this->MarshalStringLength = strLength; } // Need to add better error checking int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle, int tag) { if (data == NULL) { this->MarshalDataLength = 0; this->Send( &this->MarshalDataLength, 1, remoteHandle, tag); return 1; } if (this->WriteObject(data)) { this->Send( &this->MarshalDataLength, 1, remoteHandle, tag); // then send the string. this->Send( this->MarshalString, this->MarshalDataLength, remoteHandle, tag); return 1; } // could not marshal data return 0; } int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag) { if (data == NULL) { this->MarshalDataLength = 0; this->Send( &this->MarshalDataLength, 1, remoteHandle, tag); return 1; } // send array type int type = data->GetDataType(); this->Send( &type, 1, remoteHandle, tag); // send array size vtkIdType size = data->GetSize(); this->Send( &size, 1, remoteHandle, tag); // send number of components in array int numComponents = data->GetNumberOfComponents(); this->Send( &numComponents, 1, remoteHandle, tag); const char* name = data->GetName(); int len = strlen(name) + 1; // send length of name this->Send( &len, 1, remoteHandle, tag); // send name this->Send( const_cast<char*>(name), len, remoteHandle, tag); // now send the raw array switch (type) { case VTK_CHAR: return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); case VTK_UNSIGNED_CHAR: return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); case VTK_INT: return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); case VTK_UNSIGNED_LONG: return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); case VTK_FLOAT: return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); case VTK_DOUBLE: return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); case VTK_ID_TYPE: return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)), size, remoteHandle, tag, this); default: vtkErrorMacro(<<"Unsupported data type!"); return 0; // could not marshal data } } int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle, int tag) { int dataLength; // First receive the data length. if (!this->Receive( &dataLength, 1, remoteHandle, tag)) { vtkErrorMacro("Could not receive data!"); return 0; } if (dataLength < 0) { vtkErrorMacro("Bad data length"); return 0; } if (dataLength == 0) { // This indicates a NULL object was sent. Do nothing. return 1; } // if we cannot reuse the string, allocate a new one. if (dataLength > this->MarshalStringLength) { char *str = new char[dataLength + 10]; // maybe a little extra? this->DeleteAndSetMarshalString(str, dataLength + 10); } // Receive the string this->Receive(this->MarshalString, dataLength, remoteHandle, tag); this->MarshalDataLength = dataLength; this->ReadObject(data); // we should really look at status to determine success return 1; } int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle, int tag) { vtkIdType size; int type; int numComponents; int nameLength; char *c = 0; unsigned char *uc = 0; int *i = 0; unsigned long *ul = 0; float *f = 0; double *d = 0; vtkIdType *idt = 0; // First receive the data type. if (!this->Receive( &type, 1, remoteHandle, tag)) { vtkErrorMacro("Could not receive data!"); return 0; } // Next receive the data length. if (!this->Receive( &size, 1, remoteHandle, tag)) { vtkErrorMacro("Could not receive data!"); return 0; } // Next receive the number of components. this->Receive( &numComponents, 1, remoteHandle, tag); // Next receive the length of the name. this->Receive( &nameLength, 1, remoteHandle, tag); char *str = new char[nameLength]; this->DeleteAndSetMarshalString(str, nameLength); // Receive the name this->Receive(this->MarshalString, nameLength, remoteHandle, tag); this->MarshalDataLength = nameLength; if (size < 0) { vtkErrorMacro("Bad data length"); return 0; } if (size == 0) { // This indicates a NULL object was sent. Do nothing. return 1; } // Receive the raw data array switch (type) { case VTK_CHAR: c = new char[size]; this->Receive(c, size, remoteHandle, tag); static_cast<vtkCharArray*>(data)->SetArray(c, size, 0); break; case VTK_UNSIGNED_CHAR: uc = new unsigned char[size]; this->Receive(uc, size, remoteHandle, tag); static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0); break; case VTK_INT: i = new int[size]; this->Receive(i, size, remoteHandle, tag); static_cast<vtkIntArray*>(data)->SetArray(i, size, 0); break; case VTK_UNSIGNED_LONG: ul = new unsigned long[size]; this->Receive(ul, size, remoteHandle, tag); static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0); break; case VTK_FLOAT: f = new float[size]; this->Receive(f, size, remoteHandle, tag); static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0); break; case VTK_DOUBLE: d = new double[size]; this->Receive(d, size, remoteHandle, tag); static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0); break; case VTK_ID_TYPE: idt = new vtkIdType[size]; this->Receive(idt, size, remoteHandle, tag); static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0); break; default: vtkErrorMacro(<<"Unsupported data type!"); return 0; // could not marshal data } data->SetName(this->MarshalString); data->SetNumberOfComponents(numComponents); return 1; } int vtkCommunicator::WriteObject(vtkDataObject *data) { if (strcmp(data->GetClassName(), "vtkPolyData") == 0 || strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredPoints") == 0) { return this->WriteDataSet((vtkDataSet*)data); } if (strcmp(data->GetClassName(), "vtkImageData") == 0) { return this->WriteImageData((vtkImageData*)data); } vtkErrorMacro("Cannot marshal object of type " << data->GetClassName()); return 0; } int vtkCommunicator::ReadObject(vtkDataObject *data) { if (strcmp(data->GetClassName(), "vtkPolyData") == 0 || strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 || strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 || strcmp(data->GetClassName(), "vtkStructuredPoints") == 0) { return this->ReadDataSet((vtkDataSet*)data); } if (strcmp(data->GetClassName(), "vtkImageData") == 0) { return this->ReadImageData((vtkImageData*)data); } vtkErrorMacro("Cannot marshal object of type " << data->GetClassName()); return 1; } int vtkCommunicator::WriteImageData(vtkImageData *data) { vtkImageClip *clip; vtkStructuredPointsWriter *writer; int size; // keep Update from propagating vtkImageData *tmp = vtkImageData::New(); tmp->ShallowCopy(data); clip = vtkImageClip::New(); clip->SetInput(tmp); clip->SetOutputWholeExtent(data->GetExtent()); writer = vtkStructuredPointsWriter::New(); writer->SetFileTypeToBinary(); writer->WriteToOutputStringOn(); writer->SetInput(clip->GetOutput()); writer->Write(); size = writer->GetOutputStringLength(); this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size); this->MarshalDataLength = size; clip->Delete(); writer->Delete(); tmp->Delete(); return 1; } int vtkCommunicator::ReadImageData(vtkImageData *object) { vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New(); if (this->MarshalString == NULL || this->MarshalStringLength <= 0) { return 0; } reader->ReadFromInputStringOn(); reader->SetInputString(this->MarshalString, this->MarshalDataLength); reader->GetOutput()->Update(); object->ShallowCopy(reader->GetOutput()); reader->Delete(); return 1; } int vtkCommunicator::WriteDataSet(vtkDataSet *data) { vtkDataSet *copy; unsigned long size; vtkDataSetWriter *writer = vtkDataSetWriter::New(); copy = (vtkDataSet*)(data->MakeObject()); copy->ShallowCopy(data); // There is a problem with binary files with no data. if (copy->GetNumberOfCells() > 0) { writer->SetFileTypeToBinary(); } writer->WriteToOutputStringOn(); writer->SetInput(copy); writer->Write(); size = writer->GetOutputStringLength(); this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size); this->MarshalDataLength = size; writer->Delete(); copy->Delete(); return 1; } int vtkCommunicator::ReadDataSet(vtkDataSet *object) { vtkDataSet *output; vtkDataSetReader *reader = vtkDataSetReader::New(); if (this->MarshalString == NULL || this->MarshalStringLength <= 0) { return 0; } reader->ReadFromInputStringOn(); reader->SetInputString(this->MarshalString, this->MarshalDataLength); output = reader->GetOutput(); output->Update(); object->ShallowCopy(output); //object->DataHasBeenGenerated(); reader->Delete(); return 1; } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> Copyright (C) 2003-2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "koincidenceeditor.h" #include "koprefs.h" #include "koglobals.h" #include "koeditordetails.h" #include "koeditoralarms.h" #include "urihandler.h" #include "templatemanagementdialog.h" #include <libkdepim/designerfields.h> #include <libkdepim/embeddedurlpage.h> #include <kabc/addressee.h> #include <kcal/calendarlocal.h> #include <kcal/incidence.h> #include <kcal/icalformat.h> #include <kdebug.h> #include <klocale.h> #include <kstandarddirs.h> #include <kmessagebox.h> #include <kinputdialog.h> #include <kio/netaccess.h> #include <QPixmap> #include <QPointer> #include <QLayout> #include <QDateTime> #include <QVBoxLayout> #include <QBoxLayout> #include <QList> KOIncidenceEditor::KOIncidenceEditor( const QString &caption, Calendar *calendar, QWidget *parent ) : KPageDialog( parent ), mAttendeeEditor( 0 ), mIsCounter( false ) { setFaceType( KPageDialog::Tabbed ); setCaption( caption ); setButtons( Ok | Apply | Cancel | Default ); setDefaultButton( Ok ); setModal( false ); showButtonSeparator( false ); // Set this to be the group leader for all subdialogs - this means // modal subdialogs will only affect this dialog, not the other windows setAttribute( Qt::WA_GroupLeader ); mCalendar = calendar; if ( KOPrefs::instance()->mCompactDialogs ) { showButton( Apply, false ); showButton( Default, false ); } else { setButtonText( Default, i18n( "Manage &Templates..." ) ); } connect( this, SIGNAL(defaultClicked()), SLOT(slotManageTemplates()) ); connect( this, SIGNAL(finished()), SLOT(delayedDestruct()) ); } KOIncidenceEditor::~KOIncidenceEditor() { } void KOIncidenceEditor::slotButtonClicked( int button ) { switch( button ) { case KDialog::Ok: { // "this" can be deleted before processInput() returns (processInput() // opens a non-modal dialog when Kolab is used). So accept should only // be executed when "this" is still valid QPointer<QWidget> ptr( this ); if ( processInput() && ptr ) { KDialog::accept(); } break; } case KDialog::Apply: processInput(); break; case KDialog::Cancel: if ( KMessageBox::questionYesNo( this, i18nc( "@info", "Do you really want to cancel?" ), i18nc( "@title:window", "KOrganizer Confirmation" ) ) == KMessageBox::Yes ) { processCancel(); KDialog::reject(); } break; default: KPageDialog::slotButtonClicked( button ); break; } } void KOIncidenceEditor::setupAttendeesTab() { QFrame *topFrame = new QFrame( this ); addPage( topFrame, i18n( "Atte&ndees" ) ); topFrame->setWhatsThis( i18n( "The Attendees tab allows you to Add or Remove " "Attendees to/from this event or to-do." ) ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); mAttendeeEditor = mDetails = new KOEditorDetails( spacingHint(), topFrame ); topLayout->addWidget( mDetails ); } void KOIncidenceEditor::accept() { } void KOIncidenceEditor::reject() { } void KOIncidenceEditor::closeEvent( QCloseEvent *event ) { event->ignore(); slotButtonClicked( KDialog::Cancel ); } void KOIncidenceEditor::cancelRemovedAttendees( Incidence *incidence ) { if ( !incidence ) { return; } // cancelAttendeeIncidence removes all attendees from the incidence, // and then only adds those that need to be canceled (i.e. a mail needs to be sent to them). if ( KOPrefs::instance()->thatIsMe( incidence->organizer().email() ) ) { Incidence *inc = incidence->clone(); inc->registerObserver( 0 ); mAttendeeEditor->cancelAttendeeIncidence( inc ); if ( inc->attendeeCount() > 0 ) { emit deleteAttendee( inc ); } delete inc; } } void KOIncidenceEditor::slotManageTemplates() { QString tp = type(); TemplateManagementDialog * const d = new TemplateManagementDialog( this, templates() ); connect( d, SIGNAL( loadTemplate( const QString& ) ), this, SLOT( slotLoadTemplate( const QString& ) ) ); connect( d, SIGNAL( templatesChanged( const QStringList& ) ), this, SLOT( slotTemplatesChanged( const QStringList& ) ) ); connect( d, SIGNAL( saveTemplate( const QString& ) ), this, SLOT( slotSaveTemplate( const QString& ) ) ); d->exec(); return; } void KOIncidenceEditor::saveAsTemplate( Incidence *incidence, const QString &templateName ) { if ( !incidence || templateName.isEmpty() ) { return; } QString fileName = "templates/" + incidence->type(); fileName.append( '/' + templateName ); fileName = KStandardDirs::locateLocal( "data", "korganizer/" + fileName ); CalendarLocal cal( KOPrefs::instance()->timeSpec() ); cal.addIncidence( incidence ); ICalFormat format; format.save( &cal, fileName ); } void KOIncidenceEditor::slotLoadTemplate( const QString &templateName ) { CalendarLocal cal( KOPrefs::instance()->timeSpec() ); QString fileName = KStandardDirs::locateLocal( "data", "korganizer/templates/" + type() + '/' + templateName ); if ( fileName.isEmpty() ) { KMessageBox::error( this, i18n( "Unable to find template '%1'.", fileName ) ); } else { ICalFormat format; if ( !format.load( &cal, fileName ) ) { KMessageBox::error( this, i18n( "Error loading template file '%1'.", fileName ) ); return; } } loadTemplate( cal ); } void KOIncidenceEditor::slotTemplatesChanged( const QStringList &newTemplates ) { templates() = newTemplates; } void KOIncidenceEditor::setupDesignerTabs( const QString &type ) { QStringList activePages = KOPrefs::instance()->activeDesignerFields(); QStringList list = KGlobal::dirs()->findAllResources( "data", "korganizer/designer/" + type + "/*.ui", KStandardDirs::Recursive |KStandardDirs::NoDuplicates ); for ( QStringList::iterator it = list.begin(); it != list.end(); ++it ) { const QString &fn = (*it).mid( (*it).lastIndexOf('/') + 1 ); if ( activePages.contains( fn ) ) { addDesignerTab( *it ); } } } QWidget *KOIncidenceEditor::addDesignerTab( const QString &uifile ) { KPIM::DesignerFields *wid = new KPIM::DesignerFields( uifile, 0 ); mDesignerFields.append( wid ); QFrame *topFrame = new QFrame(); addPage( topFrame, wid->title() ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); wid->setParent( topFrame ); topLayout->addWidget( wid ); mDesignerFieldForWidget[ topFrame ] = wid; return topFrame; } class KCalStorage : public KPIM::DesignerFields::Storage { public: KCalStorage( Incidence *incidence ) : mIncidence( incidence ) { } QStringList keys() { QStringList keys; QMap<QByteArray, QString> props = mIncidence->customProperties(); QMap<QByteArray, QString>::ConstIterator it; for( it = props.constBegin(); it != props.constEnd(); ++it ) { QString customKey = it.key(); QStringList parts = customKey.split( "-", QString::SkipEmptyParts ); if ( parts.count() != 4 ) continue; if ( parts[ 2 ] != "KORGANIZER" ) continue; keys.append( parts[ 3 ] ); } return keys; } QString read( const QString &key ) { return mIncidence->customProperty( "KORGANIZER", key.toUtf8() ); } void write( const QString &key, const QString &value ) { mIncidence->setCustomProperty( "KORGANIZER", key.toUtf8(), value ); } private: Incidence *mIncidence; }; void KOIncidenceEditor::readDesignerFields( Incidence *i ) { KCalStorage storage( i ); foreach ( KPIM::DesignerFields *fields, mDesignerFields ) { if ( fields ) fields->load( &storage ); } } void KOIncidenceEditor::writeDesignerFields( Incidence *i ) { KCalStorage storage( i ); foreach ( KPIM::DesignerFields *fields, mDesignerFields ) { if ( fields ) { fields->save( &storage ); } } } void KOIncidenceEditor::setupEmbeddedURLPage( const QString &label, const QString &url, const QString &mimetype ) { QFrame *topFrame = new QFrame(); addPage( topFrame, label ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); KPIM::EmbeddedURLPage *wid = new KPIM::EmbeddedURLPage( url, mimetype, topFrame ); topLayout->addWidget( wid ); mEmbeddedURLPages.append( topFrame ); connect( wid, SIGNAL( openURL( const KUrl & ) ) , this, SLOT( openURL( const KUrl & ) ) ); // TODO: Call this method only when the tab is actually activated! wid->loadContents(); } void KOIncidenceEditor::createEmbeddedURLPages( Incidence *i ) { if ( !i ) return; if ( !mEmbeddedURLPages.isEmpty() ) { qDeleteAll( mEmbeddedURLPages ); mEmbeddedURLPages.clear(); } if ( !mAttachedDesignerFields.isEmpty() ) { for ( QList<QWidget*>::Iterator it = mAttachedDesignerFields.begin(); it != mAttachedDesignerFields.end(); ++it ) { if ( mDesignerFieldForWidget.contains( *it ) ) { mDesignerFields.removeAll( mDesignerFieldForWidget[ *it ] ); } } qDeleteAll( mAttachedDesignerFields ); mAttachedDesignerFields.clear(); } Attachment::List att = i->attachments(); for ( Attachment::List::Iterator it = att.begin(); it != att.end(); ++it ) { Attachment *a = (*it); if ( a->showInline() && a->isUri() ) { // TODO: Allow more mime-types, but add security checks! /* if ( a->mimeType() == QLatin1String("application/x-designer") ) { QString tmpFile; if ( KIO::NetAccess::download( a->uri(), tmpFile, this ) ) { mAttachedDesignerFields.append( addDesignerTab( tmpFile ) ); KIO::NetAccess::removeTempFile( tmpFile ); } } else*/ // TODO: Enable that check again! if ( a->mimeType() == QLatin1String( "text/html" ) ) { setupEmbeddedURLPage( a->label(), a->uri(), a->mimeType() ); } } } } void KOIncidenceEditor::openURL( const KUrl &url ) { QString uri = url.url(); UriHandler::process( uri ); } void KOIncidenceEditor::addAttachments( const QStringList &attachments, const QStringList &mimeTypes, bool inlineAttachments ) { emit signalAddAttachments( attachments, mimeTypes, inlineAttachments ); } void KOIncidenceEditor::addAttendees( const QStringList &attendees ) { QStringList::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { QString name, email; KABC::Addressee::parseEmailAddress( *it, name, email ); mAttendeeEditor->insertAttendee( new Attendee( name, email ) ); } } void KOIncidenceEditor::selectInvitationCounterProposal( bool enable ) { mIsCounter = enable; if ( mIsCounter ) { setCaption( i18n( "Counter proposal" ) ); setButtonText( KDialog::Ok, i18n( "Counter proposal" ) ); enableButtonApply( false ); } } #include "koincidenceeditor.moc" <commit_msg>backport SVN commit 925439 by mlaurent:<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> Copyright (C) 2003-2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "koincidenceeditor.h" #include "koprefs.h" #include "koglobals.h" #include "koeditordetails.h" #include "koeditoralarms.h" #include "urihandler.h" #include "templatemanagementdialog.h" #include <libkdepim/designerfields.h> #include <libkdepim/embeddedurlpage.h> #include <kabc/addressee.h> #include <kcal/calendarlocal.h> #include <kcal/incidence.h> #include <kcal/icalformat.h> #include <kdebug.h> #include <klocale.h> #include <kstandarddirs.h> #include <kmessagebox.h> #include <kinputdialog.h> #include <kio/netaccess.h> #include <QPixmap> #include <QPointer> #include <QLayout> #include <QDateTime> #include <QVBoxLayout> #include <QBoxLayout> #include <QList> KOIncidenceEditor::KOIncidenceEditor( const QString &caption, Calendar *calendar, QWidget *parent ) : KPageDialog( parent ), mAttendeeEditor( 0 ), mIsCounter( false ) { setFaceType( KPageDialog::Tabbed ); setCaption( caption ); setButtons( Ok | Apply | Cancel | Default ); setDefaultButton( Ok ); setModal( false ); showButtonSeparator( false ); // Set this to be the group leader for all subdialogs - this means // modal subdialogs will only affect this dialog, not the other windows setAttribute( Qt::WA_GroupLeader ); mCalendar = calendar; if ( KOPrefs::instance()->mCompactDialogs ) { showButton( Apply, false ); showButton( Default, false ); } else { setButtonText( Default, i18n( "Manage &Templates..." ) ); } connect( this, SIGNAL(defaultClicked()), SLOT(slotManageTemplates()) ); connect( this, SIGNAL(finished()), SLOT(delayedDestruct()) ); } KOIncidenceEditor::~KOIncidenceEditor() { } void KOIncidenceEditor::slotButtonClicked( int button ) { switch( button ) { case KDialog::Ok: { // "this" can be deleted before processInput() returns (processInput() // opens a non-modal dialog when Kolab is used). So accept should only // be executed when "this" is still valid QPointer<QWidget> ptr( this ); if ( processInput() && ptr ) { KDialog::accept(); } break; } case KDialog::Apply: processInput(); break; case KDialog::Cancel: if ( KMessageBox::questionYesNo( this, i18nc( "@info", "Do you really want to cancel?" ), i18nc( "@title:window", "KOrganizer Confirmation" ) ) == KMessageBox::Yes ) { processCancel(); KDialog::reject(); } break; default: KPageDialog::slotButtonClicked( button ); break; } } void KOIncidenceEditor::setupAttendeesTab() { QFrame *topFrame = new QFrame( this ); addPage( topFrame, i18n( "Atte&ndees" ) ); topFrame->setWhatsThis( i18n( "The Attendees tab allows you to Add or Remove " "Attendees to/from this event or to-do." ) ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); mAttendeeEditor = mDetails = new KOEditorDetails( spacingHint(), topFrame ); topLayout->addWidget( mDetails ); } void KOIncidenceEditor::accept() { } void KOIncidenceEditor::reject() { } void KOIncidenceEditor::closeEvent( QCloseEvent *event ) { event->ignore(); slotButtonClicked( KDialog::Cancel ); } void KOIncidenceEditor::cancelRemovedAttendees( Incidence *incidence ) { if ( !incidence ) { return; } // cancelAttendeeIncidence removes all attendees from the incidence, // and then only adds those that need to be canceled (i.e. a mail needs to be sent to them). if ( KOPrefs::instance()->thatIsMe( incidence->organizer().email() ) ) { Incidence *inc = incidence->clone(); inc->registerObserver( 0 ); mAttendeeEditor->cancelAttendeeIncidence( inc ); if ( inc->attendeeCount() > 0 ) { emit deleteAttendee( inc ); } delete inc; } } void KOIncidenceEditor::slotManageTemplates() { QString tp = type(); TemplateManagementDialog * const d = new TemplateManagementDialog( this, templates() ); connect( d, SIGNAL( loadTemplate( const QString& ) ), this, SLOT( slotLoadTemplate( const QString& ) ) ); connect( d, SIGNAL( templatesChanged( const QStringList& ) ), this, SLOT( slotTemplatesChanged( const QStringList& ) ) ); connect( d, SIGNAL( saveTemplate( const QString& ) ), this, SLOT( slotSaveTemplate( const QString& ) ) ); d->exec(); delete d; } void KOIncidenceEditor::saveAsTemplate( Incidence *incidence, const QString &templateName ) { if ( !incidence || templateName.isEmpty() ) { return; } QString fileName = "templates/" + incidence->type(); fileName.append( '/' + templateName ); fileName = KStandardDirs::locateLocal( "data", "korganizer/" + fileName ); CalendarLocal cal( KOPrefs::instance()->timeSpec() ); cal.addIncidence( incidence ); ICalFormat format; format.save( &cal, fileName ); } void KOIncidenceEditor::slotLoadTemplate( const QString &templateName ) { CalendarLocal cal( KOPrefs::instance()->timeSpec() ); QString fileName = KStandardDirs::locateLocal( "data", "korganizer/templates/" + type() + '/' + templateName ); if ( fileName.isEmpty() ) { KMessageBox::error( this, i18n( "Unable to find template '%1'.", fileName ) ); } else { ICalFormat format; if ( !format.load( &cal, fileName ) ) { KMessageBox::error( this, i18n( "Error loading template file '%1'.", fileName ) ); return; } } loadTemplate( cal ); } void KOIncidenceEditor::slotTemplatesChanged( const QStringList &newTemplates ) { templates() = newTemplates; } void KOIncidenceEditor::setupDesignerTabs( const QString &type ) { QStringList activePages = KOPrefs::instance()->activeDesignerFields(); QStringList list = KGlobal::dirs()->findAllResources( "data", "korganizer/designer/" + type + "/*.ui", KStandardDirs::Recursive |KStandardDirs::NoDuplicates ); for ( QStringList::iterator it = list.begin(); it != list.end(); ++it ) { const QString &fn = (*it).mid( (*it).lastIndexOf('/') + 1 ); if ( activePages.contains( fn ) ) { addDesignerTab( *it ); } } } QWidget *KOIncidenceEditor::addDesignerTab( const QString &uifile ) { KPIM::DesignerFields *wid = new KPIM::DesignerFields( uifile, 0 ); mDesignerFields.append( wid ); QFrame *topFrame = new QFrame(); addPage( topFrame, wid->title() ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); wid->setParent( topFrame ); topLayout->addWidget( wid ); mDesignerFieldForWidget[ topFrame ] = wid; return topFrame; } class KCalStorage : public KPIM::DesignerFields::Storage { public: KCalStorage( Incidence *incidence ) : mIncidence( incidence ) { } QStringList keys() { QStringList keys; QMap<QByteArray, QString> props = mIncidence->customProperties(); QMap<QByteArray, QString>::ConstIterator it; for( it = props.constBegin(); it != props.constEnd(); ++it ) { QString customKey = it.key(); QStringList parts = customKey.split( "-", QString::SkipEmptyParts ); if ( parts.count() != 4 ) continue; if ( parts[ 2 ] != "KORGANIZER" ) continue; keys.append( parts[ 3 ] ); } return keys; } QString read( const QString &key ) { return mIncidence->customProperty( "KORGANIZER", key.toUtf8() ); } void write( const QString &key, const QString &value ) { mIncidence->setCustomProperty( "KORGANIZER", key.toUtf8(), value ); } private: Incidence *mIncidence; }; void KOIncidenceEditor::readDesignerFields( Incidence *i ) { KCalStorage storage( i ); foreach ( KPIM::DesignerFields *fields, mDesignerFields ) { if ( fields ) fields->load( &storage ); } } void KOIncidenceEditor::writeDesignerFields( Incidence *i ) { KCalStorage storage( i ); foreach ( KPIM::DesignerFields *fields, mDesignerFields ) { if ( fields ) { fields->save( &storage ); } } } void KOIncidenceEditor::setupEmbeddedURLPage( const QString &label, const QString &url, const QString &mimetype ) { QFrame *topFrame = new QFrame(); addPage( topFrame, label ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); KPIM::EmbeddedURLPage *wid = new KPIM::EmbeddedURLPage( url, mimetype, topFrame ); topLayout->addWidget( wid ); mEmbeddedURLPages.append( topFrame ); connect( wid, SIGNAL( openURL( const KUrl & ) ) , this, SLOT( openURL( const KUrl & ) ) ); // TODO: Call this method only when the tab is actually activated! wid->loadContents(); } void KOIncidenceEditor::createEmbeddedURLPages( Incidence *i ) { if ( !i ) return; if ( !mEmbeddedURLPages.isEmpty() ) { qDeleteAll( mEmbeddedURLPages ); mEmbeddedURLPages.clear(); } if ( !mAttachedDesignerFields.isEmpty() ) { for ( QList<QWidget*>::Iterator it = mAttachedDesignerFields.begin(); it != mAttachedDesignerFields.end(); ++it ) { if ( mDesignerFieldForWidget.contains( *it ) ) { mDesignerFields.removeAll( mDesignerFieldForWidget[ *it ] ); } } qDeleteAll( mAttachedDesignerFields ); mAttachedDesignerFields.clear(); } Attachment::List att = i->attachments(); for ( Attachment::List::Iterator it = att.begin(); it != att.end(); ++it ) { Attachment *a = (*it); if ( a->showInline() && a->isUri() ) { // TODO: Allow more mime-types, but add security checks! /* if ( a->mimeType() == QLatin1String("application/x-designer") ) { QString tmpFile; if ( KIO::NetAccess::download( a->uri(), tmpFile, this ) ) { mAttachedDesignerFields.append( addDesignerTab( tmpFile ) ); KIO::NetAccess::removeTempFile( tmpFile ); } } else*/ // TODO: Enable that check again! if ( a->mimeType() == QLatin1String( "text/html" ) ) { setupEmbeddedURLPage( a->label(), a->uri(), a->mimeType() ); } } } } void KOIncidenceEditor::openURL( const KUrl &url ) { QString uri = url.url(); UriHandler::process( uri ); } void KOIncidenceEditor::addAttachments( const QStringList &attachments, const QStringList &mimeTypes, bool inlineAttachments ) { emit signalAddAttachments( attachments, mimeTypes, inlineAttachments ); } void KOIncidenceEditor::addAttendees( const QStringList &attendees ) { QStringList::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { QString name, email; KABC::Addressee::parseEmailAddress( *it, name, email ); mAttendeeEditor->insertAttendee( new Attendee( name, email ) ); } } void KOIncidenceEditor::selectInvitationCounterProposal( bool enable ) { mIsCounter = enable; if ( mIsCounter ) { setCaption( i18n( "Counter proposal" ) ); setButtonText( KDialog::Ok, i18n( "Counter proposal" ) ); enableButtonApply( false ); } } #include "koincidenceeditor.moc" <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "gmock/gmock.h" #include <dirent.h> #include <sys/types.h> #include <pwd.h> #include <ydsh/ydsh.h> #include <config.h> #include "../test_common.h" #include "../../src/constant.h" #include "../../src/misc/fatal.h" #ifndef BIN_PATH #error require BIN_PATH #endif #ifndef EXTRA_TEST_DIR #error require EXTRA_TEST_DIR #endif /** * extra test cases dependent on system directory structure * and have side effect on directory structures */ using namespace ydsh; class ModLoadTest : public ExpectOutput, public TempFileFactory {}; static ProcBuilder ds(const char *src) { return ProcBuilder{BIN_PATH, "-c", src} .setOut(IOConfig::PIPE) .setErr(IOConfig::PIPE) .setWorkingDir(EXTRA_TEST_DIR); } TEST_F(ModLoadTest, prepare) { auto src = format("assert test -f $SCRIPT_DIR/mod4extra1.ds\n" "assert !test -f $SCRIPT_DIR/mod4extra2.ds\n" "assert !test -f $SCRIPT_DIR/mod4extra3.ds\n" "assert test -f ~/.ydsh/module/mod4extra1.ds\n" "assert test -f ~/.ydsh/module/mod4extra2.ds\n" "assert !test -f ~/.ydsh/module/mod4extra3.ds\n" "assert test -f %s/mod4extra1.ds\n" "assert test -f %s/mod4extra2.ds\n" "assert test -f %s/mod4extra3.ds\n" "true", SYSTEM_MOD_DIR, SYSTEM_MOD_DIR, SYSTEM_MOD_DIR); ASSERT_NO_FATAL_FAILURE(this->expect(ds(src.c_str()), 0)); } TEST_F(ModLoadTest, scriptdir) { const char *src = R"( source mod4extra1.ds assert $OK_LOADING == "script_dir: mod4extra1.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include1.ds assert $mod1.OK_LOADING == "script_dir: mod4extra1.ds" assert $mod2.OK_LOADING == "local: mod4extra2.ds" assert $mod3.OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0, "include from script_dir!!\n")); } TEST_F(ModLoadTest, local) { const char *src = R"( source mod4extra2.ds assert $OK_LOADING == "local: mod4extra2.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include2.ds assert $mod1.OK_LOADING == "local: mod4extra1.ds" assert $mod2.OK_LOADING == "local: mod4extra2.ds" assert $mod3.OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include4.ds assert $mod.OK_LOADING == "system: mod4extra4.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); } TEST_F(ModLoadTest, system) { const char *src = R"( source mod4extra3.ds assert $OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include3.ds assert $mod1.OK_LOADING == "system: mod4extra1.ds" assert $mod2.OK_LOADING == "system: mod4extra2.ds" assert $mod3.OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include5.ds exit 100 )"; auto e = format("%s/include5.ds:2: [semantic error] module not found: `mod4extra5.ds'\n" "source mod4extra5.ds as mod\n" " ^~~~~~~~~~~~~\n" "(string):2: [note] at module import\n" " source include5.ds\n" " ^~~~~~~~~~~\n", SYSTEM_MOD_DIR); ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 1, "", e.c_str())); } class FileFactory { private: std::string name; public: /** * * @param name * must be full path * @param content */ FileFactory(const char *name, const std::string &content) : name(name) { FILE *fp = fopen(this->name.c_str(), "w"); fwrite(content.c_str(), sizeof(char), content.size(), fp); fflush(fp); fclose(fp); } ~FileFactory() { remove(this->name.c_str()); } const std::string &getFileName() const { return this->name; } }; #define XSTR(v) #v #define STR(v) XSTR(v) struct RCTest : public InteractiveShellBase { RCTest() : InteractiveShellBase(BIN_PATH, ".") { std::string v = "ydsh-" STR(X_INFO_MAJOR_VERSION) "." STR(X_INFO_MINOR_VERSION); v += (getuid() == 0 ? "# " : "$ "); this->setPrompt(v); } }; static std::string getHOME() { std::string str; struct passwd *pw = getpwuid(getuid()); if(pw == nullptr) { fatal_perror("getpwuid failed"); } str = pw->pw_dir; return str; } TEST_F(RCTest, rcfile1) { std::string rcpath = getHOME(); rcpath += "/.ydshrc"; FileFactory fileFactory(rcpath.c_str(), "var RC_VAR = 'rcfile: ~/.ydshrc'"); this->invoke("--quiet"); ASSERT_NO_FATAL_FAILURE(this->expect(this->prompt)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("assert $RC_VAR == 'rcfile: ~/.ydshrc'; exit 23", 23, WaitStatus::EXITED)); } struct APITest : public ExpectOutput { DSState *state{nullptr}; APITest() { this->state = DSState_create(); } ~APITest() override { DSState_delete(&this->state); } }; TEST_F(APITest, modFullpath) { DSError e; int r = DSState_loadModule(this->state, "edit", DS_MOD_FULLPATH, &e); // not load 'edit' ASSERT_EQ(1, r); ASSERT_EQ(DS_ERROR_KIND_FILE_ERROR, e.kind); ASSERT_STREQ(strerror(ENOENT), e.name); ASSERT_EQ(0, e.lineNum); DSError_release(&e); } TEST_F(APITest, mod) { DSError e; int r = DSState_loadModule(this->state, "edit", 0, &e); ASSERT_EQ(0, r); ASSERT_EQ(DS_ERROR_KIND_SUCCESS, e.kind); ASSERT_EQ(0, e.lineNum); DSError_release(&e); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>fix test build in extra_test<commit_after>#include "gtest/gtest.h" #include "gmock/gmock.h" #include <dirent.h> #include <sys/types.h> #include <pwd.h> #include <ydsh/ydsh.h> #include <config.h> #include "../test_common.h" #include "../../src/constant.h" #include "../../src/misc/fatal.h" #ifndef BIN_PATH #error require BIN_PATH #endif #ifndef EXTRA_TEST_DIR #error require EXTRA_TEST_DIR #endif /** * extra test cases dependent on system directory structure * and have side effect on directory structures */ using namespace ydsh; class ModLoadTest : public ExpectOutput, public TempFileFactory { ModLoadTest() : INIT_TEMP_FILE_FACTORY(extra_test) {} }; static ProcBuilder ds(const char *src) { return ProcBuilder{BIN_PATH, "-c", src} .setOut(IOConfig::PIPE) .setErr(IOConfig::PIPE) .setWorkingDir(EXTRA_TEST_DIR); } TEST_F(ModLoadTest, prepare) { auto src = format("assert test -f $SCRIPT_DIR/mod4extra1.ds\n" "assert !test -f $SCRIPT_DIR/mod4extra2.ds\n" "assert !test -f $SCRIPT_DIR/mod4extra3.ds\n" "assert test -f ~/.ydsh/module/mod4extra1.ds\n" "assert test -f ~/.ydsh/module/mod4extra2.ds\n" "assert !test -f ~/.ydsh/module/mod4extra3.ds\n" "assert test -f %s/mod4extra1.ds\n" "assert test -f %s/mod4extra2.ds\n" "assert test -f %s/mod4extra3.ds\n" "true", SYSTEM_MOD_DIR, SYSTEM_MOD_DIR, SYSTEM_MOD_DIR); ASSERT_NO_FATAL_FAILURE(this->expect(ds(src.c_str()), 0)); } TEST_F(ModLoadTest, scriptdir) { const char *src = R"( source mod4extra1.ds assert $OK_LOADING == "script_dir: mod4extra1.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include1.ds assert $mod1.OK_LOADING == "script_dir: mod4extra1.ds" assert $mod2.OK_LOADING == "local: mod4extra2.ds" assert $mod3.OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0, "include from script_dir!!\n")); } TEST_F(ModLoadTest, local) { const char *src = R"( source mod4extra2.ds assert $OK_LOADING == "local: mod4extra2.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include2.ds assert $mod1.OK_LOADING == "local: mod4extra1.ds" assert $mod2.OK_LOADING == "local: mod4extra2.ds" assert $mod3.OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include4.ds assert $mod.OK_LOADING == "system: mod4extra4.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); } TEST_F(ModLoadTest, system) { const char *src = R"( source mod4extra3.ds assert $OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include3.ds assert $mod1.OK_LOADING == "system: mod4extra1.ds" assert $mod2.OK_LOADING == "system: mod4extra2.ds" assert $mod3.OK_LOADING == "system: mod4extra3.ds" )"; ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 0)); src = R"( source include5.ds exit 100 )"; auto e = format("%s/include5.ds:2: [semantic error] module not found: `mod4extra5.ds'\n" "source mod4extra5.ds as mod\n" " ^~~~~~~~~~~~~\n" "(string):2: [note] at module import\n" " source include5.ds\n" " ^~~~~~~~~~~\n", SYSTEM_MOD_DIR); ASSERT_NO_FATAL_FAILURE(this->expect(ds(src), 1, "", e.c_str())); } class FileFactory { private: std::string name; public: /** * * @param name * must be full path * @param content */ FileFactory(const char *name, const std::string &content) : name(name) { FILE *fp = fopen(this->name.c_str(), "w"); fwrite(content.c_str(), sizeof(char), content.size(), fp); fflush(fp); fclose(fp); } ~FileFactory() { remove(this->name.c_str()); } const std::string &getFileName() const { return this->name; } }; #define XSTR(v) #v #define STR(v) XSTR(v) struct RCTest : public InteractiveShellBase { RCTest() : InteractiveShellBase(BIN_PATH, ".") { std::string v = "ydsh-" STR(X_INFO_MAJOR_VERSION) "." STR(X_INFO_MINOR_VERSION); v += (getuid() == 0 ? "# " : "$ "); this->setPrompt(v); } }; static std::string getHOME() { std::string str; struct passwd *pw = getpwuid(getuid()); if(pw == nullptr) { fatal_perror("getpwuid failed"); } str = pw->pw_dir; return str; } TEST_F(RCTest, rcfile1) { std::string rcpath = getHOME(); rcpath += "/.ydshrc"; FileFactory fileFactory(rcpath.c_str(), "var RC_VAR = 'rcfile: ~/.ydshrc'"); this->invoke("--quiet"); ASSERT_NO_FATAL_FAILURE(this->expect(this->prompt)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("assert $RC_VAR == 'rcfile: ~/.ydshrc'; exit 23", 23, WaitStatus::EXITED)); } struct APITest : public ExpectOutput { DSState *state{nullptr}; APITest() { this->state = DSState_create(); } ~APITest() override { DSState_delete(&this->state); } }; TEST_F(APITest, modFullpath) { DSError e; int r = DSState_loadModule(this->state, "edit", DS_MOD_FULLPATH, &e); // not load 'edit' ASSERT_EQ(1, r); ASSERT_EQ(DS_ERROR_KIND_FILE_ERROR, e.kind); ASSERT_STREQ(strerror(ENOENT), e.name); ASSERT_EQ(0, e.lineNum); DSError_release(&e); } TEST_F(APITest, mod) { DSError e; int r = DSState_loadModule(this->state, "edit", 0, &e); ASSERT_EQ(0, r); ASSERT_EQ(DS_ERROR_KIND_SUCCESS, e.kind); ASSERT_EQ(0, e.lineNum); DSError_release(&e); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { TORRENT_ASSERT(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return m_str && e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } #ifndef BOOST_NO_EXCEPTIONS const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } #endif entry::entry() : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(data_type t) : m_type(undefined_t) { construct(t); #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(const entry& e) : m_type(undefined_t) { copy(e); #ifndef NDEBUG m_type_queried = e.m_type_queried; #endif } entry::entry(dictionary_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(string_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) string_type(v); m_type = string_t; } entry::entry(list_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) list_type(v); m_type = list_t; } entry::entry(integer_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) integer_type(v); m_type = int_t; } void entry::operator=(dictionary_type const& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(string_type const& v) { destruct(); new(data) string_type(v); m_type = string_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(list_type const& v) { destruct(); new(data) list_type(v); m_type = list_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(integer_type const& v) { destruct(); new(data) integer_type(v); m_type = int_t; #ifndef NDEBUG m_type_queried = true; #endif } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: TORRENT_ASSERT(m_type == undefined_t); return true; } } void entry::construct(data_type t) { switch(t) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: TORRENT_ASSERT(t == undefined_t); } m_type = t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::copy(entry const& e) { switch (e.type()) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: TORRENT_ASSERT(e.type() == undefined_t); } m_type = e.type(); #ifndef NDEBUG m_type_queried = true; #endif } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: TORRENT_ASSERT(m_type == undefined_t); break; } m_type = undefined_t; #ifndef NDEBUG m_type_queried = false; #endif } void entry::swap(entry& e) { // not implemented TORRENT_ASSERT(false); } void entry::print(std::ostream& os, int indent) const { TORRENT_ASSERT(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <commit_msg>fixed include issue in entry.cpp<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include <iostream> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { TORRENT_ASSERT(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return m_str && e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } #ifndef BOOST_NO_EXCEPTIONS const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } #endif entry::entry() : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(data_type t) : m_type(undefined_t) { construct(t); #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(const entry& e) : m_type(undefined_t) { copy(e); #ifndef NDEBUG m_type_queried = e.m_type_queried; #endif } entry::entry(dictionary_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(string_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) string_type(v); m_type = string_t; } entry::entry(list_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) list_type(v); m_type = list_t; } entry::entry(integer_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) integer_type(v); m_type = int_t; } void entry::operator=(dictionary_type const& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(string_type const& v) { destruct(); new(data) string_type(v); m_type = string_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(list_type const& v) { destruct(); new(data) list_type(v); m_type = list_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(integer_type const& v) { destruct(); new(data) integer_type(v); m_type = int_t; #ifndef NDEBUG m_type_queried = true; #endif } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: TORRENT_ASSERT(m_type == undefined_t); return true; } } void entry::construct(data_type t) { switch(t) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: TORRENT_ASSERT(t == undefined_t); } m_type = t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::copy(entry const& e) { switch (e.type()) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: TORRENT_ASSERT(e.type() == undefined_t); } m_type = e.type(); #ifndef NDEBUG m_type_queried = true; #endif } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: TORRENT_ASSERT(m_type == undefined_t); break; } m_type = undefined_t; #ifndef NDEBUG m_type_queried = false; #endif } void entry::swap(entry& e) { // not implemented TORRENT_ASSERT(false); } void entry::print(std::ostream& os, int indent) const { TORRENT_ASSERT(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <|endoftext|>
<commit_before>#include <boost/python.hpp> #include "trajopt/collision_checker.hpp" #include "trajopt/problem_description.hpp" #include <stdexcept> #include <boost/python/exception_translator.hpp> #include <boost/foreach.hpp> using namespace trajopt; using namespace Eigen; using namespace OpenRAVE; using std::vector; namespace py = boost::python; namespace { bool gInteractive = true; } class PyTrajOptProb { public: TrajOptProbPtr m_prob; PyTrajOptProb(TrajOptProbPtr prob) : m_prob(prob) {} }; Json::Value readJsonFile(const std::string& doc) { Json::Value root; Json::Reader reader; bool success = reader.parse(doc, root); if (!success) throw openrave_exception("couldn't parse string as json"); return root; } PyTrajOptProb PyConstructProblem(const std::string& json_string, py::object py_env) { py::object openravepy = py::import("openravepy"); int id = py::extract<int>(openravepy.attr("RaveGetEnvironmentId")(py_env)); EnvironmentBasePtr cpp_env = RaveGetEnvironment(id); Json::Value json_root = readJsonFile(json_string); TrajOptProbPtr cpp_prob = ConstructProblem(json_root, cpp_env); return PyTrajOptProb(cpp_prob); } void SetInteractive(py::object b) { gInteractive = py::extract<bool>(b); } class PyTrajOptResult { public: PyTrajOptResult(TrajOptResultPtr result) : m_result(result) {} TrajOptResultPtr m_result; py::object GetCosts() { py::list out; int n_costs = m_result->cost_names.size(); for (int i=0; i < n_costs; ++i) { out.append(py::make_tuple(m_result->cost_names[i], m_result->cost_vals[i])); } return out; } py::object GetConstraints() { py::list out; int n_cnts = m_result->cnt_names.size(); for (int i=0; i < n_cnts; ++i) { out.append(py::make_tuple(m_result->cnt_names[i], m_result->cnt_viols[i])); } return out; } py::object __str__() { return GetCosts().attr("__str__")() + GetConstraints().attr("__str__")(); } }; PyTrajOptResult PyOptimizeProblem(PyTrajOptProb& prob) { return OptimizeProblem(prob.m_prob, gInteractive); } class PyCollision { public: Collision m_c; PyCollision(const Collision& c) : m_c(c) {} float GetDistance() {return m_c.distance;} }; py::list toPyList(const vector<Collision>& collisions) { py::list out; BOOST_FOREACH(const Collision& c, collisions) { out.append(PyCollision(c)); } return out; } class PyCollisionChecker { public: py::object AllVsAll() { vector<Collision> collisions; m_cc->AllVsAll(collisions); return toPyList(collisions); } py::object BodyVsAll(py::object py_kb) { KinBodyPtr cpp_kb = boost::const_pointer_cast<EnvironmentBase>(m_cc->GetEnv()) ->GetBodyFromEnvironmentId(py::extract<int>(py_kb.attr("GetEnvironmentId")())); if (!cpp_kb) { throw openrave_exception("body isn't part of environment!"); } vector<Collision> collisions; m_cc->BodyVsAll(*cpp_kb, collisions); return toPyList(collisions); } PyCollisionChecker(CollisionCheckerPtr cc) : m_cc(cc) {} private: PyCollisionChecker(); CollisionCheckerPtr m_cc; }; PyCollisionChecker PyGetCollisionChecker(py::object py_env) { py::object openravepy = py::import("openravepy"); int id = py::extract<int>(openravepy.attr("RaveGetEnvironmentId")(py_env)); EnvironmentBasePtr cpp_env = RaveGetEnvironment(id); CollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*cpp_env); return PyCollisionChecker(cc); } BOOST_PYTHON_MODULE(ctrajoptpy) { py::class_<PyTrajOptProb>("TrajOptProb", py::no_init) ; py::def("SetInteractive", &SetInteractive); py::def("ConstructProblem", &PyConstructProblem); py::def("OptimizeProblem", &PyOptimizeProblem); py::class_<PyTrajOptResult>("TrajOptResult", py::no_init) .def("GetCosts", &PyTrajOptResult::GetCosts) .def("GetConstraints", &PyTrajOptResult::GetConstraints) .def("__str__", &PyTrajOptResult::__str__) ; py::class_<PyCollisionChecker>("CollisionChecker", py::no_init) .def("AllVsAll", &PyCollisionChecker::AllVsAll) .def("BodyVsAll", &PyCollisionChecker::BodyVsAll) ; py::def("GetCollisionChecker", &PyGetCollisionChecker); py::class_<PyCollision>("Collision", py::no_init) .def("GetDistance", &PyCollision::GetDistance) ; } <commit_msg>add GetTraj to python TrajOptResult wrapper<commit_after>#include <boost/python.hpp> #include "trajopt/collision_checker.hpp" #include "trajopt/problem_description.hpp" #include <stdexcept> #include <boost/python/exception_translator.hpp> #include <boost/foreach.hpp> using namespace trajopt; using namespace Eigen; using namespace OpenRAVE; using std::vector; namespace py = boost::python; namespace { bool gInteractive = true; } class PyTrajOptProb { public: TrajOptProbPtr m_prob; PyTrajOptProb(TrajOptProbPtr prob) : m_prob(prob) {} }; Json::Value readJsonFile(const std::string& doc) { Json::Value root; Json::Reader reader; bool success = reader.parse(doc, root); if (!success) throw openrave_exception("couldn't parse string as json"); return root; } PyTrajOptProb PyConstructProblem(const std::string& json_string, py::object py_env) { py::object openravepy = py::import("openravepy"); int id = py::extract<int>(openravepy.attr("RaveGetEnvironmentId")(py_env)); EnvironmentBasePtr cpp_env = RaveGetEnvironment(id); Json::Value json_root = readJsonFile(json_string); TrajOptProbPtr cpp_prob = ConstructProblem(json_root, cpp_env); return PyTrajOptProb(cpp_prob); } void SetInteractive(py::object b) { gInteractive = py::extract<bool>(b); } class PyTrajOptResult { public: PyTrajOptResult(TrajOptResultPtr result) : m_result(result) {} TrajOptResultPtr m_result; py::object GetCosts() { py::list out; int n_costs = m_result->cost_names.size(); for (int i=0; i < n_costs; ++i) { out.append(py::make_tuple(m_result->cost_names[i], m_result->cost_vals[i])); } return out; } py::object GetConstraints() { py::list out; int n_cnts = m_result->cnt_names.size(); for (int i=0; i < n_cnts; ++i) { out.append(py::make_tuple(m_result->cnt_names[i], m_result->cnt_viols[i])); } return out; } py::object GetTraj() { py::object numpy = py::import("numpy"); TrajArray &traj = m_result->traj; py::object out = numpy.attr("empty")(py::make_tuple(traj.rows(), traj.cols())); for (int i = 0; i < traj.rows(); ++i) { for (int j = 0; j < traj.cols(); ++j) { out[i][j] = traj(i, j); } } return out; } py::object __str__() { return GetCosts().attr("__str__")() + GetConstraints().attr("__str__")(); } }; PyTrajOptResult PyOptimizeProblem(PyTrajOptProb& prob) { return OptimizeProblem(prob.m_prob, gInteractive); } class PyCollision { public: Collision m_c; PyCollision(const Collision& c) : m_c(c) {} float GetDistance() {return m_c.distance;} }; py::list toPyList(const vector<Collision>& collisions) { py::list out; BOOST_FOREACH(const Collision& c, collisions) { out.append(PyCollision(c)); } return out; } class PyCollisionChecker { public: py::object AllVsAll() { vector<Collision> collisions; m_cc->AllVsAll(collisions); return toPyList(collisions); } py::object BodyVsAll(py::object py_kb) { KinBodyPtr cpp_kb = boost::const_pointer_cast<EnvironmentBase>(m_cc->GetEnv()) ->GetBodyFromEnvironmentId(py::extract<int>(py_kb.attr("GetEnvironmentId")())); if (!cpp_kb) { throw openrave_exception("body isn't part of environment!"); } vector<Collision> collisions; m_cc->BodyVsAll(*cpp_kb, collisions); return toPyList(collisions); } PyCollisionChecker(CollisionCheckerPtr cc) : m_cc(cc) {} private: PyCollisionChecker(); CollisionCheckerPtr m_cc; }; PyCollisionChecker PyGetCollisionChecker(py::object py_env) { py::object openravepy = py::import("openravepy"); int id = py::extract<int>(openravepy.attr("RaveGetEnvironmentId")(py_env)); EnvironmentBasePtr cpp_env = RaveGetEnvironment(id); CollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*cpp_env); return PyCollisionChecker(cc); } BOOST_PYTHON_MODULE(ctrajoptpy) { py::class_<PyTrajOptProb>("TrajOptProb", py::no_init) ; py::def("SetInteractive", &SetInteractive); py::def("ConstructProblem", &PyConstructProblem); py::def("OptimizeProblem", &PyOptimizeProblem); py::class_<PyTrajOptResult>("TrajOptResult", py::no_init) .def("GetCosts", &PyTrajOptResult::GetCosts) .def("GetConstraints", &PyTrajOptResult::GetConstraints) .def("GetTraj", &PyTrajOptResult::GetTraj) .def("__str__", &PyTrajOptResult::__str__) ; py::class_<PyCollisionChecker>("CollisionChecker", py::no_init) .def("AllVsAll", &PyCollisionChecker::AllVsAll) .def("BodyVsAll", &PyCollisionChecker::BodyVsAll) ; py::def("GetCollisionChecker", &PyGetCollisionChecker); py::class_<PyCollision>("Collision", py::no_init) .def("GetDistance", &PyCollision::GetDistance) ; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008-2009 Gael Guennebaud <[email protected]> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/Geometry> #include <Eigen/LU> #include <Eigen/SVD> /* this test covers the following files: Geometry/OrthoMethods.h */ template<typename Scalar> void orthomethods_3() { typedef Matrix<Scalar,3,3> Matrix3; typedef Matrix<Scalar,3,1> Vector3; Vector3 v0 = Vector3::Random(), v1 = Vector3::Random(), v2 = Vector3::Random(); // cross product VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1)); Matrix3 mat3; mat3 << v0.normalized(), (v0.cross(v1)).normalized(), (v0.cross(v1).cross(v0)).normalized(); VERIFY(mat3.isUnitary()); // colwise/rowwise cross product mat3.setRandom(); Vector3 vec3 = Vector3::Random(); Matrix3 mcross; int i = ei_random<int>(0,2); mcross = mat3.colwise().cross(vec3); VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3)); mcross = mat3.rowwise().cross(vec3); VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3)); } template<typename Scalar, int Size> void orthomethods(int size=Size) { typedef Matrix<Scalar,Size,1> VectorType; typedef Matrix<Scalar,3,Size> Matrix3N; typedef Matrix<Scalar,Size,3> MatrixN3; typedef Matrix<Scalar,3,1> Vector3; VectorType v0 = VectorType::Random(size), v1 = VectorType::Random(size), v2 = VectorType::Random(size); // unitOrthogonal VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1)); VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1)); // colwise/rowwise cross product Vector3 vec3 = Vector3::Random(); int i = ei_random<int>(0,size-1); Matrix3N mat3N(3,size), mcross3N(3,size); mat3N.setRandom(); mcross3N = mat3N.colwise().cross(vec3); VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3)); MatrixN3 matN3(size,3), mcrossN3(size,3); matN3.setRandom(); mcrossN3 = matN3.rowwise().cross(vec3); VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3)); } void test_geo_orthomethods() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( orthomethods_3<float>() ); CALL_SUBTEST( orthomethods_3<double>() ); CALL_SUBTEST( (orthomethods<float,2>()) ); CALL_SUBTEST( (orthomethods<double,2>()) ); CALL_SUBTEST( (orthomethods<float,3>()) ); CALL_SUBTEST( (orthomethods<double,3>()) ); CALL_SUBTEST( (orthomethods<float,7>()) ); CALL_SUBTEST( (orthomethods<double,8>()) ); CALL_SUBTEST( (orthomethods<float,Dynamic>(36)) ); CALL_SUBTEST( (orthomethods<double,Dynamic>(35)) ); } } <commit_msg>add tests showing bug in unitOrthogonal such that we don't forget it!<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008-2009 Gael Guennebaud <[email protected]> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/Geometry> #include <Eigen/LU> #include <Eigen/SVD> /* this test covers the following files: Geometry/OrthoMethods.h */ template<typename Scalar> void orthomethods_3() { typedef Matrix<Scalar,3,3> Matrix3; typedef Matrix<Scalar,3,1> Vector3; Vector3 v0 = Vector3::Random(), v1 = Vector3::Random(), v2 = Vector3::Random(); // cross product VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1)); Matrix3 mat3; mat3 << v0.normalized(), (v0.cross(v1)).normalized(), (v0.cross(v1).cross(v0)).normalized(); VERIFY(mat3.isUnitary()); // colwise/rowwise cross product mat3.setRandom(); Vector3 vec3 = Vector3::Random(); Matrix3 mcross; int i = ei_random<int>(0,2); mcross = mat3.colwise().cross(vec3); VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3)); mcross = mat3.rowwise().cross(vec3); VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3)); } template<typename Scalar, int Size> void orthomethods(int size=Size) { typedef Matrix<Scalar,Size,1> VectorType; typedef Matrix<Scalar,3,Size> Matrix3N; typedef Matrix<Scalar,Size,3> MatrixN3; typedef Matrix<Scalar,3,1> Vector3; VectorType v0 = VectorType::Random(size), v1 = VectorType::Random(size), v2 = VectorType::Random(size); // unitOrthogonal VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1)); VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1)); if (size>3) { v0.template start<3>().setZero(); v0.end(size-3).setRandom(); VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1)); VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1)); } // colwise/rowwise cross product Vector3 vec3 = Vector3::Random(); int i = ei_random<int>(0,size-1); Matrix3N mat3N(3,size), mcross3N(3,size); mat3N.setRandom(); mcross3N = mat3N.colwise().cross(vec3); VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3)); MatrixN3 matN3(size,3), mcrossN3(size,3); matN3.setRandom(); mcrossN3 = matN3.rowwise().cross(vec3); VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3)); } void test_geo_orthomethods() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( orthomethods_3<float>() ); CALL_SUBTEST( orthomethods_3<double>() ); CALL_SUBTEST( (orthomethods<float,2>()) ); CALL_SUBTEST( (orthomethods<double,2>()) ); CALL_SUBTEST( (orthomethods<float,3>()) ); CALL_SUBTEST( (orthomethods<double,3>()) ); CALL_SUBTEST( (orthomethods<float,7>()) ); CALL_SUBTEST( (orthomethods<double,8>()) ); CALL_SUBTEST( (orthomethods<float,Dynamic>(36)) ); CALL_SUBTEST( (orthomethods<double,Dynamic>(35)) ); } } <|endoftext|>
<commit_before>#include "partners_api/booking_api.hpp" #include "platform/http_client.hpp" #include "platform/platform.hpp" #include "base/gmtime.hpp" #include "base/logging.hpp" #include "base/thread.hpp" #include "std/initializer_list.hpp" #include "std/iomanip.hpp" #include "std/iostream.hpp" #include "std/sstream.hpp" #include "std/utility.hpp" #include "3party/jansson/myjansson.hpp" #include "private.h" namespace { using namespace platform; using namespace booking; string const kBookingApiBaseUrl = "https://distribution-xml.booking.com/json/bookings"; string const kExtendedHotelInfoBaseUrl = "http://hotels.milchakov.map6.devmail.ru/getDescription"; string const kPhotoOriginalUrl = "http://aff.bstatic.com/images/hotel/max500/"; string const kPhotoSmallUrl = "http://aff.bstatic.com/images/hotel/max300/"; bool RunSimpleHttpRequest(bool const needAuth, string const & url, string & result) { HttpClient request(url); if (needAuth) request.SetUserAndPassword(BOOKING_KEY, BOOKING_SECRET); if (request.RunHttpRequest() && !request.WasRedirected() && request.ErrorCode() == 200) { result = request.ServerResponse(); return true; } return false; } string MakeApiUrl(string const & func, initializer_list<pair<string, string>> const & params, bool testing) { ostringstream os; os << kBookingApiBaseUrl << "." << func << "?"; bool firstRun = true; for (auto const & param : params) { if (firstRun) { firstRun = false; os << ""; } else { os << "&"; } os << param.first << "=" << param.second; } if (testing) os << "&show_test=1"; return os.str(); } void ClearHotelInfo(HotelInfo & info) { info.m_hotelId.clear(); info.m_description.clear(); info.m_photos.clear(); info.m_facilities.clear(); info.m_reviews.clear(); info.m_score = 0.0; info.m_scoreCount = 0; } vector<HotelFacility> ParseFacilities(json_t const * facilitiesArray) { vector<HotelFacility> facilities; if (facilitiesArray == nullptr || !json_is_array(facilitiesArray)) return facilities; size_t sz = json_array_size(facilitiesArray); for (size_t i = 0; i < sz; ++i) { auto item = json_array_get(facilitiesArray, i); HotelFacility facility; my::FromJSONObject(item, "type", facility.m_facilityType); my::FromJSONObject(item, "name", facility.m_name); facilities.push_back(move(facility)); } return facilities; } vector<HotelPhotoUrls> ParsePhotos(json_t const * photosArray) { if (photosArray == nullptr || !json_is_array(photosArray)) return {}; vector<HotelPhotoUrls> photos; size_t sz = json_array_size(photosArray); string photoId; for (size_t i = 0; i < sz; ++i) { auto item = json_array_get(photosArray, i); my::FromJSON(item, photoId); // First three digits of id are used as part of path to photo on the server. if (photoId.size() < 3) { LOG(LWARNING, ("Incorrect photo id =", photoId)); continue; } string url(photoId.substr(0, 3) + "/" + photoId + ".jpg"); photos.push_back({kPhotoSmallUrl + url, kPhotoOriginalUrl + url}); } return photos; } vector<HotelReview> ParseReviews(json_t const * reviewsArray) { if (reviewsArray == nullptr || !json_is_array(reviewsArray)) return {}; vector<HotelReview> reviews; size_t sz = json_array_size(reviewsArray); string date; for (size_t i = 0; i < sz; ++i) { auto item = json_array_get(reviewsArray, i); HotelReview review; my::FromJSONObject(item, "date", date); istringstream ss(date); tm t = {}; ss >> get_time(&t, "%Y-%m-%d %H:%M:%S"); if (ss.fail()) { LOG(LWARNING, ("Incorrect review date =", date)); continue; } review.m_date = system_clock::from_time_t(mktime(&t)); double score; my::FromJSONObject(item, "average_score", score); review.m_score = static_cast<float>(score); my::FromJSONObject(item, "author", review.m_author); my::FromJSONObject(item, "pros", review.m_pros); my::FromJSONObject(item, "cons", review.m_cons); reviews.push_back(move(review)); } return reviews; } void FillHotelInfo(string const & src, HotelInfo & info) { my::Json root(src.c_str()); my::FromJSONObjectOptionalField(root.get(), "description", info.m_description); double score; my::FromJSONObjectOptionalField(root.get(), "average_score", score); info.m_score = static_cast<float>(score); json_int_t scoreCount = 0; my::FromJSONObjectOptionalField(root.get(), "score_count", scoreCount); info.m_scoreCount = static_cast<uint32_t>(scoreCount); auto const facilitiesArray = json_object_get(root.get(), "facilities"); info.m_facilities = ParseFacilities(facilitiesArray); auto const photosArray = json_object_get(root.get(), "photos"); info.m_photos = ParsePhotos(photosArray); auto const reviewsArray = json_object_get(root.get(), "reviews"); info.m_reviews = ParseReviews(reviewsArray); } void FillPriceAndCurrency(string const & src, string const & currency, string & minPrice, string & priceCurrency) { my::Json root(src.c_str()); if (!json_is_array(root.get())) MYTHROW(my::Json::Exception, ("The answer must contain a json array.")); size_t const rootSize = json_array_size(root.get()); if (rootSize == 0) return; // Read default hotel price and currency. auto obj = json_array_get(root.get(), 0); my::FromJSONObject(obj, "min_price", minPrice); my::FromJSONObject(obj, "currency_code", priceCurrency); if (currency.empty() || priceCurrency == currency) return; // Try to get price in requested currency. json_t * arr = json_object_get(obj, "other_currency"); if (arr == nullptr || !json_is_array(arr)) return; size_t sz = json_array_size(arr); string code; for (size_t i = 0; i < sz; ++i) { auto el = json_array_get(arr, i); my::FromJSONObject(el, "currency_code", code); if (code == currency) { priceCurrency = code; my::FromJSONObject(el, "min_price", minPrice); break; } } } } // namespace namespace booking { // static bool RawApi::GetHotelAvailability(string const & hotelId, string const & currency, string & result, bool testing /* = false */) { char dateArrival[12]{}; char dateDeparture[12]{}; system_clock::time_point p = system_clock::from_time_t(time(nullptr)); tm arrival = my::GmTime(system_clock::to_time_t(p)); tm departure = my::GmTime(system_clock::to_time_t(p + hours(24))); strftime(dateArrival, sizeof(dateArrival), "%Y-%m-%d", &arrival); strftime(dateDeparture, sizeof(dateDeparture), "%Y-%m-%d", &departure); string url = MakeApiUrl("getHotelAvailability", {{"hotel_ids", hotelId}, {"currency_code", currency}, {"arrival_date", dateArrival}, {"departure_date", dateDeparture}}, testing); return RunSimpleHttpRequest(true, url, result); } // static bool RawApi::GetExtendedInfo(string const & hotelId, string const & lang, string & result) { ostringstream os; os << kExtendedHotelInfoBaseUrl << "?hotel_id=" << hotelId << "&lang=" << lang; return RunSimpleHttpRequest(false, os.str(), result); } string Api::GetBookHotelUrl(string const & baseUrl) const { return GetDescriptionUrl(baseUrl) + "#availability"; } string Api::GetDescriptionUrl(string const & baseUrl) const { return baseUrl + string("?aid=") + BOOKING_AFFILIATE_ID; } void Api::GetMinPrice(string const & hotelId, string const & currency, GetMinPriceCallback const & fn) { auto const testingMode = m_testingMode; threads::SimpleThread([hotelId, currency, fn, testingMode]() { string minPrice; string priceCurrency; string httpResult; if (!RawApi::GetHotelAvailability(hotelId, currency, httpResult, testingMode)) { fn(hotelId, minPrice, priceCurrency); return; } try { FillPriceAndCurrency(httpResult, currency, minPrice, priceCurrency); } catch (my::Json::Exception const & e) { LOG(LERROR, (e.Msg())); minPrice.clear(); priceCurrency.clear(); } fn(hotelId, minPrice, priceCurrency); }).detach(); } void Api::GetHotelInfo(string const & hotelId, string const & lang, GetHotelInfoCallback const & fn) { threads::SimpleThread([hotelId, lang, fn]() { HotelInfo info; info.m_hotelId = hotelId; string result; if (!RawApi::GetExtendedInfo(hotelId, lang, result)) { fn(info); return; } try { FillHotelInfo(result, info); } catch (my::Json::Exception const & e) { LOG(LERROR, (e.Msg())); ClearHotelInfo(info); } fn(info); }).detach(); } } // namespace booking <commit_msg>review fixes<commit_after>#include "partners_api/booking_api.hpp" #include "platform/http_client.hpp" #include "platform/platform.hpp" #include "base/gmtime.hpp" #include "base/logging.hpp" #include "base/thread.hpp" #include "std/initializer_list.hpp" #include "std/iomanip.hpp" #include "std/iostream.hpp" #include "std/sstream.hpp" #include "std/utility.hpp" #include "3party/jansson/myjansson.hpp" #include "private.h" namespace { using namespace platform; using namespace booking; string const kBookingApiBaseUrl = "https://distribution-xml.booking.com/json/bookings"; string const kExtendedHotelInfoBaseUrl = "http://hotels.milchakov.map6.devmail.ru/getDescription"; string const kPhotoOriginalUrl = "http://aff.bstatic.com/images/hotel/max500/"; string const kPhotoSmallUrl = "http://aff.bstatic.com/images/hotel/max300/"; bool RunSimpleHttpRequest(bool const needAuth, string const & url, string & result) { HttpClient request(url); if (needAuth) request.SetUserAndPassword(BOOKING_KEY, BOOKING_SECRET); if (request.RunHttpRequest() && !request.WasRedirected() && request.ErrorCode() == 200) { result = request.ServerResponse(); return true; } return false; } string MakeApiUrl(string const & func, initializer_list<pair<string, string>> const & params, bool testing) { ASSERT(!params.empty(), ()); ostringstream os; os << kBookingApiBaseUrl << "." << func << "?"; bool firstParam = true; for (auto const & param : params) { if (firstParam) { firstParam = false; os << ""; } else { os << "&"; } os << param.first << "=" << param.second; } if (testing) os << "&show_test=1"; return os.str(); } void ClearHotelInfo(HotelInfo & info) { info.m_hotelId.clear(); info.m_description.clear(); info.m_photos.clear(); info.m_facilities.clear(); info.m_reviews.clear(); info.m_score = 0.0; info.m_scoreCount = 0; } vector<HotelFacility> ParseFacilities(json_t const * facilitiesArray) { vector<HotelFacility> facilities; if (facilitiesArray == nullptr || !json_is_array(facilitiesArray)) return facilities; size_t sz = json_array_size(facilitiesArray); for (size_t i = 0; i < sz; ++i) { auto item = json_array_get(facilitiesArray, i); HotelFacility facility; my::FromJSONObject(item, "type", facility.m_facilityType); my::FromJSONObject(item, "name", facility.m_name); facilities.push_back(move(facility)); } return facilities; } vector<HotelPhotoUrls> ParsePhotos(json_t const * photosArray) { if (photosArray == nullptr || !json_is_array(photosArray)) return {}; vector<HotelPhotoUrls> photos; size_t sz = json_array_size(photosArray); string photoId; for (size_t i = 0; i < sz; ++i) { auto item = json_array_get(photosArray, i); my::FromJSON(item, photoId); // First three digits of id are used as part of path to photo on the server. if (photoId.size() < 3) { LOG(LWARNING, ("Incorrect photo id =", photoId)); continue; } string url(photoId.substr(0, 3) + "/" + photoId + ".jpg"); photos.push_back({kPhotoSmallUrl + url, kPhotoOriginalUrl + url}); } return photos; } vector<HotelReview> ParseReviews(json_t const * reviewsArray) { if (reviewsArray == nullptr || !json_is_array(reviewsArray)) return {}; vector<HotelReview> reviews; size_t sz = json_array_size(reviewsArray); string date; for (size_t i = 0; i < sz; ++i) { auto item = json_array_get(reviewsArray, i); HotelReview review; my::FromJSONObject(item, "date", date); istringstream ss(date); tm t = {}; ss >> get_time(&t, "%Y-%m-%d %H:%M:%S"); if (ss.fail()) { LOG(LWARNING, ("Incorrect review date =", date)); continue; } review.m_date = system_clock::from_time_t(mktime(&t)); double score; my::FromJSONObject(item, "average_score", score); review.m_score = static_cast<float>(score); my::FromJSONObject(item, "author", review.m_author); my::FromJSONObject(item, "pros", review.m_pros); my::FromJSONObject(item, "cons", review.m_cons); reviews.push_back(move(review)); } return reviews; } void FillHotelInfo(string const & src, HotelInfo & info) { my::Json root(src.c_str()); my::FromJSONObjectOptionalField(root.get(), "description", info.m_description); double score; my::FromJSONObjectOptionalField(root.get(), "average_score", score); info.m_score = static_cast<float>(score); json_int_t scoreCount = 0; my::FromJSONObjectOptionalField(root.get(), "score_count", scoreCount); info.m_scoreCount = static_cast<uint32_t>(scoreCount); auto const facilitiesArray = json_object_get(root.get(), "facilities"); info.m_facilities = ParseFacilities(facilitiesArray); auto const photosArray = json_object_get(root.get(), "photos"); info.m_photos = ParsePhotos(photosArray); auto const reviewsArray = json_object_get(root.get(), "reviews"); info.m_reviews = ParseReviews(reviewsArray); } void FillPriceAndCurrency(string const & src, string const & currency, string & minPrice, string & priceCurrency) { my::Json root(src.c_str()); if (!json_is_array(root.get())) MYTHROW(my::Json::Exception, ("The answer must contain a json array.")); size_t const rootSize = json_array_size(root.get()); if (rootSize == 0) return; // Read default hotel price and currency. auto obj = json_array_get(root.get(), 0); my::FromJSONObject(obj, "min_price", minPrice); my::FromJSONObject(obj, "currency_code", priceCurrency); if (currency.empty() || priceCurrency == currency) return; // Try to get price in requested currency. json_t * arr = json_object_get(obj, "other_currency"); if (arr == nullptr || !json_is_array(arr)) return; size_t sz = json_array_size(arr); string code; for (size_t i = 0; i < sz; ++i) { auto el = json_array_get(arr, i); my::FromJSONObject(el, "currency_code", code); if (code == currency) { priceCurrency = code; my::FromJSONObject(el, "min_price", minPrice); break; } } } } // namespace namespace booking { // static bool RawApi::GetHotelAvailability(string const & hotelId, string const & currency, string & result, bool testing /* = false */) { char dateArrival[12]{}; char dateDeparture[12]{}; system_clock::time_point p = system_clock::from_time_t(time(nullptr)); tm arrival = my::GmTime(system_clock::to_time_t(p)); tm departure = my::GmTime(system_clock::to_time_t(p + hours(24))); strftime(dateArrival, sizeof(dateArrival), "%Y-%m-%d", &arrival); strftime(dateDeparture, sizeof(dateDeparture), "%Y-%m-%d", &departure); string url = MakeApiUrl("getHotelAvailability", {{"hotel_ids", hotelId}, {"currency_code", currency}, {"arrival_date", dateArrival}, {"departure_date", dateDeparture}}, testing); return RunSimpleHttpRequest(true, url, result); } // static bool RawApi::GetExtendedInfo(string const & hotelId, string const & lang, string & result) { ostringstream os; os << kExtendedHotelInfoBaseUrl << "?hotel_id=" << hotelId << "&lang=" << lang; return RunSimpleHttpRequest(false, os.str(), result); } string Api::GetBookHotelUrl(string const & baseUrl) const { return GetDescriptionUrl(baseUrl) + "#availability"; } string Api::GetDescriptionUrl(string const & baseUrl) const { return baseUrl + string("?aid=") + BOOKING_AFFILIATE_ID; } void Api::GetMinPrice(string const & hotelId, string const & currency, GetMinPriceCallback const & fn) { auto const testingMode = m_testingMode; threads::SimpleThread([hotelId, currency, fn, testingMode]() { string minPrice; string priceCurrency; string httpResult; if (!RawApi::GetHotelAvailability(hotelId, currency, httpResult, testingMode)) { fn(hotelId, minPrice, priceCurrency); return; } try { FillPriceAndCurrency(httpResult, currency, minPrice, priceCurrency); } catch (my::Json::Exception const & e) { LOG(LERROR, (e.Msg())); minPrice.clear(); priceCurrency.clear(); } fn(hotelId, minPrice, priceCurrency); }).detach(); } void Api::GetHotelInfo(string const & hotelId, string const & lang, GetHotelInfoCallback const & fn) { threads::SimpleThread([hotelId, lang, fn]() { HotelInfo info; info.m_hotelId = hotelId; string result; if (!RawApi::GetExtendedInfo(hotelId, lang, result)) { fn(info); return; } try { FillHotelInfo(result, info); } catch (my::Json::Exception const & e) { LOG(LERROR, (e.Msg())); ClearHotelInfo(info); } fn(info); }).detach(); } } // namespace booking <|endoftext|>
<commit_before>/* * http_server_test.cpp * * Created on: Oct 26, 2014 * Author: liao */ #include <sstream> #include <cstdlib> #include "simple_log.h" #include "http_server.h" Response hello(Request &request) { Json::Value root; root["hello"] = "world"; return Response(STATUS_OK, root); } Response sayhello(Request &request) { std::string name = request.get_param("name"); std::string age = request.get_param("age"); Json::Value root; root["name"] = name; root["age"] = atoi(age.c_str()); return Response(STATUS_OK, root); } Response login(Request &request) { std::string name = request.get_param("name"); std::string pwd = request.get_param("pwd"); LOG_DEBUG("login user which name:%s, pwd:%s", name.c_str(), pwd.c_str()); Json::Value root; root["code"] = 0; root["msg"] = "login success!"; return Response(STATUS_OK, root); } int main(int argc, char **args) { if (argc < 2) { LOG_ERROR("usage: ./http_server_test [port]"); return -1; } HttpServer http_server; http_server.add_mapping("/hello", hello); http_server.add_mapping("/sayhello", sayhello); http_server.add_mapping("/login", login, POST_METHOD); http_server.start(atoi(args[0])); return 0; } <commit_msg>add port<commit_after>/* * http_server_test.cpp * * Created on: Oct 26, 2014 * Author: liao */ #include <sstream> #include <cstdlib> #include "simple_log.h" #include "http_server.h" Response hello(Request &request) { Json::Value root; root["hello"] = "world"; return Response(STATUS_OK, root); } Response sayhello(Request &request) { std::string name = request.get_param("name"); std::string age = request.get_param("age"); Json::Value root; root["name"] = name; root["age"] = atoi(age.c_str()); return Response(STATUS_OK, root); } Response login(Request &request) { std::string name = request.get_param("name"); std::string pwd = request.get_param("pwd"); LOG_DEBUG("login user which name:%s, pwd:%s", name.c_str(), pwd.c_str()); Json::Value root; root["code"] = 0; root["msg"] = "login success!"; return Response(STATUS_OK, root); } int main(int argc, char **args) { if (argc < 2) { LOG_ERROR("usage: ./http_server_test [port]"); return -1; } HttpServer http_server; http_server.add_mapping("/hello", hello); http_server.add_mapping("/sayhello", sayhello); http_server.add_mapping("/login", login, POST_METHOD); http_server.start(atoi(args[1])); return 0; } <|endoftext|>
<commit_before>#ifndef __BUF_HELPERS_HPP__ #define __BUF_HELPERS_HPP__ #include <vector> // This file contains a mock buffer implementation and can be used // in other tests which rely on buf_t #include "serializer/types.hpp" #include "buffer_cache/buf_patch.hpp" namespace unittest { class test_buf_t { public: test_buf_t(const block_size_t bs, const block_id_t block_id) : block_id(block_id) { data.resize(bs.value(), '\0'); dirty = false; next_patch_counter = 1; } block_id_t get_block_id() { return block_id; } const void *get_data_read() { return &data[0]; } void *get_data_major_write() { dirty = true; return &data[0]; } void set_data(const void* dest, const void* src, const size_t n) { memcpy((char*)dest, (char*)src, n); } void move_data(const void* dest, const void* src, const size_t n) { memmove((char*)dest, (char*)src, n); } void apply_patch(buf_patch_t *patch) { patch->apply_to_buf((char*)get_data_major_write()); delete patch; } patch_counter_t get_next_patch_counter() { return next_patch_counter++; } void mark_deleted() { } void release() { delete this; } bool is_dirty() { return dirty; } private: block_id_t block_id; patch_counter_t next_patch_counter; bool dirty; std::vector<char> data; }; } // namespace unittest #define CUSTOM_BUF_TYPE typedef unittest::test_buf_t buf_t; #endif /* __BUF_HELPERS_HPP__ */ <commit_msg>Made test_buf_t non-copyable.<commit_after>#ifndef __BUF_HELPERS_HPP__ #define __BUF_HELPERS_HPP__ #include <vector> // This file contains a mock buffer implementation and can be used // in other tests which rely on buf_t #include "serializer/types.hpp" #include "buffer_cache/buf_patch.hpp" namespace unittest { class test_buf_t { public: test_buf_t(const block_size_t bs, const block_id_t block_id) : block_id(block_id) { data.resize(bs.value(), '\0'); dirty = false; next_patch_counter = 1; } block_id_t get_block_id() { return block_id; } const void *get_data_read() { return &data[0]; } void *get_data_major_write() { dirty = true; return &data[0]; } void set_data(const void* dest, const void* src, const size_t n) { memcpy((char*)dest, (char*)src, n); } void move_data(const void* dest, const void* src, const size_t n) { memmove((char*)dest, (char*)src, n); } void apply_patch(buf_patch_t *patch) { patch->apply_to_buf((char*)get_data_major_write()); delete patch; } patch_counter_t get_next_patch_counter() { return next_patch_counter++; } void mark_deleted() { } void release() { delete this; } bool is_dirty() { return dirty; } private: block_id_t block_id; patch_counter_t next_patch_counter; bool dirty; std::vector<char> data; DISABLE_COPYING(test_buf_t); }; } // namespace unittest #define CUSTOM_BUF_TYPE typedef unittest::test_buf_t buf_t; #endif /* __BUF_HELPERS_HPP__ */ <|endoftext|>
<commit_before>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // --------------------------------------------------------------------------- // SString_COM.cpp // --------------------------------------------------------------------------- #include "stdafx.h" #include "sstring.h" #include "ex.h" #include "holder.h" #define DEFAULT_RESOURCE_STRING_SIZE 255 //---------------------------------------------------------------------------- // Load the string resource into this string. //---------------------------------------------------------------------------- BOOL SString::LoadResource(CCompRC::ResourceCategory eCategory, int resourceID) { return SUCCEEDED(LoadResourceAndReturnHR(eCategory, resourceID)); } HRESULT SString::LoadResourceAndReturnHR(CCompRC::ResourceCategory eCategory, int resourceID) { WRAPPER_NO_CONTRACT; return LoadResourceAndReturnHR(NULL, eCategory,resourceID); } HRESULT SString::LoadResourceAndReturnHR(CCompRC* pResourceDLL, CCompRC::ResourceCategory eCategory, int resourceID) { CONTRACT(BOOL) { INSTANCE_CHECK; NOTHROW; } CONTRACT_END; HRESULT hr = E_FAIL; #ifndef FEATURE_UTILCODE_NO_DEPENDENCIES if (pResourceDLL == NULL) { pResourceDLL = CCompRC::GetDefaultResourceDll(); } if (pResourceDLL != NULL) { int size = 0; EX_TRY { if (GetRawCount() == 0) Resize(DEFAULT_RESOURCE_STRING_SIZE, REPRESENTATION_UNICODE); while (TRUE) { // First try and load the string in the amount of space that we have. // In fatal error reporting scenarios, we may not have enough memory to // allocate a larger buffer. hr = pResourceDLL->LoadString(eCategory, resourceID, GetRawUnicode(), GetRawCount()+1,&size); if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) { if (FAILED(hr)) { Clear(); break; } // Although we cannot generally detect truncation, we can tell if we // used up all the space (in which case we will assume truncation.) if (size < (int)GetRawCount()) { break; } } // Double the size and try again. Resize(size*2, REPRESENTATION_UNICODE); } if (SUCCEEDED(hr)) { Truncate(Begin() + (COUNT_T) wcslen(GetRawUnicode())); } Normalize(); } EX_CATCH { hr = E_FAIL; } EX_END_CATCH(SwallowAllExceptions); } #endif //!FEATURE_UTILCODE_NO_DEPENDENCIES RETURN hr; } // SString::LoadResourceAndReturnHR <commit_msg>Fix a CrossGen assert on Linux<commit_after>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // --------------------------------------------------------------------------- // SString_COM.cpp // --------------------------------------------------------------------------- #include "stdafx.h" #include "sstring.h" #include "ex.h" #include "holder.h" #define DEFAULT_RESOURCE_STRING_SIZE 255 //---------------------------------------------------------------------------- // Load the string resource into this string. //---------------------------------------------------------------------------- BOOL SString::LoadResource(CCompRC::ResourceCategory eCategory, int resourceID) { return SUCCEEDED(LoadResourceAndReturnHR(eCategory, resourceID)); } HRESULT SString::LoadResourceAndReturnHR(CCompRC::ResourceCategory eCategory, int resourceID) { WRAPPER_NO_CONTRACT; return LoadResourceAndReturnHR(NULL, eCategory,resourceID); } HRESULT SString::LoadResourceAndReturnHR(CCompRC* pResourceDLL, CCompRC::ResourceCategory eCategory, int resourceID) { CONTRACT(BOOL) { INSTANCE_CHECK; NOTHROW; } CONTRACT_END; HRESULT hr = E_FAIL; #if !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && !(defined(CROSSGEN_COMPILE) && defined(PLATFORM_UNIX)) if (pResourceDLL == NULL) { pResourceDLL = CCompRC::GetDefaultResourceDll(); } if (pResourceDLL != NULL) { int size = 0; EX_TRY { if (GetRawCount() == 0) Resize(DEFAULT_RESOURCE_STRING_SIZE, REPRESENTATION_UNICODE); while (TRUE) { // First try and load the string in the amount of space that we have. // In fatal error reporting scenarios, we may not have enough memory to // allocate a larger buffer. hr = pResourceDLL->LoadString(eCategory, resourceID, GetRawUnicode(), GetRawCount()+1,&size); if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) { if (FAILED(hr)) { Clear(); break; } // Although we cannot generally detect truncation, we can tell if we // used up all the space (in which case we will assume truncation.) if (size < (int)GetRawCount()) { break; } } // Double the size and try again. Resize(size*2, REPRESENTATION_UNICODE); } if (SUCCEEDED(hr)) { Truncate(Begin() + (COUNT_T) wcslen(GetRawUnicode())); } Normalize(); } EX_CATCH { hr = E_FAIL; } EX_END_CATCH(SwallowAllExceptions); } #endif //!FEATURE_UTILCODE_NO_DEPENDENCIES RETURN hr; } // SString::LoadResourceAndReturnHR <|endoftext|>
<commit_before>#include "matcherexception.h" #include "3rd-party/catch.hpp" using namespace newsboat; extern "C" { MatcherErrorFfi rs_get_test_attr_unavail_error(); MatcherErrorFfi rs_get_test_invalid_regex_error(); } TEST_CASE("Can be constructed from Rust error returned over FFI", "[MatcherException]") { SECTION("Attribute unavailable") { const auto e = MatcherException::from_rust_error( rs_get_test_attr_unavail_error()); REQUIRE(e.type() == MatcherException::Type::ATTRIB_UNAVAIL); REQUIRE(e.info() == "test_attribute"); REQUIRE(e.info2().empty()); } SECTION("Invalid regex") { const auto e = MatcherException::from_rust_error( rs_get_test_invalid_regex_error()); REQUIRE(e.type() == MatcherException::Type::INVALID_REGEX); REQUIRE(e.info() == "?!"); REQUIRE(e.info2() == "inconceivable happened!"); } } <commit_msg>Test that MatcherException::what() returns non-empty string<commit_after>#include "matcherexception.h" #include "3rd-party/catch.hpp" #include <cstring> using namespace newsboat; extern "C" { MatcherErrorFfi rs_get_test_attr_unavail_error(); MatcherErrorFfi rs_get_test_invalid_regex_error(); } TEST_CASE("Can be constructed from Rust error returned over FFI", "[MatcherException]") { SECTION("Attribute unavailable") { const auto e = MatcherException::from_rust_error( rs_get_test_attr_unavail_error()); REQUIRE(e.type() == MatcherException::Type::ATTRIB_UNAVAIL); REQUIRE(e.info() == "test_attribute"); REQUIRE(e.info2().empty()); REQUIRE_FALSE(strlen(e.what()) == 0); } SECTION("Invalid regex") { const auto e = MatcherException::from_rust_error( rs_get_test_invalid_regex_error()); REQUIRE(e.type() == MatcherException::Type::INVALID_REGEX); REQUIRE(e.info() == "?!"); REQUIRE(e.info2() == "inconceivable happened!"); REQUIRE_FALSE(strlen(e.what()) == 0); } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------- *//** * * @file student.cpp * * @brief Evaluate the Student-T distribution function. * @author Florian Schoppmann * @date November 2010 * *//* -------------------------------------------------------------------- *//** * * @file student.cpp * * Emprirical results indicate that the numerical quality of the series * expansion from [1] (see notes below) is vastly superior to using continued * fractions for computing the cdf via the incomplete beta function. * * @literature * * [1] Abramowitz and Stegun, Handbook of Mathematical Functions with Formulas, * Graphs, and Mathematical Tables, 1972 * page 948: http://people.math.sfu.ca/~cbm/aands/page_948.htm * * Further reading (for computing the Student-T cdf via the incomplete beta * function): * * [2] NIST Digital Library of Mathematical Functions, Ch. 8, * Incomplete Gamma and Related Functions, * http://dlmf.nist.gov/8.17 * * [3] Lentz, Generating Bessel functions in Mie scattering calculations using * continued fractions, Applied Optics, Vol. 15, No. 3, 1976 * * [4] Thompson and Barnett, Coulomb and Bessel Functions of Complex Arguments * and Order, Journal of Computational Physics, Vol. 64, 1986 * * [5] Cuyt et al., Handbook of Continued Fractions for Special Functions, * Springer, 2008 * * [6] Gil et al., Numerical Methods for Special Functions, SIAM, 2008 * * [7] Press et al., Numerical Recipes in C++, 3rd edition, * Cambridge Univ. Press, 2007 * * [8] DiDonato, Morris, Jr., Algorithm 708: Significant Digit Computation of * the Incomplete Beta Function Ratios, ACM Transactions on Mathematical * Software, Vol. 18, No. 3, 1992 * * Approximating the Student-T distribution function with the normal * distribution: * * [9] Gleason, A note on a proposed student t approximation, Computational * Statistics & Data Analysis, Vol. 34, No. 1, 2000 * * [10] Gaver and Kafadar, A Retrievable Recipe for Inverse t, The American * Statistician, Vol. 38, No. 4, 1984 */ #include <modules/prob/student.hpp> // The error function is in C99 and TR1, but not in the official C++ Standard // (before C++0x). We therefore use the Boost implementation #include <boost/math/special_functions/erf.hpp> namespace madlib { namespace modules { namespace prob { /* Prototypes of internal functions */ static inline double normal_cdf(double t); static double studentT_cdf_approx(int64_t nu, double t); /** * @brief Student-t cumulative distribution function: C++ interface * * Compute \f$ Pr[T <= t] \f$ for Student-t distributed T with \f$ \nu \f$ * degrees of freedom. * * For nu >= 1000000, we just use the normal distribution as an approximation. * For 1000000 >= nu >= 200, we use a simple approximation from [9]. * We are much more cautious than usual here (it is folklore that the normal * distribution is a "good" estimate for Student-T if nu >= 30), but we can * afford the extra work as this function is not designed to be called from * inner loops. Performance should still be reasonably good, with at most ~100 * iterations in any case (just one if nu >= 200). * * For nu < 200, we use the series expansions 26.7.3 and 26.7.4 from [1] and * substitute sin(theta) = t/sqrt(n * z), where z = 1 + t^2/nu. * * This gives: * @verbatim * t * A(t|1) = 2 arctan( -------- ) , * sqrt(nu) * * (nu-3)/2 * 2 [ t t -- 2 * 4 * ... * (2i) ] * A(t|nu) = - * [ arctan( -------- ) + ------------ * \ ---------------------- ] * π [ sqrt(nu) sqrt(nu) * z /_ 3 * ... * (2i+1) * z^i ] * i=0 * for odd nu > 1, and * * (nu-2)/2 * t -- 1 * 3 * ... * (2i - 1) * A(t|nu) = ------------ * \ ------------------------ for even nu, * sqrt(nu * z) /_ 2 * 4 * ... * (2i) * z^i * i=0 * * where A(t|nu) = Pr[|T| <= t]. * @endverbatim * * @param nu Degree of freedom (>= 1) * @param t Argument to cdf. * * Note: The running time of calculating the series is proportional to nu. This * We therefore use the normal distribution as an approximation for large nu. * Another idea for handling this case can be found in reference [8]. */ double studentT_cdf(int64_t nu, double t) { double z, t_by_sqrt_nu; double A, /* contains A(t|nu) */ prod = 1., sum = 1.; /* Handle extreme cases. See above. */ if (nu <= 0) return NAN; else if (nu >= 1000000) return normal_cdf(t); else if (nu >= 200) return studentT_cdf_approx(nu, t); /* Handle main case (nu < 200) in the rest of the function. */ z = 1. + t * t / nu; t_by_sqrt_nu = std::fabs(t) / std::sqrt(nu); if (nu == 1) { A = 2. / M_PI * std::atan(t_by_sqrt_nu); } else if (nu & 1) /* odd nu > 1 */ { for (int j = 2; j <= nu - 3; j += 2) { prod = prod * j / ((j + 1) * z); sum = sum + prod; } A = 2 / M_PI * ( std::atan(t_by_sqrt_nu) + t_by_sqrt_nu / z * sum ); } else /* even nu */ { for (int j = 2; j <= nu - 2; j += 2) { prod = prod * (j - 1) / (j * z); sum = sum + prod; } A = t_by_sqrt_nu / std::sqrt(z) * sum; } /* A should obviously lie withing the interval [0,1] plus minus (hopefully * small) rounding errors. */ if (A > 1.) A = 1.; else if (A < 0.) A = 0.; /* The Student-T distribution is obviously symmetric around t=0... */ if (t < 0) return .5 * (1. - A); else return 1. - .5 * (1. - A); } /** * @brief Compute the normal distribution function using the library error function. * * This approximation satisfies * rel_error < 0.0001 || abs_error < 0.00000001 * for all nu >= 1000000. (Tested on Mac OS X 10.6, gcc-4.2.) */ static inline double normal_cdf(double t) { return .5 + .5 * boost::math::erf(t / std::sqrt(2.)); } /** * @brief Approximate Student-T distribution using a formula suggested in * [9], which goes back to an approximation suggested in [10]. * * Compared to the series expansion, this approximation satisfies * rel_error < 0.0001 || abs_error < 0.00000001 * for all nu >= 200. (Tested on Mac OS X 10.6, gcc-4.2.) */ static double studentT_cdf_approx(int64_t nu, double t) { double g = (nu - 1.5) / ((nu - 1) * (nu - 1)), z = std::sqrt( std::log(1. + t * t / nu) / g ); if (t < 0) z *= -1.; return normal_cdf(z); } /** * @brief Student-t cumulative distribution function: In-database interface */ AnyValue student_t_cdf(AbstractDBInterface &db, AnyValue args) { AnyValue::iterator arg(args); // Arguments from SQL call const int64_t nu = *arg++; const double t = *arg; arma::arma_stop("I don't like this"); /* We want to ensure nu > 0 */ if (nu <= 0) throw std::domain_error("Student-t distribution undefined for " "degree of freedom <= 0"); return studentT_cdf(nu, t); } } // namespace prob } // namespace modules } // namespace regress <commit_msg>Quick fix for MADLIB-145.<commit_after>/* ----------------------------------------------------------------------- *//** * * @file student.cpp * * @brief Evaluate the Student-T distribution function. * @author Florian Schoppmann * @date November 2010 * *//* -------------------------------------------------------------------- *//** * * @file student.cpp * * Emprirical results indicate that the numerical quality of the series * expansion from [1] (see notes below) is vastly superior to using continued * fractions for computing the cdf via the incomplete beta function. * * @literature * * [1] Abramowitz and Stegun, Handbook of Mathematical Functions with Formulas, * Graphs, and Mathematical Tables, 1972 * page 948: http://people.math.sfu.ca/~cbm/aands/page_948.htm * * Further reading (for computing the Student-T cdf via the incomplete beta * function): * * [2] NIST Digital Library of Mathematical Functions, Ch. 8, * Incomplete Gamma and Related Functions, * http://dlmf.nist.gov/8.17 * * [3] Lentz, Generating Bessel functions in Mie scattering calculations using * continued fractions, Applied Optics, Vol. 15, No. 3, 1976 * * [4] Thompson and Barnett, Coulomb and Bessel Functions of Complex Arguments * and Order, Journal of Computational Physics, Vol. 64, 1986 * * [5] Cuyt et al., Handbook of Continued Fractions for Special Functions, * Springer, 2008 * * [6] Gil et al., Numerical Methods for Special Functions, SIAM, 2008 * * [7] Press et al., Numerical Recipes in C++, 3rd edition, * Cambridge Univ. Press, 2007 * * [8] DiDonato, Morris, Jr., Algorithm 708: Significant Digit Computation of * the Incomplete Beta Function Ratios, ACM Transactions on Mathematical * Software, Vol. 18, No. 3, 1992 * * Approximating the Student-T distribution function with the normal * distribution: * * [9] Gleason, A note on a proposed student t approximation, Computational * Statistics & Data Analysis, Vol. 34, No. 1, 2000 * * [10] Gaver and Kafadar, A Retrievable Recipe for Inverse t, The American * Statistician, Vol. 38, No. 4, 1984 */ #include <modules/prob/student.hpp> // The error function is in C99 and TR1, but not in the official C++ Standard // (before C++0x). We therefore use the Boost implementation #include <boost/math/special_functions/erf.hpp> namespace madlib { namespace modules { namespace prob { /* Prototypes of internal functions */ static inline double normal_cdf(double t); static double studentT_cdf_approx(int64_t nu, double t); /** * @brief Student-t cumulative distribution function: C++ interface * * Compute \f$ Pr[T <= t] \f$ for Student-t distributed T with \f$ \nu \f$ * degrees of freedom. * * For nu >= 1000000, we just use the normal distribution as an approximation. * For 1000000 >= nu >= 200, we use a simple approximation from [9]. * We are much more cautious than usual here (it is folklore that the normal * distribution is a "good" estimate for Student-T if nu >= 30), but we can * afford the extra work as this function is not designed to be called from * inner loops. Performance should still be reasonably good, with at most ~100 * iterations in any case (just one if nu >= 200). * * For nu < 200, we use the series expansions 26.7.3 and 26.7.4 from [1] and * substitute sin(theta) = t/sqrt(n * z), where z = 1 + t^2/nu. * * This gives: * @verbatim * t * A(t|1) = 2 arctan( -------- ) , * sqrt(nu) * * (nu-3)/2 * 2 [ t t -- 2 * 4 * ... * (2i) ] * A(t|nu) = - * [ arctan( -------- ) + ------------ * \ ---------------------- ] * π [ sqrt(nu) sqrt(nu) * z /_ 3 * ... * (2i+1) * z^i ] * i=0 * for odd nu > 1, and * * (nu-2)/2 * t -- 1 * 3 * ... * (2i - 1) * A(t|nu) = ------------ * \ ------------------------ for even nu, * sqrt(nu * z) /_ 2 * 4 * ... * (2i) * z^i * i=0 * * where A(t|nu) = Pr[|T| <= t]. * @endverbatim * * @param nu Degree of freedom (>= 1) * @param t Argument to cdf. * * Note: The running time of calculating the series is proportional to nu. This * We therefore use the normal distribution as an approximation for large nu. * Another idea for handling this case can be found in reference [8]. */ double studentT_cdf(int64_t nu, double t) { double z, t_by_sqrt_nu; double A, /* contains A(t|nu) */ prod = 1., sum = 1.; /* Handle extreme cases. See above. */ if (nu <= 0) return NAN; else if (nu >= 1000000) return normal_cdf(t); else if (nu >= 200) return studentT_cdf_approx(nu, t); /* Handle main case (nu < 200) in the rest of the function. */ z = 1. + t * t / nu; t_by_sqrt_nu = std::fabs(t) / std::sqrt(nu); if (nu == 1) { A = 2. / M_PI * std::atan(t_by_sqrt_nu); } else if (nu & 1) /* odd nu > 1 */ { for (int j = 2; j <= nu - 3; j += 2) { prod = prod * j / ((j + 1) * z); sum = sum + prod; } A = 2 / M_PI * ( std::atan(t_by_sqrt_nu) + t_by_sqrt_nu / z * sum ); } else /* even nu */ { for (int j = 2; j <= nu - 2; j += 2) { prod = prod * (j - 1) / (j * z); sum = sum + prod; } A = t_by_sqrt_nu / std::sqrt(z) * sum; } /* A should obviously lie withing the interval [0,1] plus minus (hopefully * small) rounding errors. */ if (A > 1.) A = 1.; else if (A < 0.) A = 0.; /* The Student-T distribution is obviously symmetric around t=0... */ if (t < 0) return .5 * (1. - A); else return 1. - .5 * (1. - A); } /** * @brief Compute the normal distribution function using the library error function. * * This approximation satisfies * rel_error < 0.0001 || abs_error < 0.00000001 * for all nu >= 1000000. (Tested on Mac OS X 10.6, gcc-4.2.) */ static inline double normal_cdf(double t) { return .5 + .5 * boost::math::erf(t / std::sqrt(2.)); } /** * @brief Approximate Student-T distribution using a formula suggested in * [9], which goes back to an approximation suggested in [10]. * * Compared to the series expansion, this approximation satisfies * rel_error < 0.0001 || abs_error < 0.00000001 * for all nu >= 200. (Tested on Mac OS X 10.6, gcc-4.2.) */ static double studentT_cdf_approx(int64_t nu, double t) { double g = (nu - 1.5) / ((nu - 1) * (nu - 1)), z = std::sqrt( std::log(1. + t * t / nu) / g ); if (t < 0) z *= -1.; return normal_cdf(z); } /** * @brief Student-t cumulative distribution function: In-database interface */ AnyValue student_t_cdf(AbstractDBInterface &db, AnyValue args) { AnyValue::iterator arg(args); // Arguments from SQL call const int64_t nu = *arg++; const double t = *arg; /* We want to ensure nu > 0 */ if (nu <= 0) throw std::domain_error("Student-t distribution undefined for " "degree of freedom <= 0"); return studentT_cdf(nu, t); } } // namespace prob } // namespace modules } // namespace regress <|endoftext|>
<commit_before>#include "addresstablemodel.h" #include "guiutil.h" #include "main.h" #include <QFont> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} }; // Private implementation struct AddressTablePriv { QList<AddressTableEntry> cachedAddressTable; void refreshAddressTable() { cachedAddressTable.clear(); CRITICAL_BLOCK(cs_mapKeys) CRITICAL_BLOCK(cs_mapAddressBook) { BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, mapAddressBook) { std::string strAddress = item.first; std::string strName = item.second; uint160 hash160; bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160)); cachedAddressTable.append(AddressTableEntry(fMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending, QString::fromStdString(strName), QString::fromStdString(strAddress))); } } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(QObject *parent) : QAbstractTableModel(parent),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: return rec->label; case Address: return rec->address; } } else if (role == Qt::FontRole) { if(index.column() == Address) { return GUIUtil::bitcoinAddressFont(); } } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex & index, const QVariant & value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::EditRole) { switch(index.column()) { case Label: SetAddressBookName(rec->address.toStdString(), value.toString().toStdString()); rec->label = value.toString(); break; case Address: // Double-check that we're not overwriting receiving address if(rec->type == AddressTableEntry::Sending) { // Remove old entry CWalletDB().EraseName(rec->address.toStdString()); // Add new entry with new address SetAddressBookName(value.toString().toStdString(), rec->label.toStdString()); rec->address = value.toString(); } break; } emit dataChanged(index, index); return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex & parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateList() { // Update internal model from Bitcoin core beginResetModel(); priv->refreshAddressTable(); endResetModel(); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); if(type == Send) { // Check for duplicate CRITICAL_BLOCK(cs_mapAddressBook) { if(mapAddressBook.count(strAddress)) { return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label strAddress = PubKeyToAddress(GetKeyFromKeyPool()); } else { return QString(); } // Add entry and update list SetAddressBookName(strAddress, strLabel); updateList(); return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex & parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } CWalletDB().EraseName(rec->address.toStdString()); updateList(); return true; } <commit_msg>highlight default address<commit_after>#include "addresstablemodel.h" #include "guiutil.h" #include "main.h" #include <QFont> #include <QColor> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} bool isDefaultAddress() const { std::vector<unsigned char> vchPubKey; if (CWalletDB("r").ReadDefaultKey(vchPubKey)) { return address == QString::fromStdString(PubKeyToAddress(vchPubKey)); } return false; } }; // Private implementation struct AddressTablePriv { QList<AddressTableEntry> cachedAddressTable; void refreshAddressTable() { cachedAddressTable.clear(); CRITICAL_BLOCK(cs_mapKeys) CRITICAL_BLOCK(cs_mapAddressBook) { BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, mapAddressBook) { std::string strAddress = item.first; std::string strName = item.second; uint160 hash160; bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160)); cachedAddressTable.append(AddressTableEntry(fMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending, QString::fromStdString(strName), QString::fromStdString(strAddress))); } } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(QObject *parent) : QAbstractTableModel(parent),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: return rec->label; case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } if(rec->isDefaultAddress()) { font.setBold(true); } return font; } else if (role == Qt::ForegroundRole) { // Show default address in alternative color if(rec->isDefaultAddress()) { return QColor(0,0,255); } } else if (role == Qt::ToolTipRole) { if(rec->isDefaultAddress()) { return tr("Default receiving address"); } } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex & index, const QVariant & value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::EditRole) { switch(index.column()) { case Label: SetAddressBookName(rec->address.toStdString(), value.toString().toStdString()); rec->label = value.toString(); break; case Address: // Double-check that we're not overwriting receiving address if(rec->type == AddressTableEntry::Sending) { // Remove old entry CWalletDB().EraseName(rec->address.toStdString()); // Add new entry with new address SetAddressBookName(value.toString().toStdString(), rec->label.toStdString()); rec->address = value.toString(); } break; } emit dataChanged(index, index); return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex & parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateList() { // Update internal model from Bitcoin core beginResetModel(); priv->refreshAddressTable(); endResetModel(); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); if(type == Send) { // Check for duplicate CRITICAL_BLOCK(cs_mapAddressBook) { if(mapAddressBook.count(strAddress)) { return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label strAddress = PubKeyToAddress(GetKeyFromKeyPool()); } else { return QString(); } // Add entry and update list SetAddressBookName(strAddress, strLabel); updateList(); return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex & parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } CWalletDB().EraseName(rec->address.toStdString()); updateList(); return true; } <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // 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 "cpu_workspace_insertion.hpp" #include <algorithm> #include <iostream> #include <numeric> #include <unordered_set> #include "ngraph/graph_util.hpp" #include "ngraph/log.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/batch_norm.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/convolution.hpp" #include "ngraph/op/divide.hpp" #include "ngraph/op/dot.hpp" #include "ngraph/op/exp.hpp" #include "ngraph/op/get_output_element.hpp" #include "ngraph/op/max_pool.hpp" #include "ngraph/op/multiply.hpp" #include "ngraph/op/negative.hpp" #include "ngraph/op/pad.hpp" #include "ngraph/op/parameter.hpp" #include "ngraph/op/relu.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/op/sqrt.hpp" #include "ngraph/op/subtract.hpp" #include "ngraph/op/sum.hpp" #include "ngraph/pattern/matcher.hpp" #include "ngraph/pattern/op/label.hpp" #include "ngraph/pattern/op/skip.hpp" #include "ngraph/runtime/cpu/op/batch_norm_relu.hpp" #include "ngraph/runtime/cpu/op/conv_bias.hpp" #include "ngraph/runtime/cpu/op/conv_relu.hpp" #include "ngraph/runtime/cpu/op/matmul_bias.hpp" #include "ngraph/runtime/cpu/op/max_pool_with_indices.hpp" #include "ngraph/runtime/cpu/op/sigmoid.hpp" using namespace ngraph; static std::shared_ptr<pattern::Matcher> create_maxpool_with_indices_matcher() { Shape shape_data{1, 1, 14}; auto data = std::make_shared<pattern::op::Label>(element::f32, shape_data); Shape window_shape{3}; auto max_pool = std::make_shared<op::MaxPool>(data, window_shape); auto delta = std::make_shared<pattern::op::Label>(element::f32, max_pool->get_shape()); auto max_pool_label = std::make_shared<pattern::op::Label>(element::f32, max_pool->get_shape()); auto max_pool_bprop = std::make_shared<op::MaxPoolBackprop>(data, delta, max_pool_label, max_pool->get_window_shape(), max_pool->get_window_movement_strides(), max_pool->get_padding_below(), max_pool->get_padding_above()); return std::make_shared<pattern::Matcher>(max_pool_bprop); } bool runtime::cpu::pass::CPUWorkspaceInsertion::run_on_function(std::shared_ptr<ngraph::Function> f) { auto matcher = create_maxpool_with_indices_matcher(); bool replaced = false; for (auto n : f->get_ordered_ops()) { if (n->is_output() || n->is_parameter()) { continue; } if (matcher->match(n) && transform(*matcher)) { replaced = true; } } return replaced; } bool runtime::cpu::pass::CPUWorkspaceInsertion::transform(pattern::Matcher& m) { auto data = std::static_pointer_cast<pattern::op::Label>(m.get_pattern()->get_argument(0)); auto delta = std::static_pointer_cast<pattern::op::Label>(m.get_pattern()->get_argument(1)); auto max_pool = std::static_pointer_cast<pattern::op::Label>(m.get_pattern()->get_argument(2)); NGRAPH_DEBUG << "In a callback for construct_max_pool_with_indices against " << m.get_match_root()->get_name(); auto pattern_map = m.get_pattern_map(); auto m_max_pool = std::static_pointer_cast<op::MaxPool>(pattern_map[max_pool]); auto m_max_pool_bprop = std::static_pointer_cast<op::MaxPoolBackprop>(m.get_match_root()); if (m_max_pool_bprop->get_shape().size() != 4 || m_max_pool_bprop->get_window_shape().size() != 2 || m_max_pool_bprop->get_input_element_type(0) != element::f32) { NGRAPH_DEBUG << "MKLDNN doesn't support inputs of given shape type"; return false; } auto max_pool_with_indices = std::make_shared<op::MaxPoolWithIndices>(pattern_map[data], m_max_pool->get_window_shape(), m_max_pool->get_window_movement_strides(), m_max_pool->get_padding_below(), m_max_pool->get_padding_above()); auto max_pool_with_indices_output = std::make_shared<op::GetOutputElement>(max_pool_with_indices, 0); auto max_pool_with_indices_indices = std::make_shared<op::GetOutputElement>(max_pool_with_indices, 1); // rewire users to use a new MaxPoolWithIndices (maxpool's output) for (auto& o : m_max_pool->get_outputs()) { std::set<ngraph::descriptor::Input*> copy{begin(o.get_inputs()), end(o.get_inputs())}; for (auto i : copy) { i->replace_output(max_pool_with_indices_output->get_outputs().at(0)); } } // create a new max_pool_with_indices_bprop auto max_pool_with_indices_bprop = std::make_shared<op::MaxPoolWithIndicesBackprop>(pattern_map[data], pattern_map[delta], max_pool_with_indices_indices, m_max_pool->get_window_shape(), m_max_pool->get_window_movement_strides(), m_max_pool->get_padding_below(), m_max_pool->get_padding_above()); ngraph::replace_node(m_max_pool_bprop, max_pool_with_indices_bprop); if (m_return_indices) { m_indices_list.push_back(max_pool_with_indices_indices); } return true; } <commit_msg>double check that the third arg is indeed maxpool (#2116)<commit_after>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // 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 "cpu_workspace_insertion.hpp" #include <algorithm> #include <iostream> #include <numeric> #include <unordered_set> #include "ngraph/graph_util.hpp" #include "ngraph/log.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/batch_norm.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/convolution.hpp" #include "ngraph/op/divide.hpp" #include "ngraph/op/dot.hpp" #include "ngraph/op/exp.hpp" #include "ngraph/op/get_output_element.hpp" #include "ngraph/op/max_pool.hpp" #include "ngraph/op/multiply.hpp" #include "ngraph/op/negative.hpp" #include "ngraph/op/pad.hpp" #include "ngraph/op/parameter.hpp" #include "ngraph/op/relu.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/op/sqrt.hpp" #include "ngraph/op/subtract.hpp" #include "ngraph/op/sum.hpp" #include "ngraph/pattern/matcher.hpp" #include "ngraph/pattern/op/label.hpp" #include "ngraph/pattern/op/skip.hpp" #include "ngraph/runtime/cpu/op/batch_norm_relu.hpp" #include "ngraph/runtime/cpu/op/conv_bias.hpp" #include "ngraph/runtime/cpu/op/conv_relu.hpp" #include "ngraph/runtime/cpu/op/matmul_bias.hpp" #include "ngraph/runtime/cpu/op/max_pool_with_indices.hpp" #include "ngraph/runtime/cpu/op/sigmoid.hpp" using namespace ngraph; static std::shared_ptr<pattern::Matcher> create_maxpool_with_indices_matcher() { Shape shape_data{1, 1, 14}; auto data = std::make_shared<pattern::op::Label>(element::f32, shape_data); Shape window_shape{3}; auto max_pool = std::make_shared<op::MaxPool>(data, window_shape); auto delta = std::make_shared<pattern::op::Label>(element::f32, max_pool->get_shape()); auto is_max_pool = pattern::has_class<op::MaxPool>(); auto max_pool_label = std::make_shared<pattern::op::Label>(element::f32, max_pool->get_shape(), is_max_pool); auto max_pool_bprop = std::make_shared<op::MaxPoolBackprop>(data, delta, max_pool_label, max_pool->get_window_shape(), max_pool->get_window_movement_strides(), max_pool->get_padding_below(), max_pool->get_padding_above()); return std::make_shared<pattern::Matcher>(max_pool_bprop); } bool runtime::cpu::pass::CPUWorkspaceInsertion::run_on_function(std::shared_ptr<ngraph::Function> f) { auto matcher = create_maxpool_with_indices_matcher(); bool replaced = false; for (auto n : f->get_ordered_ops()) { if (n->is_output() || n->is_parameter()) { continue; } if (matcher->match(n) && transform(*matcher)) { replaced = true; } } return replaced; } bool runtime::cpu::pass::CPUWorkspaceInsertion::transform(pattern::Matcher& m) { auto data = std::static_pointer_cast<pattern::op::Label>(m.get_pattern()->get_argument(0)); auto delta = std::static_pointer_cast<pattern::op::Label>(m.get_pattern()->get_argument(1)); auto max_pool = std::static_pointer_cast<pattern::op::Label>(m.get_pattern()->get_argument(2)); NGRAPH_DEBUG << "In a callback for construct_max_pool_with_indices against " << m.get_match_root()->get_name(); auto pattern_map = m.get_pattern_map(); auto m_max_pool = std::static_pointer_cast<op::MaxPool>(pattern_map[max_pool]); auto m_max_pool_bprop = std::static_pointer_cast<op::MaxPoolBackprop>(m.get_match_root()); if (m_max_pool_bprop->get_shape().size() != 4 || m_max_pool_bprop->get_window_shape().size() != 2 || m_max_pool_bprop->get_input_element_type(0) != element::f32) { NGRAPH_DEBUG << "MKLDNN doesn't support inputs of given shape type"; return false; } auto max_pool_with_indices = std::make_shared<op::MaxPoolWithIndices>(pattern_map[data], m_max_pool->get_window_shape(), m_max_pool->get_window_movement_strides(), m_max_pool->get_padding_below(), m_max_pool->get_padding_above()); auto max_pool_with_indices_output = std::make_shared<op::GetOutputElement>(max_pool_with_indices, 0); auto max_pool_with_indices_indices = std::make_shared<op::GetOutputElement>(max_pool_with_indices, 1); // rewire users to use a new MaxPoolWithIndices (maxpool's output) for (auto& o : m_max_pool->get_outputs()) { std::set<ngraph::descriptor::Input*> copy{begin(o.get_inputs()), end(o.get_inputs())}; for (auto i : copy) { i->replace_output(max_pool_with_indices_output->get_outputs().at(0)); } } // create a new max_pool_with_indices_bprop auto max_pool_with_indices_bprop = std::make_shared<op::MaxPoolWithIndicesBackprop>(pattern_map[data], pattern_map[delta], max_pool_with_indices_indices, m_max_pool->get_window_shape(), m_max_pool->get_window_movement_strides(), m_max_pool->get_padding_below(), m_max_pool->get_padding_above()); ngraph::replace_node(m_max_pool_bprop, max_pool_with_indices_bprop); if (m_return_indices) { m_indices_list.push_back(max_pool_with_indices_indices); } return true; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * 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 * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRepAlgoAPI_BooleanOperation.hxx> # include <BRepCheck_Analyzer.hxx> # include <memory> #endif #include "FeaturePartBoolean.h" #include "modelRefine.h" #include <App/Application.h> #include <Base/Parameter.h> using namespace Part; PROPERTY_SOURCE_ABSTRACT(Part::Boolean, Part::Feature) Boolean::Boolean(void) { ADD_PROPERTY(Base,(0)); ADD_PROPERTY(Tool,(0)); ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType) (App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history"); History.setSize(0); } short Boolean::mustExecute() const { if (Base.getValue() && Tool.getValue()) { if (Base.isTouched()) return 1; if (Tool.isTouched()) return 1; } return 0; } App::DocumentObjectExecReturn *Boolean::execute(void) { try { #if defined(__GNUC__) && defined (FC_OS_LINUX) Base::SignalException se; #endif Part::Feature *base = dynamic_cast<Part::Feature*>(Base.getValue()); Part::Feature *tool = dynamic_cast<Part::Feature*>(Tool.getValue()); if (!base || !tool) return new App::DocumentObjectExecReturn("Linked object is not a Part object"); // Now, let's get the TopoDS_Shape TopoDS_Shape BaseShape = base->Shape.getValue(); if (BaseShape.IsNull()) throw Base::Exception("Base shape is null"); TopoDS_Shape ToolShape = tool->Shape.getValue(); if (ToolShape.IsNull()) throw Base::Exception("Tool shape is null"); std::unique_ptr<BRepAlgoAPI_BooleanOperation> mkBool(makeOperation(BaseShape, ToolShape)); if (!mkBool->IsDone()) { return new App::DocumentObjectExecReturn("Boolean operation failed"); } TopoDS_Shape resShape = mkBool->Shape(); if (resShape.IsNull()) { return new App::DocumentObjectExecReturn("Resulting shape is null"); } Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part/Boolean"); if (hGrp->GetBool("CheckModel", false)) { BRepCheck_Analyzer aChecker(resShape); if (! aChecker.IsValid() ) { return new App::DocumentObjectExecReturn("Resulting shape is invalid"); } } std::vector<ShapeHistory> history; history.push_back(buildHistory(*mkBool.get(), TopAbs_FACE, resShape, BaseShape)); history.push_back(buildHistory(*mkBool.get(), TopAbs_FACE, resShape, ToolShape)); if (hGrp->GetBool("RefineModel", false)) { try { TopoDS_Shape oldShape = resShape; BRepBuilderAPI_RefineModel mkRefine(oldShape); resShape = mkRefine.Shape(); ShapeHistory hist = buildHistory(mkRefine, TopAbs_FACE, resShape, oldShape); history[0] = joinHistory(history[0], hist); history[1] = joinHistory(history[1], hist); } catch (Standard_Failure) { // do nothing } } this->Shape.setValue(resShape); this->History.setValues(history); return App::DocumentObject::StdReturn; } catch (...) { return new App::DocumentObjectExecReturn("A fatal error occurred when running boolean operation"); } } <commit_msg>add missing header file<commit_after>/*************************************************************************** * Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * 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 * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRepAlgoAPI_BooleanOperation.hxx> # include <BRepCheck_Analyzer.hxx> # include <Standard_Failure.hxx> # include <memory> #endif #include "FeaturePartBoolean.h" #include "modelRefine.h" #include <App/Application.h> #include <Base/Parameter.h> using namespace Part; PROPERTY_SOURCE_ABSTRACT(Part::Boolean, Part::Feature) Boolean::Boolean(void) { ADD_PROPERTY(Base,(0)); ADD_PROPERTY(Tool,(0)); ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType) (App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history"); History.setSize(0); } short Boolean::mustExecute() const { if (Base.getValue() && Tool.getValue()) { if (Base.isTouched()) return 1; if (Tool.isTouched()) return 1; } return 0; } App::DocumentObjectExecReturn *Boolean::execute(void) { try { #if defined(__GNUC__) && defined (FC_OS_LINUX) Base::SignalException se; #endif Part::Feature *base = dynamic_cast<Part::Feature*>(Base.getValue()); Part::Feature *tool = dynamic_cast<Part::Feature*>(Tool.getValue()); if (!base || !tool) return new App::DocumentObjectExecReturn("Linked object is not a Part object"); // Now, let's get the TopoDS_Shape TopoDS_Shape BaseShape = base->Shape.getValue(); if (BaseShape.IsNull()) throw Base::Exception("Base shape is null"); TopoDS_Shape ToolShape = tool->Shape.getValue(); if (ToolShape.IsNull()) throw Base::Exception("Tool shape is null"); std::unique_ptr<BRepAlgoAPI_BooleanOperation> mkBool(makeOperation(BaseShape, ToolShape)); if (!mkBool->IsDone()) { return new App::DocumentObjectExecReturn("Boolean operation failed"); } TopoDS_Shape resShape = mkBool->Shape(); if (resShape.IsNull()) { return new App::DocumentObjectExecReturn("Resulting shape is null"); } Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part/Boolean"); if (hGrp->GetBool("CheckModel", false)) { BRepCheck_Analyzer aChecker(resShape); if (! aChecker.IsValid() ) { return new App::DocumentObjectExecReturn("Resulting shape is invalid"); } } std::vector<ShapeHistory> history; history.push_back(buildHistory(*mkBool.get(), TopAbs_FACE, resShape, BaseShape)); history.push_back(buildHistory(*mkBool.get(), TopAbs_FACE, resShape, ToolShape)); if (hGrp->GetBool("RefineModel", false)) { try { TopoDS_Shape oldShape = resShape; BRepBuilderAPI_RefineModel mkRefine(oldShape); resShape = mkRefine.Shape(); ShapeHistory hist = buildHistory(mkRefine, TopAbs_FACE, resShape, oldShape); history[0] = joinHistory(history[0], hist); history[1] = joinHistory(history[1], hist); } catch (Standard_Failure) { // do nothing } } this->Shape.setValue(resShape); this->History.setValues(history); return App::DocumentObject::StdReturn; } catch (...) { return new App::DocumentObjectExecReturn("A fatal error occurred when running boolean operation"); } } <|endoftext|>
<commit_before>#include "direct.hxx" #include "istream/istream.hxx" #include "istream/istream_byte.hxx" #include "istream/istream_cat.hxx" #include "istream/istream_fail.hxx" #include "istream/istream_four.hxx" #include "istream/istream_head.hxx" #include "istream/istream_hold.hxx" #include "istream/istream_inject.hxx" #include "istream/istream_later.hxx" #include <glib.h> #include <event.h> #include <stdio.h> #ifdef EXPECTED_RESULT #include <string.h> #endif enum { #ifdef NO_BLOCKING enable_blocking = false, #else enable_blocking = true, #endif }; static inline GQuark test_quark(void) { return g_quark_from_static_string("test"); } #ifndef FILTER_CLEANUP static void cleanup(void) { } #endif struct ctx { bool half; bool got_data, eof; #ifdef EXPECTED_RESULT bool record; char buffer[sizeof(EXPECTED_RESULT) * 2]; size_t buffer_length; #endif struct istream *abort_istream; int abort_after; int block_after; }; /* * istream handler * */ static size_t my_istream_data(const void *data, size_t length, void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; (void)data; //printf("data(%zu)\n", length); ctx->got_data = true; if (ctx->abort_istream != NULL && ctx->abort_after-- == 0) { GError *error = g_error_new_literal(test_quark(), 0, "abort_istream"); istream_inject_fault(ctx->abort_istream, error); ctx->abort_istream = NULL; return 0; } if (ctx->half && length > 8) length = (length + 1) / 2; if (ctx->block_after >= 0) { --ctx->block_after; if (ctx->block_after == -1) /* block once */ return 0; } #ifdef EXPECTED_RESULT if (ctx->record) { #ifdef __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstring-plus-int" #endif assert(ctx->buffer_length + length < sizeof(ctx->buffer)); assert(memcmp(EXPECTED_RESULT + ctx->buffer_length, data, length) == 0); #ifdef __clang__ #pragma GCC diagnostic pop #endif if (ctx->buffer_length + length < sizeof(ctx->buffer)) memcpy(ctx->buffer + ctx->buffer_length, data, length); ctx->buffer_length += length; } #endif return length; } static ssize_t my_istream_direct(gcc_unused FdType type, int fd, size_t max_length, void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; (void)fd; //printf("direct(%u, %zu)\n", type, max_length); ctx->got_data = true; if (ctx->abort_istream != NULL) { GError *error = g_error_new_literal(test_quark(), 0, "abort_istream"); istream_inject_fault(ctx->abort_istream, error); ctx->abort_istream = NULL; return 0; } return max_length; } static void my_istream_eof(void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; //printf("eof\n"); ctx->eof = true; } static void my_istream_abort(GError *error, void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; //g_printerr("%s\n", error->message); g_error_free(error); #ifdef EXPECTED_RESULT assert(!ctx->record); #endif //printf("abort\n"); ctx->eof = true; } static const struct istream_handler my_istream_handler = { .data = my_istream_data, .direct = my_istream_direct, .eof = my_istream_eof, .abort = my_istream_abort, }; /* * utils * */ static int istream_read_event(struct istream *istream) { istream_read(istream); return event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } static inline void istream_read_expect(struct ctx *ctx, struct istream *istream) { int ret; assert(!ctx->eof); ctx->got_data = false; ret = istream_read_event(istream); assert(ctx->eof || ctx->got_data || ret == 0); /* give istream_later another chance to breathe */ event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } static void run_istream_ctx(struct ctx *ctx, struct pool *pool, struct istream *istream) { ctx->eof = false; gcc_unused off_t a1 = istream_available(istream, false); gcc_unused off_t a2 = istream_available(istream, true); istream_handler_set(istream, &my_istream_handler, ctx, 0); pool_unref(pool); pool_commit(); #ifndef NO_GOT_DATA_ASSERT while (!ctx->eof) istream_read_expect(ctx, istream); #else for (int i = 0; i < 1000 && !ctx->eof; ++i) istream_read_event(istream); #endif #ifdef EXPECTED_RESULT if (ctx->record) { assert(ctx->buffer_length == sizeof(EXPECTED_RESULT) - 1); assert(memcmp(ctx->buffer, EXPECTED_RESULT, ctx->buffer_length) == 0); } #endif cleanup(); pool_commit(); } static void run_istream_block(struct pool *pool, struct istream *istream, gcc_unused bool record, int block_after) { struct ctx ctx = { .abort_istream = NULL, .block_after = block_after, #ifdef EXPECTED_RESULT .record = record, #endif }; run_istream_ctx(&ctx, pool, istream); } static void run_istream(struct pool *pool, struct istream *istream, bool record) { run_istream_block(pool, istream, record, -1); } /* * tests * */ /** normal run */ static void test_normal(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_normal", 8192); istream = create_test(pool, create_input(pool)); assert(istream != NULL); assert(!istream_has_handler(istream)); run_istream(pool, istream, true); } /** block once after n data() invocations */ static void test_block(struct pool *parent_pool) { struct pool *pool; for (int n = 0; n < 8; ++n) { struct istream *istream; pool = pool_new_linear(parent_pool, "test_block", 8192); istream = create_test(pool, create_input(pool)); assert(istream != NULL); assert(!istream_has_handler(istream)); run_istream_block(pool, istream, true, n); } } /** test with istream_byte */ static void test_byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_byte", 8192); istream = create_test(pool, istream_byte_new(*pool, *create_input(pool))); run_istream(pool, istream, true); } /** accept only half of the data */ static void test_half(struct pool *pool) { struct ctx ctx = { .eof = false, .half = true, #ifdef EXPECTED_RESULT .record = true, #endif .abort_istream = NULL, .block_after = -1, }; pool = pool_new_linear(pool, "test_half", 8192); run_istream_ctx(&ctx, pool, create_test(pool, create_input(pool))); } /** input fails */ static void test_fail(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_fail", 8192); GError *error = g_error_new_literal(test_quark(), 0, "test_fail"); istream = create_test(pool, istream_fail_new(pool, error)); run_istream(pool, istream, false); } /** input fails after the first byte */ static void test_fail_1byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_fail_1byte", 8192); GError *error = g_error_new_literal(test_quark(), 0, "test_fail"); istream = create_test(pool, istream_cat_new(pool, istream_head_new(pool, create_input(pool), 1, false), istream_fail_new(pool, error), NULL)); run_istream(pool, istream, false); } /** abort without handler */ static void test_abort_without_handler(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_abort_without_handler", 8192); istream = create_test(pool, create_input(pool)); pool_unref(pool); pool_commit(); istream_close_unused(istream); cleanup(); pool_commit(); } #ifndef NO_ABORT_ISTREAM /** abort in handler */ static void test_abort_in_handler(struct pool *pool) { struct ctx ctx = { .eof = false, .half = false, #ifdef EXPECTED_RESULT .record = false, #endif .abort_after = 0, .block_after = -1, }; pool = pool_new_linear(pool, "test_abort_in_handler", 8192); ctx.abort_istream = istream_inject_new(pool, create_input(pool)); struct istream *istream = create_test(pool, ctx.abort_istream); istream_handler_set(istream, &my_istream_handler, &ctx, 0); pool_unref(pool); pool_commit(); while (!ctx.eof) { istream_read_expect(&ctx, istream); event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } assert(ctx.abort_istream == NULL); cleanup(); pool_commit(); } /** abort in handler, with some data consumed */ static void test_abort_in_handler_half(struct pool *pool) { struct ctx ctx = { .eof = false, .half = true, #ifdef EXPECTED_RESULT .record = false, #endif .abort_after = 2, .block_after = -1, }; pool = pool_new_linear(pool, "test_abort_in_handler_half", 8192); ctx.abort_istream = istream_inject_new(pool, istream_four_new(pool, create_input(pool))); struct istream *istream = create_test(pool, istream_byte_new(*pool, *ctx.abort_istream)); istream_handler_set(istream, &my_istream_handler, &ctx, 0); pool_unref(pool); pool_commit(); while (!ctx.eof) { istream_read_expect(&ctx, istream); event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } assert(ctx.abort_istream == NULL || ctx.abort_after >= 0); cleanup(); pool_commit(); } #endif /** abort after 1 byte of output */ static void test_abort_1byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_abort_1byte", 8192); istream = istream_head_new(pool, create_test(pool, create_input(pool)), 1, false); run_istream(pool, istream, false); } /** test with istream_later filter */ static void test_later(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_later", 8192); istream = create_test(pool, istream_later_new(pool, create_input(pool))); run_istream(pool, istream, true); } #ifdef EXPECTED_RESULT /** test with large input and blocking handler */ static void test_big_hold(struct pool *pool) { pool = pool_new_linear(pool, "test_big_hold", 8192); struct istream *istream = create_input(pool); for (unsigned i = 0; i < 1024; ++i) istream = istream_cat_new(pool, istream, create_input(pool), NULL); istream = create_test(pool, istream); struct istream *hold = istream_hold_new(pool, istream); istream_read(istream); istream_close_unused(hold); pool_unref(pool); } #endif /* * main * */ int main(int argc, char **argv) { struct pool *root_pool; struct event_base *event_base; (void)argc; (void)argv; direct_global_init(); event_base = event_init(); root_pool = pool_new_libc(NULL, "root"); /* run test suite */ test_normal(root_pool); if (enable_blocking) test_block(root_pool); if (enable_blocking) test_byte(root_pool); test_half(root_pool); test_fail(root_pool); test_fail_1byte(root_pool); test_abort_without_handler(root_pool); #ifndef NO_ABORT_ISTREAM test_abort_in_handler(root_pool); if (enable_blocking) test_abort_in_handler_half(root_pool); #endif test_abort_1byte(root_pool); test_later(root_pool); #ifdef EXPECTED_RESULT test_big_hold(root_pool); #endif #ifdef CUSTOM_TEST test_custom(root_pool); #endif /* cleanup */ pool_unref(root_pool); pool_commit(); pool_recycler_clear(); event_base_free(event_base); direct_global_deinit(); } <commit_msg>test/t_istream_filter: add another blocking test<commit_after>#include "direct.hxx" #include "istream/istream.hxx" #include "istream/istream_byte.hxx" #include "istream/istream_cat.hxx" #include "istream/istream_fail.hxx" #include "istream/istream_four.hxx" #include "istream/istream_head.hxx" #include "istream/istream_hold.hxx" #include "istream/istream_inject.hxx" #include "istream/istream_later.hxx" #include <glib.h> #include <event.h> #include <stdio.h> #ifdef EXPECTED_RESULT #include <string.h> #endif enum { #ifdef NO_BLOCKING enable_blocking = false, #else enable_blocking = true, #endif }; static inline GQuark test_quark(void) { return g_quark_from_static_string("test"); } #ifndef FILTER_CLEANUP static void cleanup(void) { } #endif struct ctx { bool half; bool got_data, eof; #ifdef EXPECTED_RESULT bool record; char buffer[sizeof(EXPECTED_RESULT) * 2]; size_t buffer_length; #endif struct istream *abort_istream; int abort_after; int block_after; bool block_byte, block_byte_state; }; /* * istream handler * */ static size_t my_istream_data(const void *data, size_t length, void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; (void)data; //printf("data(%zu)\n", length); ctx->got_data = true; if (ctx->block_byte) { ctx->block_byte_state = !ctx->block_byte_state; if (ctx->block_byte_state) return 0; } if (ctx->abort_istream != NULL && ctx->abort_after-- == 0) { GError *error = g_error_new_literal(test_quark(), 0, "abort_istream"); istream_inject_fault(ctx->abort_istream, error); ctx->abort_istream = NULL; return 0; } if (ctx->half && length > 8) length = (length + 1) / 2; if (ctx->block_after >= 0) { --ctx->block_after; if (ctx->block_after == -1) /* block once */ return 0; } #ifdef EXPECTED_RESULT if (ctx->record) { #ifdef __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstring-plus-int" #endif assert(ctx->buffer_length + length < sizeof(ctx->buffer)); assert(memcmp(EXPECTED_RESULT + ctx->buffer_length, data, length) == 0); #ifdef __clang__ #pragma GCC diagnostic pop #endif if (ctx->buffer_length + length < sizeof(ctx->buffer)) memcpy(ctx->buffer + ctx->buffer_length, data, length); ctx->buffer_length += length; } #endif return length; } static ssize_t my_istream_direct(gcc_unused FdType type, int fd, size_t max_length, void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; (void)fd; //printf("direct(%u, %zu)\n", type, max_length); ctx->got_data = true; if (ctx->abort_istream != NULL) { GError *error = g_error_new_literal(test_quark(), 0, "abort_istream"); istream_inject_fault(ctx->abort_istream, error); ctx->abort_istream = NULL; return 0; } return max_length; } static void my_istream_eof(void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; //printf("eof\n"); ctx->eof = true; } static void my_istream_abort(GError *error, void *_ctx) { struct ctx *ctx = (struct ctx *)_ctx; //g_printerr("%s\n", error->message); g_error_free(error); #ifdef EXPECTED_RESULT assert(!ctx->record); #endif //printf("abort\n"); ctx->eof = true; } static const struct istream_handler my_istream_handler = { .data = my_istream_data, .direct = my_istream_direct, .eof = my_istream_eof, .abort = my_istream_abort, }; /* * utils * */ static int istream_read_event(struct istream *istream) { istream_read(istream); return event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } static inline void istream_read_expect(struct ctx *ctx, struct istream *istream) { int ret; assert(!ctx->eof); ctx->got_data = false; ret = istream_read_event(istream); assert(ctx->eof || ctx->got_data || ret == 0); /* give istream_later another chance to breathe */ event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } static void run_istream_ctx(struct ctx *ctx, struct pool *pool, struct istream *istream) { ctx->eof = false; gcc_unused off_t a1 = istream_available(istream, false); gcc_unused off_t a2 = istream_available(istream, true); istream_handler_set(istream, &my_istream_handler, ctx, 0); pool_unref(pool); pool_commit(); #ifndef NO_GOT_DATA_ASSERT while (!ctx->eof) istream_read_expect(ctx, istream); #else for (int i = 0; i < 1000 && !ctx->eof; ++i) istream_read_event(istream); #endif #ifdef EXPECTED_RESULT if (ctx->record) { assert(ctx->buffer_length == sizeof(EXPECTED_RESULT) - 1); assert(memcmp(ctx->buffer, EXPECTED_RESULT, ctx->buffer_length) == 0); } #endif cleanup(); pool_commit(); } static void run_istream_block(struct pool *pool, struct istream *istream, gcc_unused bool record, int block_after) { struct ctx ctx = { .abort_istream = NULL, .block_after = block_after, #ifdef EXPECTED_RESULT .record = record, #endif }; run_istream_ctx(&ctx, pool, istream); } static void run_istream(struct pool *pool, struct istream *istream, bool record) { run_istream_block(pool, istream, record, -1); } /* * tests * */ /** normal run */ static void test_normal(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_normal", 8192); istream = create_test(pool, create_input(pool)); assert(istream != NULL); assert(!istream_has_handler(istream)); run_istream(pool, istream, true); } /** block once after n data() invocations */ static void test_block(struct pool *parent_pool) { struct pool *pool; for (int n = 0; n < 8; ++n) { struct istream *istream; pool = pool_new_linear(parent_pool, "test_block", 8192); istream = create_test(pool, create_input(pool)); assert(istream != NULL); assert(!istream_has_handler(istream)); run_istream_block(pool, istream, true, n); } } /** test with istream_byte */ static void test_byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_byte", 8192); istream = create_test(pool, istream_byte_new(*pool, *create_input(pool))); run_istream(pool, istream, true); } /** block and consume one byte at a time */ static void test_block_byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_byte", 8192); istream = create_test(pool, istream_byte_new(*pool, *create_input(pool))); struct ctx ctx = { .abort_istream = NULL, .block_after = -1, .block_byte = true, #ifdef EXPECTED_RESULT .record = true, #endif }; run_istream_ctx(&ctx, pool, istream); } /** accept only half of the data */ static void test_half(struct pool *pool) { struct ctx ctx = { .eof = false, .half = true, #ifdef EXPECTED_RESULT .record = true, #endif .abort_istream = NULL, .block_after = -1, }; pool = pool_new_linear(pool, "test_half", 8192); run_istream_ctx(&ctx, pool, create_test(pool, create_input(pool))); } /** input fails */ static void test_fail(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_fail", 8192); GError *error = g_error_new_literal(test_quark(), 0, "test_fail"); istream = create_test(pool, istream_fail_new(pool, error)); run_istream(pool, istream, false); } /** input fails after the first byte */ static void test_fail_1byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_fail_1byte", 8192); GError *error = g_error_new_literal(test_quark(), 0, "test_fail"); istream = create_test(pool, istream_cat_new(pool, istream_head_new(pool, create_input(pool), 1, false), istream_fail_new(pool, error), NULL)); run_istream(pool, istream, false); } /** abort without handler */ static void test_abort_without_handler(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_abort_without_handler", 8192); istream = create_test(pool, create_input(pool)); pool_unref(pool); pool_commit(); istream_close_unused(istream); cleanup(); pool_commit(); } #ifndef NO_ABORT_ISTREAM /** abort in handler */ static void test_abort_in_handler(struct pool *pool) { struct ctx ctx = { .eof = false, .half = false, #ifdef EXPECTED_RESULT .record = false, #endif .abort_after = 0, .block_after = -1, }; pool = pool_new_linear(pool, "test_abort_in_handler", 8192); ctx.abort_istream = istream_inject_new(pool, create_input(pool)); struct istream *istream = create_test(pool, ctx.abort_istream); istream_handler_set(istream, &my_istream_handler, &ctx, 0); pool_unref(pool); pool_commit(); while (!ctx.eof) { istream_read_expect(&ctx, istream); event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } assert(ctx.abort_istream == NULL); cleanup(); pool_commit(); } /** abort in handler, with some data consumed */ static void test_abort_in_handler_half(struct pool *pool) { struct ctx ctx = { .eof = false, .half = true, #ifdef EXPECTED_RESULT .record = false, #endif .abort_after = 2, .block_after = -1, }; pool = pool_new_linear(pool, "test_abort_in_handler_half", 8192); ctx.abort_istream = istream_inject_new(pool, istream_four_new(pool, create_input(pool))); struct istream *istream = create_test(pool, istream_byte_new(*pool, *ctx.abort_istream)); istream_handler_set(istream, &my_istream_handler, &ctx, 0); pool_unref(pool); pool_commit(); while (!ctx.eof) { istream_read_expect(&ctx, istream); event_loop(EVLOOP_ONCE|EVLOOP_NONBLOCK); } assert(ctx.abort_istream == NULL || ctx.abort_after >= 0); cleanup(); pool_commit(); } #endif /** abort after 1 byte of output */ static void test_abort_1byte(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_abort_1byte", 8192); istream = istream_head_new(pool, create_test(pool, create_input(pool)), 1, false); run_istream(pool, istream, false); } /** test with istream_later filter */ static void test_later(struct pool *pool) { struct istream *istream; pool = pool_new_linear(pool, "test_later", 8192); istream = create_test(pool, istream_later_new(pool, create_input(pool))); run_istream(pool, istream, true); } #ifdef EXPECTED_RESULT /** test with large input and blocking handler */ static void test_big_hold(struct pool *pool) { pool = pool_new_linear(pool, "test_big_hold", 8192); struct istream *istream = create_input(pool); for (unsigned i = 0; i < 1024; ++i) istream = istream_cat_new(pool, istream, create_input(pool), NULL); istream = create_test(pool, istream); struct istream *hold = istream_hold_new(pool, istream); istream_read(istream); istream_close_unused(hold); pool_unref(pool); } #endif /* * main * */ int main(int argc, char **argv) { struct pool *root_pool; struct event_base *event_base; (void)argc; (void)argv; direct_global_init(); event_base = event_init(); root_pool = pool_new_libc(NULL, "root"); /* run test suite */ test_normal(root_pool); if (enable_blocking) { test_block(root_pool); test_byte(root_pool); test_block_byte(root_pool); } test_half(root_pool); test_fail(root_pool); test_fail_1byte(root_pool); test_abort_without_handler(root_pool); #ifndef NO_ABORT_ISTREAM test_abort_in_handler(root_pool); if (enable_blocking) test_abort_in_handler_half(root_pool); #endif test_abort_1byte(root_pool); test_later(root_pool); #ifdef EXPECTED_RESULT test_big_hold(root_pool); #endif #ifdef CUSTOM_TEST test_custom(root_pool); #endif /* cleanup */ pool_unref(root_pool); pool_commit(); pool_recycler_clear(); event_base_free(event_base); direct_global_deinit(); } <|endoftext|>
<commit_before>#include <CUndo.h> #include <CFuncs.h> #include <cassert> #include <climits> #include <algorithm> CUndo:: CUndo() : undo_group_(0), depth_(0), locked_(false) { } CUndo:: ~CUndo() { std::for_each(undo_list_.begin(), undo_list_.end(), CDeletePointer()); std::for_each(redo_list_.begin(), redo_list_.end(), CDeletePointer()); } bool CUndo:: isInGroup() const { return (depth_ > 0); } bool CUndo:: startGroup() { if (locked()) return false; if (depth_ == 0) { assert(undo_group_ == 0); undo_group_ = new CUndoGroup(this); } ++depth_; return true; } bool CUndo:: endGroup() { if (locked()) return false; assert(depth_ > 0); --depth_; if (depth_ == 0) { undo_list_.push_back(undo_group_); undo_group_ = 0; } return true; } bool CUndo:: addUndo(CUndoData *data) { if (locked()) return false; std::for_each(redo_list_.begin(), redo_list_.end(), CDeletePointer()); redo_list_.clear(); if (undo_group_ == 0) { startGroup(); addUndo(data); endGroup(); } else undo_group_->addUndo(data); return true; } bool CUndo:: undoAll() { return undo(INT_MAX); } bool CUndo:: redoAll() { return redo(INT_MAX); } bool CUndo:: undo(uint n) { bool flag = true; for (uint i = 0; i < n; ++i) { if (undo_list_.empty()) return false; CUndoGroup *undo_group = undo_list_.back(); undo_list_.pop_back(); lock(); if (! undo_group->undo()) flag = false; unlock(); redo_list_.push_back(undo_group); } return flag; } bool CUndo:: redo(uint n) { bool flag = true; for (uint i = 0; i < n; ++i) { if (redo_list_.empty()) return false; CUndoGroup *undo_group = redo_list_.back(); redo_list_.pop_back(); lock(); if (! undo_group->redo()) flag = false; unlock(); undo_list_.push_back(undo_group); } return flag; } void CUndo:: clear() { std::for_each(undo_list_.begin(), undo_list_.end(), CDeletePointer()); std::for_each(redo_list_.begin(), redo_list_.end(), CDeletePointer()); undo_list_.clear(); redo_list_.clear(); } bool CUndo:: canUndo() const { return (! undo_list_.empty()); } bool CUndo:: canRedo() const { return (! redo_list_.empty()); } void CUndo:: lock() { assert(! locked_); locked_ = true; } void CUndo:: unlock() { assert(locked_); locked_ = false; } //-------------------- CUndoGroup:: CUndoGroup(CUndo *) : desc_("") { } CUndoGroup:: ~CUndoGroup() { std::for_each(data_list_.begin(), data_list_.end(), CDeletePointer()); } void CUndoGroup:: addUndo(CUndoData *data) { data_list_.push_back(data); data->setGroup(this); } std::string CUndoGroup:: getDesc() const { if (desc_ != "") return desc_; if (data_list_.empty()) return ""; else return data_list_.front()->getDesc(); } bool CUndoGroup:: undo() { CUndoData::setError(false); std::for_each(data_list_.rbegin(), data_list_.rend(), &CUndoData::execUndoFunc); return CUndoData::isError(); } bool CUndoGroup:: redo() { CUndoData::setError(false); std::for_each(data_list_.begin(), data_list_.end(), &CUndoData::execRedoFunc); return CUndoData::isError(); } //-------------------- CUndoData:: CUndoData() : group_(0), state_(UNDO_STATE) { } CUndoData:: ~CUndoData() { } void CUndoData:: execUndoFunc(CUndoData *data) { data->setState(CUndoData::UNDO_STATE); CUndoData::setError(data->exec()); } void CUndoData:: execRedoFunc(CUndoData *data) { data->setState(CUndoData::REDO_STATE); CUndoData::setError(data->exec()); } bool CUndoData:: setError(bool flag) { static bool error; std::swap(flag, error); return flag; } bool CUndoData:: isError() { bool error; setError(error = setError(false)); return error; } <commit_msg>new files<commit_after>#include <CUndo.h> #include <CFuncs.h> #include <cassert> #include <climits> #include <algorithm> CUndo:: CUndo() : undo_group_(0), depth_(0), locked_(false) { } CUndo:: ~CUndo() { std::for_each(undo_list_.begin(), undo_list_.end(), CDeletePointer()); std::for_each(redo_list_.begin(), redo_list_.end(), CDeletePointer()); } bool CUndo:: isInGroup() const { return (depth_ > 0); } bool CUndo:: startGroup() { if (locked()) return false; if (depth_ == 0) { assert(undo_group_ == 0); undo_group_ = new CUndoGroup(this); } ++depth_; return true; } bool CUndo:: endGroup() { if (locked()) return false; assert(depth_ > 0); --depth_; if (depth_ == 0) { undo_list_.push_back(undo_group_); undo_group_ = 0; } return true; } bool CUndo:: addUndo(CUndoData *data) { if (locked()) return false; std::for_each(redo_list_.begin(), redo_list_.end(), CDeletePointer()); redo_list_.clear(); if (undo_group_ == 0) { startGroup(); addUndo(data); endGroup(); } else undo_group_->addUndo(data); return true; } bool CUndo:: undoAll() { return undo(INT_MAX); } bool CUndo:: redoAll() { return redo(INT_MAX); } bool CUndo:: undo(uint n) { bool flag = true; for (uint i = 0; i < n; ++i) { if (undo_list_.empty()) return false; CUndoGroup *undo_group = undo_list_.back(); undo_list_.pop_back(); lock(); if (! undo_group->undo()) flag = false; unlock(); redo_list_.push_back(undo_group); } return flag; } bool CUndo:: redo(uint n) { bool flag = true; for (uint i = 0; i < n; ++i) { if (redo_list_.empty()) return false; CUndoGroup *undo_group = redo_list_.back(); redo_list_.pop_back(); lock(); if (! undo_group->redo()) flag = false; unlock(); undo_list_.push_back(undo_group); } return flag; } void CUndo:: clear() { std::for_each(undo_list_.begin(), undo_list_.end(), CDeletePointer()); std::for_each(redo_list_.begin(), redo_list_.end(), CDeletePointer()); undo_list_.clear(); redo_list_.clear(); } bool CUndo:: canUndo() const { return (! undo_list_.empty()); } bool CUndo:: canRedo() const { return (! redo_list_.empty()); } void CUndo:: lock() { assert(! locked_); locked_ = true; } void CUndo:: unlock() { assert(locked_); locked_ = false; } //-------------------- CUndoGroup:: CUndoGroup(CUndo *undo) : undo_(undo), desc_("") { } CUndoGroup:: ~CUndoGroup() { std::for_each(data_list_.begin(), data_list_.end(), CDeletePointer()); } void CUndoGroup:: addUndo(CUndoData *data) { data_list_.push_back(data); data->setGroup(this); } std::string CUndoGroup:: getDesc() const { if (desc_ != "") return desc_; if (data_list_.empty()) return ""; else return data_list_.front()->getDesc(); } bool CUndoGroup:: undo() { CUndoData::setError(false); std::for_each(data_list_.rbegin(), data_list_.rend(), &CUndoData::execUndoFunc); return CUndoData::isError(); } bool CUndoGroup:: redo() { CUndoData::setError(false); std::for_each(data_list_.begin(), data_list_.end(), &CUndoData::execRedoFunc); return CUndoData::isError(); } //-------------------- CUndoData:: CUndoData() : group_(0), state_(UNDO_STATE) { } CUndoData:: ~CUndoData() { } void CUndoData:: execUndoFunc(CUndoData *data) { data->setState(CUndoData::UNDO_STATE); CUndoData::setError(data->exec()); } void CUndoData:: execRedoFunc(CUndoData *data) { data->setState(CUndoData::REDO_STATE); CUndoData::setError(data->exec()); } bool CUndoData:: setError(bool flag) { static bool error; std::swap(flag, error); return flag; } bool CUndoData:: isError() { bool error; setError(error = setError(false)); return error; } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Camera/CameraModel.h> #include <vw/Stereo/StereoModel.h> #include <vw/Math/LevenbergMarquardt.h> namespace vw { namespace stereo { namespace detail { class PointLMA : public math::LeastSquaresModelBase<PointLMA> { const camera::CameraModel *m_camera1, *m_camera2; public: typedef Vector<double,4> result_type; typedef Vector<double,3> domain_type; typedef Matrix<double> jacobian_type; PointLMA( camera::CameraModel const* cam1, camera::CameraModel const* cam2 ) : m_camera1(cam1), m_camera2(cam2) {} inline result_type operator()( domain_type const& x ) const { Vector4 output; subvector(output,0,2) = m_camera1->point_to_pixel( x ); subvector(output,2,2) = m_camera2->point_to_pixel( x ); return output; } }; } ImageView<Vector3> StereoModel::operator()(ImageView<PixelMask<Vector2f> > const& disparity_map, ImageView<double> &error) const { // Error analysis double mean_error = 0.0; double max_error = 0.0; int32 point_count = 0; int32 divergent = 0; // Allocate xyz image and get pointer to buffer ImageView<Vector3> xyz(disparity_map.cols(), disparity_map.rows()); error.set_size(disparity_map.cols(), disparity_map.rows()); // Compute 3D position for each pixel in the disparity map vw_out() << "StereoModel: Applying camera models\n"; for (int32 y = 0; y < disparity_map.rows(); y++) { if (y % 100 == 0) { printf("\tStereoModel computing points: %0.2f%% complete.\r", 100.0f*float(y)/disparity_map.rows()); fflush(stdout); } for (int32 x = 0; x < disparity_map.cols(); x++) { if ( is_valid(disparity_map(x,y)) ) { xyz(x,y) = (*this)(Vector2( x, y), Vector2( x+disparity_map(x,y)[0], y+disparity_map(x,y)[1]), error(x,y) ); if (error(x,y) >= 0) { // Keep track of error statistics if (error(x,y) > max_error) max_error = error(x,y); mean_error += error(x,y); ++point_count; } else { // rays diverge or are parallel xyz(x,y) = Vector3(); divergent++; } } else { xyz(x,y) = Vector3(); error(x,y) = 0; } } } if (divergent != 0) vw_out() << "WARNING in StereoModel: " << divergent << " rays diverged or were parallel!\n"; vw_out() << "\tStereoModel computing points: Done. \n"; vw_out() << "\tMean error = " << mean_error/double(point_count) << ", Max error = " << max_error << std::endl; return xyz; } Vector3 StereoModel::operator()(Vector2 const& pix1, Vector2 const& pix2, double& error ) const { try { // determine range by triangulation Vector3 vecFromA = m_camera1->pixel_to_vector(pix1); Vector3 vecFromB = m_camera2->pixel_to_vector(pix2); // If vecFromA and vecFromB are nearly parallel, there will be // very large numerical uncertainty about where to place the // point. We set a threshold here to reject points that are // on nearly parallel rays. The threshold of 1e-4 corresponds // to a convergence of less than theta = 0.81 degrees, so if // the two rays are within 0.81 degrees of being parallel, we // reject this point. // // This threshold was chosen empirically for now, but should // probably be revisited once a more rigorous analysis has // been completed. -mbroxton (11-MAR-07) if ( (1-dot_prod(vecFromA, vecFromB) < 1e-4 && !m_least_squares) || (1-dot_prod(vecFromA, vecFromB) < 1e-5 && m_least_squares) ) { error = 0; return Vector3(); } Vector3 originA = m_camera1->camera_center(pix1); Vector3 originB = m_camera2->camera_center(pix2); Vector3 result = triangulate_point(originA, vecFromA, originB, vecFromB, error); if ( m_least_squares ) refine_point(pix1, pix2, result); // Reflect points that fall behind one of the two cameras if ( dot_prod(result - originA, vecFromA) < 0 || dot_prod(result - originB, vecFromB) < 0 ) { result = -result + 2*originA; } return result; } catch (const camera::PixelToRayErr& /*e*/) { error = 0; return Vector3(); } } double StereoModel::convergence_angle(Vector2 const& pix1, Vector2 const& pix2) const { return acos(dot_prod(m_camera1->pixel_to_vector(pix1), m_camera2->pixel_to_vector(pix2))); } Vector3 StereoModel::triangulate_point(Vector3 const& pointA, Vector3 const& vecFromA, Vector3 const& pointB, Vector3 const& vecFromB, double& error) const { Vector3 v12 = cross_prod(vecFromA, vecFromB); Vector3 v1 = cross_prod(v12, vecFromA); Vector3 v2 = cross_prod(v12, vecFromB); Vector3 closestPointA = pointA + dot_prod(v2, pointB-pointA)/dot_prod(v2, vecFromA)*vecFromA; Vector3 closestPointB = pointB + dot_prod(v1, pointA-pointB)/dot_prod(v1, vecFromB)*vecFromB; error = norm_2(closestPointA - closestPointB); return 0.5 * (closestPointA + closestPointB); } void StereoModel::refine_point(Vector2 const& pix1, Vector2 const& pix2, Vector3& point) const { detail::PointLMA model( m_camera1, m_camera2 ); Vector4 objective( pix1[0], pix1[1], pix2[0], pix2[1] ); int status = 0; Vector3 npoint = levenberg_marquardt( model, point, objective, status ); if ( status > 0 ) point = npoint; } }} // vw::stereo <commit_msg>stereo: Put a limit on iterations in LSQ triangulation<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Camera/CameraModel.h> #include <vw/Stereo/StereoModel.h> #include <vw/Math/LevenbergMarquardt.h> namespace vw { namespace stereo { namespace detail { class PointLMA : public math::LeastSquaresModelBase<PointLMA> { const camera::CameraModel *m_camera1, *m_camera2; public: typedef Vector<double,4> result_type; typedef Vector<double,3> domain_type; typedef Matrix<double> jacobian_type; PointLMA( camera::CameraModel const* cam1, camera::CameraModel const* cam2 ) : m_camera1(cam1), m_camera2(cam2) {} inline result_type operator()( domain_type const& x ) const { Vector4 output; subvector(output,0,2) = m_camera1->point_to_pixel( x ); subvector(output,2,2) = m_camera2->point_to_pixel( x ); return output; } }; } ImageView<Vector3> StereoModel::operator()(ImageView<PixelMask<Vector2f> > const& disparity_map, ImageView<double> &error) const { // Error analysis double mean_error = 0.0; double max_error = 0.0; int32 point_count = 0; int32 divergent = 0; // Allocate xyz image and get pointer to buffer ImageView<Vector3> xyz(disparity_map.cols(), disparity_map.rows()); error.set_size(disparity_map.cols(), disparity_map.rows()); // Compute 3D position for each pixel in the disparity map vw_out() << "StereoModel: Applying camera models\n"; for (int32 y = 0; y < disparity_map.rows(); y++) { if (y % 100 == 0) { printf("\tStereoModel computing points: %0.2f%% complete.\r", 100.0f*float(y)/disparity_map.rows()); fflush(stdout); } for (int32 x = 0; x < disparity_map.cols(); x++) { if ( is_valid(disparity_map(x,y)) ) { xyz(x,y) = (*this)(Vector2( x, y), Vector2( x+disparity_map(x,y)[0], y+disparity_map(x,y)[1]), error(x,y) ); if (error(x,y) >= 0) { // Keep track of error statistics if (error(x,y) > max_error) max_error = error(x,y); mean_error += error(x,y); ++point_count; } else { // rays diverge or are parallel xyz(x,y) = Vector3(); divergent++; } } else { xyz(x,y) = Vector3(); error(x,y) = 0; } } } if (divergent != 0) vw_out() << "WARNING in StereoModel: " << divergent << " rays diverged or were parallel!\n"; vw_out() << "\tStereoModel computing points: Done. \n"; vw_out() << "\tMean error = " << mean_error/double(point_count) << ", Max error = " << max_error << std::endl; return xyz; } Vector3 StereoModel::operator()(Vector2 const& pix1, Vector2 const& pix2, double& error ) const { try { // determine range by triangulation Vector3 vecFromA = m_camera1->pixel_to_vector(pix1); Vector3 vecFromB = m_camera2->pixel_to_vector(pix2); // If vecFromA and vecFromB are nearly parallel, there will be // very large numerical uncertainty about where to place the // point. We set a threshold here to reject points that are // on nearly parallel rays. The threshold of 1e-4 corresponds // to a convergence of less than theta = 0.81 degrees, so if // the two rays are within 0.81 degrees of being parallel, we // reject this point. // // This threshold was chosen empirically for now, but should // probably be revisited once a more rigorous analysis has // been completed. -mbroxton (11-MAR-07) if ( (1-dot_prod(vecFromA, vecFromB) < 1e-4 && !m_least_squares) || (1-dot_prod(vecFromA, vecFromB) < 1e-5 && m_least_squares) ) { error = 0; return Vector3(); } Vector3 originA = m_camera1->camera_center(pix1); Vector3 originB = m_camera2->camera_center(pix2); Vector3 result = triangulate_point(originA, vecFromA, originB, vecFromB, error); if ( m_least_squares ) refine_point(pix1, pix2, result); // Reflect points that fall behind one of the two cameras if ( dot_prod(result - originA, vecFromA) < 0 || dot_prod(result - originB, vecFromB) < 0 ) { result = -result + 2*originA; } return result; } catch (const camera::PixelToRayErr& /*e*/) { error = 0; return Vector3(); } } double StereoModel::convergence_angle(Vector2 const& pix1, Vector2 const& pix2) const { return acos(dot_prod(m_camera1->pixel_to_vector(pix1), m_camera2->pixel_to_vector(pix2))); } Vector3 StereoModel::triangulate_point(Vector3 const& pointA, Vector3 const& vecFromA, Vector3 const& pointB, Vector3 const& vecFromB, double& error) const { Vector3 v12 = cross_prod(vecFromA, vecFromB); Vector3 v1 = cross_prod(v12, vecFromA); Vector3 v2 = cross_prod(v12, vecFromB); Vector3 closestPointA = pointA + dot_prod(v2, pointB-pointA)/dot_prod(v2, vecFromA)*vecFromA; Vector3 closestPointB = pointB + dot_prod(v1, pointA-pointB)/dot_prod(v1, vecFromB)*vecFromB; error = norm_2(closestPointA - closestPointB); return 0.5 * (closestPointA + closestPointB); } void StereoModel::refine_point(Vector2 const& pix1, Vector2 const& pix2, Vector3& point) const { detail::PointLMA model( m_camera1, m_camera2 ); Vector4 objective( pix1[0], pix1[1], pix2[0], pix2[1] ); int status = 0; Vector3 npoint = levenberg_marquardt( model, point, objective, status, 1e-3, 1e-6, 10 ); if ( status > 0 ) point = npoint; } }} // vw::stereo <|endoftext|>
<commit_before>#include "stdafx.h" #include "stdio.h" #include "FlyCapture2.h" #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <future> #include <chrono> #include <ctime> #include <thread> using namespace FlyCapture2; using namespace std; void PrintError( Error error ) { error.PrintErrorTrace(); } int get_current_time() { chrono::milliseconds ms = chrono::duration_cast<chrono::milliseconds>( chrono::system_clock::now().time_since_epoch()); return ms.count(); } int main(int argc, char* argv[]) { const Mode k_fmt7Mode = MODE_7; const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW16; const vector<int> SHUTTER_SPEEDS { 10,20,50,100,200,500 }; BusManager busMgr; unsigned int numCameras; Camera cam; Error error; PGRGuid guid; // TEST FILE WRITE ACCESS cout << "Testing file access..." << endl; FILE* tempFile = fopen("test.txt", "w+"); if (tempFile == NULL) { cout << "Failed to create file in current folder. Please check permissions." << endl; return -1; } fclose(tempFile); remove("test.txt"); // TEST CAMERA DETECTION cout << "Testing camera detection..." << endl; error = busMgr.GetNumOfCameras(&numCameras); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // GET CAMERA FROM INDEX cout << "Fetching camera from port index" << endl; error = busMgr.GetCameraFromIndex(0, &guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CONNECT cout << "Connecting to camera..." << endl; error = cam.Connect(&guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // GET CAMERA INFORMATION cout << "Fetching camera information..." << endl; CameraInfo camInfo; error = cam.GetCameraInfo(&camInfo); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CREATE FORMAT7 SETTINGS cout << "Creating fmt7 settings..." << endl; Format7ImageSettings fmt7ImageSettings; bool valid; Format7PacketInfo fmt7PacketInfo; fmt7ImageSettings.mode = k_fmt7Mode; fmt7ImageSettings.offsetX = 0; fmt7ImageSettings.offsetY = 0; fmt7ImageSettings.width = 1920; fmt7ImageSettings.height = 1200; fmt7ImageSettings.pixelFormat = k_fmt7PixFmt; // VALIDATE FORMAT7 SETTINGS cout << "Validating fmt7 settings..." << endl; error = cam.ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } if ( !valid ){ // Settings are not valid cout << "Format7 settings are not valid" << endl; return -1; } // SET FORMAT7 SETTINGS cout << "Writing fmt7 settings..." << endl; error = cam.SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SEQUENCE cout << "Starting image sequence..." << endl; unsigned int imageCount = 0; for(auto const& shutter_speed: SHUTTER_SPEEDS) { cout << "Writing image " << imageCount << " ..." << endl; imageCount++; // CREATE SHUTTER PROPERTY Property prop; prop.type = SHUTTER; prop.onOff = true; prop.autoManualMode = false; prop.absControl = true; prop.absValue = shutter_speed; // WRITE SHUTTE PROPERTY error = cam.SetProperty(&prop); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // START CAPTURE error = cam.StartCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // DELAY FOR CLARITY this_thread::sleep_for(chrono::milliseconds(1000)); // RETRIEVE IMAGE BUFFER Image rawImage; error = cam.RetrieveBuffer( &rawImage ); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // SET IMAGE DIMENSIONS PixelFormat pixFormat; unsigned int rows, cols, stride; rawImage.GetDimensions( &rows, &cols, &stride, &pixFormat ); // CONVERT IMAGE Image convertedImage; error = rawImage.Convert( PIXEL_FORMAT_BGRU, &convertedImage ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SAVE IMAGE ostringstream filename; int ms_time = get_current_time(); filename << "img_" << shutter_speed << "_" << ms_time << "_" << argv[1] << ".bmp"; error = convertedImage.Save( filename.str().c_str() ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // STOP CAPTURE error = cam.StopCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } } // DISCONNECT error = cam.Disconnect(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } cout << "Done." << endl; return 0; } <commit_msg>changed filenames to order by gps and pi timestamps<commit_after>#include "stdafx.h" #include "stdio.h" #include "FlyCapture2.h" #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <future> #include <chrono> #include <ctime> #include <thread> using namespace FlyCapture2; using namespace std; void PrintError( Error error ) { error.PrintErrorTrace(); } int get_current_time() { chrono::milliseconds ms = chrono::duration_cast<chrono::milliseconds>( chrono::system_clock::now().time_since_epoch()); return ms.count(); } int main(int argc, char* argv[]) { const Mode k_fmt7Mode = MODE_7; const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW16; const vector<int> SHUTTER_SPEEDS { 10,20,50,100,200,500 }; BusManager busMgr; unsigned int numCameras; Camera cam; Error error; PGRGuid guid; // TEST FILE WRITE ACCESS cout << "Testing file access..." << endl; FILE* tempFile = fopen("test.txt", "w+"); if (tempFile == NULL) { cout << "Failed to create file in current folder. Please check permissions." << endl; return -1; } fclose(tempFile); remove("test.txt"); // TEST CAMERA DETECTION cout << "Testing camera detection..." << endl; error = busMgr.GetNumOfCameras(&numCameras); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // GET CAMERA FROM INDEX cout << "Fetching camera from port index" << endl; error = busMgr.GetCameraFromIndex(0, &guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CONNECT cout << "Connecting to camera..." << endl; error = cam.Connect(&guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // GET CAMERA INFORMATION cout << "Fetching camera information..." << endl; CameraInfo camInfo; error = cam.GetCameraInfo(&camInfo); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CREATE FORMAT7 SETTINGS cout << "Creating fmt7 settings..." << endl; Format7ImageSettings fmt7ImageSettings; bool valid; Format7PacketInfo fmt7PacketInfo; fmt7ImageSettings.mode = k_fmt7Mode; fmt7ImageSettings.offsetX = 0; fmt7ImageSettings.offsetY = 0; fmt7ImageSettings.width = 1920; fmt7ImageSettings.height = 1200; fmt7ImageSettings.pixelFormat = k_fmt7PixFmt; // VALIDATE FORMAT7 SETTINGS cout << "Validating fmt7 settings..." << endl; error = cam.ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } if ( !valid ){ // Settings are not valid cout << "Format7 settings are not valid" << endl; return -1; } // SET FORMAT7 SETTINGS cout << "Writing fmt7 settings..." << endl; error = cam.SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SEQUENCE cout << "Starting image sequence..." << endl; unsigned int imageCount = 0; for(auto const& shutter_speed: SHUTTER_SPEEDS) { cout << "Writing image " << imageCount << " ..." << endl; imageCount++; // CREATE SHUTTER PROPERTY Property prop; prop.type = SHUTTER; prop.onOff = true; prop.autoManualMode = false; prop.absControl = true; prop.absValue = shutter_speed; // WRITE SHUTTE PROPERTY error = cam.SetProperty(&prop); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // START CAPTURE error = cam.StartCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // DELAY FOR CLARITY this_thread::sleep_for(chrono::milliseconds(1000)); // RETRIEVE IMAGE BUFFER Image rawImage; error = cam.RetrieveBuffer( &rawImage ); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // SET IMAGE DIMENSIONS PixelFormat pixFormat; unsigned int rows, cols, stride; rawImage.GetDimensions( &rows, &cols, &stride, &pixFormat ); // CONVERT IMAGE Image convertedImage; error = rawImage.Convert( PIXEL_FORMAT_BGRU, &convertedImage ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SAVE IMAGE ostringstream filename; int ms_time = get_current_time(); filename << "img_gps_" << argv[1] << "_pi_" << ms_time << "_shutter_" << shutter_speed << ".bmp"; error = convertedImage.Save( filename.str().c_str() ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // STOP CAPTURE error = cam.StopCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } } // DISCONNECT error = cam.Disconnect(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } cout << "Done." << endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2019, 2021 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/internal/mepoo/memory_manager.hpp" #include "iceoryx_posh/internal/mepoo/shared_chunk.hpp" #include "iceoryx_posh/mepoo/chunk_header.hpp" #include "iceoryx_utils/internal/posix_wrapper/shared_memory_object/allocator.hpp" #include "test.hpp" using namespace ::testing; using namespace iox::mepoo; class SharedChunk_Test : public Test { public: void SetUp() override { } void TearDown() override { } ChunkManagement* GetChunkManagement(void* memoryChunk) { ChunkManagement* v = static_cast<ChunkManagement*>(chunkMgmtPool.getChunk()); auto chunkSettingsResult = ChunkSettings::create(USER_PAYLOAD_SIZE, iox::CHUNK_DEFAULT_USER_PAYLOAD_ALIGNMENT); EXPECT_FALSE(chunkSettingsResult.has_error()); if (chunkSettingsResult.has_error()) { return nullptr; } auto& chunkSettings = chunkSettingsResult.value(); ChunkHeader* chunkHeader = new (memoryChunk) ChunkHeader(mempool.getChunkSize(), chunkSettings); new (v) ChunkManagement{chunkHeader, &mempool, &chunkMgmtPool}; return v; } static constexpr uint32_t CHUNK_SIZE{64U}; static constexpr uint32_t NUMBER_OF_CHUNKS{10U}; static constexpr uint32_t USER_PAYLOAD_SIZE{64U}; char memory[4096U]; iox::posix::Allocator allocator{memory, 4096U}; MemPool mempool{sizeof(ChunkHeader) + USER_PAYLOAD_SIZE, 10U, allocator, allocator}; MemPool chunkMgmtPool{64U, 10U, allocator, allocator}; void* memoryChunk{mempool.getChunk()}; ChunkManagement* chunkManagement = GetChunkManagement(memoryChunk); SharedChunk sut{chunkManagement}; }; TEST_F(SharedChunk_Test, SharedChunkObjectUpOnInitilizationSetsTheChunkHeaderToNullPointer) { SharedChunk sut; EXPECT_THAT(sut.getChunkHeader(), Eq(nullptr)); } TEST_F(SharedChunk_Test, VerifyCopyConstructorOfSharedChunk) { SharedChunk sut1(sut); EXPECT_EQ((sut1.getChunkHeader())->chunkSize(), (sut.getChunkHeader())->chunkSize()); EXPECT_EQ(sut.release(), sut1.release()); } TEST_F(SharedChunk_Test, VerifyMoveConstructorOfSharedChunk) { SharedChunk sut1(chunkManagement); ChunkHeader* header = sut1.getChunkHeader(); SharedChunk sut2(std::move(sut1)); ASSERT_EQ(sut1.getChunkHeader(), nullptr); ASSERT_EQ(sut2.getChunkHeader(), header); EXPECT_EQ((sut2.getChunkHeader())->chunkSize(), (sizeof(ChunkHeader) + USER_PAYLOAD_SIZE)); } TEST_F(SharedChunk_Test, VerifiyCopyAssigmentWithSharedChunk) { SharedChunk sut1; sut1 = sut; EXPECT_EQ((sut1.getChunkHeader())->chunkSize(), (sut.getChunkHeader())->chunkSize()); EXPECT_EQ(sut.release(), sut1.release()); } TEST_F(SharedChunk_Test, VerifiyMoveAssigmentForSharedChunk) { SharedChunk sut1(chunkManagement); SharedChunk sut2; ChunkHeader* header = sut1.getChunkHeader(); sut2 = std::move(sut1); ASSERT_EQ(sut1.getChunkHeader(), nullptr); ASSERT_EQ(sut2.getChunkHeader(), header); EXPECT_EQ((sut2.getChunkHeader())->chunkSize(), (sizeof(ChunkHeader) + USER_PAYLOAD_SIZE)); } TEST_F(SharedChunk_Test, CompareWithSameMemoryChunkComparesToUserPayload) { EXPECT_THAT(sut == sut.getUserPayload(), Eq(true)); } TEST_F(SharedChunk_Test, GetChunkHeaderMethodReturnsNullPointerWhenSharedChunkObjectIsInitialisedWithNullPointer) { SharedChunk sut; EXPECT_THAT(sut.getChunkHeader(), Eq(nullptr)); } TEST_F(SharedChunk_Test, GetChunkHeaderMethodReturnsValidPointerWhenSharedChunkObjectIsInitialisedWithAValidPointer) { void* newChunk = mempool.getChunk(); SharedChunk sut(GetChunkManagement(newChunk)); EXPECT_THAT(sut.getChunkHeader(), Eq(newChunk)); } TEST_F(SharedChunk_Test, EqualityOperatorOnTwoSharedChunkWithTheSameContentReturnsTrue) { SharedChunk sut1{chunkManagement}; EXPECT_TRUE(sut == sut1); } TEST_F(SharedChunk_Test, EqualityOperatorOnTwoSharedChunkWithDifferentContentReturnsFalse) { SharedChunk sut1; EXPECT_FALSE(sut == sut1); } TEST_F(SharedChunk_Test, EqualityOperatorOnSharedChunkAndSharedChunkPayloadWithDifferentChunkManagementsReturnFalse) { SharedChunk sut1; EXPECT_FALSE(sut1 == sut.getUserPayload()); } TEST_F(SharedChunk_Test, EqualityOperatorOnSharedChunkAndSharedChunkPayloadWithSameChunkManagementsReturnTrue) { SharedChunk sut1{chunkManagement}; EXPECT_TRUE(sut == sut1.getUserPayload()); } TEST_F(SharedChunk_Test, BoolOperatorOnValidSharedChunkReturnsTrue) { EXPECT_TRUE(sut); } TEST_F(SharedChunk_Test, BoolOperatorOnSharedChunkWithChunkManagementAsNullPointerReturnsFalse) { SharedChunk sut; EXPECT_FALSE(sut); } TEST_F(SharedChunk_Test, GetUserPayloadMethodReturnsNullPointerWhen_m_chunkmanagmentIsInvalid) { SharedChunk sut1; EXPECT_THAT(sut1.getUserPayload(), Eq(nullptr)); } TEST_F(SharedChunk_Test, GetUserPayloadMethodReturnsValidPointerWhen_m_chunkmanagmentIsValid) { using DATA_TYPE = uint32_t; constexpr DATA_TYPE USER_DATA{7337U}; ChunkHeader* newChunk = static_cast<ChunkHeader*>(mempool.getChunk()); auto chunkSettingsResult = ChunkSettings::create(sizeof(DATA_TYPE), alignof(DATA_TYPE)); ASSERT_FALSE(chunkSettingsResult.has_error()); auto& chunkSettings = chunkSettingsResult.value(); new (newChunk) ChunkHeader(mempool.getChunkSize(), chunkSettings); new (static_cast<DATA_TYPE*>(newChunk->userPayload())) DATA_TYPE{USER_DATA}; iox::mepoo::SharedChunk sut1(GetChunkManagement(newChunk)); EXPECT_THAT(*static_cast<DATA_TYPE*>(sut1.getUserPayload()), Eq(USER_DATA)); } TEST_F(SharedChunk_Test, MultipleSharedChunksCleanup) { { SharedChunk sut3, sut4, sut5; { { SharedChunk sut6, sut7, sut8; { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); sut3 = sut2; sut4 = sut2; sut5 = sut3; sut6 = sut5; sut7 = sut4; sut8 = sut2; EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(1U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(1U)); } TEST_F(SharedChunk_Test, MultipleChunksCleanup) { { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); iox::mepoo::SharedChunk sut4(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); iox::mepoo::SharedChunk sut4(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); iox::mepoo::SharedChunk sut4(GetChunkManagement(mempool.getChunk())); EXPECT_THAT(mempool.getUsedChunks(), Eq(9U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(9U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(7U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(7U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(5U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(5U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(3U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(3U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(1U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(1U)); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnTwoSharedChunkWithDifferentContentReturnsTrue) { SharedChunk sut1; EXPECT_TRUE(sut1 != sut); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnTwoSharedChunkWithSameContentReturnsFalse) { SharedChunk sut1{chunkManagement}; EXPECT_FALSE(sut1 != sut); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnSharedChunkAndSharedChunkPayloadWithDifferentChunkManagementsReturnTrue) { SharedChunk sut1; EXPECT_TRUE(sut != sut1.getUserPayload()); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnSharedChunkAndSharedChunkPayloadWithSameChunkManagementsReturnFalse) { SharedChunk sut1{chunkManagement}; EXPECT_FALSE(sut != sut1.getUserPayload()); } TEST_F(SharedChunk_Test, ReleaseMethodReturnsChunkManagementPointerOfSharedChunkObjectAndSetsTheChunkHeaderToNull) { ChunkManagement* returnValue = sut.release(); EXPECT_EQ(returnValue, chunkManagement); EXPECT_EQ(sut.getChunkHeader(), nullptr); } <commit_msg>iox-#496 Review comments fix: Refactoring the testcases of Move and copy constructors and assignment operators<commit_after>// Copyright (c) 2019, 2021 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/internal/mepoo/memory_manager.hpp" #include "iceoryx_posh/internal/mepoo/shared_chunk.hpp" #include "iceoryx_posh/mepoo/chunk_header.hpp" #include "iceoryx_utils/internal/posix_wrapper/shared_memory_object/allocator.hpp" #include "test.hpp" using namespace ::testing; using namespace iox::mepoo; class SharedChunk_Test : public Test { public: void SetUp() override { } void TearDown() override { } ChunkManagement* GetChunkManagement(void* memoryChunk) { ChunkManagement* v = static_cast<ChunkManagement*>(chunkMgmtPool.getChunk()); auto chunkSettingsResult = ChunkSettings::create(USER_PAYLOAD_SIZE, iox::CHUNK_DEFAULT_USER_PAYLOAD_ALIGNMENT); EXPECT_FALSE(chunkSettingsResult.has_error()); if (chunkSettingsResult.has_error()) { return nullptr; } auto& chunkSettings = chunkSettingsResult.value(); ChunkHeader* chunkHeader = new (memoryChunk) ChunkHeader(mempool.getChunkSize(), chunkSettings); new (v) ChunkManagement{chunkHeader, &mempool, &chunkMgmtPool}; return v; } static constexpr uint32_t CHUNK_SIZE{64U}; static constexpr uint32_t NUMBER_OF_CHUNKS{10U}; static constexpr uint32_t USER_PAYLOAD_SIZE{64U}; char memory[4096U]; iox::posix::Allocator allocator{memory, 4096U}; MemPool mempool{sizeof(ChunkHeader) + USER_PAYLOAD_SIZE, 10U, allocator, allocator}; MemPool chunkMgmtPool{64U, 10U, allocator, allocator}; void* memoryChunk{mempool.getChunk()}; ChunkManagement* chunkManagement = GetChunkManagement(memoryChunk); SharedChunk sut{chunkManagement}; }; TEST_F(SharedChunk_Test, SharedChunkObjectUpOnInitilizationSetsTheChunkHeaderToNullPointer) { SharedChunk sut; EXPECT_THAT(sut.getChunkHeader(), Eq(nullptr)); } TEST_F(SharedChunk_Test, VerifyCopyConstructorOfSharedChunk) { SharedChunk sut1(sut); EXPECT_EQ(sut.release(), sut1.release()); } TEST_F(SharedChunk_Test, VerifyMoveConstructorOfSharedChunk) { SharedChunk sut1(chunkManagement); SharedChunk sut2(std::move(sut1)); EXPECT_THAT(sut1, Eq(false)); EXPECT_THAT(sut2.release(), Eq(chunkManagement)); } TEST_F(SharedChunk_Test, VerifiyCopyAssigmentWithSharedChunk) { SharedChunk sut1; sut1 = sut; EXPECT_EQ(sut.release(), sut1.release()); } TEST_F(SharedChunk_Test, VerifiyMoveAssigmentForSharedChunk) { SharedChunk sut1(chunkManagement); SharedChunk sut2; sut2 = std::move(sut1); EXPECT_THAT(sut1, Eq(false)); EXPECT_THAT(sut2.release(), Eq(chunkManagement)); } TEST_F(SharedChunk_Test, CompareWithSameMemoryChunkComparesToUserPayload) { EXPECT_THAT(sut == sut.getUserPayload(), Eq(true)); } TEST_F(SharedChunk_Test, GetChunkHeaderMethodReturnsNullPointerWhenSharedChunkObjectIsInitialisedWithNullPointer) { SharedChunk sut; EXPECT_THAT(sut.getChunkHeader(), Eq(nullptr)); } TEST_F(SharedChunk_Test, GetChunkHeaderMethodReturnsValidPointerWhenSharedChunkObjectIsInitialisedWithAValidPointer) { void* newChunk = mempool.getChunk(); SharedChunk sut(GetChunkManagement(newChunk)); EXPECT_THAT(sut.getChunkHeader(), Eq(newChunk)); } TEST_F(SharedChunk_Test, EqualityOperatorOnTwoSharedChunkWithTheSameContentReturnsTrue) { SharedChunk sut1{chunkManagement}; EXPECT_TRUE(sut == sut1); } TEST_F(SharedChunk_Test, EqualityOperatorOnTwoSharedChunkWithDifferentContentReturnsFalse) { SharedChunk sut1; EXPECT_FALSE(sut == sut1); } TEST_F(SharedChunk_Test, EqualityOperatorOnSharedChunkAndSharedChunkPayloadWithDifferentChunkManagementsReturnFalse) { SharedChunk sut1; EXPECT_FALSE(sut1 == sut.getUserPayload()); } TEST_F(SharedChunk_Test, EqualityOperatorOnSharedChunkAndSharedChunkPayloadWithSameChunkManagementsReturnTrue) { SharedChunk sut1{chunkManagement}; EXPECT_TRUE(sut == sut1.getUserPayload()); } TEST_F(SharedChunk_Test, BoolOperatorOnValidSharedChunkReturnsTrue) { EXPECT_TRUE(sut); } TEST_F(SharedChunk_Test, BoolOperatorOnSharedChunkWithChunkManagementAsNullPointerReturnsFalse) { SharedChunk sut; EXPECT_FALSE(sut); } TEST_F(SharedChunk_Test, GetUserPayloadMethodReturnsNullPointerWhen_m_chunkmanagmentIsInvalid) { SharedChunk sut1; EXPECT_THAT(sut1.getUserPayload(), Eq(nullptr)); } TEST_F(SharedChunk_Test, GetUserPayloadMethodReturnsValidPointerWhen_m_chunkmanagmentIsValid) { using DATA_TYPE = uint32_t; constexpr DATA_TYPE USER_DATA{7337U}; ChunkHeader* newChunk = static_cast<ChunkHeader*>(mempool.getChunk()); auto chunkSettingsResult = ChunkSettings::create(sizeof(DATA_TYPE), alignof(DATA_TYPE)); ASSERT_FALSE(chunkSettingsResult.has_error()); auto& chunkSettings = chunkSettingsResult.value(); new (newChunk) ChunkHeader(mempool.getChunkSize(), chunkSettings); new (static_cast<DATA_TYPE*>(newChunk->userPayload())) DATA_TYPE{USER_DATA}; iox::mepoo::SharedChunk sut1(GetChunkManagement(newChunk)); EXPECT_THAT(*static_cast<DATA_TYPE*>(sut1.getUserPayload()), Eq(USER_DATA)); } TEST_F(SharedChunk_Test, MultipleSharedChunksCleanup) { { SharedChunk sut3, sut4, sut5; { { SharedChunk sut6, sut7, sut8; { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); sut3 = sut2; sut4 = sut2; sut5 = sut3; sut6 = sut5; sut7 = sut4; sut8 = sut2; EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(1U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(1U)); } TEST_F(SharedChunk_Test, MultipleChunksCleanup) { { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); iox::mepoo::SharedChunk sut4(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); iox::mepoo::SharedChunk sut4(GetChunkManagement(mempool.getChunk())); { iox::mepoo::SharedChunk sut2(GetChunkManagement(mempool.getChunk())); iox::mepoo::SharedChunk sut4(GetChunkManagement(mempool.getChunk())); EXPECT_THAT(mempool.getUsedChunks(), Eq(9U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(9U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(7U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(7U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(5U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(5U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(3U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(3U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(2U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(2U)); } EXPECT_THAT(mempool.getUsedChunks(), Eq(1U)); EXPECT_THAT(chunkMgmtPool.getUsedChunks(), Eq(1U)); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnTwoSharedChunkWithDifferentContentReturnsTrue) { SharedChunk sut1; EXPECT_TRUE(sut1 != sut); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnTwoSharedChunkWithSameContentReturnsFalse) { SharedChunk sut1{chunkManagement}; EXPECT_FALSE(sut1 != sut); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnSharedChunkAndSharedChunkPayloadWithDifferentChunkManagementsReturnTrue) { SharedChunk sut1; EXPECT_TRUE(sut != sut1.getUserPayload()); } TEST_F(SharedChunk_Test, NonEqualityOperatorOnSharedChunkAndSharedChunkPayloadWithSameChunkManagementsReturnFalse) { SharedChunk sut1{chunkManagement}; EXPECT_FALSE(sut != sut1.getUserPayload()); } TEST_F(SharedChunk_Test, ReleaseMethodReturnsChunkManagementPointerOfSharedChunkObjectAndSetsTheChunkHeaderToNull) { ChunkManagement* returnValue = sut.release(); EXPECT_EQ(returnValue, chunkManagement); EXPECT_EQ(sut.getChunkHeader(), nullptr); } <|endoftext|>
<commit_before>/* Q Light Controller olaoutthread.cpp Copyright (c) Simon Newton 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.txt 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 <QDebug> #include <ola/Callback.h> #include "olaoutthread.h" OlaOutThread::OlaOutThread() : QThread() , m_init_run(false) , m_ss(NULL) , m_pipe(NULL) , m_client(NULL) { } /* * Clean up. */ OlaOutThread::~OlaOutThread() { wait(); if (m_client) { m_client->Stop(); delete m_client; } if (m_pipe) delete m_pipe; cleanup(); } /* * Start the OLA thread * * @return true if sucessfull, false otherwise */ bool OlaOutThread::start(Priority priority) { if (!init()) return false; if (!m_pipe) { // setup the pipe to recv dmx data on m_pipe = new ola::io::LoopbackDescriptor(); m_pipe->Init(); m_pipe->SetOnData(ola::NewCallback(this, &OlaOutThread::new_pipe_data)); m_pipe->SetOnClose(ola::NewSingleCallback(this, &OlaOutThread::pipe_closed)); m_ss->AddReadDescriptor(m_pipe); } QThread::start(priority); return true; } /* * Close the socket which stops the thread. */ void OlaOutThread::stop() { if (m_pipe) m_pipe->CloseClient(); return; } /* * Run the select server. */ void OlaOutThread::run() { m_ss->Run(); return; } /* * Send the new data over the socket so that the other thread picks it up. * @param universe the universe nmuber this data is for * @param data a pointer to the data * @param channels the number of channels */ int OlaOutThread::write_dmx(unsigned int universe, const QByteArray& data) { m_data.universe = universe; memcpy(m_data.data, data.data(), data.size()); if (m_pipe) m_pipe->Send((uint8_t*) &m_data, sizeof(m_data)); return 0; } /* * Called when the pipe used to communicate between QLC and OLA is closed */ void OlaOutThread::pipe_closed() { // We don't need to delete the socket here because that gets done in the // Destructor. m_ss->Terminate(); } /* * Called when there is data to be read on the pipe socket. */ void OlaOutThread::new_pipe_data() { dmx_data data; unsigned int data_read; int ret = m_pipe->Receive((uint8_t*) &data, sizeof(data), data_read); if (ret < 0) { qCritical() << "olaout: socket receive failed"; return; } m_buffer.Set(data.data, data_read - sizeof(data.universe)); if (!m_client->SendDmx(data.universe, m_buffer)) qWarning() << "olaout:: SendDmx() failed"; } /* * Setup the OlaCallbackClient to communicate with the server. * @return true if the setup worked corectly. */ bool OlaOutThread::setup_client(ola::io::ConnectedDescriptor *descriptor) { if (!m_client) { m_client = new ola::OlaCallbackClient(descriptor); if (!m_client->Setup()) { qWarning() << "olaout: client setup failed"; delete m_client; m_client = NULL; return false; } m_ss->AddReadDescriptor(descriptor); } return true; } /* * Cleanup after the main destructor has run */ void OlaStandaloneClient::cleanup() { if (m_tcp_socket) { if (m_ss) m_ss->RemoveReadDescriptor(m_tcp_socket); delete m_tcp_socket; m_tcp_socket = NULL; } if (m_ss) delete m_ss; } /* * Setup the standalone client. * @return true is successful. */ bool OlaStandaloneClient::init() { if (m_init_run) return true; if (!m_ss) m_ss = new ola::io::SelectServer(); if (!m_tcp_socket) { ola::network::IPV4SocketAddress server_address( ola::network::IPV4Address::Loopback(), ola::OLA_DEFAULT_PORT); m_tcp_socket = ola::network::TCPSocket::Connect(server_address); if (!m_tcp_socket) { qWarning() << "olaout: Connect failed, is OLAD running?"; delete m_tcp_socket; m_tcp_socket = NULL; delete m_ss; m_ss = NULL; return false; } } if (!setup_client(m_tcp_socket)) { m_tcp_socket->Close(); delete m_tcp_socket; m_tcp_socket = NULL; delete m_ss; m_ss = NULL; return false; } m_init_run = true; return true; } /* * Clean up the embedded server. */ void OlaEmbeddedServer::cleanup() { if (m_daemon) delete m_daemon; if (m_pipe_socket) delete m_pipe_socket; } /* * Setup the embedded server. * @return true is successful. */ bool OlaEmbeddedServer::init() { if (m_init_run) return true; ola::OlaServer::Options options; options.http_enable = true; options.http_port = ola::OlaServer::DEFAULT_HTTP_PORT; m_daemon = new ola::OlaDaemon(options); if (!m_daemon->Init()) { qWarning() << "OLA Server failed init"; delete m_daemon; m_daemon = NULL; return false; } m_ss = m_daemon->GetSelectServer(); // setup the pipe socket used to communicate with the OlaServer if (!m_pipe_socket) { m_pipe_socket = new ola::io::PipeDescriptor(); if (!m_pipe_socket->Init()) { qWarning() << "olaout: pipe failed"; delete m_pipe_socket; m_pipe_socket = NULL; delete m_daemon; m_daemon = NULL; return false; } } if (!setup_client(m_pipe_socket)) { delete m_pipe_socket; m_pipe_socket = NULL; delete m_daemon; m_daemon = NULL; return false; } m_daemon->GetOlaServer()->NewConnection(m_pipe_socket->OppositeEnd()); m_init_run = true; return true; } <commit_msg>OLA: Fill extra output buffer with zeros<commit_after>/* Q Light Controller olaoutthread.cpp Copyright (c) Simon Newton 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.txt 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 <QDebug> #include <ola/Callback.h> #include "olaoutthread.h" OlaOutThread::OlaOutThread() : QThread() , m_init_run(false) , m_ss(NULL) , m_pipe(NULL) , m_client(NULL) { } /* * Clean up. */ OlaOutThread::~OlaOutThread() { wait(); if (m_client) { m_client->Stop(); delete m_client; } if (m_pipe) delete m_pipe; cleanup(); } /* * Start the OLA thread * * @return true if sucessfull, false otherwise */ bool OlaOutThread::start(Priority priority) { if (!init()) return false; if (!m_pipe) { // setup the pipe to recv dmx data on m_pipe = new ola::io::LoopbackDescriptor(); m_pipe->Init(); m_pipe->SetOnData(ola::NewCallback(this, &OlaOutThread::new_pipe_data)); m_pipe->SetOnClose(ola::NewSingleCallback(this, &OlaOutThread::pipe_closed)); m_ss->AddReadDescriptor(m_pipe); } QThread::start(priority); return true; } /* * Close the socket which stops the thread. */ void OlaOutThread::stop() { if (m_pipe) m_pipe->CloseClient(); return; } /* * Run the select server. */ void OlaOutThread::run() { m_ss->Run(); return; } /* * Send the new data over the socket so that the other thread picks it up. * @param universe the universe nmuber this data is for * @param data a pointer to the data * @param channels the number of channels */ int OlaOutThread::write_dmx(unsigned int universe, const QByteArray& data) { if (m_pipe) { Q_ASSERT(data.size() <= (int)sizeof(m_data.data)); m_data.universe = universe; memset(m_data.data, 0, sizeof(m_data.data)); memcpy(m_data.data, data.data(), data.size()); m_pipe->Send((uint8_t*) &m_data, sizeof(m_data)); } return 0; } /* * Called when the pipe used to communicate between QLC and OLA is closed */ void OlaOutThread::pipe_closed() { // We don't need to delete the socket here because that gets done in the // Destructor. m_ss->Terminate(); } /* * Called when there is data to be read on the pipe socket. */ void OlaOutThread::new_pipe_data() { dmx_data data; unsigned int data_read; int ret = m_pipe->Receive((uint8_t*) &data, sizeof(data), data_read); if (ret < 0) { qCritical() << "olaout: socket receive failed"; return; } m_buffer.Set(data.data, data_read - sizeof(data.universe)); if (!m_client->SendDmx(data.universe, m_buffer)) qWarning() << "olaout:: SendDmx() failed"; } /* * Setup the OlaCallbackClient to communicate with the server. * @return true if the setup worked corectly. */ bool OlaOutThread::setup_client(ola::io::ConnectedDescriptor *descriptor) { if (!m_client) { m_client = new ola::OlaCallbackClient(descriptor); if (!m_client->Setup()) { qWarning() << "olaout: client setup failed"; delete m_client; m_client = NULL; return false; } m_ss->AddReadDescriptor(descriptor); } return true; } /* * Cleanup after the main destructor has run */ void OlaStandaloneClient::cleanup() { if (m_tcp_socket) { if (m_ss) m_ss->RemoveReadDescriptor(m_tcp_socket); delete m_tcp_socket; m_tcp_socket = NULL; } if (m_ss) delete m_ss; } /* * Setup the standalone client. * @return true is successful. */ bool OlaStandaloneClient::init() { if (m_init_run) return true; if (!m_ss) m_ss = new ola::io::SelectServer(); if (!m_tcp_socket) { ola::network::IPV4SocketAddress server_address( ola::network::IPV4Address::Loopback(), ola::OLA_DEFAULT_PORT); m_tcp_socket = ola::network::TCPSocket::Connect(server_address); if (!m_tcp_socket) { qWarning() << "olaout: Connect failed, is OLAD running?"; delete m_tcp_socket; m_tcp_socket = NULL; delete m_ss; m_ss = NULL; return false; } } if (!setup_client(m_tcp_socket)) { m_tcp_socket->Close(); delete m_tcp_socket; m_tcp_socket = NULL; delete m_ss; m_ss = NULL; return false; } m_init_run = true; return true; } /* * Clean up the embedded server. */ void OlaEmbeddedServer::cleanup() { if (m_daemon) delete m_daemon; if (m_pipe_socket) delete m_pipe_socket; } /* * Setup the embedded server. * @return true is successful. */ bool OlaEmbeddedServer::init() { if (m_init_run) return true; ola::OlaServer::Options options; options.http_enable = true; options.http_port = ola::OlaServer::DEFAULT_HTTP_PORT; m_daemon = new ola::OlaDaemon(options); if (!m_daemon->Init()) { qWarning() << "OLA Server failed init"; delete m_daemon; m_daemon = NULL; return false; } m_ss = m_daemon->GetSelectServer(); // setup the pipe socket used to communicate with the OlaServer if (!m_pipe_socket) { m_pipe_socket = new ola::io::PipeDescriptor(); if (!m_pipe_socket->Init()) { qWarning() << "olaout: pipe failed"; delete m_pipe_socket; m_pipe_socket = NULL; delete m_daemon; m_daemon = NULL; return false; } } if (!setup_client(m_pipe_socket)) { delete m_pipe_socket; m_pipe_socket = NULL; delete m_daemon; m_daemon = NULL; return false; } m_daemon->GetOlaServer()->NewConnection(m_pipe_socket->OppositeEnd()); m_init_run = true; return true; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <seastar/net/stack.hh> #include <iostream> #include <seastar/net/inet_address.hh> namespace seastar { namespace net { using namespace seastar; template <typename Protocol> class native_server_socket_impl; template <typename Protocol> class native_connected_socket_impl; class native_network_stack; // native_server_socket_impl template <typename Protocol> class native_server_socket_impl : public server_socket_impl { typename Protocol::listener _listener; public: native_server_socket_impl(Protocol& proto, uint16_t port, listen_options opt); virtual future<accept_result> accept() override; virtual void abort_accept() override; virtual socket_address local_address() const override; }; template <typename Protocol> native_server_socket_impl<Protocol>::native_server_socket_impl(Protocol& proto, uint16_t port, listen_options opt) : _listener(proto.listen(port)) { } template <typename Protocol> future<accept_result> native_server_socket_impl<Protocol>::accept() { return _listener.accept().then([] (typename Protocol::connection conn) { // Save "conn" contents before call below function // "conn" is moved in 1st argument, and used in 2nd argument // It causes trouble on Arm which passes arguments from left to right auto ip = conn.foreign_ip().ip; auto port = conn.foreign_port(); return make_ready_future<accept_result>(accept_result{ connected_socket(std::make_unique<native_connected_socket_impl<Protocol>>(make_lw_shared(std::move(conn)))), make_ipv4_address(ip, port)}); }); } template <typename Protocol> void native_server_socket_impl<Protocol>::abort_accept() { _listener.abort_accept(); } template <typename Protocol> socket_address native_server_socket_impl<Protocol>::local_address() const { return socket_address(_listener.get_tcp().inet().inet().host_address(), _listener.port()); } // native_connected_socket_impl template <typename Protocol> class native_connected_socket_impl : public connected_socket_impl { lw_shared_ptr<typename Protocol::connection> _conn; class native_data_source_impl; class native_data_sink_impl; public: explicit native_connected_socket_impl(lw_shared_ptr<typename Protocol::connection> conn) : _conn(std::move(conn)) {} virtual data_source source() override; virtual data_sink sink() override; virtual void shutdown_input() override; virtual void shutdown_output() override; virtual void set_nodelay(bool nodelay) override; virtual bool get_nodelay() const override; void set_keepalive(bool keepalive) override; bool get_keepalive() const override; void set_keepalive_parameters(const keepalive_params&) override; keepalive_params get_keepalive_parameters() const override; int get_sockopt(int level, int optname, void* data, size_t len) const; void set_sockopt(int level, int optname, const void* data, size_t len); }; template <typename Protocol> class native_socket_impl final : public socket_impl { Protocol& _proto; lw_shared_ptr<typename Protocol::connection> _conn; public: explicit native_socket_impl(Protocol& proto) : _proto(proto), _conn(nullptr) { } virtual future<connected_socket> connect(socket_address sa, socket_address local, transport proto = transport::TCP) override { //TODO: implement SCTP assert(proto == transport::TCP); // FIXME: local is ignored since native stack does not support multiple IPs yet assert(sa.as_posix_sockaddr().sa_family == AF_INET); _conn = make_lw_shared<typename Protocol::connection>(_proto.connect(sa)); return _conn->connected().then([conn = _conn]() mutable { auto csi = std::make_unique<native_connected_socket_impl<Protocol>>(std::move(conn)); return make_ready_future<connected_socket>(connected_socket(std::move(csi))); }); } virtual void set_reuseaddr(bool reuseaddr) override { // FIXME: implement std::cerr << "Reuseaddr is not supported by native stack" << std::endl; } virtual bool get_reuseaddr() const override { // FIXME: implement return false; } virtual void shutdown() override { if (_conn) { _conn->shutdown_connect(); } } }; template <typename Protocol> class native_connected_socket_impl<Protocol>::native_data_source_impl final : public data_source_impl { typedef typename Protocol::connection connection_type; lw_shared_ptr<connection_type> _conn; size_t _cur_frag = 0; bool _eof = false; packet _buf; public: explicit native_data_source_impl(lw_shared_ptr<connection_type> conn) : _conn(std::move(conn)) {} virtual future<temporary_buffer<char>> get() override { if (_eof) { return make_ready_future<temporary_buffer<char>>(temporary_buffer<char>(0)); } if (_cur_frag != _buf.nr_frags()) { auto& f = _buf.fragments()[_cur_frag++]; return make_ready_future<temporary_buffer<char>>( temporary_buffer<char>(f.base, f.size, make_deleter(deleter(), [p = _buf.share()] () mutable {}))); } return _conn->wait_for_data().then([this] { _buf = _conn->read(); _cur_frag = 0; _eof = !_buf.len(); return get(); }); } future<> close() override { _conn->close_write(); return make_ready_future<>(); } }; template <typename Protocol> class native_connected_socket_impl<Protocol>::native_data_sink_impl final : public data_sink_impl { typedef typename Protocol::connection connection_type; lw_shared_ptr<connection_type> _conn; public: explicit native_data_sink_impl(lw_shared_ptr<connection_type> conn) : _conn(std::move(conn)) {} using data_sink_impl::put; virtual future<> put(packet p) override { return _conn->send(std::move(p)); } virtual future<> close() override { _conn->close_write(); return make_ready_future<>(); } }; template <typename Protocol> data_source native_connected_socket_impl<Protocol>::source() { return data_source(std::make_unique<native_data_source_impl>(_conn)); } template <typename Protocol> data_sink native_connected_socket_impl<Protocol>::sink() { return data_sink(std::make_unique<native_data_sink_impl>(_conn)); } template <typename Protocol> void native_connected_socket_impl<Protocol>::shutdown_input() { _conn->close_read(); } template <typename Protocol> void native_connected_socket_impl<Protocol>::shutdown_output() { _conn->close_write(); } template <typename Protocol> void native_connected_socket_impl<Protocol>::set_nodelay(bool nodelay) { // FIXME: implement } template <typename Protocol> bool native_connected_socket_impl<Protocol>::get_nodelay() const { // FIXME: implement return true; } template <typename Protocol> void native_connected_socket_impl<Protocol>::set_keepalive(bool keepalive) { // FIXME: implement std::cerr << "Keepalive is not supported by native stack" << std::endl; } template <typename Protocol> bool native_connected_socket_impl<Protocol>::get_keepalive() const { // FIXME: implement return false; } template <typename Protocol> void native_connected_socket_impl<Protocol>::set_keepalive_parameters(const keepalive_params&) { // FIXME: implement std::cerr << "Keepalive parameters are not supported by native stack" << std::endl; } template <typename Protocol> keepalive_params native_connected_socket_impl<Protocol>::get_keepalive_parameters() const { // FIXME: implement return tcp_keepalive_params {std::chrono::seconds(0), std::chrono::seconds(0), 0}; } template<typename Protocol> void native_connected_socket_impl<Protocol>::set_sockopt(int level, int optname, const void* data, size_t len) { throw std::runtime_error("Setting custom socket options is not supported for native stack"); } template<typename Protocol> int native_connected_socket_impl<Protocol>::get_sockopt(int level, int optname, void* data, size_t len) const { throw std::runtime_error("Getting custom socket options is not supported for native stack"); } } } <commit_msg>net: expose hidden method from parent class<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <seastar/net/stack.hh> #include <iostream> #include <seastar/net/inet_address.hh> namespace seastar { namespace net { using namespace seastar; template <typename Protocol> class native_server_socket_impl; template <typename Protocol> class native_connected_socket_impl; class native_network_stack; // native_server_socket_impl template <typename Protocol> class native_server_socket_impl : public server_socket_impl { typename Protocol::listener _listener; public: native_server_socket_impl(Protocol& proto, uint16_t port, listen_options opt); virtual future<accept_result> accept() override; virtual void abort_accept() override; virtual socket_address local_address() const override; }; template <typename Protocol> native_server_socket_impl<Protocol>::native_server_socket_impl(Protocol& proto, uint16_t port, listen_options opt) : _listener(proto.listen(port)) { } template <typename Protocol> future<accept_result> native_server_socket_impl<Protocol>::accept() { return _listener.accept().then([] (typename Protocol::connection conn) { // Save "conn" contents before call below function // "conn" is moved in 1st argument, and used in 2nd argument // It causes trouble on Arm which passes arguments from left to right auto ip = conn.foreign_ip().ip; auto port = conn.foreign_port(); return make_ready_future<accept_result>(accept_result{ connected_socket(std::make_unique<native_connected_socket_impl<Protocol>>(make_lw_shared(std::move(conn)))), make_ipv4_address(ip, port)}); }); } template <typename Protocol> void native_server_socket_impl<Protocol>::abort_accept() { _listener.abort_accept(); } template <typename Protocol> socket_address native_server_socket_impl<Protocol>::local_address() const { return socket_address(_listener.get_tcp().inet().inet().host_address(), _listener.port()); } // native_connected_socket_impl template <typename Protocol> class native_connected_socket_impl : public connected_socket_impl { lw_shared_ptr<typename Protocol::connection> _conn; class native_data_source_impl; class native_data_sink_impl; public: explicit native_connected_socket_impl(lw_shared_ptr<typename Protocol::connection> conn) : _conn(std::move(conn)) {} using connected_socket_impl::source; virtual data_source source() override; virtual data_sink sink() override; virtual void shutdown_input() override; virtual void shutdown_output() override; virtual void set_nodelay(bool nodelay) override; virtual bool get_nodelay() const override; void set_keepalive(bool keepalive) override; bool get_keepalive() const override; void set_keepalive_parameters(const keepalive_params&) override; keepalive_params get_keepalive_parameters() const override; int get_sockopt(int level, int optname, void* data, size_t len) const; void set_sockopt(int level, int optname, const void* data, size_t len); }; template <typename Protocol> class native_socket_impl final : public socket_impl { Protocol& _proto; lw_shared_ptr<typename Protocol::connection> _conn; public: explicit native_socket_impl(Protocol& proto) : _proto(proto), _conn(nullptr) { } virtual future<connected_socket> connect(socket_address sa, socket_address local, transport proto = transport::TCP) override { //TODO: implement SCTP assert(proto == transport::TCP); // FIXME: local is ignored since native stack does not support multiple IPs yet assert(sa.as_posix_sockaddr().sa_family == AF_INET); _conn = make_lw_shared<typename Protocol::connection>(_proto.connect(sa)); return _conn->connected().then([conn = _conn]() mutable { auto csi = std::make_unique<native_connected_socket_impl<Protocol>>(std::move(conn)); return make_ready_future<connected_socket>(connected_socket(std::move(csi))); }); } virtual void set_reuseaddr(bool reuseaddr) override { // FIXME: implement std::cerr << "Reuseaddr is not supported by native stack" << std::endl; } virtual bool get_reuseaddr() const override { // FIXME: implement return false; } virtual void shutdown() override { if (_conn) { _conn->shutdown_connect(); } } }; template <typename Protocol> class native_connected_socket_impl<Protocol>::native_data_source_impl final : public data_source_impl { typedef typename Protocol::connection connection_type; lw_shared_ptr<connection_type> _conn; size_t _cur_frag = 0; bool _eof = false; packet _buf; public: explicit native_data_source_impl(lw_shared_ptr<connection_type> conn) : _conn(std::move(conn)) {} virtual future<temporary_buffer<char>> get() override { if (_eof) { return make_ready_future<temporary_buffer<char>>(temporary_buffer<char>(0)); } if (_cur_frag != _buf.nr_frags()) { auto& f = _buf.fragments()[_cur_frag++]; return make_ready_future<temporary_buffer<char>>( temporary_buffer<char>(f.base, f.size, make_deleter(deleter(), [p = _buf.share()] () mutable {}))); } return _conn->wait_for_data().then([this] { _buf = _conn->read(); _cur_frag = 0; _eof = !_buf.len(); return get(); }); } future<> close() override { _conn->close_write(); return make_ready_future<>(); } }; template <typename Protocol> class native_connected_socket_impl<Protocol>::native_data_sink_impl final : public data_sink_impl { typedef typename Protocol::connection connection_type; lw_shared_ptr<connection_type> _conn; public: explicit native_data_sink_impl(lw_shared_ptr<connection_type> conn) : _conn(std::move(conn)) {} using data_sink_impl::put; virtual future<> put(packet p) override { return _conn->send(std::move(p)); } virtual future<> close() override { _conn->close_write(); return make_ready_future<>(); } }; template <typename Protocol> data_source native_connected_socket_impl<Protocol>::source() { return data_source(std::make_unique<native_data_source_impl>(_conn)); } template <typename Protocol> data_sink native_connected_socket_impl<Protocol>::sink() { return data_sink(std::make_unique<native_data_sink_impl>(_conn)); } template <typename Protocol> void native_connected_socket_impl<Protocol>::shutdown_input() { _conn->close_read(); } template <typename Protocol> void native_connected_socket_impl<Protocol>::shutdown_output() { _conn->close_write(); } template <typename Protocol> void native_connected_socket_impl<Protocol>::set_nodelay(bool nodelay) { // FIXME: implement } template <typename Protocol> bool native_connected_socket_impl<Protocol>::get_nodelay() const { // FIXME: implement return true; } template <typename Protocol> void native_connected_socket_impl<Protocol>::set_keepalive(bool keepalive) { // FIXME: implement std::cerr << "Keepalive is not supported by native stack" << std::endl; } template <typename Protocol> bool native_connected_socket_impl<Protocol>::get_keepalive() const { // FIXME: implement return false; } template <typename Protocol> void native_connected_socket_impl<Protocol>::set_keepalive_parameters(const keepalive_params&) { // FIXME: implement std::cerr << "Keepalive parameters are not supported by native stack" << std::endl; } template <typename Protocol> keepalive_params native_connected_socket_impl<Protocol>::get_keepalive_parameters() const { // FIXME: implement return tcp_keepalive_params {std::chrono::seconds(0), std::chrono::seconds(0), 0}; } template<typename Protocol> void native_connected_socket_impl<Protocol>::set_sockopt(int level, int optname, const void* data, size_t len) { throw std::runtime_error("Setting custom socket options is not supported for native stack"); } template<typename Protocol> int native_connected_socket_impl<Protocol>::get_sockopt(int level, int optname, void* data, size_t len) const { throw std::runtime_error("Getting custom socket options is not supported for native stack"); } } } <|endoftext|>
<commit_before> #include <configure/Application.hpp> #include <boost/filesystem.hpp> #include <fstream> #include <vector> namespace fs = boost::filesystem; typedef configure::Application app_t; BOOST_AUTO_TEST_CASE(invalid_args) { std::vector<std::string> empty_args; BOOST_CHECK_THROW(configure::Application(0, nullptr), std::exception); BOOST_CHECK_THROW(configure::Application(-1, nullptr), std::exception); BOOST_CHECK_THROW(configure::Application(empty_args), std::exception); } struct Env { fs::path _dir; fs::path _old_cwd; Env() : _dir{fs::temp_directory_path() / fs::unique_path()} , _old_cwd{fs::current_path()} { fs::create_directories(_dir); fs::current_path(_dir); } ~Env() { fs::current_path(_old_cwd); fs::remove_all(_dir); } void add_project() { std::ofstream out{(_dir / "configure.lua").string()}; out << "something"; out.close(); } fs::path const& dir() { return _dir; } }; BOOST_AUTO_TEST_CASE(missing_project) { Env env; BOOST_CHECK_THROW(app_t({"pif"}), std::exception); } BOOST_AUTO_TEST_CASE(no_build_dir) { Env env; env.add_project(); app_t app({"pif"}); BOOST_CHECK_EQUAL(app.build_directories().size(), 0); BOOST_CHECK_EQUAL(app.project_directory(), env.dir()); } <commit_msg>Prevent messed up macros with parenthesis.<commit_after> #include <configure/Application.hpp> #include <boost/filesystem.hpp> #include <fstream> namespace fs = boost::filesystem; typedef configure::Application app_t; BOOST_AUTO_TEST_CASE(invalid_args) { BOOST_CHECK_THROW(configure::Application(0, nullptr), std::exception); BOOST_CHECK_THROW(configure::Application(-1, nullptr), std::exception); BOOST_CHECK_THROW( (configure::Application(std::vector<std::string>())), std::exception ); } struct Env { fs::path _dir; fs::path _old_cwd; Env() : _dir{fs::temp_directory_path() / fs::unique_path()} , _old_cwd{fs::current_path()} { fs::create_directories(_dir); fs::current_path(_dir); } ~Env() { fs::current_path(_old_cwd); fs::remove_all(_dir); } void add_project() { std::ofstream out{(_dir / "configure.lua").string()}; out << "something"; out.close(); } fs::path const& dir() { return _dir; } }; BOOST_AUTO_TEST_CASE(missing_project) { Env env; BOOST_CHECK_THROW(app_t({"pif"}), std::exception); } BOOST_AUTO_TEST_CASE(no_build_dir) { Env env; env.add_project(); app_t app({"pif"}); BOOST_CHECK_EQUAL(app.build_directories().size(), 0); BOOST_CHECK_EQUAL(app.project_directory(), env.dir()); } <|endoftext|>
<commit_before>#pragma once #include<vector> #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/optimization/multicut/multicut_base.hxx" #include "nifty/graph/optimization/multicut/multicut_factory.hxx" #include "nifty/graph/optimization/multicut/multicut_greedy_additive.hxx" #include "nifty/graph/optimization/multicut/multicut_kernighan_lin.hxx" #include "nifty/ufd/ufd.hxx" // LP_MP includes #include "visitors/standard_visitor.hxx" #include "solvers/multicut/multicut.h" namespace nifty{ namespace graph{ template<class OBJECTIVE> class MulticutMp : public MulticutBase<OBJECTIVE> { public: typedef OBJECTIVE Objective; typedef MulticutBase<OBJECTIVE> Base; typedef typename Base::VisitorBase VisitorBase; typedef typename Base::VisitorProxy VisitorProxy; typedef typename Base::EdgeLabels EdgeLabels; typedef typename Base::NodeLabels NodeLabels; typedef typename Objective::Graph Graph; // factory for the lp_mp primal rounder typedef MulticutFactoryBase<Objective> McFactoryBase; public: struct NiftyRounder { typedef Graph GraphType; NiftyRounder(std::shared_ptr<McFactoryBase> factory, const bool greedyWarmstart) : factory_(factory), greedyWarmstart_(greedyWarmstart) {} // TODO do we have to call by value here due to using async or could we also use a call by refernce? // TODO need to change between between edge and node labelings -> could be done more efficient ?! std::vector<char> operator()(GraphType g, std::vector<double> edgeValues) { std::vector<char> labeling(g.numberOfEdges(), 0); if(g.numberOfEdges() > 0) { Objective obj(g); auto & objWeights = obj.weights(); for(auto eId = 0; eId < edgeValues.size(); ++eId) { objWeights[eId] = edgeValues[eId]; } NodeLabels nodeLabels(g.numberOfNodes()); // TODO is there a bug in here ?!? if(greedyWarmstart_) { MulticutGreedyAdditive<Objective> greedy(obj); greedy.optimize(nodeLabels, nullptr); } auto solverPtr = factory_->createRawPtr(obj); std::cout << "compute multicut primal with " << (greedyWarmstart_ ? "GAEC + " : "") << solverPtr->name() << std::endl; solverPtr->optimize(nodeLabels, nullptr); delete solverPtr; // node labeling to edge labeling for(auto eId = 0; eId < g.numberOfEdges(); ++eId) { const auto & uv = g.uv(eId); labeling[eId] = nodeLabels[uv.first] != nodeLabels[uv.second]; } } return labeling; } // TODO add factory name here static std::string name() { return "NiftyRounder"; } private: std::shared_ptr<McFactoryBase> factory_; bool greedyWarmstart_; }; //typedef LP_MP::KlRounder Rounder; typedef NiftyRounder Rounder; // TODO with or without odd wheel ? //typedef LP_MP::FMC_MULTICUT<LP_MP::MessageSendingType::SRMP,NiftyRounder> FMC; typedef LP_MP::FMC_ODD_WHEEL_MULTICUT<LP_MP::MessageSendingType::SRMP,Rounder> FMC; typedef LP_MP::Solver<FMC,LP_MP::LP,LP_MP::StandardTighteningVisitor,Rounder> SolverBase; typedef LP_MP::ProblemConstructorRoundingSolver<SolverBase> SolverType; // FIXME verbose deosn't have any effect right now struct Settings{ // multicut factory for the primal rounder used in lp_mp std::shared_ptr<McFactoryBase> mcFactory; bool greedyWarmstart{false}; // settings for the lp_mp solver size_t numberOfIterations{1000}; int verbose{0}; size_t primalComputationInterval{100}; std::string standardReparametrization{"anisotropic"}; std::string roundingReparametrization{"damped_uniform"}; std::string tightenReparametrization{"damped_uniform"}; bool tighten{true}; size_t tightenInterval{100}; size_t tightenIteration{10}; double tightenSlope{0.02}; double tightenConstraintsPercentage{0.1}; double minDualImprovement{0.}; size_t minDualImprovementInterval{0}; size_t timeout{0}; size_t numberOfThreads{1}; }; virtual ~MulticutMp(){ delete mpSolver_; } MulticutMp(const Objective & objective, const Settings & settings = Settings()); virtual void optimize(NodeLabels & nodeLabels, VisitorBase * visitor); virtual const Objective & objective() const {return objective_;} virtual const NodeLabels & currentBestNodeLabels() {return *currentBest_;} virtual std::string name() const { return std::string("MulticutMp"); } // TODO do we need this, what does it do? // reset ?! //virtual void weightsChanged(){ //} private: void initializeMp(); void nodeLabeling(); std::vector<std::string> toOptionsVector() const; const Objective & objective_; const Graph & graph_; Settings settings_; NodeLabels * currentBest_; size_t numberOfOptRuns_; SolverType * mpSolver_; ufd::Ufd<uint64_t> ufd_; }; template<class OBJECTIVE> MulticutMp<OBJECTIVE>:: MulticutMp( const Objective & objective, const Settings & settings ) : objective_(objective), graph_(objective.graph()), settings_(settings), currentBest_(nullptr), mpSolver_(nullptr), ufd_(graph_.numberOfNodes()) { // if we don't have a mc-factory, we use the LP_MP default rounder if(!bool(settings_.mcFactory)) { typedef MulticutKernighanLin<Objective> DefaultSolver; typedef MulticutFactory<DefaultSolver> DefaultFactory; settings_.mcFactory = std::make_shared<DefaultFactory>(); } mpSolver_ = new SolverType( toOptionsVector() ,NiftyRounder(settings_.mcFactory, settings_.greedyWarmstart) ); this->initializeMp(); } template<class OBJECTIVE> void MulticutMp<OBJECTIVE>:: initializeMp() { if(graph_.numberOfEdges()!= 0 ){ auto & constructor = (*mpSolver_).template GetProblemConstructor<0>(); const auto & weights = objective_.weights(); for(auto e : graph_.edges()){ const auto & uv = graph_.uv(e); constructor.AddUnaryFactor(uv.first, uv.second, weights[e]); } } } // returns options in correct format for the LP_MP solver // TODO would be bettter to have a decent interface for LP_MP and then // get rid of this template<class OBJECTIVE> std::vector<std::string> MulticutMp<OBJECTIVE>:: toOptionsVector() const { std::vector<std::string> options = { "multicut_mp", "-i", " ", // empty input file "--primalComputationInterval", std::to_string(settings_.primalComputationInterval), "--standardReparametrization", settings_.standardReparametrization, "--roundingReparametrization", settings_.roundingReparametrization, "--tightenReparametrization", settings_.tightenReparametrization, "--tightenInterval", std::to_string(settings_.tightenInterval), "--tightenIteration", std::to_string(settings_.tightenIteration), "--tightenSlope", std::to_string(settings_.tightenSlope), "--tightenConstraintsPercentage", std::to_string(settings_.tightenConstraintsPercentage), "--maxIter", std::to_string(settings_.numberOfIterations), #ifdef LP_MP_PARALLEL "--numLpThreads", std::to_string(settings_.numberOfThreads) #endif }; if(settings_.tighten) options.push_back("--tighten"); if(settings_.minDualImprovement > 0) { options.push_back("--minDualImprovement"); options.push_back(std::to_string(settings_.minDualImprovement)); } if(settings_.minDualImprovementInterval > 0) { options.push_back("--minDualImprovementInterval"); options.push_back(std::to_string(settings_.minDualImprovementInterval)); } if(settings_.timeout > 0) { options.push_back("--timeout"); options.push_back(std::to_string(settings_.timeout)); } return options; } // TODO maybe this can be done more efficient // (if we only call it once, this should be fine, but if we need // to call this more often for some reason, this might get expensive) template<class OBJECTIVE> void MulticutMp<OBJECTIVE>:: nodeLabeling() { ufd_.reset(); auto & constructor = (*mpSolver_).template GetProblemConstructor<0>(); for(auto e : graph_.edges()){ const auto & uv = graph_.uv(e); const bool cut = constructor.get_edge_label(uv.first, uv.second); if(!cut){ ufd_.merge(uv.first, uv.second); } } ufd_.elementLabeling(currentBest_->begin()); } template<class OBJECTIVE> void MulticutMp<OBJECTIVE>:: optimize( NodeLabels & nodeLabels, VisitorBase * visitor ){ //VisitorProxy visitorProxy(visitor); currentBest_ = &nodeLabels; // TODO for now the visitor is doing nothing, but we should implement one, that is // compatible with lp_mp visitor //visitorProxy.begin(this); if(graph_.numberOfEdges()>0){ mpSolver_->Solve(); nodeLabeling(); } //visitorProxy.end(this); } } // namespace nifty::graph } // namespace nifty <commit_msg>different default rounder<commit_after>#pragma once #include<vector> #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/optimization/multicut/multicut_base.hxx" #include "nifty/graph/optimization/multicut/multicut_factory.hxx" //#include "nifty/graph/optimization/multicut/multicut_greedy_additive.hxx" //#include "nifty/graph/optimization/multicut/multicut_kernighan_lin.hxx" #include "nifty/graph/optimization/multicut/multicut_andres.hxx" #include "nifty/ufd/ufd.hxx" // LP_MP includes #include "visitors/standard_visitor.hxx" #include "solvers/multicut/multicut.h" namespace nifty{ namespace graph{ template<class OBJECTIVE> class MulticutMp : public MulticutBase<OBJECTIVE> { public: typedef OBJECTIVE Objective; typedef MulticutBase<OBJECTIVE> Base; typedef typename Base::VisitorBase VisitorBase; typedef typename Base::VisitorProxy VisitorProxy; typedef typename Base::EdgeLabels EdgeLabels; typedef typename Base::NodeLabels NodeLabels; typedef typename Objective::Graph Graph; // factory for the lp_mp primal rounder typedef MulticutFactoryBase<Objective> McFactoryBase; public: struct NiftyRounder { typedef Graph GraphType; NiftyRounder(std::shared_ptr<McFactoryBase> factory, const bool greedyWarmstart) : factory_(factory), greedyWarmstart_(greedyWarmstart) {} // TODO do we have to call by value here due to using async or could we also use a call by refernce? // TODO need to change between between edge and node labelings -> could be done more efficient ?! std::vector<char> operator()(GraphType g, std::vector<double> edgeValues) { std::vector<char> labeling(g.numberOfEdges(), 0); if(g.numberOfEdges() > 0) { Objective obj(g); auto & objWeights = obj.weights(); for(auto eId = 0; eId < edgeValues.size(); ++eId) { objWeights[eId] = edgeValues[eId]; } NodeLabels nodeLabels(g.numberOfNodes()); // TODO is there a bug in here ?!? if(greedyWarmstart_) { MulticutGreedyAdditive<Objective> greedy(obj); greedy.optimize(nodeLabels, nullptr); } auto solverPtr = factory_->createRawPtr(obj); std::cout << "compute multicut primal with " << (greedyWarmstart_ ? "GAEC + " : "") << solverPtr->name() << std::endl; solverPtr->optimize(nodeLabels, nullptr); delete solverPtr; // node labeling to edge labeling for(auto eId = 0; eId < g.numberOfEdges(); ++eId) { const auto & uv = g.uv(eId); labeling[eId] = nodeLabels[uv.first] != nodeLabels[uv.second]; } } return labeling; } // TODO add factory name here static std::string name() { return "NiftyRounder"; } private: std::shared_ptr<McFactoryBase> factory_; bool greedyWarmstart_; }; //typedef LP_MP::KlRounder Rounder; typedef NiftyRounder Rounder; // TODO with or without odd wheel ? //typedef LP_MP::FMC_MULTICUT<LP_MP::MessageSendingType::SRMP,NiftyRounder> FMC; typedef LP_MP::FMC_ODD_WHEEL_MULTICUT<LP_MP::MessageSendingType::SRMP,Rounder> FMC; typedef LP_MP::Solver<FMC,LP_MP::LP,LP_MP::StandardTighteningVisitor,Rounder> SolverBase; typedef LP_MP::ProblemConstructorRoundingSolver<SolverBase> SolverType; // FIXME verbose deosn't have any effect right now struct Settings{ // multicut factory for the primal rounder used in lp_mp std::shared_ptr<McFactoryBase> mcFactory; bool greedyWarmstart{false}; // settings for the lp_mp solver size_t numberOfIterations{1000}; int verbose{0}; size_t primalComputationInterval{100}; std::string standardReparametrization{"anisotropic"}; std::string roundingReparametrization{"damped_uniform"}; std::string tightenReparametrization{"damped_uniform"}; bool tighten{true}; size_t tightenInterval{100}; size_t tightenIteration{10}; double tightenSlope{0.02}; double tightenConstraintsPercentage{0.1}; double minDualImprovement{0.}; size_t minDualImprovementInterval{0}; size_t timeout{0}; size_t numberOfThreads{1}; }; virtual ~MulticutMp(){ delete mpSolver_; } MulticutMp(const Objective & objective, const Settings & settings = Settings()); virtual void optimize(NodeLabels & nodeLabels, VisitorBase * visitor); virtual const Objective & objective() const {return objective_;} virtual const NodeLabels & currentBestNodeLabels() {return *currentBest_;} virtual std::string name() const { return std::string("MulticutMp"); } // TODO do we need this, what does it do? // reset ?! //virtual void weightsChanged(){ //} private: void initializeMp(); void nodeLabeling(); std::vector<std::string> toOptionsVector() const; const Objective & objective_; const Graph & graph_; Settings settings_; NodeLabels * currentBest_; size_t numberOfOptRuns_; SolverType * mpSolver_; ufd::Ufd<uint64_t> ufd_; }; template<class OBJECTIVE> MulticutMp<OBJECTIVE>:: MulticutMp( const Objective & objective, const Settings & settings ) : objective_(objective), graph_(objective.graph()), settings_(settings), currentBest_(nullptr), mpSolver_(nullptr), ufd_(graph_.numberOfNodes()) { // if we don't have a mc-factory, we use the LP_MP default rounder if(!bool(settings_.mcFactory)) { typedef MulticutAndresKernighanLin<Objective> DefaultSolver; typedef MulticutFactory<DefaultSolver> DefaultFactory; settings_.mcFactory = std::make_shared<DefaultFactory>(); } mpSolver_ = new SolverType( toOptionsVector() ,NiftyRounder(settings_.mcFactory, settings_.greedyWarmstart) ); this->initializeMp(); } template<class OBJECTIVE> void MulticutMp<OBJECTIVE>:: initializeMp() { if(graph_.numberOfEdges()!= 0 ){ auto & constructor = (*mpSolver_).template GetProblemConstructor<0>(); const auto & weights = objective_.weights(); for(auto e : graph_.edges()){ const auto & uv = graph_.uv(e); constructor.AddUnaryFactor(uv.first, uv.second, weights[e]); } } } // returns options in correct format for the LP_MP solver // TODO would be bettter to have a decent interface for LP_MP and then // get rid of this template<class OBJECTIVE> std::vector<std::string> MulticutMp<OBJECTIVE>:: toOptionsVector() const { std::vector<std::string> options = { "multicut_mp", "-i", " ", // empty input file "--primalComputationInterval", std::to_string(settings_.primalComputationInterval), "--standardReparametrization", settings_.standardReparametrization, "--roundingReparametrization", settings_.roundingReparametrization, "--tightenReparametrization", settings_.tightenReparametrization, "--tightenInterval", std::to_string(settings_.tightenInterval), "--tightenIteration", std::to_string(settings_.tightenIteration), "--tightenSlope", std::to_string(settings_.tightenSlope), "--tightenConstraintsPercentage", std::to_string(settings_.tightenConstraintsPercentage), "--maxIter", std::to_string(settings_.numberOfIterations), #ifdef LP_MP_PARALLEL "--numLpThreads", std::to_string(settings_.numberOfThreads) #endif }; if(settings_.tighten) options.push_back("--tighten"); if(settings_.minDualImprovement > 0) { options.push_back("--minDualImprovement"); options.push_back(std::to_string(settings_.minDualImprovement)); } if(settings_.minDualImprovementInterval > 0) { options.push_back("--minDualImprovementInterval"); options.push_back(std::to_string(settings_.minDualImprovementInterval)); } if(settings_.timeout > 0) { options.push_back("--timeout"); options.push_back(std::to_string(settings_.timeout)); } return options; } // TODO maybe this can be done more efficient // (if we only call it once, this should be fine, but if we need // to call this more often for some reason, this might get expensive) template<class OBJECTIVE> void MulticutMp<OBJECTIVE>:: nodeLabeling() { ufd_.reset(); auto & constructor = (*mpSolver_).template GetProblemConstructor<0>(); for(auto e : graph_.edges()){ const auto & uv = graph_.uv(e); const bool cut = constructor.get_edge_label(uv.first, uv.second); if(!cut){ ufd_.merge(uv.first, uv.second); } } ufd_.elementLabeling(currentBest_->begin()); } template<class OBJECTIVE> void MulticutMp<OBJECTIVE>:: optimize( NodeLabels & nodeLabels, VisitorBase * visitor ){ //VisitorProxy visitorProxy(visitor); currentBest_ = &nodeLabels; // TODO for now the visitor is doing nothing, but we should implement one, that is // compatible with lp_mp visitor //visitorProxy.begin(this); if(graph_.numberOfEdges()>0){ mpSolver_->Solve(); nodeLabeling(); } //visitorProxy.end(this); } } // namespace nifty::graph } // namespace nifty <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 <iostream> #include <sstream> #include <zorba/zorba.h> #include <inmemorystore/inmemorystore.h> using namespace zorba; void* query_thread_1(void *param); void* query_thread_2(void *param); void* query_thread_3(void *param); void* query_thread_4(void *param); #define NR_THREADS 20 struct data { Zorba* lZorba; Item lItem; } dataObj; static XQuery_t lQuery; std::string make_absolute_file_name(const char *target_file_name, const char *this_file_name); #ifdef ZORBA_HAVE_PTHREAD_H /* Simple cloning test */ bool multithread_example_1(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { lQuery = aZorba->compileQuery("1+1"); for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_1, (void*)i); } //wait for threads to finish for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } lQuery = NULL; return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } /* Create multiple threads that compile and execute a query */ bool multithread_example_2(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_2, (void*)aZorba); } //wait for threads to finish for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } /* Create separate queries that are working with the same document loaded in store. */ bool multithread_example_3(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { std::stringstream lInStream("<books><book>Book 1</book><book>Book 2</book><book>Book 3</book></books>"); Item aItem = aZorba->getXmlDataManager()->loadDocument("books.xml", lInStream); dataObj.lZorba = aZorba; dataObj.lItem = aItem; for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_3, (void*)(&dataObj)); } for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } /* Load a big document in store and query it from diffrent threads. */ bool multithread_example_4(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { Item aItem = aZorba->getXmlDataManager()->loadDocument(make_absolute_file_name("XQTSCatalog.xml", __FILE__)); dataObj.lZorba = aZorba; dataObj.lItem = aItem; for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_4, (void*)(&dataObj)); } for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } int multithread(int argc, char* argv[]) { store::SimpleStore* lStore = inmemorystore::InMemoryStore::getInstance(); Zorba* lZorba = Zorba::getInstance(lStore); bool res = false; std::cout << std::endl << "executing multithread test 1 : "; res = multithread_example_1(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; std::cout << std::endl << "executing multithread test 2 : "; res = multithread_example_2(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; std::cout << std::endl << "executing multithread test 3 : "; res = multithread_example_3(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; std::cout << std::endl << "executing multithread test 4 : "; res = multithread_example_4(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 0; } void* query_thread_1(void *param) { XQuery_t xquery_clone; xquery_clone = lQuery->clone(); if(xquery_clone == NULL) { std::cout << "cannot clone xquery object" << std::endl; return (void*)1; } std::ostringstream os; os << xquery_clone << std::endl; xquery_clone->close(); return (void*)0; } void* query_thread_2(void *param) { XQuery_t query; query = ((Zorba*)param)->compileQuery("2+2"); std::ostringstream os; os << query << std::endl; query->close(); return (void*)0; } void* query_thread_3(void *param) { data* var = (data*)param; XQuery_t lQuery = var->lZorba->compileQuery("declare variable $var external; doc('books.xml')//book"); DynamicContext* lCtx = lQuery->getDynamicContext(); lCtx->setVariable("var", var->lItem); std::ostringstream os; os << lQuery << std::endl; return (void*)0; } void* query_thread_4(void *param) { data* var = (data*)param; XQuery_t aQuery = var->lZorba->compileQuery(".//citation-spec"); DynamicContext* lCtx = aQuery->getDynamicContext(); lCtx->setContextItem(var->lItem); std::ostringstream os; os << aQuery << std::endl; aQuery->close(); return (void*)0; } std::string make_absolute_file_name(const char *target_file_name, const char *this_file_name) { std::string str_result; std::string::size_type pos; str_result = this_file_name; pos = str_result.rfind('/'); if(pos == std::string::npos) pos = str_result.rfind('\\'); if(pos == std::string::npos) return target_file_name; str_result.erase(pos+1); str_result += target_file_name; // std::cout << "make_absolute_file_name -> " << str_result << std::endl; return str_result; } #endif <commit_msg>Fixed test no. 4.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 <iostream> #include <sstream> #include <zorba/zorba.h> #include <inmemorystore/inmemorystore.h> using namespace zorba; void* query_thread_1(void *param); void* query_thread_2(void *param); void* query_thread_3(void *param); void* query_thread_4(void *param); #define NR_THREADS 20 struct data { Zorba* lZorba; Item lItem; } dataObj; static XQuery_t lQuery; std::string make_absolute_file_name(const char *target_file_name, const char *this_file_name); #ifdef ZORBA_HAVE_PTHREAD_H /* Simple cloning test */ bool multithread_example_1(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { lQuery = aZorba->compileQuery("1+1"); for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_1, (void*)i); } //wait for threads to finish for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } lQuery = NULL; return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } /* Create multiple threads that compile and execute a query */ bool multithread_example_2(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_2, (void*)aZorba); } //wait for threads to finish for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } /* Create separate queries that are working with the same document loaded in store. */ bool multithread_example_3(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { std::stringstream lInStream("<books><book>Book 1</book><book>Book 2</book><book>Book 3</book></books>"); Item aItem = aZorba->getXmlDataManager()->loadDocument("books.xml", lInStream); dataObj.lZorba = aZorba; dataObj.lItem = aItem; for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_3, (void*)(&dataObj)); } for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } /* Load a big document in store and query it from diffrent threads. */ bool multithread_example_4(Zorba* aZorba) { unsigned int i; pthread_t pt[NR_THREADS]; try { Item aItem = aZorba->getXmlDataManager()->loadDocument(make_absolute_file_name("XQTSCatalog.xml", __FILE__)); dataObj.lZorba = aZorba; dataObj.lItem = aItem; for(i=0; i<NR_THREADS; i++) { pthread_create(&pt[i], NULL, query_thread_4, (void*)(&dataObj)); } for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } dataObj.lItem = NULL; return true; } catch (ZorbaException &e) { std::cerr << "some exception " << e << std::endl; return false; } } int multithread(int argc, char* argv[]) { store::SimpleStore* lStore = inmemorystore::InMemoryStore::getInstance(); Zorba* lZorba = Zorba::getInstance(lStore); bool res = false; std::cout << std::endl << "executing multithread test 1 : "; res = multithread_example_1(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; std::cout << std::endl << "executing multithread test 2 : "; res = multithread_example_2(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; std::cout << std::endl << "executing multithread test 3 : "; res = multithread_example_3(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; std::cout << std::endl << "executing multithread test 4 : "; res = multithread_example_4(lZorba); if (!res) { std::cout << "Failed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 1; } else std::cout << "Passed" << std::endl; lZorba->shutdown(); inmemorystore::InMemoryStore::shutdown(lStore); return 0; } void* query_thread_1(void *param) { XQuery_t xquery_clone; xquery_clone = lQuery->clone(); if(xquery_clone == NULL) { std::cout << "cannot clone xquery object" << std::endl; return (void*)1; } std::ostringstream os; os << xquery_clone << std::endl; xquery_clone->close(); return (void*)0; } void* query_thread_2(void *param) { XQuery_t query; query = ((Zorba*)param)->compileQuery("2+2"); std::ostringstream os; os << query << std::endl; query->close(); return (void*)0; } void* query_thread_3(void *param) { data* var = (data*)param; XQuery_t lQuery = var->lZorba->compileQuery("declare variable $var external; doc('books.xml')//book"); DynamicContext* lCtx = lQuery->getDynamicContext(); lCtx->setVariable("var", var->lItem); std::ostringstream os; os << lQuery << std::endl; return (void*)0; } void* query_thread_4(void *param) { data* var = (data*)param; XQuery_t aQuery = var->lZorba->compileQuery(".//citation-spec"); DynamicContext* lCtx = aQuery->getDynamicContext(); lCtx->setContextItem(var->lItem); std::ostringstream os; os << aQuery << std::endl; aQuery->close(); return (void*)0; } std::string make_absolute_file_name(const char *target_file_name, const char *this_file_name) { std::string str_result; std::string::size_type pos; str_result = this_file_name; pos = str_result.rfind('/'); if(pos == std::string::npos) pos = str_result.rfind('\\'); if(pos == std::string::npos) return target_file_name; str_result.erase(pos+1); str_result += target_file_name; // std::cout << "make_absolute_file_name -> " << str_result << std::endl; return str_result; } #endif <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ClingPragmas.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "cling/Utils/Paths.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TokenKinds.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "clang/Parse/Parser.h" #include "clang/Parse/ParseDiagnostic.h" #include <cstdlib> using namespace cling; using namespace clang; namespace { class ClingPragmaHandler: public PragmaHandler { Interpreter& m_Interp; struct SkipToEOD { Preprocessor& m_PP; Token& m_Tok; SkipToEOD(Preprocessor& PParg, Token& Tok): m_PP(PParg), m_Tok(Tok) { } ~SkipToEOD() { // Can't use Preprocessor::DiscardUntilEndOfDirective, as we may // already be on an eod token while (!m_Tok.isOneOf(tok::eod, tok::eof)) m_PP.LexUnexpandedToken(m_Tok); } }; enum { kLoadFile, kAddLibrary, kAddInclude, // Put all commands that expand environment variables above this kExpandEnvCommands, // Put all commands that only take string literals above this kArgumentsAreLiterals, kOptimize, kInvalidCommand, }; bool GetNextLiteral(Preprocessor& PP, Token& Tok, std::string& Literal, unsigned Cmd, const char* firstTime = nullptr) const { Literal.clear(); PP.Lex(Tok); if (Tok.isLiteral()) { if (clang::tok::isStringLiteral(Tok.getKind())) { SmallVector<Token, 1> StrToks(1, Tok); StringLiteralParser LitParse(StrToks, PP); if (!LitParse.hadError) Literal = LitParse.GetString(); } else { llvm::SmallString<64> Buffer; Literal = PP.getSpelling(Tok, Buffer).str(); } } else if (Tok.is(tok::comma)) return GetNextLiteral(PP, Tok, Literal, Cmd); else if (firstTime) { if (Tok.is(tok::l_paren)) { if (Cmd < kArgumentsAreLiterals) { if (!PP.LexStringLiteral(Tok, Literal, firstTime, false /*allowMacroExpansion*/)) { // already diagnosed. return false; } } else { PP.Lex(Tok); llvm::SmallString<64> Buffer; Literal = PP.getSpelling(Tok, Buffer).str(); } } } if (Literal.empty()) return false; if (Cmd < kExpandEnvCommands) utils::ExpandEnvVars(Literal); return true; } void ReportCommandErr(Preprocessor& PP, const Token& Tok) { PP.Diag(Tok.getLocation(), diag::err_expected) << "load, add_library_path, or add_include_path"; } int GetCommand(const StringRef CommandStr) { if (CommandStr == "load") return kLoadFile; else if (CommandStr == "add_library_path") return kAddLibrary; else if (CommandStr == "add_include_path") return kAddInclude; else if (CommandStr == "optimize") return kOptimize; return kInvalidCommand; } void LoadCommand(Preprocessor& PP, Token& Tok, std::string Literal) { // No need to load libraries when not executing anything. if (m_Interp.isInSyntaxOnlyMode()) return; // Need to parse them all until the end to handle the possible // #include statements that will be generated struct LibraryFileInfo { std::string FileName; SourceLocation StartLoc; }; std::vector<LibraryFileInfo> FileInfos; FileInfos.push_back({std::move(Literal), Tok.getLocation()}); while (GetNextLiteral(PP, Tok, Literal, kLoadFile)) FileInfos.push_back({std::move(Literal), Tok.getLocation()}); clang::Parser& P = m_Interp.getParser(); Parser::ParserCurTokRestoreRAII savedCurToken(P); // After we have saved the token reset the current one to something // which is safe (semi colon usually means empty decl) Token& CurTok = const_cast<Token&>(P.getCurToken()); CurTok.setKind(tok::semi); Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); // We can't PushDeclContext, because we go up and the routine that // pops the DeclContext assumes that we drill down always. // We have to be on the global context. At that point we are in a // wrapper function so the parent context must be the global. TranslationUnitDecl* TU = m_Interp.getCI()->getASTContext().getTranslationUnitDecl(); Sema::ContextAndScopeRAII pushedDCAndS(m_Interp.getSema(), TU, m_Interp.getSema().TUScope); Interpreter::PushTransactionRAII pushedT(&m_Interp); for (const LibraryFileInfo& FI : FileInfos) { // FIXME: Consider the case where the library static init section has // a call to interpreter parsing header file. It will suffer the same // issue as if we included the file within the pragma. if (m_Interp.loadLibrary(FI.FileName, true) != Interpreter::kSuccess) { const clang::DirectoryLookup *CurDir = nullptr; if (PP.getHeaderSearchInfo().LookupFile(FI.FileName, FI.StartLoc, /*isAngled*/ false, /*fromDir*/ nullptr, /*CurDir*/ CurDir, /*Includers*/ {}, /*SearchPath*/ nullptr, /*RelativePath*/ nullptr, /*RequestingModule*/ nullptr, /*suggestedModule*/ nullptr, /*IsMapped*/ nullptr, /*IsFrameworkFound*/ nullptr, /*SkipCache*/ true, /*BuildSystemModule*/ false, /*OpenFile*/ false, /*CacheFailures*/ false)) { PP.Diag(FI.StartLoc, diag::err_expected) << FI.FileName + " to be a library, but it is not. If this is a source file, use `#include \"" + FI.FileName + "\"`"; } else { PP.Diag(FI.StartLoc, diag::err_pp_file_not_found) << FI.FileName; } return; } } } void OptimizeCommand(const char* Str) { char* ConvEnd = nullptr; int OptLevel = std::strtol(Str, &ConvEnd, 10 /*base*/); if (!ConvEnd || ConvEnd == Str) { cling::errs() << "cling::PHOptLevel: " "missing or non-numerical optimization level.\n" ; return; } auto T = const_cast<Transaction*>(m_Interp.getCurrentTransaction()); assert(T && "Parsing code without transaction!"); // The topmost Transaction drives the jitting. T = T->getTopmostParent(); CompilationOptions& CO = T->getCompilationOpts(); if (CO.OptLevel != m_Interp.getDefaultOptLevel()) { // Another #pragma already changed the opt level, a conflict that // cannot be resolve here. Mention and keep the lower one. cling::errs() << "cling::PHOptLevel: " "conflicting `#pragma cling optimize` directives: " "was already set to " << CO.OptLevel << '\n'; if (CO.OptLevel > OptLevel) { CO.OptLevel = OptLevel; cling::errs() << "Setting to lower value of " << OptLevel << '\n'; } else { cling::errs() << "Ignoring higher value of " << OptLevel << '\n'; } } else CO.OptLevel = OptLevel; } public: ClingPragmaHandler(Interpreter& interp): PragmaHandler("cling"), m_Interp(interp) {} void HandlePragma(Preprocessor& PP, PragmaIntroducer /*Introducer*/, Token& /*FirstToken*/) override { Token Tok; PP.Lex(Tok); SkipToEOD OnExit(PP, Tok); // #pragma cling(load, "A") if (Tok.is(tok::l_paren)) PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { ReportCommandErr(PP, Tok); return; } const StringRef CommandStr = Tok.getIdentifierInfo()->getName(); const unsigned Command = GetCommand(CommandStr); assert(Command != kArgumentsAreLiterals && Command != kExpandEnvCommands); if (Command == kInvalidCommand) { ReportCommandErr(PP, Tok); return; } std::string Literal; if (!GetNextLiteral(PP, Tok, Literal, Command, CommandStr.data())) { PP.Diag(Tok.getLocation(), diag::err_expected_after) << CommandStr << "argument"; return; } switch (Command) { case kLoadFile: return LoadCommand(PP, Tok, std::move(Literal)); case kOptimize: return OptimizeCommand(Literal.c_str()); default: do { if (Command == kAddLibrary) m_Interp.getOptions().LibSearchPath.push_back(std::move(Literal)); else if (Command == kAddInclude) m_Interp.AddIncludePath(Literal); } while (GetNextLiteral(PP, Tok, Literal, Command)); break; } } }; } void cling::addClingPragmas(Interpreter& interp) { Preprocessor& PP = interp.getCI()->getPreprocessor(); // PragmaNamespace / PP takes ownership of sub-handlers. PP.AddPragmaHandler(StringRef(), new ClingPragmaHandler(interp)); } <commit_msg>Fix regression in #pragma cling add_library_path().<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ClingPragmas.h" #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "cling/Utils/Paths.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TokenKinds.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "clang/Parse/Parser.h" #include "clang/Parse/ParseDiagnostic.h" #include <cstdlib> using namespace cling; using namespace clang; namespace { class ClingPragmaHandler: public PragmaHandler { Interpreter& m_Interp; struct SkipToEOD { Preprocessor& m_PP; Token& m_Tok; SkipToEOD(Preprocessor& PParg, Token& Tok): m_PP(PParg), m_Tok(Tok) { } ~SkipToEOD() { // Can't use Preprocessor::DiscardUntilEndOfDirective, as we may // already be on an eod token while (!m_Tok.isOneOf(tok::eod, tok::eof)) m_PP.LexUnexpandedToken(m_Tok); } }; enum { kLoadFile, kAddLibrary, kAddInclude, // Put all commands that expand environment variables above this kExpandEnvCommands, // Put all commands that only take string literals above this kArgumentsAreLiterals, kOptimize, kInvalidCommand, }; bool GetNextLiteral(Preprocessor& PP, Token& Tok, std::string& Literal, unsigned Cmd, const char* firstTime = nullptr) const { Literal.clear(); PP.Lex(Tok); if (Tok.isLiteral()) { if (clang::tok::isStringLiteral(Tok.getKind())) { SmallVector<Token, 1> StrToks(1, Tok); StringLiteralParser LitParse(StrToks, PP); if (!LitParse.hadError) Literal = LitParse.GetString(); } else { llvm::SmallString<64> Buffer; Literal = PP.getSpelling(Tok, Buffer).str(); } } else if (Tok.is(tok::comma)) return GetNextLiteral(PP, Tok, Literal, Cmd); else if (firstTime) { if (Tok.is(tok::l_paren)) { if (Cmd < kArgumentsAreLiterals) { if (!PP.LexStringLiteral(Tok, Literal, firstTime, false /*allowMacroExpansion*/)) { // already diagnosed. return false; } } else { PP.Lex(Tok); llvm::SmallString<64> Buffer; Literal = PP.getSpelling(Tok, Buffer).str(); } } } if (Literal.empty()) return false; if (Cmd < kExpandEnvCommands) utils::ExpandEnvVars(Literal); return true; } void ReportCommandErr(Preprocessor& PP, const Token& Tok) { PP.Diag(Tok.getLocation(), diag::err_expected) << "load, add_library_path, or add_include_path"; } int GetCommand(const StringRef CommandStr) { if (CommandStr == "load") return kLoadFile; else if (CommandStr == "add_library_path") return kAddLibrary; else if (CommandStr == "add_include_path") return kAddInclude; else if (CommandStr == "optimize") return kOptimize; return kInvalidCommand; } void LoadCommand(Preprocessor& PP, Token& Tok, std::string Literal) { // No need to load libraries when not executing anything. if (m_Interp.isInSyntaxOnlyMode()) return; // Need to parse them all until the end to handle the possible // #include statements that will be generated struct LibraryFileInfo { std::string FileName; SourceLocation StartLoc; }; std::vector<LibraryFileInfo> FileInfos; FileInfos.push_back({std::move(Literal), Tok.getLocation()}); while (GetNextLiteral(PP, Tok, Literal, kLoadFile)) FileInfos.push_back({std::move(Literal), Tok.getLocation()}); clang::Parser& P = m_Interp.getParser(); Parser::ParserCurTokRestoreRAII savedCurToken(P); // After we have saved the token reset the current one to something // which is safe (semi colon usually means empty decl) Token& CurTok = const_cast<Token&>(P.getCurToken()); CurTok.setKind(tok::semi); Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); // We can't PushDeclContext, because we go up and the routine that // pops the DeclContext assumes that we drill down always. // We have to be on the global context. At that point we are in a // wrapper function so the parent context must be the global. TranslationUnitDecl* TU = m_Interp.getCI()->getASTContext().getTranslationUnitDecl(); Sema::ContextAndScopeRAII pushedDCAndS(m_Interp.getSema(), TU, m_Interp.getSema().TUScope); Interpreter::PushTransactionRAII pushedT(&m_Interp); for (const LibraryFileInfo& FI : FileInfos) { // FIXME: Consider the case where the library static init section has // a call to interpreter parsing header file. It will suffer the same // issue as if we included the file within the pragma. if (m_Interp.loadLibrary(FI.FileName, true) != Interpreter::kSuccess) { const clang::DirectoryLookup *CurDir = nullptr; if (PP.getHeaderSearchInfo().LookupFile(FI.FileName, FI.StartLoc, /*isAngled*/ false, /*fromDir*/ nullptr, /*CurDir*/ CurDir, /*Includers*/ {}, /*SearchPath*/ nullptr, /*RelativePath*/ nullptr, /*RequestingModule*/ nullptr, /*suggestedModule*/ nullptr, /*IsMapped*/ nullptr, /*IsFrameworkFound*/ nullptr, /*SkipCache*/ true, /*BuildSystemModule*/ false, /*OpenFile*/ false, /*CacheFailures*/ false)) { PP.Diag(FI.StartLoc, diag::err_expected) << FI.FileName + " to be a library, but it is not. If this is a source file, use `#include \"" + FI.FileName + "\"`"; } else { PP.Diag(FI.StartLoc, diag::err_pp_file_not_found) << FI.FileName; } return; } } } void OptimizeCommand(const char* Str) { char* ConvEnd = nullptr; int OptLevel = std::strtol(Str, &ConvEnd, 10 /*base*/); if (!ConvEnd || ConvEnd == Str) { cling::errs() << "cling::PHOptLevel: " "missing or non-numerical optimization level.\n" ; return; } auto T = const_cast<Transaction*>(m_Interp.getCurrentTransaction()); assert(T && "Parsing code without transaction!"); // The topmost Transaction drives the jitting. T = T->getTopmostParent(); CompilationOptions& CO = T->getCompilationOpts(); if (CO.OptLevel != m_Interp.getDefaultOptLevel()) { // Another #pragma already changed the opt level, a conflict that // cannot be resolve here. Mention and keep the lower one. cling::errs() << "cling::PHOptLevel: " "conflicting `#pragma cling optimize` directives: " "was already set to " << CO.OptLevel << '\n'; if (CO.OptLevel > OptLevel) { CO.OptLevel = OptLevel; cling::errs() << "Setting to lower value of " << OptLevel << '\n'; } else { cling::errs() << "Ignoring higher value of " << OptLevel << '\n'; } } else CO.OptLevel = OptLevel; } public: ClingPragmaHandler(Interpreter& interp): PragmaHandler("cling"), m_Interp(interp) {} void HandlePragma(Preprocessor& PP, PragmaIntroducer /*Introducer*/, Token& /*FirstToken*/) override { Token Tok; PP.Lex(Tok); SkipToEOD OnExit(PP, Tok); // #pragma cling(load, "A") if (Tok.is(tok::l_paren)) PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { ReportCommandErr(PP, Tok); return; } const StringRef CommandStr = Tok.getIdentifierInfo()->getName(); const unsigned Command = GetCommand(CommandStr); assert(Command != kArgumentsAreLiterals && Command != kExpandEnvCommands); if (Command == kInvalidCommand) { ReportCommandErr(PP, Tok); return; } std::string Literal; if (!GetNextLiteral(PP, Tok, Literal, Command, CommandStr.data())) { PP.Diag(Tok.getLocation(), diag::err_expected_after) << CommandStr << "argument"; return; } switch (Command) { case kLoadFile: return LoadCommand(PP, Tok, std::move(Literal)); case kOptimize: return OptimizeCommand(Literal.c_str()); default: do { if (Command == kAddLibrary) m_Interp.getDynamicLibraryManager()->addSearchPath(std::move(Literal)); else if (Command == kAddInclude) m_Interp.AddIncludePath(Literal); } while (GetNextLiteral(PP, Tok, Literal, Command)); break; } } }; } void cling::addClingPragmas(Interpreter& interp) { Preprocessor& PP = interp.getCI()->getPreprocessor(); // PragmaNamespace / PP takes ownership of sub-handlers. PP.AddPragmaHandler(StringRef(), new ClingPragmaHandler(interp)); } <|endoftext|>
<commit_before>// Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_DATA_HPP #define OPENMVG_SFM_DATA_HPP #include "openMVG/types.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/sfm/sfm_landmark.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/cameras/cameras.hpp" namespace openMVG { namespace sfm { /// Define a collection of View typedef Hash_Map<IndexT, std::shared_ptr<View> > Views; /// Define a collection of Pose (indexed by View::id_pose) typedef Hash_Map<IndexT, geometry::Pose3> Poses; /// Define a collection of IntrinsicParameter (indexed by View::id_intrinsic) typedef Hash_Map<IndexT, std::shared_ptr<cameras::IntrinsicBase> > Intrinsics; /// Define a collection of landmarks are indexed by their TrackId typedef Hash_Map<IndexT, Landmark> Landmarks; /// Generic SfM data container /// Store structure and camera properties: struct SfM_Data { /// Considered views Views views; /// Considered poses (indexed by view.id_pose) Poses poses; /// Considered camera intrinsics (indexed by view.id_cam) Intrinsics intrinsics; /// Structure (3D points with their 2D observations) Landmarks structure; /// Root Views path std::string s_root_path; //-- // Accessors //-- const Views & GetViews() const {return views;} const Poses & GetPoses() const {return poses;} const Intrinsics & GetIntrinsics() const {return intrinsics;} const Landmarks & GetLandmarks() const {return structure;} /// Check if the View have defined intrinsic and pose bool IsPoseAndIntrinsicDefined(const View * view) const { if (view == NULL) return false; return ( view->id_intrinsic != UndefinedIndexT && view->id_pose != UndefinedIndexT && intrinsics.find(view->id_intrinsic) != intrinsics.end() && poses.find(view->id_pose) != poses.end()); } /// Get the pose associated to a view const geometry::Pose3 GetPoseOrDie(const View * view) const { return poses.at(view->id_pose); } }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_DATA_HPP <commit_msg>Fix a typo error in comments.<commit_after>// Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_DATA_HPP #define OPENMVG_SFM_DATA_HPP #include "openMVG/types.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/sfm/sfm_landmark.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/cameras/cameras.hpp" namespace openMVG { namespace sfm { /// Define a collection of View typedef Hash_Map<IndexT, std::shared_ptr<View> > Views; /// Define a collection of Pose (indexed by View::id_pose) typedef Hash_Map<IndexT, geometry::Pose3> Poses; /// Define a collection of IntrinsicParameter (indexed by View::id_intrinsic) typedef Hash_Map<IndexT, std::shared_ptr<cameras::IntrinsicBase> > Intrinsics; /// Define a collection of landmarks are indexed by their TrackId typedef Hash_Map<IndexT, Landmark> Landmarks; /// Generic SfM data container /// Store structure and camera properties: struct SfM_Data { /// Considered views Views views; /// Considered poses (indexed by view.id_pose) Poses poses; /// Considered camera intrinsics (indexed by view.id_intrinsic) Intrinsics intrinsics; /// Structure (3D points with their 2D observations) Landmarks structure; /// Root Views path std::string s_root_path; //-- // Accessors //-- const Views & GetViews() const {return views;} const Poses & GetPoses() const {return poses;} const Intrinsics & GetIntrinsics() const {return intrinsics;} const Landmarks & GetLandmarks() const {return structure;} /// Check if the View have defined intrinsic and pose bool IsPoseAndIntrinsicDefined(const View * view) const { if (view == NULL) return false; return ( view->id_intrinsic != UndefinedIndexT && view->id_pose != UndefinedIndexT && intrinsics.find(view->id_intrinsic) != intrinsics.end() && poses.find(view->id_pose) != poses.end()); } /// Get the pose associated to a view const geometry::Pose3 GetPoseOrDie(const View * view) const { return poses.at(view->id_pose); } }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_DATA_HPP <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/Interpreter/StoredValueRef.h" #include "cling/Interpreter/Value.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ExecutionEngine/GenericValue.h" #include <string> #include <sstream> #include <cstdio> // Fragment copied from LLVM's raw_ostream.cpp #if defined(_MSC_VER) #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #else //#if defined(HAVE_UNISTD_H) # include <unistd.h> //#endif #endif using namespace cling; // Implements the CValuePrinter interface. extern "C" void cling_PrintValue(void* /*clang::Expr**/ E, void* /*clang::ASTContext**/ C, const void* value) { clang::Expr* Exp = (clang::Expr*)E; clang::ASTContext* Context = (clang::ASTContext*)C; ValuePrinterInfo VPI(Exp->getType(), Context); // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). llvm::raw_fd_ostream outs (STDOUT_FILENO, /*ShouldClose*/false); valuePrinterInternal::flushToStream(outs, printType(value, value, VPI) + printValue(value, value, VPI)); } static void StreamValue(llvm::raw_ostream& o, const void* const p, const ValuePrinterInfo& VPI); static void StreamChar(llvm::raw_ostream& o, const char v) { if (isprint(v)) o << '"' << v << "\""; else { o << "\\0x"; o.write_hex(v); } } static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) { if (!v) { o << "<<<NULL>>>"; return; } o << '"'; const char* p = v; for (;*p && p - v < 128; ++p) { o << *p; } if (*p) o << "\"..."; else o << "\""; } static void StreamRef(llvm::raw_ostream& o, const void* v, const ValuePrinterInfo& VPI) { const clang::ReferenceType* RTy = llvm::dyn_cast<clang::ReferenceType>(VPI.getType().getTypePtr()); ValuePrinterInfo VPIRefed(RTy->getPointeeType(), VPI.getASTContext()); StreamValue(o, v, VPIRefed); } static void StreamPtr(llvm::raw_ostream& o, const void* v) { o << v; } static void StreamArr(llvm::raw_ostream& o, const void* p, const ValuePrinterInfo& VPI) { const clang::QualType& Ty = VPI.getType(); clang::ASTContext& C = *VPI.getASTContext(); const clang::ArrayType* ArrTy = Ty->getAsArrayTypeUnsafe(); clang::QualType ElementTy = ArrTy->getElementType(); if (ElementTy->isCharType()) StreamCharPtr(o, (const char*)p); else if (Ty->isConstantArrayType()) { // Stream a constant array by streaming up to 5 elements. const clang::ConstantArrayType* CArrTy = C.getAsConstantArrayType(Ty); const llvm::APInt& APSize = CArrTy->getSize(); size_t ElBytes = C.getTypeSize(ElementTy) / C.getCharWidth(); size_t Size = (size_t)APSize.getZExtValue(); o << "{ "; ValuePrinterInfo ElVPI(ElementTy, &C); for (size_t i = 0; i < Size; ++i) { StreamValue(o, ((const char*)p) + i * ElBytes, ElVPI); if (i + 1 < Size) { if (i == 4) { o << "..."; break; } else o << ", "; } } o << " }"; } else StreamPtr(o, p); } static void StreamFunction(llvm::raw_ostream& o, const void* addr, ValuePrinterInfo VPI) { o << "Function @" << addr << '\n'; const clang::DeclRefExpr* DeclRefExp = llvm::dyn_cast_or_null<clang::DeclRefExpr>(VPI.getExpr()); const clang::FunctionDecl* FD = 0; if (DeclRefExp) FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(DeclRefExp->getDecl()); if (FD) { clang::SourceRange SRange = FD->getSourceRange(); const char* cBegin = 0; const char* cEnd = 0; bool Invalid; if (SRange.isValid()) { clang::SourceManager& SM = VPI.getASTContext()->getSourceManager(); clang::SourceLocation LocBegin = SRange.getBegin(); LocBegin = SM.getExpansionRange(LocBegin).first; o << " at " << SM.getFilename(LocBegin); unsigned LineNo = SM.getSpellingLineNumber(LocBegin, &Invalid); if (!Invalid) o << ':' << LineNo; o << ":\n"; bool Invalid = false; cBegin = SM.getCharacterData(LocBegin, &Invalid); if (!Invalid) { clang::SourceLocation LocEnd = SRange.getEnd(); LocEnd = SM.getExpansionRange(LocEnd).second; cEnd = SM.getCharacterData(LocEnd, &Invalid); if (Invalid) cBegin = 0; } else { cBegin = 0; } } if (cBegin && cEnd && cEnd > cBegin && cEnd - cBegin < 16 * 1024) { o << llvm::StringRef(cBegin, cEnd - cBegin + 1); } else { const clang::FunctionDecl* FDef; if (FD->hasBody(FDef)) FD = FDef; FD->print(o); //const clang::FunctionDecl* FD // = llvm::cast<const clang::FunctionType>(Ty)->getDecl(); } } else { o << ":\n"; // type-based printing: VPI.getType().print(o, VPI.getASTContext()->getPrintingPolicy()); } // type-based print() never and decl-based print() sometimes does not include // a final newline: o << '\n'; } static void StreamLongDouble(llvm::raw_ostream& o, const Value* value, clang::ASTContext& C) { llvm::APFloat LDbl(C.getFloatTypeSemantics(value->getClangType()), value->getGV().IntVal); llvm::SmallString<24> Buf; LDbl.toString(Buf); o << Buf << 'L'; } static void StreamClingValue(llvm::raw_ostream& o, const Value* value, clang::ASTContext& C) { if (!value || !value->isValid()) { o << "<<<invalid>>> @" << value; } else { o << "boxes ["; o << "(" << value->getClangType().getAsString(C.getPrintingPolicy()) << ") "; clang::QualType valType = value->getClangType().getDesugaredType(C); if (C.hasSameType(valType, C.LongDoubleTy)) StreamLongDouble(o, value, C); else if (valType->isFloatingType()) o << value->getGV().DoubleVal; else if (valType->isIntegerType()) o << value->getGV().IntVal.getSExtValue(); else if (valType->isBooleanType()) o << value->getGV().IntVal.getBoolValue(); else StreamValue(o, value->getGV().PointerVal, ValuePrinterInfo(valType, &C)); o << "]"; } } static void StreamObj(llvm::raw_ostream& o, const void* v, const ValuePrinterInfo& VPI) { const clang::Type* Ty = VPI.getType().getTypePtr(); if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) { std::string QualName = CXXRD->getQualifiedNameAsString(); if (QualName == "cling::StoredValueRef"){ valuePrinterInternal::StreamStoredValueRef(o, (const StoredValueRef*)v, *VPI.getASTContext()); return; } else if (QualName == "cling::Value") { StreamClingValue(o, (const Value*)v, *VPI.getASTContext()); return; } } // if CXXRecordDecl // TODO: Print the object members. o << "@" << v; } static void StreamValue(llvm::raw_ostream& o, const void* const p, const ValuePrinterInfo& VPI) { clang::ASTContext& C = *VPI.getASTContext(); clang::QualType Ty = VPI.getType().getDesugaredType(C); if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) { switch (BT->getKind()) { case clang::BuiltinType::Bool: if (*(const bool*)p) o << "true"; else o << "false"; break; case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: StreamChar(o, *(const char*)p); break; case clang::BuiltinType::Short: o << *(const short*)p; break; case clang::BuiltinType::UShort: o << *(const unsigned short*)p; break; case clang::BuiltinType::Int: o << *(const int*)p; break; case clang::BuiltinType::UInt: o << *(const unsigned int*)p; break; case clang::BuiltinType::Long: o << *(const long*)p; break; case clang::BuiltinType::ULong: o << *(const unsigned long*)p; break; case clang::BuiltinType::LongLong: o << *(const long long*)p; break; case clang::BuiltinType::ULongLong: o << *(const unsigned long long*)p; break; case clang::BuiltinType::Float: o << *(const float*)p; break; case clang::BuiltinType::Double: o << *(const double*)p; break; case clang::BuiltinType::LongDouble: { std::stringstream ssLD; ssLD << *(const long double*)p; o << ssLD.str() << 'L'; break; } default: StreamObj(o, p, ValuePrinterInfo(Ty, &C)); } } else if (Ty.getAsString().compare("class std::basic_string<char>") == 0 || Ty.getAsString().compare("class std::__1::basic_string<char, " "struct std::__1::char_traits<char>, " "class std::__1::allocator<char> >") == 0) { StreamObj(o, p, ValuePrinterInfo(Ty, &C)); o << " "; // force a space o <<"c_str: "; StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str())); } else if (Ty->isEnumeralType()) { clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl(); uint64_t value = *(const uint64_t*)p; bool IsFirst = true; llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty); for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; ++I) { if (I->getInitVal() == ValAsAPSInt) { if (!IsFirst) { o << " ? "; } o << "(" << I->getQualifiedNameAsString() << ")"; IsFirst = false; } } o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10); } else if (Ty->isReferenceType()) StreamRef(o, p, VPI); else if (Ty->isPointerType()) { clang::QualType PointeeTy = Ty->getPointeeType(); if (PointeeTy->isCharType()) StreamCharPtr(o, (const char*)p); else StreamPtr(o, p); } else if (Ty->isArrayType()) StreamArr(o, p, ValuePrinterInfo(Ty, &C)); else if (Ty->isFunctionType()) StreamFunction(o, p, VPI); else StreamObj(o, p, ValuePrinterInfo(Ty, &C)); } namespace cling { namespace valuePrinterInternal { std::string printValue_Default(const void* const p, const ValuePrinterInfo& VPI) { std::string buf; { llvm::raw_string_ostream o(buf); StreamValue(o, p, VPI); } return buf; } std::string printType_Default(const ValuePrinterInfo& VPI) { std::string buf; { llvm::raw_string_ostream o(buf); o << "("; o << VPI.getType().getAsString(); o << ") "; } return buf; } void StreamStoredValueRef(llvm::raw_ostream& o, const StoredValueRef* VR, clang::ASTContext& C) { if (VR->isValid()) { StreamClingValue(o, &VR->get(), C); } else { o << "<<<invalid>>> @" << VR; } } void flushToStream(llvm::raw_ostream& o, const std::string& s) { // We want to keep stdout and o in sync if o is different from stdout. fflush(stdout); o << s; o.flush(); } } // end namespace valuePrinterInternal } // end namespace cling <commit_msg>Support new name of std::string in libc++.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/Interpreter/StoredValueRef.h" #include "cling/Interpreter/Value.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ExecutionEngine/GenericValue.h" #include <string> #include <sstream> #include <cstdio> // Fragment copied from LLVM's raw_ostream.cpp #if defined(_MSC_VER) #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #else //#if defined(HAVE_UNISTD_H) # include <unistd.h> //#endif #endif using namespace cling; // Implements the CValuePrinter interface. extern "C" void cling_PrintValue(void* /*clang::Expr**/ E, void* /*clang::ASTContext**/ C, const void* value) { clang::Expr* Exp = (clang::Expr*)E; clang::ASTContext* Context = (clang::ASTContext*)C; ValuePrinterInfo VPI(Exp->getType(), Context); // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). llvm::raw_fd_ostream outs (STDOUT_FILENO, /*ShouldClose*/false); valuePrinterInternal::flushToStream(outs, printType(value, value, VPI) + printValue(value, value, VPI)); } static void StreamValue(llvm::raw_ostream& o, const void* const p, const ValuePrinterInfo& VPI); static void StreamChar(llvm::raw_ostream& o, const char v) { if (isprint(v)) o << '"' << v << "\""; else { o << "\\0x"; o.write_hex(v); } } static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) { if (!v) { o << "<<<NULL>>>"; return; } o << '"'; const char* p = v; for (;*p && p - v < 128; ++p) { o << *p; } if (*p) o << "\"..."; else o << "\""; } static void StreamRef(llvm::raw_ostream& o, const void* v, const ValuePrinterInfo& VPI) { const clang::ReferenceType* RTy = llvm::dyn_cast<clang::ReferenceType>(VPI.getType().getTypePtr()); ValuePrinterInfo VPIRefed(RTy->getPointeeType(), VPI.getASTContext()); StreamValue(o, v, VPIRefed); } static void StreamPtr(llvm::raw_ostream& o, const void* v) { o << v; } static void StreamArr(llvm::raw_ostream& o, const void* p, const ValuePrinterInfo& VPI) { const clang::QualType& Ty = VPI.getType(); clang::ASTContext& C = *VPI.getASTContext(); const clang::ArrayType* ArrTy = Ty->getAsArrayTypeUnsafe(); clang::QualType ElementTy = ArrTy->getElementType(); if (ElementTy->isCharType()) StreamCharPtr(o, (const char*)p); else if (Ty->isConstantArrayType()) { // Stream a constant array by streaming up to 5 elements. const clang::ConstantArrayType* CArrTy = C.getAsConstantArrayType(Ty); const llvm::APInt& APSize = CArrTy->getSize(); size_t ElBytes = C.getTypeSize(ElementTy) / C.getCharWidth(); size_t Size = (size_t)APSize.getZExtValue(); o << "{ "; ValuePrinterInfo ElVPI(ElementTy, &C); for (size_t i = 0; i < Size; ++i) { StreamValue(o, ((const char*)p) + i * ElBytes, ElVPI); if (i + 1 < Size) { if (i == 4) { o << "..."; break; } else o << ", "; } } o << " }"; } else StreamPtr(o, p); } static void StreamFunction(llvm::raw_ostream& o, const void* addr, ValuePrinterInfo VPI) { o << "Function @" << addr << '\n'; const clang::DeclRefExpr* DeclRefExp = llvm::dyn_cast_or_null<clang::DeclRefExpr>(VPI.getExpr()); const clang::FunctionDecl* FD = 0; if (DeclRefExp) FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(DeclRefExp->getDecl()); if (FD) { clang::SourceRange SRange = FD->getSourceRange(); const char* cBegin = 0; const char* cEnd = 0; bool Invalid; if (SRange.isValid()) { clang::SourceManager& SM = VPI.getASTContext()->getSourceManager(); clang::SourceLocation LocBegin = SRange.getBegin(); LocBegin = SM.getExpansionRange(LocBegin).first; o << " at " << SM.getFilename(LocBegin); unsigned LineNo = SM.getSpellingLineNumber(LocBegin, &Invalid); if (!Invalid) o << ':' << LineNo; o << ":\n"; bool Invalid = false; cBegin = SM.getCharacterData(LocBegin, &Invalid); if (!Invalid) { clang::SourceLocation LocEnd = SRange.getEnd(); LocEnd = SM.getExpansionRange(LocEnd).second; cEnd = SM.getCharacterData(LocEnd, &Invalid); if (Invalid) cBegin = 0; } else { cBegin = 0; } } if (cBegin && cEnd && cEnd > cBegin && cEnd - cBegin < 16 * 1024) { o << llvm::StringRef(cBegin, cEnd - cBegin + 1); } else { const clang::FunctionDecl* FDef; if (FD->hasBody(FDef)) FD = FDef; FD->print(o); //const clang::FunctionDecl* FD // = llvm::cast<const clang::FunctionType>(Ty)->getDecl(); } } else { o << ":\n"; // type-based printing: VPI.getType().print(o, VPI.getASTContext()->getPrintingPolicy()); } // type-based print() never and decl-based print() sometimes does not include // a final newline: o << '\n'; } static void StreamLongDouble(llvm::raw_ostream& o, const Value* value, clang::ASTContext& C) { llvm::APFloat LDbl(C.getFloatTypeSemantics(value->getClangType()), value->getGV().IntVal); llvm::SmallString<24> Buf; LDbl.toString(Buf); o << Buf << 'L'; } static void StreamClingValue(llvm::raw_ostream& o, const Value* value, clang::ASTContext& C) { if (!value || !value->isValid()) { o << "<<<invalid>>> @" << value; } else { o << "boxes ["; o << "(" << value->getClangType().getAsString(C.getPrintingPolicy()) << ") "; clang::QualType valType = value->getClangType().getDesugaredType(C); if (C.hasSameType(valType, C.LongDoubleTy)) StreamLongDouble(o, value, C); else if (valType->isFloatingType()) o << value->getGV().DoubleVal; else if (valType->isIntegerType()) o << value->getGV().IntVal.getSExtValue(); else if (valType->isBooleanType()) o << value->getGV().IntVal.getBoolValue(); else StreamValue(o, value->getGV().PointerVal, ValuePrinterInfo(valType, &C)); o << "]"; } } static void StreamObj(llvm::raw_ostream& o, const void* v, const ValuePrinterInfo& VPI) { const clang::Type* Ty = VPI.getType().getTypePtr(); if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) { std::string QualName = CXXRD->getQualifiedNameAsString(); if (QualName == "cling::StoredValueRef"){ valuePrinterInternal::StreamStoredValueRef(o, (const StoredValueRef*)v, *VPI.getASTContext()); return; } else if (QualName == "cling::Value") { StreamClingValue(o, (const Value*)v, *VPI.getASTContext()); return; } } // if CXXRecordDecl // TODO: Print the object members. o << "@" << v; } static void StreamValue(llvm::raw_ostream& o, const void* const p, const ValuePrinterInfo& VPI) { clang::ASTContext& C = *VPI.getASTContext(); clang::QualType Ty = VPI.getType().getDesugaredType(C); if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) { switch (BT->getKind()) { case clang::BuiltinType::Bool: if (*(const bool*)p) o << "true"; else o << "false"; break; case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: StreamChar(o, *(const char*)p); break; case clang::BuiltinType::Short: o << *(const short*)p; break; case clang::BuiltinType::UShort: o << *(const unsigned short*)p; break; case clang::BuiltinType::Int: o << *(const int*)p; break; case clang::BuiltinType::UInt: o << *(const unsigned int*)p; break; case clang::BuiltinType::Long: o << *(const long*)p; break; case clang::BuiltinType::ULong: o << *(const unsigned long*)p; break; case clang::BuiltinType::LongLong: o << *(const long long*)p; break; case clang::BuiltinType::ULongLong: o << *(const unsigned long long*)p; break; case clang::BuiltinType::Float: o << *(const float*)p; break; case clang::BuiltinType::Double: o << *(const double*)p; break; case clang::BuiltinType::LongDouble: { std::stringstream ssLD; ssLD << *(const long double*)p; o << ssLD.str() << 'L'; break; } default: StreamObj(o, p, ValuePrinterInfo(Ty, &C)); } } else if (Ty.getAsString().compare("class std::basic_string<char>") == 0 || Ty.getAsString().compare("class std::__1::basic_string<char, " "struct std::__1::char_traits<char>, " "class std::__1::allocator<char> >") == 0 || Ty.getAsString().compare("class std::__1::basic_string<char>") == 0) { StreamObj(o, p, ValuePrinterInfo(Ty, &C)); o << " "; // force a space o <<"c_str: "; StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str())); } else if (Ty->isEnumeralType()) { clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl(); uint64_t value = *(const uint64_t*)p; bool IsFirst = true; llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty); for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; ++I) { if (I->getInitVal() == ValAsAPSInt) { if (!IsFirst) { o << " ? "; } o << "(" << I->getQualifiedNameAsString() << ")"; IsFirst = false; } } o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10); } else if (Ty->isReferenceType()) StreamRef(o, p, VPI); else if (Ty->isPointerType()) { clang::QualType PointeeTy = Ty->getPointeeType(); if (PointeeTy->isCharType()) StreamCharPtr(o, (const char*)p); else StreamPtr(o, p); } else if (Ty->isArrayType()) StreamArr(o, p, ValuePrinterInfo(Ty, &C)); else if (Ty->isFunctionType()) StreamFunction(o, p, VPI); else StreamObj(o, p, ValuePrinterInfo(Ty, &C)); } namespace cling { namespace valuePrinterInternal { std::string printValue_Default(const void* const p, const ValuePrinterInfo& VPI) { std::string buf; { llvm::raw_string_ostream o(buf); StreamValue(o, p, VPI); } return buf; } std::string printType_Default(const ValuePrinterInfo& VPI) { std::string buf; { llvm::raw_string_ostream o(buf); o << "("; o << VPI.getType().getAsString(); o << ") "; } return buf; } void StreamStoredValueRef(llvm::raw_ostream& o, const StoredValueRef* VR, clang::ASTContext& C) { if (VR->isValid()) { StreamClingValue(o, &VR->get(), C); } else { o << "<<<invalid>>> @" << VR; } } void flushToStream(llvm::raw_ostream& o, const std::string& s) { // We want to keep stdout and o in sync if o is different from stdout. fflush(stdout); o << s; o.flush(); } } // end namespace valuePrinterInternal } // end namespace cling <|endoftext|>
<commit_before>#include "thrusttest/testframework.h" #include "thrusttest/exceptions.h" #include <cuda_runtime.h> #include <iostream> #include <cstdlib> void UnitTestDriver::register_test(UnitTest *test) { UnitTestDriver::s_driver()._test_list.push_back(test); } UnitTest::UnitTest(const char * _name) : name(_name) { UnitTestDriver::s_driver().register_test(this); } bool UnitTestDriver::run_tests(const std::vector<UnitTest *> &tests_to_run, const bool verbose) { bool any_failed = false; std::cout << "Running " << tests_to_run.size() << " unit tests." << std::endl; std::vector< std::pair<UnitTest *,thrusttest::UnitTestFailure> > test_failures; std::vector< std::pair<UnitTest *,thrusttest::UnitTestKnownFailure> > test_known_failures; std::vector< std::pair<UnitTest *,thrusttest::UnitTestError> > test_errors; std::vector< UnitTest * > test_exceptions; cudaError_t error = cudaGetLastError(); if(error){ std::cerr << "[ERROR] CUDA Error detected before running tests: ["; std::cerr << std::string(cudaGetErrorString(error)); std::cerr << "]" << std::endl; exit(EXIT_FAILURE); } for(size_t i = 0; i < tests_to_run.size(); i++){ UnitTest * test = tests_to_run[i]; if (verbose) std::cout << test->name << " : " << std::flush; try { test->run(); if (verbose) std::cout << "[PASS] " << std::endl; else std::cout << "."; } catch (thrusttest::UnitTestFailure& f){ any_failed = true; if (verbose) std::cout << "[FAILURE] " << std::endl; else std::cout << "F"; test_failures.push_back(std::make_pair(test,f)); } catch (thrusttest::UnitTestKnownFailure& f){ if (verbose) std::cout << "[KNOWN FAILURE] " << std::endl; else std::cout << "K"; test_known_failures.push_back(std::make_pair(test,f)); } catch (thrusttest::UnitTestError& e){ any_failed = true; if (verbose) std::cout << "[ERROR] " << std::endl; else std::cout << "E"; test_errors.push_back(std::make_pair(test,e)); } catch (...){ any_failed = true; if (verbose) std::cout << "[UNKNOWN EXCEPTION] " << std::endl; else std::cout << "U"; test_exceptions.push_back(test); } error = cudaGetLastError(); if(error){ std::cerr << "\t[ERROR] CUDA Error detected after running " << test->name << ": ["; std::cerr << std::string(cudaGetErrorString(error)); std::cerr << "]" << std::endl; exit(EXIT_FAILURE); } std::cout.flush(); } std::cout << std::endl; std::string hline = "================================================================"; for(size_t i = 0; i < test_failures.size(); i++){ std::cout << hline << std::endl; std::cout << "FAILURE: " << test_failures[i].first->name << std::endl; std::cout << test_failures[i].second << std::endl; } for(size_t i = 0; i < test_known_failures.size(); i++){ std::cout << hline << std::endl; std::cout << "KNOWN FAILURE: " << test_known_failures[i].first->name << std::endl; std::cout << test_known_failures[i].second << std::endl; } for(size_t i = 0; i < test_errors.size(); i++){ std::cout << hline << std::endl; std::cout << "ERROR: " << test_errors[i].first->name << std::endl; std::cout << test_errors[i].second << std::endl; } for(size_t i = 0; i < test_exceptions.size(); i++){ std::cout << hline << std::endl; std::cout << "UNKNOWN EXCEPTION: " << test_exceptions[i]->name << std::endl; } std::cout << hline << std::endl; std::cout << "Totals: "; std::cout << test_failures.size() << " failures, "; std::cout << test_known_failures.size() << " known failures, "; std::cout << test_errors.size() << " errors and "; std::cout << test_exceptions.size() << " unknown exceptions." << std::endl; return any_failed; } bool UnitTestDriver::run_all_tests(const bool verbose) { return run_tests(_test_list, verbose); } bool UnitTestDriver::run_tests(const std::vector<std::string> &tests, const bool verbose) { int i, j; std::vector<UnitTest *> tests_to_run; for (j=0; j < tests.size(); j++) { bool found = false; for (i = 0; !found && i < _test_list.size(); i++) if (tests[j] == _test_list[i]->name) { tests_to_run.push_back(_test_list[i]); found = true; } if (!found) { printf("[WARNING] UnitTestDriver::run_tests - test %s not found\n", tests[j].c_str()); } } return run_tests(tests_to_run, verbose); } UnitTestDriver & UnitTestDriver::s_driver() { static UnitTestDriver s_instance; return s_instance; } <commit_msg>unit test driver now sorts tests by name for deterministic ordering<commit_after>#include "thrusttest/testframework.h" #include "thrusttest/exceptions.h" #include <cuda_runtime.h> #include <iostream> #include <cstdlib> #include <algorithm> void UnitTestDriver::register_test(UnitTest *test) { UnitTestDriver::s_driver()._test_list.push_back(test); } UnitTest::UnitTest(const char * _name) : name(_name) { UnitTestDriver::s_driver().register_test(this); } bool UnitTestDriver::run_tests(const std::vector<UnitTest *> &tests_to_run, const bool verbose) { bool any_failed = false; std::cout << "Running " << tests_to_run.size() << " unit tests." << std::endl; std::vector< std::pair<UnitTest *,thrusttest::UnitTestFailure> > test_failures; std::vector< std::pair<UnitTest *,thrusttest::UnitTestKnownFailure> > test_known_failures; std::vector< std::pair<UnitTest *,thrusttest::UnitTestError> > test_errors; std::vector< UnitTest * > test_exceptions; cudaError_t error = cudaGetLastError(); if(error){ std::cerr << "[ERROR] CUDA Error detected before running tests: ["; std::cerr << std::string(cudaGetErrorString(error)); std::cerr << "]" << std::endl; exit(EXIT_FAILURE); } for(size_t i = 0; i < tests_to_run.size(); i++){ UnitTest * test = tests_to_run[i]; if (verbose) std::cout << test->name << " : " << std::flush; try { test->run(); if (verbose) std::cout << "[PASS] " << std::endl; else std::cout << "."; } catch (thrusttest::UnitTestFailure& f){ any_failed = true; if (verbose) std::cout << "[FAILURE] " << std::endl; else std::cout << "F"; test_failures.push_back(std::make_pair(test,f)); } catch (thrusttest::UnitTestKnownFailure& f){ if (verbose) std::cout << "[KNOWN FAILURE] " << std::endl; else std::cout << "K"; test_known_failures.push_back(std::make_pair(test,f)); } catch (thrusttest::UnitTestError& e){ any_failed = true; if (verbose) std::cout << "[ERROR] " << std::endl; else std::cout << "E"; test_errors.push_back(std::make_pair(test,e)); } catch (...){ any_failed = true; if (verbose) std::cout << "[UNKNOWN EXCEPTION] " << std::endl; else std::cout << "U"; test_exceptions.push_back(test); } error = cudaGetLastError(); if(error){ std::cerr << "\t[ERROR] CUDA Error detected after running " << test->name << ": ["; std::cerr << std::string(cudaGetErrorString(error)); std::cerr << "]" << std::endl; exit(EXIT_FAILURE); } std::cout.flush(); } std::cout << std::endl; std::string hline = "================================================================"; for(size_t i = 0; i < test_failures.size(); i++){ std::cout << hline << std::endl; std::cout << "FAILURE: " << test_failures[i].first->name << std::endl; std::cout << test_failures[i].second << std::endl; } for(size_t i = 0; i < test_known_failures.size(); i++){ std::cout << hline << std::endl; std::cout << "KNOWN FAILURE: " << test_known_failures[i].first->name << std::endl; std::cout << test_known_failures[i].second << std::endl; } for(size_t i = 0; i < test_errors.size(); i++){ std::cout << hline << std::endl; std::cout << "ERROR: " << test_errors[i].first->name << std::endl; std::cout << test_errors[i].second << std::endl; } for(size_t i = 0; i < test_exceptions.size(); i++){ std::cout << hline << std::endl; std::cout << "UNKNOWN EXCEPTION: " << test_exceptions[i]->name << std::endl; } std::cout << hline << std::endl; std::cout << "Totals: "; std::cout << test_failures.size() << " failures, "; std::cout << test_known_failures.size() << " known failures, "; std::cout << test_errors.size() << " errors and "; std::cout << test_exceptions.size() << " unknown exceptions." << std::endl; return any_failed; } // for sorting UnitTests by name struct UnitTest_name_cmp { bool operator()(const UnitTest * a, const UnitTest * b) const { return a->name < b->name; } }; bool UnitTestDriver::run_all_tests(const bool verbose) { std::vector<UnitTest *> tests_to_run(_test_list); // sort tests by name for deterministic results std::sort(tests_to_run.begin(), tests_to_run.end(), UnitTest_name_cmp()); return run_tests(tests_to_run, verbose); } bool UnitTestDriver::run_tests(const std::vector<std::string> &tests, const bool verbose) { int i, j; std::vector<UnitTest *> tests_to_run; for (j=0; j < tests.size(); j++) { bool found = false; for (i = 0; !found && i < _test_list.size(); i++) if (tests[j] == _test_list[i]->name) { tests_to_run.push_back(_test_list[i]); found = true; } if (!found) { printf("[WARNING] UnitTestDriver::run_tests - test %s not found\n", tests[j].c_str()); } } return run_tests(tests_to_run, verbose); } UnitTestDriver & UnitTestDriver::s_driver() { static UnitTestDriver s_instance; return s_instance; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static int classifyWordVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.') || (styler[start] == '&' && tolower(styler[start+1]) == 'h'); unsigned int i; for (i = 0; i < end - start + 1 && i < 30; i++) { s[i] = static_cast<char>(tolower(styler[start + i])); } s[i] = '\0'; char chAttr = SCE_C_DEFAULT; if (wordIsNumber) chAttr = SCE_C_NUMBER; else { if (strcmp(s, "rem") == 0) chAttr = SCE_C_COMMENTLINE; else if (keywords.InList(s)) chAttr = SCE_C_WORD; } styler.ColourTo(end, chAttr); if (chAttr == SCE_C_COMMENTLINE) return SCE_C_COMMENTLINE; else return SCE_C_DEFAULT; } static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); int visibleChars = 0; int state = initStyle; char chNext = styler[startPos]; styler.StartSegment(startPos); int lengthDoc = startPos + length; for (int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); i += 1; continue; } if (ch == '\r' || ch == '\n') { // End of line if (state == SCE_C_COMMENTLINE || state == SCE_C_PREPROCESSOR) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; if (state == SCE_C_DEFAULT) { if (iswordstart(ch)) { styler.ColourTo(i - 1, state); state = SCE_C_WORD; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_C_COMMENTLINE; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_STRING; } else if (ch == '#' && visibleChars == 1) { // Preprocessor commands are alone on their line styler.ColourTo(i - 1, state); state = SCE_C_PREPROCESSOR; } else if (ch == '&' && tolower(chNext) == 'h') { styler.ColourTo(i - 1, state); state = SCE_C_WORD; } else if (isoperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } else if (state == SCE_C_WORD) { if (!iswordchar(ch)) { state = classifyWordVB(styler.GetStartSegment(), i - 1, keywords, styler); if (state == SCE_C_DEFAULT) { if (ch == '\'') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (isoperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } } } else { if (state == SCE_C_STRING) { // VB doubles quotes to preserve them if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } if (state == SCE_C_DEFAULT) { // One of the above succeeded if (ch == '\'') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (iswordstart(ch)) { state = SCE_C_WORD; } } } } styler.ColourTo(lengthDoc, state); } LexerModule lmVB(SCLEX_VB, ColouriseVBDoc, "vb"); <commit_msg>Folding added by Willy Devaux.<commit_after>// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static int classifyWordVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.') || (styler[start] == '&' && tolower(styler[start+1]) == 'h'); unsigned int i; for (i = 0; i < end - start + 1 && i < 30; i++) { s[i] = static_cast<char>(tolower(styler[start + i])); } s[i] = '\0'; char chAttr = SCE_C_DEFAULT; if (wordIsNumber) chAttr = SCE_C_NUMBER; else { if (strcmp(s, "rem") == 0) chAttr = SCE_C_COMMENTLINE; else if (keywords.InList(s)) chAttr = SCE_C_WORD; } styler.ColourTo(end, chAttr); if (chAttr == SCE_C_COMMENTLINE) return SCE_C_COMMENTLINE; else return SCE_C_DEFAULT; } static bool IsVBComment(Accessor &styler, int pos, int len) { return len>0 && styler[pos]=='\''; } static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); int visibleChars = 0; int state = initStyle; char chNext = styler[startPos]; styler.StartSegment(startPos); int lengthDoc = startPos + length; for (int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); i += 1; continue; } if (ch == '\r' || ch == '\n') { // End of line if (state == SCE_C_COMMENTLINE || state == SCE_C_PREPROCESSOR) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; if (state == SCE_C_DEFAULT) { if (iswordstart(ch)) { styler.ColourTo(i - 1, state); state = SCE_C_WORD; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_C_COMMENTLINE; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_STRING; } else if (ch == '#' && visibleChars == 1) { // Preprocessor commands are alone on their line styler.ColourTo(i - 1, state); state = SCE_C_PREPROCESSOR; } else if (ch == '&' && tolower(chNext) == 'h') { styler.ColourTo(i - 1, state); state = SCE_C_WORD; } else if (isoperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } else if (state == SCE_C_WORD) { if (!iswordchar(ch)) { state = classifyWordVB(styler.GetStartSegment(), i - 1, keywords, styler); if (state == SCE_C_DEFAULT) { if (ch == '\'') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (isoperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } } } else { if (state == SCE_C_STRING) { // VB doubles quotes to preserve them if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } if (state == SCE_C_DEFAULT) { // One of the above succeeded if (ch == '\'') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (iswordstart(ch)) { state = SCE_C_WORD; } } } } styler.ColourTo(lengthDoc, state); } static void FoldVBDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { int lengthDoc = startPos + length; // Backtrack to previous line in case need to fix its fold status int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); if (startPos == 0) initStyle = SCE_P_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } int state = initStyle & 31; int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment); if ((state == SCE_P_TRIPLE) || (state == SCE_P_TRIPLEDOUBLE)) indentCurrent |= SC_FOLDLEVELWHITEFLAG; char chNext = styler[startPos]; for (int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styler.StyleAt(i) & 31; if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment); if ((style == SCE_P_TRIPLE) || (style== SCE_P_TRIPLEDOUBLE)) indentNext |= SC_FOLDLEVELWHITEFLAG; if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } LexerModule lmVB(SCLEX_VB, ColouriseVBDoc, "vb", FoldVBDoc); <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // 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 <ResourceManager/ResourceFactory.hpp> #include <ResourceManager/ResourceCreator.hpp> namespace rm { //////////////////////////////////////////////////////////// /// Initialise member variables //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Function definitions //////////////////////////////////////////////////////////// BaseResource::ResourceFactory() { } BaseResource::~ResourceFactory() { } } //rm <commit_msg>Added Functions to ResourceMananger.cpp<commit_after>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // 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 <ResourceManager/ResourceFactory.hpp> #include <ResourceManager/ResourceCreator.hpp> namespace rm { //////////////////////////////////////////////////////////// /// Initialise member variables //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Function definitions //////////////////////////////////////////////////////////// BaseResource::ResourceFactory() { } BaseResource::~ResourceFactory() { } static std::shared_ptr<BaseResource> createResource(const std::string& path, const std::string& type) { throw("Not implemented"); } static void addType() { } } //rm <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpClient.h> #include <x0/Buffer.h> #include <iostream> #include <fstream> #include <ev++.h> using namespace x0; class HttpServerTest : public ::testing::Test { public: HttpServerTest(); void SetUp(); void TearDown(); void DirectoryTraversal(); private: struct ev::loop_ref loop_; HttpServer* http_; }; HttpServerTest::HttpServerTest() : loop_(ev::default_loop()), http_(nullptr) { FlowRunner::initialize(); } void HttpServerTest::SetUp() { http_ = new HttpServer(loop_); } void HttpServerTest::TearDown() { delete http_; http_ = nullptr; } void HttpServerTest::request(const std::string& method, const std::string& path, const std::initializer_list<std::pair<std::string, std::string>>& headers, const Buffer& content, ResponseHandler callback) { std::unordered_map<std::string, std::string> headerMap; for (auto item: headers) headerMap[item.first] = item.second; HttpClient::request(host_, port_, method, path, headerMap, content, callback); } TEST_F(HttpServerTest, Get) { HttpClient::HeaderMap headers; Buffer body; HttpClient::request(IPAddress("127.0.0.1"), 8080, "GET", "/", {{"Foo", "bar"}, {"User-Agent", "HttpClient/1.0"}}, body, [&](HttpClientError ec, int status, const HttpClient::HeaderMap& headers, const BufferRef& content) { ASSERT_EQ(200, status); ASSERT_EQ(0, content.size()); }); } TEST_F(HttpServerTest, DirectoryTraversal) { // TODO } <commit_msg>[tests] fixed compile issues<commit_after>#include <gtest/gtest.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpClient.h> #include <x0/Buffer.h> #include <iostream> #include <fstream> #include <ev++.h> using namespace x0; class HttpServerTest : public ::testing::Test { public: HttpServerTest(); void SetUp(); void TearDown(); void DirectoryTraversal(); void request(const std::string& method, const std::string& path, const std::initializer_list<std::pair<std::string, std::string>>& headers, const Buffer& content, HttpClient::ResponseHandler callback); private: struct ev::loop_ref loop_; IPAddress host_; int port_; HttpServer* http_; }; HttpServerTest::HttpServerTest() : loop_(ev::default_loop()), host_("127.0.0.1"), port_(8080), http_(nullptr) { FlowRunner::initialize(); } void HttpServerTest::SetUp() { http_ = new HttpServer(loop_); } void HttpServerTest::TearDown() { delete http_; http_ = nullptr; } void HttpServerTest::request(const std::string& method, const std::string& path, const std::initializer_list<std::pair<std::string, std::string>>& headers, const Buffer& content, HttpClient::ResponseHandler callback) { std::unordered_map<std::string, std::string> headerMap; for (auto item: headers) headerMap[item.first] = item.second; HttpClient::request(host_, port_, method, path, headerMap, content, callback); } TEST_F(HttpServerTest, Get) { HttpClient::HeaderMap headers; Buffer body; HttpClient::request(IPAddress("127.0.0.1"), 8080, "GET", "/", {{"Foo", "bar"}, {"User-Agent", "HttpClient/1.0"}}, body, [&](HttpClientError ec, int status, const HttpClient::HeaderMap& headers, const BufferRef& content) { ASSERT_EQ(200, status); ASSERT_EQ(0, content.size()); }); } TEST_F(HttpServerTest, DirectoryTraversal) { // TODO } <|endoftext|>
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/transactionrecord.h> #include <consensus/consensus.h> #include <interfaces/wallet.h> #include <key_io.h> #include <policy/policy.h> #include <timedata.h> #include <validation.h> #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction() { // There are currently no cases where we hide transactions, but // we may want to use this in the future for things like RBF. return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interfaces::WalletTx& wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.time; CAmount nCredit = valueFor(wtx.credit, ::policyAsset); CAmount nDebit = valueFor(wtx.debit, ::policyAsset); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.tx->GetHash(); std::map<std::string, std::string> mapValue = wtx.value_map; if (nNet > 0 || wtx.is_coinbase) { // // Credit // for(unsigned int i = 0; i < wtx.tx->vout.size(); i++) { isminetype mine = wtx.txout_is_mine[i]; if(mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = i; // vout index sub.amount = wtx.txout_amounts[i]; sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; if (wtx.txout_address_is_mine[i]) { // Received by Bitcoin Address sub.type = TransactionRecord::RecvWithAddress; sub.address = EncodeDestination(wtx.txout_address[i]); sub.asset = wtx.txout_assets[i]; } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; sub.asset = wtx.txout_assets[i]; } if (wtx.is_coinbase) { // Generated sub.type = TransactionRecord::Generated; sub.asset = wtx.txout_assets[i]; } parts.append(sub); } } } else { bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; for (const isminetype mine : wtx.txin_is_mine) { if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; for (unsigned int i = 0; i < wtx.txout_is_mine.size(); ++i) { const isminetype mine = wtx.txout_is_mine[i]; const CTxOut txout = wtx.tx->vout[i]; if (txout.IsFee()) { // explicit fee; ignore continue; } if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe && fAllToMe) { // Payment to self CAmount nChange = valueFor(wtx.change, ::policyAsset); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange) + (nCredit - nChange), ::policyAsset)); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // for (unsigned int nOut = 0; nOut < wtx.tx->vout.size(); nOut++) { const CTxOut& txout = wtx.tx->vout[nOut]; if(wtx.txout_is_mine[nOut] || txout.IsFee()) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } TransactionRecord sub(hash, nTime); sub.idx = nOut; sub.involvesWatchAddress = involvesWatchAddress; sub.amount = -wtx.txout_amounts[nOut]; sub.asset = wtx.txout_assets[nOut]; if (!boost::get<CNoDestination>(&wtx.txout_address[nOut])) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = EncodeDestination(wtx.txout_address[nOut]); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } parts.append(sub); } CAmount nTxFee = GetFeeMap(*wtx.tx)[::policyAsset]; if (nTxFee > 0) { TransactionRecord sub(hash, nTime); sub.type = TransactionRecord::Fee; sub.amount = -nTxFee; sub.asset = ::policyAsset; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, CAsset())); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; } void TransactionRecord::updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime) { // Determine transaction status // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", wtx.block_height, wtx.is_coinbase ? 1 : 0, wtx.time_received, idx); status.countsForBalance = wtx.is_trusted && !(wtx.blocks_to_maturity > 0); status.depth = wtx.depth_in_main_chain; status.cur_num_blocks = numBlocks; if (!wtx.is_final) { if (wtx.lock_time < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.lock_time - numBlocks; } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.lock_time; } } // For generated transactions, determine maturity else if(type == TransactionRecord::Generated) { if (wtx.blocks_to_maturity > 0) { status.status = TransactionStatus::Immature; if (wtx.is_in_main_chain) { status.matures_in = wtx.blocks_to_maturity; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; if (wtx.is_abandoned) status.status = TransactionStatus::Abandoned; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } status.needsUpdate = false; } bool TransactionRecord::statusUpdateNeeded(int numBlocks) const { return status.cur_num_blocks != numBlocks || status.needsUpdate; } QString TransactionRecord::getTxHash() const { return QString::fromStdString(hash.ToString()); } int TransactionRecord::getOutputIndex() const { return idx; } <commit_msg>GUI: TransactionRecord: Turn non-bitcoin fees into entries<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/transactionrecord.h> #include <consensus/consensus.h> #include <interfaces/wallet.h> #include <key_io.h> #include <policy/policy.h> #include <timedata.h> #include <validation.h> #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction() { // There are currently no cases where we hide transactions, but // we may want to use this in the future for things like RBF. return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interfaces::WalletTx& wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.time; CAmount nCredit = valueFor(wtx.credit, ::policyAsset); CAmount nDebit = valueFor(wtx.debit, ::policyAsset); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.tx->GetHash(); std::map<std::string, std::string> mapValue = wtx.value_map; if (nNet > 0 || wtx.is_coinbase) { // // Credit // for(unsigned int i = 0; i < wtx.tx->vout.size(); i++) { isminetype mine = wtx.txout_is_mine[i]; if(mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = i; // vout index sub.amount = wtx.txout_amounts[i]; sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; if (wtx.txout_address_is_mine[i]) { // Received by Bitcoin Address sub.type = TransactionRecord::RecvWithAddress; sub.address = EncodeDestination(wtx.txout_address[i]); sub.asset = wtx.txout_assets[i]; } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; sub.asset = wtx.txout_assets[i]; } if (wtx.is_coinbase) { // Generated sub.type = TransactionRecord::Generated; sub.asset = wtx.txout_assets[i]; } parts.append(sub); } } } else { bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; for (const isminetype mine : wtx.txin_is_mine) { if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; for (unsigned int i = 0; i < wtx.txout_is_mine.size(); ++i) { const isminetype mine = wtx.txout_is_mine[i]; const CTxOut txout = wtx.tx->vout[i]; if (txout.IsFee()) { // explicit fee; ignore continue; } if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe && fAllToMe) { // Payment to self CAmount nChange = valueFor(wtx.change, ::policyAsset); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange) + (nCredit - nChange), ::policyAsset)); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // for (unsigned int nOut = 0; nOut < wtx.tx->vout.size(); nOut++) { const CTxOut& txout = wtx.tx->vout[nOut]; if(wtx.txout_is_mine[nOut] || txout.IsFee()) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } TransactionRecord sub(hash, nTime); sub.idx = nOut; sub.involvesWatchAddress = involvesWatchAddress; sub.amount = -wtx.txout_amounts[nOut]; sub.asset = wtx.txout_assets[nOut]; if (!boost::get<CNoDestination>(&wtx.txout_address[nOut])) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = EncodeDestination(wtx.txout_address[nOut]); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } parts.append(sub); } for (const auto& tx_fee : GetFeeMap(*wtx.tx)) { if (!tx_fee.second) continue; TransactionRecord sub(hash, nTime); sub.type = TransactionRecord::Fee; sub.asset = tx_fee.first; sub.amount = -tx_fee.second; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, CAsset())); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; } void TransactionRecord::updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime) { // Determine transaction status // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", wtx.block_height, wtx.is_coinbase ? 1 : 0, wtx.time_received, idx); status.countsForBalance = wtx.is_trusted && !(wtx.blocks_to_maturity > 0); status.depth = wtx.depth_in_main_chain; status.cur_num_blocks = numBlocks; if (!wtx.is_final) { if (wtx.lock_time < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.lock_time - numBlocks; } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.lock_time; } } // For generated transactions, determine maturity else if(type == TransactionRecord::Generated) { if (wtx.blocks_to_maturity > 0) { status.status = TransactionStatus::Immature; if (wtx.is_in_main_chain) { status.matures_in = wtx.blocks_to_maturity; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; if (wtx.is_abandoned) status.status = TransactionStatus::Abandoned; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } status.needsUpdate = false; } bool TransactionRecord::statusUpdateNeeded(int numBlocks) const { return status.cur_num_blocks != numBlocks || status.needsUpdate; } QString TransactionRecord::getTxHash() const { return QString::fromStdString(hash.ToString()); } int TransactionRecord::getOutputIndex() const { return idx; } <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc. // // 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 <memory> #include <string> #include <vector> #include "gtest/gtest.h" #ifdef __GNUC__ #include <cxxabi.h> #include <execinfo.h> #include <malloc.h> #endif #include "rclcpp/strategies/allocator_memory_strategy.hpp" #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/u_int32.hpp" #include "tlsf_cpp/tlsf.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif // TODO(jacquelinekay) improve this ignore rule (dogfooding or no allocations) static const size_t num_rmw_tokens = 6; static const char * rmw_tokens[num_rmw_tokens] = { "librmw", "dds", "DDS", "dcps", "DCPS", "fastrtps" }; static const size_t iterations = 1; static bool verbose = false; static bool ignore_middleware_tokens = true; static bool test_init = false; static bool fail = false; inline bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames = 15); /// Declare a function pointer into which we will store the default malloc. static void * (* prev_malloc_hook)(size_t, const void *); // Use pragma to ignore a warning for using __malloc_hook, which is deprecated (but still awesome). #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" static void * testing_malloc(size_t size, const void * caller) { (void)caller; // Set the malloc implementation to the default malloc hook so that we can call it implicitly // to initialize a string, otherwise this function will loop infinitely. __malloc_hook = prev_malloc_hook; if (test_init) { fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } // Execute the requested malloc. void * mem = std::malloc(size); // Set the malloc hook back to this function, so that we can intercept future mallocs. __malloc_hook = testing_malloc; return mem; } /// Function to be called when the malloc hook is initialized. void init_malloc_hook() { // Store the default malloc. prev_malloc_hook = __malloc_hook; // Set our custom malloc to the malloc hook. __malloc_hook = testing_malloc; } #pragma GCC diagnostic pop /// Set the hook for malloc initialize so that init_malloc_hook gets called. void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook; /** Check a demangled stack backtrace of the caller function for the given tokens. ** Adapted from: https://panthema.net/2008/0901-stacktrace-demangled **/ bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames) { #ifdef __GNUC__ bool match = false; // storage array for stack trace address data void * addrlist[max_frames + 1]; // retrieve current stack addresses int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void *)); if (addrlen == 0) { fprintf(stderr, "WARNING: stack trace empty, possibly corrupt\n"); return false; } // resolve addresses into strings containing "filename(function+address)", // this array must be free()-ed char ** symbollist = backtrace_symbols(addrlist, addrlen); // initialize string string which will be filled with the demangled function name // allocate string which will be filled with the demangled function name size_t funcnamesize = 256; char * funcname = static_cast<char *>(std::malloc(funcnamesize)); if (verbose) { fprintf(stderr, ">>>> stack trace:\n"); } // iterate over the returned symbol lines. skip the first, it is the // address of this function. for (int i = 1; i < addrlen; i++) { char * begin_name = 0, * begin_offset = 0, * end_offset = 0; // find parentheses and +address offset surrounding the mangled name: // ./module(function+0x15c) [0x8048a6d] for (char * p = symbollist[i]; *p; ++p) { if (*p == '(') { begin_name = p; } else if (*p == '+') { begin_offset = p; } else if (*p == ')' && begin_offset) { end_offset = p; break; } } if (begin_name && begin_offset && end_offset && begin_name < begin_offset) { *begin_name++ = '\0'; *begin_offset++ = '\0'; *end_offset = '\0'; int status; char * ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status); if (status == 0) { funcname = ret; // use possibly realloc()-ed string for (size_t j = 0; j < num_tokens; ++j) { if (strstr(symbollist[i], tokens[j]) != nullptr || strstr(funcname, tokens[j]) != nullptr) { match = true; break; } } if (verbose) { fprintf(stderr, " %s : %s+%s\n", symbollist[i], funcname, begin_offset); } } else { // demangling failed. Output function name as a C function with // no arguments. for (size_t j = 0; j < num_tokens; j++) { if (strstr(symbollist[i], tokens[j]) != nullptr || strstr(begin_name, tokens[j]) != nullptr) { match = true; break; } } if (verbose) { fprintf(stderr, " %s : %s()+%s\n", symbollist[i], begin_name, begin_offset); } } } else { // couldn't parse the line? print the whole line. for (size_t j = 0; j < num_tokens; j++) { if (strstr(symbollist[i], tokens[j]) != nullptr) { match = true; break; } } if (verbose) { fprintf(stderr, " %s\n", symbollist[i]); } } } free(funcname); free(symbollist); if (!ignore_middleware_tokens) { return false; } return match; #else return true; #endif // __GNUC__ } void * operator new(std::size_t size) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" __malloc_hook = prev_malloc_hook; if (test_init) { // Check the stacktrace to see the call originated in librmw or a DDS implementation fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } void * ptr = std::malloc(size); __malloc_hook = testing_malloc; #pragma GCC diagnostic pop return ptr; } void operator delete(void * ptr) noexcept { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" __malloc_hook = prev_malloc_hook; if (ptr != nullptr) { if (test_init) { // Check the stacktrace to see the call originated in librmw or a DDS implementation fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } std::free(ptr); ptr = nullptr; } __malloc_hook = testing_malloc; #pragma GCC diagnostic pop } void operator delete(void * ptr, size_t) noexcept { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" __malloc_hook = prev_malloc_hook; if (ptr != nullptr) { if (test_init) { // Check the stacktrace to see the call originated in librmw or a DDS implementation fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } std::free(ptr); ptr = nullptr; } __malloc_hook = testing_malloc; #pragma GCC diagnostic pop } template<typename T = void> using TLSFAllocator = tlsf_heap_allocator<T>; using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy; class CLASSNAME (AllocatorTest, RMW_IMPLEMENTATION) : public::testing::Test { protected: std::string test_name_; rclcpp::node::Node::SharedPtr node_; rclcpp::executors::SingleThreadedExecutor::SharedPtr executor_; rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy_; rclcpp::publisher::Publisher<std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr publisher_; rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr msg_memory_strategy_; std::shared_ptr<TLSFAllocator<void>> alloc; bool intra_process_; using UInt32Allocator = TLSFAllocator<std_msgs::msg::UInt32>; using UInt32Deleter = rclcpp::allocator::Deleter<UInt32Allocator, std_msgs::msg::UInt32>; void initialize(bool intra_process, const std::string & name) { test_name_ = name; intra_process_ = intra_process; auto context = rclcpp::contexts::default_context::get_global_default_context(); auto intra_process_manager_state = std::make_shared<rclcpp::intra_process_manager::IntraProcessManagerImpl<UInt32Allocator>>(); context->get_sub_context<rclcpp::intra_process_manager::IntraProcessManager>( intra_process_manager_state); node_ = rclcpp::Node::make_shared(name, context, intra_process); alloc = std::make_shared<TLSFAllocator<void>>(); msg_memory_strategy_ = std::make_shared<rclcpp::message_memory_strategy::MessageMemoryStrategy <std_msgs::msg::UInt32, TLSFAllocator<void>>>(alloc); publisher_ = node_->create_publisher<std_msgs::msg::UInt32>(name, 10, alloc); memory_strategy_ = std::make_shared<AllocatorMemoryStrategy<TLSFAllocator<void>>>(alloc); rclcpp::executor::ExecutorArgs args; args.memory_strategy = memory_strategy_; rclcpp::executors::SingleThreadedExecutor executor(args); executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(args); executor_->add_node(node_); } CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() { } ~CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() { } }; TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), allocator_shared_ptr) { initialize(false, "allocator_shared_ptr"); size_t counter = 0; auto callback = [&counter](std_msgs::msg::UInt32::SharedPtr msg) -> void { EXPECT_EQ(counter, msg->data); counter++; }; auto subscriber = node_->create_subscription<std_msgs::msg::UInt32>( "allocator_shared_ptr", 10, callback, nullptr, false, msg_memory_strategy_, alloc); // Create msg to be published auto msg = std::allocate_shared<std_msgs::msg::UInt32>(*alloc.get()); rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); // After test_initialization, global new should only be called from within TLSFAllocator. test_init = true; for (uint32_t i = 0; i < iterations; i++) { msg->data = i; publisher_->publish(msg); rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); executor_->spin_some(); } test_init = false; EXPECT_FALSE(fail); fail = false; } TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), allocator_unique_ptr) { initialize(true, "allocator_unique_ptr"); size_t counter = 0; auto callback = [&counter](std_msgs::msg::UInt32::UniquePtrWithDeleter<UInt32Deleter> msg) -> void { EXPECT_EQ(counter, msg->data); counter++; }; auto subscriber = node_->create_subscription<std_msgs::msg::UInt32>( "allocator_unique_ptr", 10, callback, nullptr, false, msg_memory_strategy_, alloc); TLSFAllocator<std_msgs::msg::UInt32> msg_alloc; rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); // After test_initialization, global new should only be called from within TLSFAllocator. test_init = true; for (uint32_t i = 0; i < iterations; i++) { auto msg = std::unique_ptr<std_msgs::msg::UInt32, UInt32Deleter>( std::allocator_traits<UInt32Allocator>::allocate(msg_alloc, 1)); msg->data = i; publisher_->publish(msg); rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); executor_->spin_some(); } test_init = false; EXPECT_FALSE(fail); fail = false; } void print_help() { printf("--all-tokens: Do not ignore middleware tokens.\n"); printf("--verbose: Report stack traces and allocation statistics.\n"); } int main(int argc, char ** argv) { rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); // argc and argv are modified by InitGoogleTest std::vector<std::string> args(argv + 1, argv + argc); if (std::find(args.begin(), args.end(), "--help") != args.end()) { print_help(); return 0; } verbose = std::find(args.begin(), args.end(), "--verbose") != args.end(); ignore_middleware_tokens = std::find(args.begin(), args.end(), "--all-tokens") == args.end(); return RUN_ALL_TESTS(); } <commit_msg>fix style<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc. // // 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 <memory> #include <string> #include <vector> #include "gtest/gtest.h" #ifdef __GNUC__ #include <cxxabi.h> #include <execinfo.h> #include <malloc.h> #endif #include "rclcpp/strategies/allocator_memory_strategy.hpp" #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/u_int32.hpp" #include "tlsf_cpp/tlsf.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif // TODO(jacquelinekay) improve this ignore rule (dogfooding or no allocations) static const size_t num_rmw_tokens = 6; static const char * rmw_tokens[num_rmw_tokens] = { "librmw", "dds", "DDS", "dcps", "DCPS", "fastrtps" }; static const size_t iterations = 1; static bool verbose = false; static bool ignore_middleware_tokens = true; static bool test_init = false; static bool fail = false; inline bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames = 15); /// Declare a function pointer into which we will store the default malloc. static void * (* prev_malloc_hook)(size_t, const void *); // Use pragma to ignore a warning for using __malloc_hook, which is deprecated (but still awesome). #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" static void * testing_malloc(size_t size, const void * caller) { (void)caller; // Set the malloc implementation to the default malloc hook so that we can call it implicitly // to initialize a string, otherwise this function will loop infinitely. __malloc_hook = prev_malloc_hook; if (test_init) { fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } // Execute the requested malloc. void * mem = std::malloc(size); // Set the malloc hook back to this function, so that we can intercept future mallocs. __malloc_hook = testing_malloc; return mem; } /// Function to be called when the malloc hook is initialized. void init_malloc_hook() { // Store the default malloc. prev_malloc_hook = __malloc_hook; // Set our custom malloc to the malloc hook. __malloc_hook = testing_malloc; } #pragma GCC diagnostic pop /// Set the hook for malloc initialize so that init_malloc_hook gets called. void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook; /** Check a demangled stack backtrace of the caller function for the given tokens. ** Adapted from: https://panthema.net/2008/0901-stacktrace-demangled **/ bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames) { #ifdef __GNUC__ bool match = false; // storage array for stack trace address data void * addrlist[max_frames + 1]; // retrieve current stack addresses int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void *)); if (addrlen == 0) { fprintf(stderr, "WARNING: stack trace empty, possibly corrupt\n"); return false; } // resolve addresses into strings containing "filename(function+address)", // this array must be free()-ed char ** symbollist = backtrace_symbols(addrlist, addrlen); // initialize string string which will be filled with the demangled function name // allocate string which will be filled with the demangled function name size_t funcnamesize = 256; char * funcname = static_cast<char *>(std::malloc(funcnamesize)); if (verbose) { fprintf(stderr, ">>>> stack trace:\n"); } // iterate over the returned symbol lines. skip the first, it is the // address of this function. for (int i = 1; i < addrlen; i++) { char * begin_name = 0, * begin_offset = 0, * end_offset = 0; // find parentheses and +address offset surrounding the mangled name: // ./module(function+0x15c) [0x8048a6d] for (char * p = symbollist[i]; *p; ++p) { if (*p == '(') { begin_name = p; } else if (*p == '+') { begin_offset = p; } else if (*p == ')' && begin_offset) { end_offset = p; break; } } if (begin_name && begin_offset && end_offset && begin_name < begin_offset) { *begin_name++ = '\0'; *begin_offset++ = '\0'; *end_offset = '\0'; int status; char * ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status); if (status == 0) { funcname = ret; // use possibly realloc()-ed string for (size_t j = 0; j < num_tokens; ++j) { if (strstr(symbollist[i], tokens[j]) != nullptr || strstr(funcname, tokens[j]) != nullptr) { match = true; break; } } if (verbose) { fprintf(stderr, " %s : %s+%s\n", symbollist[i], funcname, begin_offset); } } else { // demangling failed. Output function name as a C function with // no arguments. for (size_t j = 0; j < num_tokens; j++) { if (strstr(symbollist[i], tokens[j]) != nullptr || strstr(begin_name, tokens[j]) != nullptr) { match = true; break; } } if (verbose) { fprintf(stderr, " %s : %s()+%s\n", symbollist[i], begin_name, begin_offset); } } } else { // couldn't parse the line? print the whole line. for (size_t j = 0; j < num_tokens; j++) { if (strstr(symbollist[i], tokens[j]) != nullptr) { match = true; break; } } if (verbose) { fprintf(stderr, " %s\n", symbollist[i]); } } } free(funcname); free(symbollist); if (!ignore_middleware_tokens) { return false; } return match; #else return true; #endif // __GNUC__ } void * operator new(std::size_t size) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" __malloc_hook = prev_malloc_hook; if (test_init) { // Check the stacktrace to see the call originated in librmw or a DDS implementation fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } void * ptr = std::malloc(size); __malloc_hook = testing_malloc; #pragma GCC diagnostic pop return ptr; } void operator delete(void * ptr) noexcept { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" __malloc_hook = prev_malloc_hook; if (ptr != nullptr) { if (test_init) { // Check the stacktrace to see the call originated in librmw or a DDS implementation fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } std::free(ptr); ptr = nullptr; } __malloc_hook = testing_malloc; #pragma GCC diagnostic pop } void operator delete(void * ptr, size_t) noexcept { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" __malloc_hook = prev_malloc_hook; if (ptr != nullptr) { if (test_init) { // Check the stacktrace to see the call originated in librmw or a DDS implementation fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens); } std::free(ptr); ptr = nullptr; } __malloc_hook = testing_malloc; #pragma GCC diagnostic pop } template<typename T = void> using TLSFAllocator = tlsf_heap_allocator<T>; using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy; class CLASSNAME (AllocatorTest, RMW_IMPLEMENTATION) : public ::testing::Test { protected: std::string test_name_; rclcpp::node::Node::SharedPtr node_; rclcpp::executors::SingleThreadedExecutor::SharedPtr executor_; rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy_; rclcpp::publisher::Publisher<std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr publisher_; rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr msg_memory_strategy_; std::shared_ptr<TLSFAllocator<void>> alloc; bool intra_process_; using UInt32Allocator = TLSFAllocator<std_msgs::msg::UInt32>; using UInt32Deleter = rclcpp::allocator::Deleter<UInt32Allocator, std_msgs::msg::UInt32>; void initialize(bool intra_process, const std::string & name) { test_name_ = name; intra_process_ = intra_process; auto context = rclcpp::contexts::default_context::get_global_default_context(); auto intra_process_manager_state = std::make_shared<rclcpp::intra_process_manager::IntraProcessManagerImpl<UInt32Allocator>>(); context->get_sub_context<rclcpp::intra_process_manager::IntraProcessManager>( intra_process_manager_state); node_ = rclcpp::Node::make_shared(name, context, intra_process); alloc = std::make_shared<TLSFAllocator<void>>(); msg_memory_strategy_ = std::make_shared<rclcpp::message_memory_strategy::MessageMemoryStrategy <std_msgs::msg::UInt32, TLSFAllocator<void>>>(alloc); publisher_ = node_->create_publisher<std_msgs::msg::UInt32>(name, 10, alloc); memory_strategy_ = std::make_shared<AllocatorMemoryStrategy<TLSFAllocator<void>>>(alloc); rclcpp::executor::ExecutorArgs args; args.memory_strategy = memory_strategy_; rclcpp::executors::SingleThreadedExecutor executor(args); executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(args); executor_->add_node(node_); } CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() { } ~CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() { } }; TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), allocator_shared_ptr) { initialize(false, "allocator_shared_ptr"); size_t counter = 0; auto callback = [&counter](std_msgs::msg::UInt32::SharedPtr msg) -> void { EXPECT_EQ(counter, msg->data); counter++; }; auto subscriber = node_->create_subscription<std_msgs::msg::UInt32>( "allocator_shared_ptr", 10, callback, nullptr, false, msg_memory_strategy_, alloc); // Create msg to be published auto msg = std::allocate_shared<std_msgs::msg::UInt32>(*alloc.get()); rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); // After test_initialization, global new should only be called from within TLSFAllocator. test_init = true; for (uint32_t i = 0; i < iterations; i++) { msg->data = i; publisher_->publish(msg); rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); executor_->spin_some(); } test_init = false; EXPECT_FALSE(fail); fail = false; } TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), allocator_unique_ptr) { initialize(true, "allocator_unique_ptr"); size_t counter = 0; auto callback = [&counter](std_msgs::msg::UInt32::UniquePtrWithDeleter<UInt32Deleter> msg) -> void { EXPECT_EQ(counter, msg->data); counter++; }; auto subscriber = node_->create_subscription<std_msgs::msg::UInt32>( "allocator_unique_ptr", 10, callback, nullptr, false, msg_memory_strategy_, alloc); TLSFAllocator<std_msgs::msg::UInt32> msg_alloc; rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); // After test_initialization, global new should only be called from within TLSFAllocator. test_init = true; for (uint32_t i = 0; i < iterations; i++) { auto msg = std::unique_ptr<std_msgs::msg::UInt32, UInt32Deleter>( std::allocator_traits<UInt32Allocator>::allocate(msg_alloc, 1)); msg->data = i; publisher_->publish(msg); rclcpp::utilities::sleep_for(std::chrono::milliseconds(1)); executor_->spin_some(); } test_init = false; EXPECT_FALSE(fail); fail = false; } void print_help() { printf("--all-tokens: Do not ignore middleware tokens.\n"); printf("--verbose: Report stack traces and allocation statistics.\n"); } int main(int argc, char ** argv) { rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); // argc and argv are modified by InitGoogleTest std::vector<std::string> args(argv + 1, argv + argc); if (std::find(args.begin(), args.end(), "--help") != args.end()) { print_help(); return 0; } verbose = std::find(args.begin(), args.end(), "--verbose") != args.end(); ignore_middleware_tokens = std::find(args.begin(), args.end(), "--all-tokens") == args.end(); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "fluidsystem.h" #include "camera.h" #include "vertexrecorder.h" #include <iostream> #include <math.h> #include "particle.h" using namespace std; // your system should at least contain 8x8 particles. const int N = 5; const float PARTICLE_SPACING = .2; const float PARTICLE_RADIUS = PARTICLE_SPACING/2.0; const int H = PARTICLE_RADIUS; const float SPRING_CONSTANT = 5; // N/m const float PARTICLE_MASS = .03; // kg const float GRAVITY = 9.8; // m/s const float DRAG_CONSTANT = .05; FluidSystem::FluidSystem() { // TODO 5. Initialize m_vVecState with cloth particles. // You can again use rand_uniform(lo, hi) to make things a bit more interesting m_vVecState.clear(); int particleCount = 0; for (unsigned i = 0; i < N; i++){ for (unsigned j = 0; j< N; j++){ for (unsigned l = 0; l < N; l++){ float x = i*PARTICLE_SPACING; float y = j*PARTICLE_SPACING; float z = l*PARTICLE_SPACING; // particles evenly spaced Vector3f position = Vector3f(x, y, z); // all particles stationary Vector3f velocity = Vector3f(0, 0, 0); Particle particle = Particle(particleCount, position, velocity); m_vVecState.push_back(particle); particleCount += 1; } } } } std::vector<Particle> FluidSystem::evalF(std::vector<Particle> state) { std::vector<Particle> f; // TODO 5. implement evalF // - gravity // - viscous drag // - structural springs // - shear springs // - flexion springs // Particle p = Particle(4.0, Vector3f(0,0,0), Vector3f(0,0,0)); // Gravity and Wind will be independent of the particle in question // F = mg -> GRAVITY // ---------------------------------------- float gForce = PARTICLE_MASS*GRAVITY; // only in the y-direction Vector3f gravityForce = Vector3f(0,-gForce, 0); // ---------------------------------------- // 315/[64*pi*h^9] float kernel_constant_density = 315.0 / (64.0 * M_PI * pow(H, 9)); // -45/[pi*h^6] float kernel_constant_pressure = -45.0 / (M_PI * pow(H, 6)); for (unsigned i = 0; i < state.size(); i+=1){ Particle particle = state[i]; Vector3f position = particle.getPosition(); Vector3f velocity = particle.getVelocity(); float density = particle.getDensity(); Vector3f viscosity = particle.getViscosity(); float pressure = particle.getPressure(); // compute updated density and gradient of pressure // based on all other particles float density_i = 0; Vector3f f_pressure; Vector3f f_viscosity; for (unsigned j = 0; j < state.size(); j+=1) { if (j != i) { Particle particle_j = state[j]; Vector3f delta = position - particle_j.getPosition(); // ---------------density computation----------------- float kernel_distance_density = pow((H*H - delta.absSquared()), 3); density_i += PARTICLE_MASS*kernel_constant_density*kernel_distance_density; // ---------------gradient of pressure computation----------------- // Mueller value: (pi + pj) / 2pj // Vector3f p_factor = (pressure+particle_j.getPressure()) / (2*particle_j.getDensity()); float p_factor = pressure/density + particle_j.getPressure()/particle_j.getDensity(); // (h-d)^2 * d/|d| Vector3f kernel_distance_pressure = pow((H - delta.absSquared()), 2) * delta / delta.abs(); f_pressure += PARTICLE_MASS*p_factor*kernel_constant_pressure*kernel_distance_pressure; // ---------------viscosity computation----------------- float kernel_distance_viscosity = H-delta.abs(); Vector3f v_factor = (particle_j.getViscosity() - viscosity) / particle_j.getDensity(); f_viscosity += PARTICLE_MASS*v_factor*-1.0*kernel_constant_pressure*kernel_distance_viscosity; // printf("F Pressure: "); // f_pressure.print(); // printf("F Viscosity: "); // f_viscosity.print(); } } // Total Force Vector3f totalForce = gravityForce - f_pressure + f_viscosity; Vector3f acceleration = (1.0/PARTICLE_MASS)*totalForce; if (position.y() < -0.95){ velocity = Vector3f(velocity.x(), 0, velocity.z()); } Particle newParticle = Particle(i, velocity, acceleration); newParticle.setDensity(density_i); f.push_back(newParticle); } return f; } void FluidSystem::draw(GLProgram& gl) { //TODO 5: render the system // - ie draw the particles as little spheres // - or draw the springs as little lines or cylinders // - or draw wireframe mesh const Vector3f blue(0.0f, 0.0f, 1.0f); // EXAMPLE for how to render cloth particles. // - you should replace this code. // EXAMPLE: This shows you how to render lines to debug the spring system. // // You should replace this code. // // Since lines don't have a clearly defined normal, we can't use // a regular lighting model. // GLprogram has a "color only" mode, where illumination // is disabled, and you specify color directly as vertex attribute. // Note: enableLighting/disableLighting invalidates uniforms, // so you'll have to update the transformation/material parameters // after a mode change. gl.disableLighting(); gl.updateModelMatrix(Matrix4f::identity()); // update uniforms after mode change // drawBox(Vector3f(0,0,0), 1); // not working :( gl.updateMaterial(blue); for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle p = m_vVecState[i]; Vector3f pos = p.getPosition(); gl.updateModelMatrix(Matrix4f::translation(pos)); drawSphere(PARTICLE_RADIUS, 5, 4); } gl.enableLighting(); // reset to default lighting model } <commit_msg>implemented clamping for kernel functions<commit_after>#include "fluidsystem.h" #include "camera.h" #include "vertexrecorder.h" #include <iostream> #include <math.h> #include "particle.h" using namespace std; // your system should at least contain 8x8 particles. const int N = 5; const float PARTICLE_SPACING = .2; const float PARTICLE_RADIUS = PARTICLE_SPACING/2.0; const int H = PARTICLE_RADIUS; const float SPRING_CONSTANT = 5; // N/m const float PARTICLE_MASS = .03; // kg const float GRAVITY = 9.8; // m/s const float DRAG_CONSTANT = .05; FluidSystem::FluidSystem() { // TODO 5. Initialize m_vVecState with cloth particles. // You can again use rand_uniform(lo, hi) to make things a bit more interesting m_vVecState.clear(); int particleCount = 0; for (unsigned i = 0; i < N; i++){ for (unsigned j = 0; j< N; j++){ for (unsigned l = 0; l < N; l++){ float x = i*PARTICLE_SPACING; float y = j*PARTICLE_SPACING; float z = l*PARTICLE_SPACING; // particles evenly spaced Vector3f position = Vector3f(x, y, z); // all particles stationary Vector3f velocity = Vector3f(0, 0, 0); Particle particle = Particle(particleCount, position, velocity); m_vVecState.push_back(particle); particleCount += 1; } } } } std::vector<Particle> FluidSystem::evalF(std::vector<Particle> state) { std::vector<Particle> f; // TODO 5. implement evalF // - gravity // - viscous drag // - structural springs // - shear springs // - flexion springs // Particle p = Particle(4.0, Vector3f(0,0,0), Vector3f(0,0,0)); // Gravity and Wind will be independent of the particle in question // F = mg -> GRAVITY // ---------------------------------------- float gForce = PARTICLE_MASS*GRAVITY; // only in the y-direction Vector3f gravityForce = Vector3f(0,-gForce, 0); // ---------------------------------------- // 315/[64*pi*h^9] float kernel_constant_density = 315.0 / (64.0 * M_PI * pow(H, 9)); // -45/[pi*h^6] float kernel_constant_pressure = -45.0 / (M_PI * pow(H, 6)); for (unsigned i = 0; i < state.size(); i+=1){ Particle particle = state[i]; Vector3f position = particle.getPosition(); Vector3f velocity = particle.getVelocity(); float density = particle.getDensity(); Vector3f viscosity = particle.getViscosity(); float pressure = particle.getPressure(); // compute updated density and gradient of pressure // based on all other particles float density_i = 0; Vector3f f_pressure; Vector3f f_viscosity; for (unsigned j = 0; j < state.size(); j+=1) { if (j != i) { Particle particle_j = state[j]; Vector3f delta = position - particle_j.getPosition(); // ---------------density computation----------------- float kernel_distance_density = pow((H*H - delta.absSquared()), 3); if (delta.abs() < H) { kernel_distance_density = 0; } cout << kernel_distance_density << endl; density_i += PARTICLE_MASS*kernel_constant_density*kernel_distance_density; // ---------------gradient of pressure computation----------------- // Mueller value: (pi + pj) / 2pj // Vector3f p_factor = (pressure+particle_j.getPressure()) / (2*particle_j.getDensity()); float p_factor = pressure/density + particle_j.getPressure()/particle_j.getDensity(); // (h-d)^2 * d/|d| Vector3f kernel_distance_pressure = pow((H - delta.absSquared()), 2) * delta / delta.abs(); f_pressure += PARTICLE_MASS*p_factor*kernel_constant_pressure*kernel_distance_pressure; // ---------------viscosity computation----------------- float kernel_distance_viscosity = H-delta.abs(); if (delta.abs() < H) { kernel_distance_viscosity = 0; } Vector3f v_factor = (particle_j.getViscosity() - viscosity) / particle_j.getDensity(); f_viscosity += PARTICLE_MASS*v_factor*-1.0*kernel_constant_pressure*kernel_distance_viscosity; // printf("F Pressure: "); // f_pressure.print(); // printf("F Viscosity: "); // f_viscosity.print(); } } // Total Force Vector3f totalForce = gravityForce - f_pressure + f_viscosity; Vector3f acceleration = (1.0/PARTICLE_MASS)*totalForce; if (position.y() < -0.95){ velocity = Vector3f(velocity.x(), 0, velocity.z()); } Particle newParticle = Particle(i, velocity, acceleration); newParticle.setDensity(density_i); f.push_back(newParticle); } return f; } void FluidSystem::draw(GLProgram& gl) { //TODO 5: render the system // - ie draw the particles as little spheres // - or draw the springs as little lines or cylinders // - or draw wireframe mesh const Vector3f blue(0.0f, 0.0f, 1.0f); // EXAMPLE for how to render cloth particles. // - you should replace this code. // EXAMPLE: This shows you how to render lines to debug the spring system. // // You should replace this code. // // Since lines don't have a clearly defined normal, we can't use // a regular lighting model. // GLprogram has a "color only" mode, where illumination // is disabled, and you specify color directly as vertex attribute. // Note: enableLighting/disableLighting invalidates uniforms, // so you'll have to update the transformation/material parameters // after a mode change. gl.disableLighting(); gl.updateModelMatrix(Matrix4f::identity()); // update uniforms after mode change // drawBox(Vector3f(0,0,0), 1); // not working :( gl.updateMaterial(blue); for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle p = m_vVecState[i]; Vector3f pos = p.getPosition(); gl.updateModelMatrix(Matrix4f::translation(pos)); drawSphere(PARTICLE_RADIUS, 5, 4); } gl.enableLighting(); // reset to default lighting model } <|endoftext|>
<commit_before>// // globe.cpp // GlobeVisualization // // Created by Johannes Neumeier on 03/06/15. // // #include "globe.h" globe::globe() { sphere.setRadius(100); } void globe::update() { } void globe::draw() { ofPushMatrix(); ofSetColor(255); sphere.enableNormals(); sphere.enableTextures(); ofTexture tex = textureImage.getTextureReference(); //tex.bind(); sphere.mapTexCoordsFromTexture(tex); //tex.draw(0, 0); tex.bind(); ofRotateX(180); sphere.draw(); textureImage.unbind(); ofSetColor(150, 255, 100); sphere.drawNormals(5); sphere.drawAxes(150); ofSetLineWidth(0.5); ofSetColor(0, 50, 75, 50); sphere.drawWireframe(); ofPopMatrix(); } void globe::setTexture(string path) { textureImage.loadImage(path); textureImage.mirror(false, true); // vertical, horizontal }<commit_msg>finally figured out a fix to the transparency rendering issue... open gl backface culling to the rescue<commit_after>// // globe.cpp // GlobeVisualization // // Created by Johannes Neumeier on 03/06/15. // // #include "globe.h" globe::globe() { sphere.setRadius(100); } void globe::update() { } void globe::draw() { ofPushMatrix(); ofSetColor(255); //sphere.enableNormals(); sphere.enableTextures(); textureImage.getTextureReference().bind(); ofRotateX(180); // enable solid surface and backface culling in Open GL glEnable(GL_CULL_FACE); // Cull back facing polygons glCullFace(GL_FRONT); sphere.draw(); textureImage.unbind(); ofSetColor(150, 255, 100); //sphere.drawNormals(5); sphere.drawAxes(150); ofSetLineWidth(0.5); ofSetColor(0, 50, 75, 50); sphere.drawWireframe(); ofPopMatrix(); } void globe::setTexture(string path) { textureImage.loadImage(path); textureImage.mirror(false, true); // vertical, horizontal }<|endoftext|>
<commit_before>/* * Copyright (C) 2016 Dan Leinir Turthra Jensen <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ #include "PeruseConfig.h" #include <KFileMetaData/UserMetaData> #include <KConfig> #include <KConfigGroup> #include <KNSCore/Engine> #include <QTimer> #include <QFile> class PeruseConfig::Private { public: Private() : config("peruserc") {}; KConfig config; }; PeruseConfig::PeruseConfig(QObject* parent) : QObject(parent) , d(new Private) { QStringList locations = d->config.group("general").readEntry("book locations", QStringList()); if(locations.count() < 1) { locations = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation); locations << QStandardPaths::standardLocations(QStandardPaths::DownloadLocation); locations << QString("%1/comics").arg(QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).first()); d->config.group("general").writeEntry("book locations", locations); d->config.sync(); } } PeruseConfig::~PeruseConfig() { delete d; } void PeruseConfig::bookOpened(QString path) { QStringList recent = recentlyOpened(); int i = recent.indexOf(path); if(i == 0) { // This is already first, don't do work we don't need to, because that's just silly return; } else { recent.removeAll(path); recent.prepend(path); } d->config.group("general").writeEntry("recently opened", recent); d->config.sync(); emit recentlyOpenedChanged(); } QStringList PeruseConfig::recentlyOpened() const { QStringList recent = d->config.group("general").readEntry("recently opened", QStringList()); QStringList actualRecent; while(recent.count() > 0) { QString current = recent.takeFirst(); if(QFile::exists(current)) { actualRecent.append(current); } } return actualRecent; } void PeruseConfig::addBookLocation(const QString& location) { if(location.startsWith("file://")) { #ifdef Q_OS_WIN QString newLocation = location.mid(8); #else QString newLocation = location.mid(7); #endif QStringList locations = bookLocations(); // First, get rid of all the entries which start with the newly added location, because that's silly QStringList newLocations; bool alreadyInThere = false; Q_FOREACH(QString entry, locations) { if(!entry.startsWith(newLocation)) { newLocations.append(entry); } if(newLocation.startsWith(entry)) { alreadyInThere = true; } } if(alreadyInThere) { // Don't be silly, don't add a new location if it's already covered by something more high level... emit showMessage("Attempted to add a new location to the list of search folders which is a sub-folder to something already in the list."); return; } newLocations.append(newLocation); d->config.group("general").writeEntry("book locations", newLocations); d->config.sync(); emit bookLocationsChanged(); } } void PeruseConfig::removeBookLocation(const QString& location) { QStringList locations = bookLocations(); locations.removeAll(location); d->config.group("general").writeEntry("book locations", locations); d->config.sync(); QTimer::singleShot(100, this, SIGNAL(bookLocationsChanged())); } QStringList PeruseConfig::bookLocations() const { QStringList locations = d->config.group("general").readEntry("book locations", QStringList()); return locations; } QString PeruseConfig::newstuffLocation() const { const QStringList locations = KNSCore::Engine::configSearchLocations(); QString knsrc; for (const QString& location : locations) { knsrc = QString::fromLocal8Bit("%1/peruse.knsrc").arg(location); if (QFile(knsrc).exists()) { break; } } if(qEnvironmentVariableIsSet("APPDIR")) { // Because appimage install happens into /app/usr... knsrc = knsrc.prepend("/usr").prepend(qgetenv("APPDIR")); } return knsrc; } QString PeruseConfig::homeDir() const { return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first(); } void PeruseConfig::setFilesystemProperty(QString fileName, QString propertyName, QString value) { KFileMetaData::UserMetaData data(fileName); if (propertyName == "rating") { data.setRating(value.toInt()); } else if (propertyName == "tags") { data.setTags(value.split(",")); } else if (propertyName == "comment") { data.setUserComment(value); } else { data.setAttribute(QString("peruse.").append(propertyName), value); } } QString PeruseConfig::getFilesystemProperty(QString fileName, QString propertyName) { QString value; KFileMetaData::UserMetaData data(fileName); if (propertyName == "rating") { value = QString::number(data.rating()); } else if (propertyName == "tags") { value = data.tags().join(","); } else if (propertyName == "comment") { value = data.userComment(); } else { value = data.attribute(QString("peruse.").append(propertyName)); } return value; } <commit_msg>Add mimetype and bytes getters for the file info fetcher<commit_after>/* * Copyright (C) 2016 Dan Leinir Turthra Jensen <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ #include "PeruseConfig.h" #include <KFileMetaData/UserMetaData> #include <KConfig> #include <KConfigGroup> #include <KNSCore/Engine> #include <QTimer> #include <QFile> #include <QFileInfo> #include <QMimeDatabase> class PeruseConfig::Private { public: Private() : config("peruserc") {}; KConfig config; }; PeruseConfig::PeruseConfig(QObject* parent) : QObject(parent) , d(new Private) { QStringList locations = d->config.group("general").readEntry("book locations", QStringList()); if(locations.count() < 1) { locations = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation); locations << QStandardPaths::standardLocations(QStandardPaths::DownloadLocation); locations << QString("%1/comics").arg(QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).first()); d->config.group("general").writeEntry("book locations", locations); d->config.sync(); } } PeruseConfig::~PeruseConfig() { delete d; } void PeruseConfig::bookOpened(QString path) { QStringList recent = recentlyOpened(); int i = recent.indexOf(path); if(i == 0) { // This is already first, don't do work we don't need to, because that's just silly return; } else { recent.removeAll(path); recent.prepend(path); } d->config.group("general").writeEntry("recently opened", recent); d->config.sync(); emit recentlyOpenedChanged(); } QStringList PeruseConfig::recentlyOpened() const { QStringList recent = d->config.group("general").readEntry("recently opened", QStringList()); QStringList actualRecent; while(recent.count() > 0) { QString current = recent.takeFirst(); if(QFile::exists(current)) { actualRecent.append(current); } } return actualRecent; } void PeruseConfig::addBookLocation(const QString& location) { if(location.startsWith("file://")) { #ifdef Q_OS_WIN QString newLocation = location.mid(8); #else QString newLocation = location.mid(7); #endif QStringList locations = bookLocations(); // First, get rid of all the entries which start with the newly added location, because that's silly QStringList newLocations; bool alreadyInThere = false; Q_FOREACH(QString entry, locations) { if(!entry.startsWith(newLocation)) { newLocations.append(entry); } if(newLocation.startsWith(entry)) { alreadyInThere = true; } } if(alreadyInThere) { // Don't be silly, don't add a new location if it's already covered by something more high level... emit showMessage("Attempted to add a new location to the list of search folders which is a sub-folder to something already in the list."); return; } newLocations.append(newLocation); d->config.group("general").writeEntry("book locations", newLocations); d->config.sync(); emit bookLocationsChanged(); } } void PeruseConfig::removeBookLocation(const QString& location) { QStringList locations = bookLocations(); locations.removeAll(location); d->config.group("general").writeEntry("book locations", locations); d->config.sync(); QTimer::singleShot(100, this, SIGNAL(bookLocationsChanged())); } QStringList PeruseConfig::bookLocations() const { QStringList locations = d->config.group("general").readEntry("book locations", QStringList()); return locations; } QString PeruseConfig::newstuffLocation() const { const QStringList locations = KNSCore::Engine::configSearchLocations(); QString knsrc; for (const QString& location : locations) { knsrc = QString::fromLocal8Bit("%1/peruse.knsrc").arg(location); if (QFile(knsrc).exists()) { break; } } if(qEnvironmentVariableIsSet("APPDIR")) { // Because appimage install happens into /app/usr... knsrc = knsrc.prepend("/usr").prepend(qgetenv("APPDIR")); } return knsrc; } QString PeruseConfig::homeDir() const { return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first(); } void PeruseConfig::setFilesystemProperty(QString fileName, QString propertyName, QString value) { KFileMetaData::UserMetaData data(fileName); if (propertyName == "rating") { data.setRating(value.toInt()); } else if (propertyName == "tags") { data.setTags(value.split(",")); } else if (propertyName == "comment") { data.setUserComment(value); } else { data.setAttribute(QString("peruse.").append(propertyName), value); } } QString PeruseConfig::getFilesystemProperty(QString fileName, QString propertyName) { QString value; KFileMetaData::UserMetaData data(fileName); if (propertyName == "rating") { value = QString::number(data.rating()); } else if (propertyName == "tags") { value = data.tags().join(","); } else if (propertyName == "comment") { value = data.userComment(); } else if (propertyName == "bytes") { value = QString::number(QFileInfo(fileName).size()); } else if (propertyName == "mimetype") { QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(fileName); value = mime.name(); } else { value = data.attribute(QString("peruse.").append(propertyName)); } return value; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Adrian Draghici <[email protected]> // // Self #include "EditGroundOverlayDialog.h" #include "ui_EditGroundOverlayDialog.h" // Qt #include <QFileDialog> #include <QMessageBox> #include <QPushButton> namespace Marble { class EditGroundOverlayDialog::Private : public Ui::UiEditGroundOverlayDialog { public: GeoDataGroundOverlay *m_overlay; TextureLayer *m_textureLayer; Private( GeoDataGroundOverlay *overlay, TextureLayer *textureLayer ); ~Private(); void updateCoordinates(); }; EditGroundOverlayDialog::Private::Private( GeoDataGroundOverlay *overlay, TextureLayer *textureLayer ) : Ui::UiEditGroundOverlayDialog(), m_overlay( overlay ), m_textureLayer( textureLayer ) { // nothing to do } EditGroundOverlayDialog::Private::~Private() { // nothing to do } EditGroundOverlayDialog::EditGroundOverlayDialog( GeoDataGroundOverlay *overlay, TextureLayer *textureLayer, QWidget *parent ) : QDialog( parent ), d( new Private( overlay, textureLayer ) ) { d->setupUi( this ); d->m_header->setName( overlay->name() ); d->m_header->setIconLink( overlay->absoluteIconFile() ); d->m_header->setPositionVisible(false); d->m_description->setText( overlay->description() ); d->m_north->setRange( -90, 90 ); d->m_south->setRange( -90, 90 ); d->m_west->setRange( -180, 180 ); d->m_east->setRange( -180, 180 ); d->m_rotation->setRange( -360, 360 ); GeoDataLatLonBox latLonBox = overlay->latLonBox(); d->m_north->setValue( latLonBox.north( GeoDataCoordinates::Degree ) ); d->m_south->setValue( latLonBox.south( GeoDataCoordinates::Degree ) ); d->m_west->setValue( latLonBox.west( GeoDataCoordinates::Degree ) ); d->m_east->setValue( latLonBox.east( GeoDataCoordinates::Degree ) ); d->m_rotation->setValue( latLonBox.rotation( GeoDataCoordinates::Degree ) ); connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(pressed()), this, SLOT(checkFields()) ); connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(clicked()), this, SLOT(updateGroundOverlay()) ); connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(clicked()), this, SLOT(setGroundOverlayUpdated()) ); connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(clicked()), d->m_textureLayer, SLOT(reset()) ); } EditGroundOverlayDialog::~EditGroundOverlayDialog() { delete d; } void EditGroundOverlayDialog::updateGroundOverlay() { d->m_overlay->setName( d->m_header->name() ); d->m_overlay->setIconFile( d->m_header->iconLink() ); d->m_overlay->setDescription( d->m_description->toPlainText() ); d->m_overlay->latLonBox().setBoundaries( d->m_north->value(), d->m_south->value(), d->m_east->value(), d->m_west->value(), GeoDataCoordinates::Degree ); d->m_overlay->latLonBox().setRotation( d->m_rotation->value(), GeoDataCoordinates::Degree ); } void EditGroundOverlayDialog::setGroundOverlayUpdated() { emit groundOverlayUpdated( d->m_overlay ); } void EditGroundOverlayDialog::checkFields() { if ( d->m_header->name().isEmpty() ) { QMessageBox::warning( this, tr( "No name specified" ), tr( "Please specify a name for this ground overlay." ) ); } else if ( d->m_header->iconLink().isEmpty() ) { QMessageBox::warning( this, tr( "No image specified" ), tr( "Please specify an image file." ) ); } else if( !QFileInfo( d->m_header->iconLink() ).exists() ) { QMessageBox::warning( this, tr( "Invalid image path" ), tr( "Please specify a valid path for the image file." ) ); } else { accept(); } } } #include "EditGroundOverlayDialog.moc" <commit_msg>REVIEW: 122977<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Adrian Draghici <[email protected]> // // Self #include "EditGroundOverlayDialog.h" #include "ui_EditGroundOverlayDialog.h" // Qt #include <QFileDialog> #include <QMessageBox> #include <QPushButton> namespace Marble { class EditGroundOverlayDialog::Private : public Ui::UiEditGroundOverlayDialog { public: GeoDataGroundOverlay *m_overlay; TextureLayer *m_textureLayer; Private( GeoDataGroundOverlay *overlay, TextureLayer *textureLayer ); ~Private(); void updateCoordinates(); }; EditGroundOverlayDialog::Private::Private( GeoDataGroundOverlay *overlay, TextureLayer *textureLayer ) : Ui::UiEditGroundOverlayDialog(), m_overlay( overlay ), m_textureLayer( textureLayer ) { // nothing to do } EditGroundOverlayDialog::Private::~Private() { // nothing to do } EditGroundOverlayDialog::EditGroundOverlayDialog( GeoDataGroundOverlay *overlay, TextureLayer *textureLayer, QWidget *parent ) : QDialog( parent ), d( new Private( overlay, textureLayer ) ) { d->setupUi( this ); d->m_header->setName( overlay->name() ); d->m_header->setIconLink( overlay->absoluteIconFile() ); d->m_header->setPositionVisible(false); d->m_description->setText( overlay->description() ); d->m_north->setRange( -90, 90 ); d->m_south->setRange( -90, 90 ); d->m_west->setRange( -180, 180 ); d->m_east->setRange( -180, 180 ); d->m_rotation->setRange( -360, 360 ); GeoDataLatLonBox latLonBox = overlay->latLonBox(); d->m_north->setValue( latLonBox.north( GeoDataCoordinates::Degree ) ); d->m_south->setValue( latLonBox.south( GeoDataCoordinates::Degree ) ); d->m_west->setValue( latLonBox.west( GeoDataCoordinates::Degree ) ); d->m_east->setValue( latLonBox.east( GeoDataCoordinates::Degree ) ); d->m_rotation->setValue( latLonBox.rotation( GeoDataCoordinates::Degree ) ); connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(pressed()), this, SLOT(checkFields()) ); } EditGroundOverlayDialog::~EditGroundOverlayDialog() { delete d; } void EditGroundOverlayDialog::updateGroundOverlay() { d->m_overlay->setName( d->m_header->name() ); d->m_overlay->setIconFile( d->m_header->iconLink() ); d->m_overlay->setDescription( d->m_description->toPlainText() ); d->m_overlay->latLonBox().setBoundaries( d->m_north->value(), d->m_south->value(), d->m_east->value(), d->m_west->value(), GeoDataCoordinates::Degree ); d->m_overlay->latLonBox().setRotation( d->m_rotation->value(), GeoDataCoordinates::Degree ); } void EditGroundOverlayDialog::setGroundOverlayUpdated() { emit groundOverlayUpdated( d->m_overlay ); } void EditGroundOverlayDialog::checkFields() { if ( d->m_header->name().isEmpty() ) { QMessageBox::warning( this, tr( "No name specified" ), tr( "Please specify a name for this ground overlay." ) ); } else if ( d->m_header->iconLink().isEmpty() ) { QMessageBox::warning( this, tr( "No image specified" ), tr( "Please specify an image file." ) ); } else if( !QFileInfo( d->m_header->iconLink() ).exists() ) { QMessageBox::warning( this, tr( "Invalid image path" ), tr( "Please specify a valid path for the image file." ) ); } else { this->updateGroundOverlay(); this->setGroundOverlayUpdated(); d->m_textureLayer->reset(); accept(); } } } #include "EditGroundOverlayDialog.moc" <|endoftext|>
<commit_before>#include "catch/catch.hpp" #include "RaZ/Math/Matrix.hpp" #include "RaZ/Math/Vector.hpp" namespace { // Declaring vectors to be tested const Raz::Vec3f vec31({ 3.18f, 42.f, 0.874f }); const Raz::Vec3f vec32({ 541.41f, 47.25f, 6.321f }); const Raz::Vec4f vec41({ 84.47f, 2.f, 0.001f, 847.12f }); const Raz::Vec4f vec42({ 13.01f, 0.15f, 84.8f, 72.f }); // Near-equality floating point check template <typename T> bool compareFloatingPoint(T val1, T val2) { static_assert(std::is_floating_point<T>::value, "Error: Values' type must be floating point."); return std::abs(val1 - val2) <= std::numeric_limits<T>::epsilon() * std::max({ static_cast<T>(1), std::abs(val1), std::abs(val2) }); } } // namespace TEST_CASE("Vector near-equality") { REQUIRE_FALSE(vec31 == vec32); const Raz::Vec3f baseVec(1.f); Raz::Vec3f compVec = baseVec; REQUIRE(baseVec[0] == compVec[0]); // Copied, strict equality REQUIRE(baseVec[1] == compVec[1]); REQUIRE(baseVec[2] == compVec[2]); compVec += 0.0000001f; // Adding a tiny offset REQUIRE_FALSE(baseVec[0] == compVec[0]); // Values not strictly equal REQUIRE_FALSE(baseVec[1] == compVec[1]); REQUIRE_FALSE(baseVec[2] == compVec[2]); REQUIRE(compareFloatingPoint(baseVec[0], compVec[0])); // Near-equality components check REQUIRE(compareFloatingPoint(baseVec[1], compVec[1])); REQUIRE(compareFloatingPoint(baseVec[2], compVec[2])); REQUIRE(baseVec == compVec); // Vector::operator== does a near-equality check on floating point types } TEST_CASE("Vector/scalar operations") { REQUIRE((vec31 * 3.f) == Raz::Vec3f({ 9.54f, 126.f, 2.622f })); REQUIRE((vec31 * 4.152f) == Raz::Vec3f({ 13.20336f, 174.384f, 3.628848f })); REQUIRE((vec41 * 7.5f) == Raz::Vec4f({ 633.525f, 15.f, 0.0075f, 6353.4f })); REQUIRE((vec41 * 8.0002f) == Raz::Vec4f({ 675.776894f, 16.0004f, 0.0080002f, 6777.129424f })); REQUIRE((vec41 * 0.f) == Raz::Vec4f({ 0.f, 0.f, 0.f, 0.f })); } TEST_CASE("Vector/vector operations") { REQUIRE((vec31 - vec31) == Raz::Vec3f(0.f)); REQUIRE((vec31 * vec32) == Raz::Vec3f({ 1721.6838f, 1984.5f, 5.524554f })); REQUIRE(vec31.dot(vec31) == vec31.computeSquaredLength()); REQUIRE(compareFloatingPoint(vec31.dot(vec31), 1774.876276f)); REQUIRE(compareFloatingPoint(vec31.dot(vec32), 3711.708354f)); REQUIRE(vec31.dot(vec32) == vec32.dot(vec31)); // A · B == B · A REQUIRE(vec31.cross(vec32) == Raz::Vec3f({ 224.1855f, 453.09156f, -22588.965f })); REQUIRE(vec31.cross(vec32) == -vec32.cross(vec31)); // A x B == -(B x A) } TEST_CASE("Vector/matrix operation") { const Raz::Mat3f mat3({{ 4.12f, 25.1f, 30.7842f }, { 3.04f, 5.f, -64.5f }, { -1.f, -7.54f, 8.41f }}); REQUIRE((vec31 * mat3) == Raz::Vec3f({ 139.9076f, 283.22804f, -2603.755904f })); REQUIRE((vec32 * mat3) == Raz::Vec3f({ 2367.9282f, 13'777.980'66f, 13'672.408'332f })); const Raz::Mat4f mat4({{ -3.2f, 53.032f, 832.451f, 74.2f }, { 10.01f, 3.15f, -91.41f, 187.46f }, { -6.f, -7.78f, 90.f, 38.f }, { 123.f, -74.8f, 147.0001f, 748.6f }}); REQUIRE((vec41 * mat4) == Raz::Vec4f({ 103'945.47f, -58878.67074f, 194'661.130'682f, 640'796.664f })); REQUIRE((vec42 * mat4) == Raz::Vec4f({ 8307.0695f, -5354.92518f, 29032.48321f, 58115.061f })); REQUIRE((vec31 * Raz::Mat3f::identity()) == vec31); REQUIRE((vec41 * Raz::Mat4f::identity()) == vec41); } TEST_CASE("Vector manipulations") { REQUIRE(compareFloatingPoint(vec31.normalize().computeLength(), 1.f)); REQUIRE(compareFloatingPoint(vec41.normalize().computeSquaredLength(), 1.f)); REQUIRE(compareFloatingPoint(Raz::Vec3f({ 0.f, 1.f, 0.f }).computeLength(), 1.f)); // Testing Vector::reflect(): // // IncVec N Reflection // \ | / // \ | / // \ | / //________\|/___________ // REQUIRE(Raz::Vec3f({ 1.f, -1.f, 0.f }).reflect(Raz::Vec3f({ 0.f, 1.f, 0.f })) == Raz::Vec3f({ 1.f, 1.f, 0.f })); REQUIRE(vec31.reflect(Raz::Vec3f({ 0.f, 1.f, 0.f })) == Raz::Vec3f({ 3.18f, -42.f, 0.874f })); REQUIRE(vec31.reflect(vec32) == Raz::Vec3f({ -4'019'108.859'878'28f, -350'714.439'453f, -46'922.543'011'268f })); } <commit_msg>[Update] Vector tests now make use of FloatUtils::checkNearEquality()<commit_after>#include "catch/catch.hpp" #include "RaZ/Math/Matrix.hpp" #include "RaZ/Math/Vector.hpp" #include "RaZ/Utils/FloatUtils.hpp" namespace { // Declaring vectors to be tested const Raz::Vec3f vec31({ 3.18f, 42.f, 0.874f }); const Raz::Vec3f vec32({ 541.41f, 47.25f, 6.321f }); const Raz::Vec4f vec41({ 84.47f, 2.f, 0.001f, 847.12f }); const Raz::Vec4f vec42({ 13.01f, 0.15f, 84.8f, 72.f }); } // namespace TEST_CASE("Vector near-equality") { REQUIRE_FALSE(vec31 == vec32); const Raz::Vec3f baseVec(1.f); Raz::Vec3f compVec = baseVec; REQUIRE(baseVec[0] == compVec[0]); // Copied, strict equality REQUIRE(baseVec[1] == compVec[1]); REQUIRE(baseVec[2] == compVec[2]); compVec += 0.0000001f; // Adding a tiny offset REQUIRE_FALSE(baseVec[0] == compVec[0]); // Values not strictly equal REQUIRE_FALSE(baseVec[1] == compVec[1]); REQUIRE_FALSE(baseVec[2] == compVec[2]); REQUIRE(Raz::FloatUtils::checkNearEquality(baseVec[0], compVec[0])); // Near-equality components check REQUIRE(Raz::FloatUtils::checkNearEquality(baseVec[1], compVec[1])); REQUIRE(Raz::FloatUtils::checkNearEquality(baseVec[2], compVec[2])); REQUIRE(baseVec == compVec); // Vector::operator== does a near-equality check on floating point types } TEST_CASE("Vector/scalar operations") { REQUIRE((vec31 * 3.f) == Raz::Vec3f({ 9.54f, 126.f, 2.622f })); REQUIRE((vec31 * 4.152f) == Raz::Vec3f({ 13.20336f, 174.384f, 3.628848f })); REQUIRE((vec41 * 7.5f) == Raz::Vec4f({ 633.525f, 15.f, 0.0075f, 6353.4f })); REQUIRE((vec41 * 8.0002f) == Raz::Vec4f({ 675.776894f, 16.0004f, 0.0080002f, 6777.129424f })); REQUIRE((vec41 * 0.f) == Raz::Vec4f({ 0.f, 0.f, 0.f, 0.f })); } TEST_CASE("Vector/vector operations") { REQUIRE((vec31 - vec31) == Raz::Vec3f(0.f)); REQUIRE((vec31 * vec32) == Raz::Vec3f({ 1721.6838f, 1984.5f, 5.524554f })); REQUIRE(vec31.dot(vec31) == vec31.computeSquaredLength()); REQUIRE(Raz::FloatUtils::checkNearEquality(vec31.dot(vec31), 1774.876276f)); REQUIRE(Raz::FloatUtils::checkNearEquality(vec31.dot(vec32), 3711.708354f)); REQUIRE(vec31.dot(vec32) == vec32.dot(vec31)); // A · B == B · A REQUIRE(vec31.cross(vec32) == Raz::Vec3f({ 224.1855f, 453.09156f, -22588.965f })); REQUIRE(vec31.cross(vec32) == -vec32.cross(vec31)); // A x B == -(B x A) } TEST_CASE("Vector/matrix operation") { const Raz::Mat3f mat3({{ 4.12f, 25.1f, 30.7842f }, { 3.04f, 5.f, -64.5f }, { -1.f, -7.54f, 8.41f }}); REQUIRE((vec31 * mat3) == Raz::Vec3f({ 139.9076f, 283.22804f, -2603.755904f })); REQUIRE((vec32 * mat3) == Raz::Vec3f({ 2367.9282f, 13'777.980'66f, 13'672.408'332f })); const Raz::Mat4f mat4({{ -3.2f, 53.032f, 832.451f, 74.2f }, { 10.01f, 3.15f, -91.41f, 187.46f }, { -6.f, -7.78f, 90.f, 38.f }, { 123.f, -74.8f, 147.0001f, 748.6f }}); REQUIRE((vec41 * mat4) == Raz::Vec4f({ 103'945.47f, -58878.67074f, 194'661.130'682f, 640'796.664f })); REQUIRE((vec42 * mat4) == Raz::Vec4f({ 8307.0695f, -5354.92518f, 29032.48321f, 58115.061f })); REQUIRE((vec31 * Raz::Mat3f::identity()) == vec31); REQUIRE((vec41 * Raz::Mat4f::identity()) == vec41); } TEST_CASE("Vector manipulations") { REQUIRE(Raz::FloatUtils::checkNearEquality(vec31.normalize().computeLength(), 1.f)); REQUIRE(Raz::FloatUtils::checkNearEquality(vec41.normalize().computeSquaredLength(), 1.f)); REQUIRE(Raz::FloatUtils::checkNearEquality(Raz::Vec3f({ 0.f, 1.f, 0.f }).computeLength(), 1.f)); // Testing Vector::reflect(): // // IncVec N Reflection // \ | / // \ | / // \ | / //________\|/___________ // REQUIRE(Raz::Vec3f({ 1.f, -1.f, 0.f }).reflect(Raz::Vec3f({ 0.f, 1.f, 0.f })) == Raz::Vec3f({ 1.f, 1.f, 0.f })); REQUIRE(vec31.reflect(Raz::Vec3f({ 0.f, 1.f, 0.f })) == Raz::Vec3f({ 3.18f, -42.f, 0.874f })); REQUIRE(vec31.reflect(vec32) == Raz::Vec3f({ -4'019'108.859'878'28f, -350'714.439'453f, -46'922.543'011'268f })); } <|endoftext|>
<commit_before>//===- NativeFormatting.cpp - Low level formatting helpers -------*- C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/NativeFormatting.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Format.h" using namespace llvm; template<typename T, std::size_t N> static int format_to_buffer(T Value, char (&Buffer)[N]) { char *EndPtr = std::end(Buffer); char *CurPtr = EndPtr; do { *--CurPtr = '0' + char(Value % 10); Value /= 10; } while (Value); return EndPtr - CurPtr; } static void writeWithCommas(raw_ostream &S, ArrayRef<char> Buffer) { assert(!Buffer.empty()); ArrayRef<char> ThisGroup; int InitialDigits = ((Buffer.size() - 1) % 3) + 1; ThisGroup = Buffer.take_front(InitialDigits); S.write(ThisGroup.data(), ThisGroup.size()); Buffer = Buffer.drop_front(InitialDigits); assert(Buffer.size() % 3 == 0); while (!Buffer.empty()) { S << ','; ThisGroup = Buffer.take_front(3); S.write(ThisGroup.data(), 3); Buffer = Buffer.drop_front(3); } } template <typename T> static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative) { static_assert(std::is_unsigned<T>::value, "Value is not unsigned!"); char NumberBuffer[128]; std::memset(NumberBuffer, '0', sizeof(NumberBuffer)); size_t Len = 0; Len = format_to_buffer(N, NumberBuffer); if (IsNegative) S << '-'; if (Len < MinDigits && Style != IntegerStyle::Number) { for (size_t I = Len; I < MinDigits; ++I) S << '0'; } if (Style == IntegerStyle::Number) { writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len)); } else { S.write(std::end(NumberBuffer) - Len, Len); } } template <typename T> static void write_unsigned(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative = false) { // Output using 32-bit div/mod if possible. if (N == static_cast<uint32_t>(N)) write_unsigned_impl(S, static_cast<uint32_t>(N), MinDigits, Style, IsNegative); else write_unsigned_impl(S, N, MinDigits, Style, IsNegative); } template <typename T> static void write_signed(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style) { static_assert(std::is_signed<T>::value, "Value is not signed!"); using UnsignedT = typename std::make_unsigned<T>::type; if (N >= 0) { write_unsigned(S, static_cast<UnsignedT>(N), MinDigits, Style); return; } UnsignedT UN = -(UnsignedT)N; write_unsigned(S, UN, MinDigits, Style, true); } void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style) { write_unsigned(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits, IntegerStyle Style) { write_signed(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits, IntegerStyle Style) { write_unsigned(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits, IntegerStyle Style) { write_signed(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits, IntegerStyle Style) { write_unsigned(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits, IntegerStyle Style) { write_signed(S, N, MinDigits, Style); } void llvm::write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, Optional<size_t> Width) { const size_t kMaxWidth = 128u; size_t W = std::min(kMaxWidth, Width.getValueOr(0u)); unsigned Nibbles = (64 - countLeadingZeros(N) + 3) / 4; bool Prefix = (Style == HexPrintStyle::PrefixLower || Style == HexPrintStyle::PrefixUpper); bool Upper = (Style == HexPrintStyle::Upper || Style == HexPrintStyle::PrefixUpper); unsigned PrefixChars = Prefix ? 2 : 0; unsigned NumChars = std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars); char NumberBuffer[kMaxWidth]; ::memset(NumberBuffer, '0', llvm::array_lengthof(NumberBuffer)); if (Prefix) NumberBuffer[1] = 'x'; char *EndPtr = NumberBuffer + NumChars; char *CurPtr = EndPtr; while (N) { unsigned char x = static_cast<unsigned char>(N) % 16; *--CurPtr = hexdigit(x, !Upper); N /= 16; } S.write(NumberBuffer, NumChars); } void llvm::write_double(raw_ostream &S, double N, FloatStyle Style, Optional<size_t> Precision) { size_t Prec = Precision.getValueOr(getDefaultPrecision(Style)); if (std::isnan(N)) { S << "nan"; return; } else if (std::isinf(N)) { S << "INF"; return; } char Letter; if (Style == FloatStyle::Exponent) Letter = 'e'; else if (Style == FloatStyle::ExponentUpper) Letter = 'E'; else Letter = 'f'; SmallString<8> Spec; llvm::raw_svector_ostream Out(Spec); Out << "%." << Prec << Letter; if (Style == FloatStyle::Exponent || Style == FloatStyle::ExponentUpper) { #ifdef _WIN32 // On MSVCRT and compatible, output of %e is incompatible to Posix // by default. Number of exponent digits should be at least 2. "%+03d" // FIXME: Implement our formatter to here or Support/Format.h! #if defined(__MINGW32__) // FIXME: It should be generic to C++11. if (N == 0.0 && std::signbit(N)) { char NegativeZero[] = "-0.000000e+00"; if (Style == FloatStyle::ExponentUpper) NegativeZero[strlen(NegativeZero) - 4] = 'E'; S << NegativeZero; return; } #else int fpcl = _fpclass(N); // negative zero if (fpcl == _FPCLASS_NZ) { char NegativeZero[] = "-0.000000e+00"; if (Style == FloatStyle::ExponentUpper) NegativeZero[strlen(NegativeZero) - 4] = 'E'; S << NegativeZero; return; } #endif char buf[32]; unsigned len; len = format(Spec.c_str(), N).snprint(buf, sizeof(buf)); if (len <= sizeof(buf) - 2) { if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') && buf[len - 3] == '0') { int cs = buf[len - 4]; if (cs == '+' || cs == '-') { int c1 = buf[len - 2]; int c0 = buf[len - 1]; if (isdigit(static_cast<unsigned char>(c1)) && isdigit(static_cast<unsigned char>(c0))) { // Trim leading '0': "...e+012" -> "...e+12\0" buf[len - 3] = c1; buf[len - 2] = c0; buf[--len] = 0; } } } S << buf; return; } #endif } if (Style == FloatStyle::Percent) N *= 100.0; char Buf[32]; unsigned Len; Len = format(Spec.c_str(), N).snprint(Buf, sizeof(Buf)); if (Style == FloatStyle::Percent) ++Len; S << Buf; if (Style == FloatStyle::Percent) S << '%'; } bool llvm::isPrefixedHexStyle(HexPrintStyle S) { return (S == HexPrintStyle::PrefixLower || S == HexPrintStyle::PrefixUpper); } size_t llvm::getDefaultPrecision(FloatStyle Style) { switch (Style) { case FloatStyle::Exponent: case FloatStyle::ExponentUpper: return 6; // Number of decimal places. case FloatStyle::Fixed: case FloatStyle::Percent: return 2; // Number of decimal places. } LLVM_BUILTIN_UNREACHABLE; } <commit_msg>Remove dead variable Len.<commit_after>//===- NativeFormatting.cpp - Low level formatting helpers -------*- C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/NativeFormatting.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Format.h" using namespace llvm; template<typename T, std::size_t N> static int format_to_buffer(T Value, char (&Buffer)[N]) { char *EndPtr = std::end(Buffer); char *CurPtr = EndPtr; do { *--CurPtr = '0' + char(Value % 10); Value /= 10; } while (Value); return EndPtr - CurPtr; } static void writeWithCommas(raw_ostream &S, ArrayRef<char> Buffer) { assert(!Buffer.empty()); ArrayRef<char> ThisGroup; int InitialDigits = ((Buffer.size() - 1) % 3) + 1; ThisGroup = Buffer.take_front(InitialDigits); S.write(ThisGroup.data(), ThisGroup.size()); Buffer = Buffer.drop_front(InitialDigits); assert(Buffer.size() % 3 == 0); while (!Buffer.empty()) { S << ','; ThisGroup = Buffer.take_front(3); S.write(ThisGroup.data(), 3); Buffer = Buffer.drop_front(3); } } template <typename T> static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative) { static_assert(std::is_unsigned<T>::value, "Value is not unsigned!"); char NumberBuffer[128]; std::memset(NumberBuffer, '0', sizeof(NumberBuffer)); size_t Len = 0; Len = format_to_buffer(N, NumberBuffer); if (IsNegative) S << '-'; if (Len < MinDigits && Style != IntegerStyle::Number) { for (size_t I = Len; I < MinDigits; ++I) S << '0'; } if (Style == IntegerStyle::Number) { writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len)); } else { S.write(std::end(NumberBuffer) - Len, Len); } } template <typename T> static void write_unsigned(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative = false) { // Output using 32-bit div/mod if possible. if (N == static_cast<uint32_t>(N)) write_unsigned_impl(S, static_cast<uint32_t>(N), MinDigits, Style, IsNegative); else write_unsigned_impl(S, N, MinDigits, Style, IsNegative); } template <typename T> static void write_signed(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style) { static_assert(std::is_signed<T>::value, "Value is not signed!"); using UnsignedT = typename std::make_unsigned<T>::type; if (N >= 0) { write_unsigned(S, static_cast<UnsignedT>(N), MinDigits, Style); return; } UnsignedT UN = -(UnsignedT)N; write_unsigned(S, UN, MinDigits, Style, true); } void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style) { write_unsigned(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits, IntegerStyle Style) { write_signed(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits, IntegerStyle Style) { write_unsigned(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits, IntegerStyle Style) { write_signed(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits, IntegerStyle Style) { write_unsigned(S, N, MinDigits, Style); } void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits, IntegerStyle Style) { write_signed(S, N, MinDigits, Style); } void llvm::write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, Optional<size_t> Width) { const size_t kMaxWidth = 128u; size_t W = std::min(kMaxWidth, Width.getValueOr(0u)); unsigned Nibbles = (64 - countLeadingZeros(N) + 3) / 4; bool Prefix = (Style == HexPrintStyle::PrefixLower || Style == HexPrintStyle::PrefixUpper); bool Upper = (Style == HexPrintStyle::Upper || Style == HexPrintStyle::PrefixUpper); unsigned PrefixChars = Prefix ? 2 : 0; unsigned NumChars = std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars); char NumberBuffer[kMaxWidth]; ::memset(NumberBuffer, '0', llvm::array_lengthof(NumberBuffer)); if (Prefix) NumberBuffer[1] = 'x'; char *EndPtr = NumberBuffer + NumChars; char *CurPtr = EndPtr; while (N) { unsigned char x = static_cast<unsigned char>(N) % 16; *--CurPtr = hexdigit(x, !Upper); N /= 16; } S.write(NumberBuffer, NumChars); } void llvm::write_double(raw_ostream &S, double N, FloatStyle Style, Optional<size_t> Precision) { size_t Prec = Precision.getValueOr(getDefaultPrecision(Style)); if (std::isnan(N)) { S << "nan"; return; } else if (std::isinf(N)) { S << "INF"; return; } char Letter; if (Style == FloatStyle::Exponent) Letter = 'e'; else if (Style == FloatStyle::ExponentUpper) Letter = 'E'; else Letter = 'f'; SmallString<8> Spec; llvm::raw_svector_ostream Out(Spec); Out << "%." << Prec << Letter; if (Style == FloatStyle::Exponent || Style == FloatStyle::ExponentUpper) { #ifdef _WIN32 // On MSVCRT and compatible, output of %e is incompatible to Posix // by default. Number of exponent digits should be at least 2. "%+03d" // FIXME: Implement our formatter to here or Support/Format.h! #if defined(__MINGW32__) // FIXME: It should be generic to C++11. if (N == 0.0 && std::signbit(N)) { char NegativeZero[] = "-0.000000e+00"; if (Style == FloatStyle::ExponentUpper) NegativeZero[strlen(NegativeZero) - 4] = 'E'; S << NegativeZero; return; } #else int fpcl = _fpclass(N); // negative zero if (fpcl == _FPCLASS_NZ) { char NegativeZero[] = "-0.000000e+00"; if (Style == FloatStyle::ExponentUpper) NegativeZero[strlen(NegativeZero) - 4] = 'E'; S << NegativeZero; return; } #endif char buf[32]; unsigned len; len = format(Spec.c_str(), N).snprint(buf, sizeof(buf)); if (len <= sizeof(buf) - 2) { if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') && buf[len - 3] == '0') { int cs = buf[len - 4]; if (cs == '+' || cs == '-') { int c1 = buf[len - 2]; int c0 = buf[len - 1]; if (isdigit(static_cast<unsigned char>(c1)) && isdigit(static_cast<unsigned char>(c0))) { // Trim leading '0': "...e+012" -> "...e+12\0" buf[len - 3] = c1; buf[len - 2] = c0; buf[--len] = 0; } } } S << buf; return; } #endif } if (Style == FloatStyle::Percent) N *= 100.0; char Buf[32]; format(Spec.c_str(), N).snprint(Buf, sizeof(Buf)); S << Buf; if (Style == FloatStyle::Percent) S << '%'; } bool llvm::isPrefixedHexStyle(HexPrintStyle S) { return (S == HexPrintStyle::PrefixLower || S == HexPrintStyle::PrefixUpper); } size_t llvm::getDefaultPrecision(FloatStyle Style) { switch (Style) { case FloatStyle::Exponent: case FloatStyle::ExponentUpper: return 6; // Number of decimal places. case FloatStyle::Fixed: case FloatStyle::Percent: return 2; // Number of decimal places. } LLVM_BUILTIN_UNREACHABLE; } <|endoftext|>
<commit_before>//===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the Darwin specific implementation of the MappedFile // concept. // //===----------------------------------------------------------------------===// // Include the generic unix implementation #include "../Unix/MappedFile.cpp" // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab <commit_msg>Allow this file to compile on Darwin.<commit_after>//===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the Darwin specific implementation of the MappedFile // concept. // //===----------------------------------------------------------------------===// // Include the generic unix implementation #include <sys/stat.h> #include "../Unix/MappedFile.cpp" // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab <|endoftext|>
<commit_before>//===- BuildTree.cpp ------------------------------------------*- C++ -*-=====// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Tooling/Syntax/BuildTree.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/Stmt.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TokenKinds.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Syntax/Nodes.h" #include "clang/Tooling/Syntax/Tokens.h" #include "clang/Tooling/Syntax/Tree.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_ostream.h" #include <map> using namespace clang; /// A helper class for constructing the syntax tree while traversing a clang /// AST. /// /// At each point of the traversal we maintain a list of pending nodes. /// Initially all tokens are added as pending nodes. When processing a clang AST /// node, the clients need to: /// - create a corresponding syntax node, /// - assign roles to all pending child nodes with 'markChild' and /// 'markChildToken', /// - replace the child nodes with the new syntax node in the pending list /// with 'foldNode'. /// /// Note that all children are expected to be processed when building a node. /// /// Call finalize() to finish building the tree and consume the root node. class syntax::TreeBuilder { public: TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) {} llvm::BumpPtrAllocator &allocator() { return Arena.allocator(); } /// Populate children for \p New node, assuming it covers tokens from \p /// Range. void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New); /// Set role for a token starting at \p Loc. void markChildToken(SourceLocation Loc, tok::TokenKind Kind, NodeRole R); /// Finish building the tree and consume the root node. syntax::TranslationUnit *finalize() && { auto Tokens = Arena.tokenBuffer().expandedTokens(); // Build the root of the tree, consuming all the children. Pending.foldChildren(Tokens, new (Arena.allocator()) syntax::TranslationUnit); return cast<syntax::TranslationUnit>(std::move(Pending).finalize()); } /// getRange() finds the syntax tokens corresponding to the passed source /// locations. /// \p First is the start position of the first token and \p Last is the start /// position of the last token. llvm::ArrayRef<syntax::Token> getRange(SourceLocation First, SourceLocation Last) const { assert(First.isValid()); assert(Last.isValid()); assert(First == Last || Arena.sourceManager().isBeforeInTranslationUnit(First, Last)); return llvm::makeArrayRef(findToken(First), std::next(findToken(Last))); } llvm::ArrayRef<syntax::Token> getRange(const Decl *D) const { return getRange(D->getBeginLoc(), D->getEndLoc()); } llvm::ArrayRef<syntax::Token> getRange(const Stmt *S) const { return getRange(S->getBeginLoc(), S->getEndLoc()); } private: /// Finds a token starting at \p L. The token must exist. const syntax::Token *findToken(SourceLocation L) const; /// A collection of trees covering the input tokens. /// When created, each tree corresponds to a single token in the file. /// Clients call 'foldChildren' to attach one or more subtrees to a parent /// node and update the list of trees accordingly. /// /// Ensures that added nodes properly nest and cover the whole token stream. struct Forest { Forest(syntax::Arena &A) { // FIXME: do not add 'eof' to the tree. // Create all leaf nodes. for (auto &T : A.tokenBuffer().expandedTokens()) Trees.insert(Trees.end(), {&T, NodeAndRole{new (A.allocator()) syntax::Leaf(&T)}}); } void assignRole(llvm::ArrayRef<syntax::Token> Range, syntax::NodeRole Role) { assert(!Range.empty()); auto It = Trees.lower_bound(Range.begin()); assert(It != Trees.end() && "no node found"); assert(It->first == Range.begin() && "no child with the specified range"); assert(std::next(It) == Trees.end() || std::next(It)->first == Range.end() && "no child with the specified range"); It->second.Role = Role; } /// Add \p Node to the forest and fill its children nodes based on the \p /// NodeRange. void foldChildren(llvm::ArrayRef<syntax::Token> NodeTokens, syntax::Tree *Node) { assert(!NodeTokens.empty()); assert(Node->firstChild() == nullptr && "node already has children"); auto *FirstToken = NodeTokens.begin(); auto BeginChildren = Trees.lower_bound(FirstToken); assert(BeginChildren != Trees.end() && BeginChildren->first == FirstToken && "fold crosses boundaries of existing subtrees"); auto EndChildren = Trees.lower_bound(NodeTokens.end()); assert(EndChildren == Trees.end() || EndChildren->first == NodeTokens.end() && "fold crosses boundaries of existing subtrees"); // (!) we need to go in reverse order, because we can only prepend. for (auto It = EndChildren; It != BeginChildren; --It) Node->prependChildLowLevel(std::prev(It)->second.Node, std::prev(It)->second.Role); Trees.erase(BeginChildren, EndChildren); Trees.insert({FirstToken, NodeAndRole(Node)}); } // EXPECTS: all tokens were consumed and are owned by a single root node. syntax::Node *finalize() && { assert(Trees.size() == 1); auto *Root = Trees.begin()->second.Node; Trees = {}; return Root; } std::string str(const syntax::Arena &A) const { std::string R; for (auto It = Trees.begin(); It != Trees.end(); ++It) { unsigned CoveredTokens = It != Trees.end() ? (std::next(It)->first - It->first) : A.tokenBuffer().expandedTokens().end() - It->first; R += llvm::formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second.Node->kind(), It->first->text(A.sourceManager()), CoveredTokens); R += It->second.Node->dump(A); } return R; } private: /// A with a role that should be assigned to it when adding to a parent. struct NodeAndRole { explicit NodeAndRole(syntax::Node *Node) : Node(Node), Role(NodeRoleUnknown) {} syntax::Node *Node; NodeRole Role; }; /// Maps from the start token to a subtree starting at that token. /// FIXME: storing the end tokens is redundant. /// FIXME: the key of a map is redundant, it is also stored in NodeForRange. std::map<const syntax::Token *, NodeAndRole> Trees; }; /// For debugging purposes. std::string str() { return Pending.str(Arena); } syntax::Arena &Arena; Forest Pending; }; namespace { class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> { public: explicit BuildTreeVisitor(ASTContext &Ctx, syntax::TreeBuilder &Builder) : Builder(Builder), LangOpts(Ctx.getLangOpts()) {} bool shouldTraversePostOrder() const { return true; } bool TraverseDecl(Decl *D) { if (!D || isa<TranslationUnitDecl>(D)) return RecursiveASTVisitor::TraverseDecl(D); if (!llvm::isa<TranslationUnitDecl>(D->getDeclContext())) return true; // Only build top-level decls for now, do not recurse. return RecursiveASTVisitor::TraverseDecl(D); } bool VisitDecl(Decl *D) { assert(llvm::isa<TranslationUnitDecl>(D->getDeclContext()) && "expected a top-level decl"); assert(!D->isImplicit()); Builder.foldNode(Builder.getRange(D), new (allocator()) syntax::TopLevelDeclaration()); return true; } bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) { // (!) we do not want to call VisitDecl(), the declaration for translation // unit is built by finalize(). return true; } bool WalkUpFromCompoundStmt(CompoundStmt *S) { using Roles = syntax::CompoundStatement::Roles; Builder.markChildToken(S->getLBracLoc(), tok::l_brace, Roles::lbrace); Builder.markChildToken(S->getRBracLoc(), tok::r_brace, Roles::rbrace); Builder.foldNode(Builder.getRange(S), new (allocator()) syntax::CompoundStatement); return true; } private: /// A small helper to save some typing. llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); } syntax::TreeBuilder &Builder; const LangOptions &LangOpts; }; } // namespace void syntax::TreeBuilder::foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New) { Pending.foldChildren(Range, New); } void syntax::TreeBuilder::markChildToken(SourceLocation Loc, tok::TokenKind Kind, NodeRole Role) { if (Loc.isInvalid()) return; Pending.assignRole(*findToken(Loc), Role); } const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const { auto Tokens = Arena.tokenBuffer().expandedTokens(); auto &SM = Arena.sourceManager(); auto It = llvm::partition_point(Tokens, [&](const syntax::Token &T) { return SM.isBeforeInTranslationUnit(T.location(), L); }); assert(It != Tokens.end()); assert(It->location() == L); return &*It; } syntax::TranslationUnit * syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) { TreeBuilder Builder(A); BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext()); return std::move(Builder).finalize(); } <commit_msg>Add parentheses to silence warnings.<commit_after>//===- BuildTree.cpp ------------------------------------------*- C++ -*-=====// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Tooling/Syntax/BuildTree.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/Stmt.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TokenKinds.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Syntax/Nodes.h" #include "clang/Tooling/Syntax/Tokens.h" #include "clang/Tooling/Syntax/Tree.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_ostream.h" #include <map> using namespace clang; /// A helper class for constructing the syntax tree while traversing a clang /// AST. /// /// At each point of the traversal we maintain a list of pending nodes. /// Initially all tokens are added as pending nodes. When processing a clang AST /// node, the clients need to: /// - create a corresponding syntax node, /// - assign roles to all pending child nodes with 'markChild' and /// 'markChildToken', /// - replace the child nodes with the new syntax node in the pending list /// with 'foldNode'. /// /// Note that all children are expected to be processed when building a node. /// /// Call finalize() to finish building the tree and consume the root node. class syntax::TreeBuilder { public: TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) {} llvm::BumpPtrAllocator &allocator() { return Arena.allocator(); } /// Populate children for \p New node, assuming it covers tokens from \p /// Range. void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New); /// Set role for a token starting at \p Loc. void markChildToken(SourceLocation Loc, tok::TokenKind Kind, NodeRole R); /// Finish building the tree and consume the root node. syntax::TranslationUnit *finalize() && { auto Tokens = Arena.tokenBuffer().expandedTokens(); // Build the root of the tree, consuming all the children. Pending.foldChildren(Tokens, new (Arena.allocator()) syntax::TranslationUnit); return cast<syntax::TranslationUnit>(std::move(Pending).finalize()); } /// getRange() finds the syntax tokens corresponding to the passed source /// locations. /// \p First is the start position of the first token and \p Last is the start /// position of the last token. llvm::ArrayRef<syntax::Token> getRange(SourceLocation First, SourceLocation Last) const { assert(First.isValid()); assert(Last.isValid()); assert(First == Last || Arena.sourceManager().isBeforeInTranslationUnit(First, Last)); return llvm::makeArrayRef(findToken(First), std::next(findToken(Last))); } llvm::ArrayRef<syntax::Token> getRange(const Decl *D) const { return getRange(D->getBeginLoc(), D->getEndLoc()); } llvm::ArrayRef<syntax::Token> getRange(const Stmt *S) const { return getRange(S->getBeginLoc(), S->getEndLoc()); } private: /// Finds a token starting at \p L. The token must exist. const syntax::Token *findToken(SourceLocation L) const; /// A collection of trees covering the input tokens. /// When created, each tree corresponds to a single token in the file. /// Clients call 'foldChildren' to attach one or more subtrees to a parent /// node and update the list of trees accordingly. /// /// Ensures that added nodes properly nest and cover the whole token stream. struct Forest { Forest(syntax::Arena &A) { // FIXME: do not add 'eof' to the tree. // Create all leaf nodes. for (auto &T : A.tokenBuffer().expandedTokens()) Trees.insert(Trees.end(), {&T, NodeAndRole{new (A.allocator()) syntax::Leaf(&T)}}); } void assignRole(llvm::ArrayRef<syntax::Token> Range, syntax::NodeRole Role) { assert(!Range.empty()); auto It = Trees.lower_bound(Range.begin()); assert(It != Trees.end() && "no node found"); assert(It->first == Range.begin() && "no child with the specified range"); assert((std::next(It) == Trees.end() || std::next(It)->first == Range.end()) && "no child with the specified range"); It->second.Role = Role; } /// Add \p Node to the forest and fill its children nodes based on the \p /// NodeRange. void foldChildren(llvm::ArrayRef<syntax::Token> NodeTokens, syntax::Tree *Node) { assert(!NodeTokens.empty()); assert(Node->firstChild() == nullptr && "node already has children"); auto *FirstToken = NodeTokens.begin(); auto BeginChildren = Trees.lower_bound(FirstToken); assert(BeginChildren != Trees.end() && BeginChildren->first == FirstToken && "fold crosses boundaries of existing subtrees"); auto EndChildren = Trees.lower_bound(NodeTokens.end()); assert((EndChildren == Trees.end() || EndChildren->first == NodeTokens.end()) && "fold crosses boundaries of existing subtrees"); // (!) we need to go in reverse order, because we can only prepend. for (auto It = EndChildren; It != BeginChildren; --It) Node->prependChildLowLevel(std::prev(It)->second.Node, std::prev(It)->second.Role); Trees.erase(BeginChildren, EndChildren); Trees.insert({FirstToken, NodeAndRole(Node)}); } // EXPECTS: all tokens were consumed and are owned by a single root node. syntax::Node *finalize() && { assert(Trees.size() == 1); auto *Root = Trees.begin()->second.Node; Trees = {}; return Root; } std::string str(const syntax::Arena &A) const { std::string R; for (auto It = Trees.begin(); It != Trees.end(); ++It) { unsigned CoveredTokens = It != Trees.end() ? (std::next(It)->first - It->first) : A.tokenBuffer().expandedTokens().end() - It->first; R += llvm::formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second.Node->kind(), It->first->text(A.sourceManager()), CoveredTokens); R += It->second.Node->dump(A); } return R; } private: /// A with a role that should be assigned to it when adding to a parent. struct NodeAndRole { explicit NodeAndRole(syntax::Node *Node) : Node(Node), Role(NodeRoleUnknown) {} syntax::Node *Node; NodeRole Role; }; /// Maps from the start token to a subtree starting at that token. /// FIXME: storing the end tokens is redundant. /// FIXME: the key of a map is redundant, it is also stored in NodeForRange. std::map<const syntax::Token *, NodeAndRole> Trees; }; /// For debugging purposes. std::string str() { return Pending.str(Arena); } syntax::Arena &Arena; Forest Pending; }; namespace { class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> { public: explicit BuildTreeVisitor(ASTContext &Ctx, syntax::TreeBuilder &Builder) : Builder(Builder), LangOpts(Ctx.getLangOpts()) {} bool shouldTraversePostOrder() const { return true; } bool TraverseDecl(Decl *D) { if (!D || isa<TranslationUnitDecl>(D)) return RecursiveASTVisitor::TraverseDecl(D); if (!llvm::isa<TranslationUnitDecl>(D->getDeclContext())) return true; // Only build top-level decls for now, do not recurse. return RecursiveASTVisitor::TraverseDecl(D); } bool VisitDecl(Decl *D) { assert(llvm::isa<TranslationUnitDecl>(D->getDeclContext()) && "expected a top-level decl"); assert(!D->isImplicit()); Builder.foldNode(Builder.getRange(D), new (allocator()) syntax::TopLevelDeclaration()); return true; } bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) { // (!) we do not want to call VisitDecl(), the declaration for translation // unit is built by finalize(). return true; } bool WalkUpFromCompoundStmt(CompoundStmt *S) { using Roles = syntax::CompoundStatement::Roles; Builder.markChildToken(S->getLBracLoc(), tok::l_brace, Roles::lbrace); Builder.markChildToken(S->getRBracLoc(), tok::r_brace, Roles::rbrace); Builder.foldNode(Builder.getRange(S), new (allocator()) syntax::CompoundStatement); return true; } private: /// A small helper to save some typing. llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); } syntax::TreeBuilder &Builder; const LangOptions &LangOpts; }; } // namespace void syntax::TreeBuilder::foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New) { Pending.foldChildren(Range, New); } void syntax::TreeBuilder::markChildToken(SourceLocation Loc, tok::TokenKind Kind, NodeRole Role) { if (Loc.isInvalid()) return; Pending.assignRole(*findToken(Loc), Role); } const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const { auto Tokens = Arena.tokenBuffer().expandedTokens(); auto &SM = Arena.sourceManager(); auto It = llvm::partition_point(Tokens, [&](const syntax::Token &T) { return SM.isBeforeInTranslationUnit(T.location(), L); }); assert(It != Tokens.end()); assert(It->location() == L); return &*It; } syntax::TranslationUnit * syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) { TreeBuilder Builder(A); BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext()); return std::move(Builder).finalize(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "tests/test-utils.hh" #include <seastar/core/thread.hh> #include "cell_locking.hh" #include "mutation.hh" #include "schema_builder.hh" static schema_ptr make_schema() { return schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("s1", bytes_type, column_kind::static_column) .with_column("s2", bytes_type, column_kind::static_column) .with_column("s3", bytes_type, column_kind::static_column) .with_column("r1", bytes_type) .with_column("r2", bytes_type) .with_column("r3", bytes_type) .build(); } static schema_ptr make_alternative_schema() { return schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("s0", bytes_type, column_kind::static_column) .with_column("s1", bytes_type, column_kind::static_column) .with_column("s2.5", bytes_type, column_kind::static_column) .with_column("s3", bytes_type, column_kind::static_column) .with_column("r0", bytes_type) .with_column("r1", bytes_type) .with_column("r2.5", bytes_type) .with_column("r3", bytes_type) .build(); } static schema_ptr make_schema_disjoint_with_others() { return schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("s8", bytes_type, column_kind::static_column) .with_column("s9", bytes_type, column_kind::static_column) .with_column("r8", bytes_type) .with_column("r9", bytes_type) .build(); } static data_value empty_value = data_value(to_bytes("")); static db::timeout_clock::time_point no_timeout { db::timeout_clock::duration(std::numeric_limits<db::timeout_clock::duration::rep>::max()) }; static auto make_row(const sstring& key, std::initializer_list<sstring> cells) { return std::pair<sstring, std::initializer_list<sstring>>(key, cells); } static mutation make_mutation(schema_ptr s, const sstring& pk, std::initializer_list<sstring> static_cells, std::initializer_list<std::pair<sstring, std::initializer_list<sstring>>> clustering_cells) { auto m = mutation(s, partition_key::from_single_value(*s, to_bytes(pk))); for (auto&& c : static_cells) { m.set_static_cell(to_bytes(c), empty_value, api::new_timestamp()); } for (auto&& r : clustering_cells) { auto ck = clustering_key::from_single_value(*s, to_bytes(r.first)); for (auto&& c : r.second) { m.set_clustered_cell(ck, to_bytes(c), empty_value, api::new_timestamp()); } } return m; } SEASTAR_TEST_CASE(test_simple_locking_cells) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m = make_mutation(s, "0", { "s1", "s3" }, { make_row("one", { "r1", "r2" }), make_row("two", { "r2", "r3" }), }); auto l1 = cl.lock_cells(m.decorated_key(), partition_cells_range(m.partition()), no_timeout).get0(); auto f2 = cl.lock_cells(m.decorated_key(), partition_cells_range(m.partition()), no_timeout); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); destroy(f2.get0()); }); } SEASTAR_TEST_CASE(test_disjoint_mutations) { return seastar::async([&] { auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s1" }, { make_row("one", { "r1", "r2" }), make_row("two", { "r3" }), }); auto m2 = make_mutation(s, "0", { "s2" }, { make_row("two", { "r1", "r2" }), make_row("one", { "r3" }), }); auto m3 = mutation(s, partition_key::from_single_value(*s, to_bytes("1"))); m3.partition() = mutation_partition(*s, m1.partition()); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); auto l2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout).get0(); auto l3 = cl.lock_cells(m3.decorated_key(), partition_cells_range(m3.partition()), no_timeout).get0(); }); } SEASTAR_TEST_CASE(test_single_cell_overlap) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s1" }, { make_row("one", { "r1", "r2" }), make_row("two", { "r3" }), }); auto m2 = make_mutation(s, "0", { "s1" }, { make_row("two", { "r1", "r2" }), make_row("one", { "r3" }), }); auto m3 = make_mutation(s, "0", { "s2" }, { make_row("two", { "r1" }), make_row("one", { "r2", "r3" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); auto f2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); auto l2 = f2.get0(); auto f3 = cl.lock_cells(m3.decorated_key(), partition_cells_range(m3.partition()), no_timeout); BOOST_REQUIRE(!f3.available()); destroy(std::move(l2)); auto l3 = f3.get0(); }); } SEASTAR_TEST_CASE(test_schema_change) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s1 = make_schema(); auto s2 = make_alternative_schema(); cell_locker_stats cl_stats; cell_locker cl(s1, cl_stats); auto m1 = make_mutation(s1, "0", { "s1", "s2", "s3"}, { make_row("one", { "r1", "r2", "r3" }), }); // disjoint with m1 auto m2 = make_mutation(s2, "0", { "s0", "s2.5"}, { make_row("one", { "r0", "r2.5" }), make_row("two", { "r1", "r3" }), }); // overlaps with m1 auto m3 = make_mutation(s2, "0", { "s1" }, { make_row("one", { "r1", "r3" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); destroy(std::move(m1)); destroy(std::move(s1)); cl.set_schema(s2); auto l2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout).get0(); auto f3 = cl.lock_cells(m3.decorated_key(), partition_cells_range(m3.partition()), no_timeout); BOOST_REQUIRE(!f3.available()); destroy(std::move(l1)); auto l3 = f3.get0(); auto s3 = make_schema_disjoint_with_others(); cl.set_schema(s3); auto m4 = make_mutation(s3, "0", { "s8", "s9"}, { make_row("one", { "r8", "r9" }), make_row("two", { "r8", "r9" }), }); auto l4 = cl.lock_cells(m4.decorated_key(), partition_cells_range(m4.partition()), no_timeout).get0(); }); } SEASTAR_TEST_CASE(test_timed_out) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s1", "s2", "s3"}, { make_row("one", { "r2", "r3" }), }); auto m2 = make_mutation(s, "0", { }, { make_row("one", { "r1", "r2" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); auto timeout = saturating_subtract(db::timeout_clock::now(), std::chrono::hours(1)); BOOST_REQUIRE_THROW(cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), timeout).get0(), timed_out_error); auto f2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); auto l2 = f2.get0(); }); } SEASTAR_TEST_CASE(test_locker_stats) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s2", "s3" }, { make_row("one", { "r1", "r2" }), }); auto m2 = make_mutation(s, "0", { "s1", "s3" }, { make_row("one", { "r2", "r3" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); BOOST_REQUIRE_EQUAL(cl_stats.lock_acquisitions, 4); BOOST_REQUIRE_EQUAL(cl_stats.operations_waiting_for_lock, 0); auto f2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout); BOOST_REQUIRE_EQUAL(cl_stats.lock_acquisitions, 5); BOOST_REQUIRE_EQUAL(cl_stats.operations_waiting_for_lock, 1); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); destroy(f2.get0()); BOOST_REQUIRE_EQUAL(cl_stats.lock_acquisitions, 8); BOOST_REQUIRE_EQUAL(cl_stats.operations_waiting_for_lock, 0); }); } <commit_msg>tests/cell_locker_test: Prevent timeout underflow<commit_after>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "tests/test-utils.hh" #include <seastar/core/thread.hh> #include "cell_locking.hh" #include "mutation.hh" #include "schema_builder.hh" using namespace std::literals::chrono_literals; static schema_ptr make_schema() { return schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("s1", bytes_type, column_kind::static_column) .with_column("s2", bytes_type, column_kind::static_column) .with_column("s3", bytes_type, column_kind::static_column) .with_column("r1", bytes_type) .with_column("r2", bytes_type) .with_column("r3", bytes_type) .build(); } static schema_ptr make_alternative_schema() { return schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("s0", bytes_type, column_kind::static_column) .with_column("s1", bytes_type, column_kind::static_column) .with_column("s2.5", bytes_type, column_kind::static_column) .with_column("s3", bytes_type, column_kind::static_column) .with_column("r0", bytes_type) .with_column("r1", bytes_type) .with_column("r2.5", bytes_type) .with_column("r3", bytes_type) .build(); } static schema_ptr make_schema_disjoint_with_others() { return schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("s8", bytes_type, column_kind::static_column) .with_column("s9", bytes_type, column_kind::static_column) .with_column("r8", bytes_type) .with_column("r9", bytes_type) .build(); } static data_value empty_value = data_value(to_bytes("")); static db::timeout_clock::time_point no_timeout { db::timeout_clock::duration(std::numeric_limits<db::timeout_clock::duration::rep>::max()) }; static auto make_row(const sstring& key, std::initializer_list<sstring> cells) { return std::pair<sstring, std::initializer_list<sstring>>(key, cells); } static mutation make_mutation(schema_ptr s, const sstring& pk, std::initializer_list<sstring> static_cells, std::initializer_list<std::pair<sstring, std::initializer_list<sstring>>> clustering_cells) { auto m = mutation(s, partition_key::from_single_value(*s, to_bytes(pk))); for (auto&& c : static_cells) { m.set_static_cell(to_bytes(c), empty_value, api::new_timestamp()); } for (auto&& r : clustering_cells) { auto ck = clustering_key::from_single_value(*s, to_bytes(r.first)); for (auto&& c : r.second) { m.set_clustered_cell(ck, to_bytes(c), empty_value, api::new_timestamp()); } } return m; } SEASTAR_TEST_CASE(test_simple_locking_cells) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m = make_mutation(s, "0", { "s1", "s3" }, { make_row("one", { "r1", "r2" }), make_row("two", { "r2", "r3" }), }); auto l1 = cl.lock_cells(m.decorated_key(), partition_cells_range(m.partition()), no_timeout).get0(); auto f2 = cl.lock_cells(m.decorated_key(), partition_cells_range(m.partition()), no_timeout); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); destroy(f2.get0()); }); } SEASTAR_TEST_CASE(test_disjoint_mutations) { return seastar::async([&] { auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s1" }, { make_row("one", { "r1", "r2" }), make_row("two", { "r3" }), }); auto m2 = make_mutation(s, "0", { "s2" }, { make_row("two", { "r1", "r2" }), make_row("one", { "r3" }), }); auto m3 = mutation(s, partition_key::from_single_value(*s, to_bytes("1"))); m3.partition() = mutation_partition(*s, m1.partition()); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); auto l2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout).get0(); auto l3 = cl.lock_cells(m3.decorated_key(), partition_cells_range(m3.partition()), no_timeout).get0(); }); } SEASTAR_TEST_CASE(test_single_cell_overlap) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s1" }, { make_row("one", { "r1", "r2" }), make_row("two", { "r3" }), }); auto m2 = make_mutation(s, "0", { "s1" }, { make_row("two", { "r1", "r2" }), make_row("one", { "r3" }), }); auto m3 = make_mutation(s, "0", { "s2" }, { make_row("two", { "r1" }), make_row("one", { "r2", "r3" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); auto f2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); auto l2 = f2.get0(); auto f3 = cl.lock_cells(m3.decorated_key(), partition_cells_range(m3.partition()), no_timeout); BOOST_REQUIRE(!f3.available()); destroy(std::move(l2)); auto l3 = f3.get0(); }); } SEASTAR_TEST_CASE(test_schema_change) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s1 = make_schema(); auto s2 = make_alternative_schema(); cell_locker_stats cl_stats; cell_locker cl(s1, cl_stats); auto m1 = make_mutation(s1, "0", { "s1", "s2", "s3"}, { make_row("one", { "r1", "r2", "r3" }), }); // disjoint with m1 auto m2 = make_mutation(s2, "0", { "s0", "s2.5"}, { make_row("one", { "r0", "r2.5" }), make_row("two", { "r1", "r3" }), }); // overlaps with m1 auto m3 = make_mutation(s2, "0", { "s1" }, { make_row("one", { "r1", "r3" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); destroy(std::move(m1)); destroy(std::move(s1)); cl.set_schema(s2); auto l2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout).get0(); auto f3 = cl.lock_cells(m3.decorated_key(), partition_cells_range(m3.partition()), no_timeout); BOOST_REQUIRE(!f3.available()); destroy(std::move(l1)); auto l3 = f3.get0(); auto s3 = make_schema_disjoint_with_others(); cl.set_schema(s3); auto m4 = make_mutation(s3, "0", { "s8", "s9"}, { make_row("one", { "r8", "r9" }), make_row("two", { "r8", "r9" }), }); auto l4 = cl.lock_cells(m4.decorated_key(), partition_cells_range(m4.partition()), no_timeout).get0(); }); } SEASTAR_TEST_CASE(test_timed_out) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s1", "s2", "s3"}, { make_row("one", { "r2", "r3" }), }); auto m2 = make_mutation(s, "0", { }, { make_row("one", { "r1", "r2" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); auto timeout = db::timeout_clock::now(); forward_jump_clocks(1h); BOOST_REQUIRE_THROW(cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), timeout).get0(), timed_out_error); auto f2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); auto l2 = f2.get0(); }); } SEASTAR_TEST_CASE(test_locker_stats) { return seastar::async([&] { auto destroy = [] (auto) { }; auto s = make_schema(); cell_locker_stats cl_stats; cell_locker cl(s, cl_stats); auto m1 = make_mutation(s, "0", { "s2", "s3" }, { make_row("one", { "r1", "r2" }), }); auto m2 = make_mutation(s, "0", { "s1", "s3" }, { make_row("one", { "r2", "r3" }), }); auto l1 = cl.lock_cells(m1.decorated_key(), partition_cells_range(m1.partition()), no_timeout).get0(); BOOST_REQUIRE_EQUAL(cl_stats.lock_acquisitions, 4); BOOST_REQUIRE_EQUAL(cl_stats.operations_waiting_for_lock, 0); auto f2 = cl.lock_cells(m2.decorated_key(), partition_cells_range(m2.partition()), no_timeout); BOOST_REQUIRE_EQUAL(cl_stats.lock_acquisitions, 5); BOOST_REQUIRE_EQUAL(cl_stats.operations_waiting_for_lock, 1); BOOST_REQUIRE(!f2.available()); destroy(std::move(l1)); destroy(f2.get0()); BOOST_REQUIRE_EQUAL(cl_stats.lock_acquisitions, 8); BOOST_REQUIRE_EQUAL(cl_stats.operations_waiting_for_lock, 0); }); } <|endoftext|>
<commit_before>#define SPICA_MLT_RENDERER_EXPORT #include "mlt_renderer.h" #include <algorithm> #include <vector> #include <stack> namespace spica { namespace { struct PrimarySample { int modify_time; double value; PrimarySample() { modify_time = 0; value = rng.randReal(); } }; struct KelemenMLT { private: inline double mutate(const double x) { const double r = rng.randReal(); const double s1 = 1.0 / 512.0; const double s2 = 1.0 / 16.0; const double dx = s1 / (s1 / s2 + abs(2.0 * r - 1.0)) - s1 / (s1 / s2 + 1.0); if (r < 0.5) { const double x1 = x + dx; return (x1 < 1.0) ? x1 : x1 - 1.0; } else { const double x1 = x - dx; return (x1 < 0.0) ? x1 + 1.0 : x1; } } public: int global_time; int large_step; int large_step_time; int used_rand_coords; std::vector<PrimarySample> primary_samples; std::stack<PrimarySample> primary_samples_stack; KelemenMLT() { global_time = large_step = large_step_time = used_rand_coords = 0; primary_samples.resize(128); } void initUsedRandCoords() { used_rand_coords = 0; } inline double nextSample() { if (primary_samples.size() <= used_rand_coords) { primary_samples.resize(primary_samples.size() * 1.5); } if (primary_samples[used_rand_coords].modify_time < global_time) { if (large_step > 0) { primary_samples_stack.push(primary_samples[used_rand_coords]); primary_samples[used_rand_coords].modify_time = global_time; primary_samples[used_rand_coords].value = rng.randReal(); } else { if (primary_samples[used_rand_coords].modify_time < large_step_time) { primary_samples[used_rand_coords].modify_time = large_step_time; primary_samples[used_rand_coords].value = rng.randReal(); } while (primary_samples[used_rand_coords].modify_time < global_time - 1) { primary_samples[used_rand_coords].value = mutate(primary_samples[used_rand_coords].value); primary_samples[used_rand_coords].modify_time++; } primary_samples_stack.push(primary_samples[used_rand_coords]); primary_samples[used_rand_coords].value = mutate(primary_samples[used_rand_coords].value); primary_samples[used_rand_coords].modify_time = global_time; } used_rand_coords++; return primary_samples[used_rand_coords - 1].value; } } }; Color radiance(const Scene& scene, const Ray& ray, const int depth, KelemenMLT& mlt) { Intersection intersection; if (!scene.intersect(ray, intersection)) { return Color(0.0, 0.0, 0.0); } const Primitive* obj_ptr = scene.getObjectPtr(intersection.objectId()); const HitPoint& hitpoint = intersection.hitPoint(); const Vector3 orient_normal = hitpoint.normal().dot(ray.direction()) < 0.0 ? hitpoint.normal() : -hitpoint.normal(); const Color& light_color = obj_ptr->color(); double roulette_probability = std::max(light_color.red(), std::max(light_color.green(), light_color.blue())); if (depth > maxDepth) { if (mlt.nextSample() >= roulette_probability) { return Color(0.0, 0.0, 0.0); } } else { roulette_probability = 1.0; } if (obj_ptr->reftype() == REFLECTION_DIFFUSE) { if (intersection.objectId() != scene.lightId()) { const int shadow_ray = 1; Vector3 direct_light; for (int i = 0; i < shadow_ray; i++) { direct_light = direct_light + direct_radiance_sample(hitpoint.position(), orient_normal, intersection.objectId(), mlt) / shadow_ray; } Vector3 w, u, v; w = orient_normal; if (abs(w.x()) > EPS) { u = Vector3(0.0, 1.0, 0.0).cross(w).normalize(); } else { u = Vector3(1.0, 0.0, 0.0).cross(w).normalize(); } v = w.cross(u); const double r1 = 2.0 * PI * mlt.nextSample(); const double r2 = mlt.nextSample(); const double r2s = sqrt(r2); Vector3 next_dir = (u * cos(r1) * r2s + v * sin(r1) * r2s + w * sqrt(1.0 - r2)).normalize(); const Color next_bounce_color = radiance(scene, Ray(hitpoint.position(), next_dir), depth + 1, mlt); return direct_light + light_color.cwiseMultiply(next_bounce_color) / roulette_probability; } else if (depth == 0) { return obj_ptr->emission(); } else { return Color(0.0, 0.0, 0.0); } } else if (obj_ptr->reftype() == REFLECTION_SPECULAR) { Intersection light_intersect; Ray reflection_ray = Ray(hitpoint.position(), ray.direction() - hitpoint.normal() * 2.0 * hitpoint.normal().dot(ray.direction())); scene.intersect(reflection_ray, light_intersect); Vector3 direct_light; if (light_intersect.objectId() == scene.lightId()) { direct_light = scene.getObjectPtr(scene.lightId())->emission(); } const Color next_bounce_color = radiance(scene, reflection_ray, depth + 1, mlt); return direct_light + obj_ptr->color().cwiseMultiply(next_bounce_color) / roulette_probability; } else if (obj_ptr->reftype() == REFLECTION_REFRACTION) { Intersection light_intersect; Ray reflection_ray = Ray(hitpoint.position(), ray.direction() - hitpoint.normal() * 2.0 * hitpoint.normal().dot(ray.direction())); scene.intersect(reflection_ray, light_intersect); Vector3 direct_light; if (light_intersect.objectId() == scene.lightId()) { direct_light = scene.getObjectPtr(scene.lightId())->emission(); } bool is_incoming = hitpoint.normal().dot(orient_normal) > 0.0; // Snell const double nc = 1.0; const double nt = 1.5; const double nnt = is_incoming ? nc / nt : nt / nc; const double ddn = ray.direction().dot(orient_normal); const double cos2t = 1.0 - nnt * nnt * (1.0 - ddn * ddn); if (cos2t < 0.0) { const Color next_bounce_color = radiance(scene, reflection_ray, depth + 1, mlt); return direct_light + obj_ptr->color().cwiseMultiply(next_bounce_color) / roulette_probability; } Vector3 tdir = (ray.direction() * nnt - hitpoint.normal() * (is_incoming ? 1.0 : -1.0) * (ddn * nnt + sqrt(cos2t))); // Schlick const double a = nt - nc; const double b = nt + nc; const double R0 = (a * a) / (b * b); const double c = 1.0 - (is_incoming ? -ddn : tdir.dot(hitpoint.normal())); const double Re = R0 + (1.0 - R0) * pow(c, 5.0); const double Tr = 1.0 - Re; const double probability = 0.25 + 0.5 * Re; Ray refraction_ray = Ray(hitpoint.position(), tdir); scene.intersect(reflection_ray, light_intersect); Vector3 direct_light_refraction; if (light_intersect.objectId() == scene.lightId()) { direct_light_refraction = scene.getObjectPtr(scene.lightId())->emission(); } if (depth > 2) { if (mlt.nextSample() < probability) { const Color next_bounce_color = radiance(scene, reflection_ray, depth + 1, mlt); return obj_ptr->color().cwiseMultiply(direct_light + Re * next_bounce_color) / (probability * roulette_probability); } else { const Color next_bounce_color = radiance(scene, refraction_ray, depth + 1, mlt); return obj_ptr->color().cwiseMultiply(direct_light_refraction + Tr * next_bounce_color) / ((1.0 - probability) * roulette_probability); } } else { const Color next_bounce_color_reflect = radiance(scene, reflection_ray, depth + 1, mlt); const Color next_bounce_color_refract = radiance(scene, refraction_ray, depth + 1, mlt); const Color next_bounce_color = Re * next_bounce_color_reflect + Tr * next_bounce_color_refract; return obj_ptr->color().cwiseMultiply(direct_light + next_bounce_color) / roulette_probability; } } return Color(0.0, 0.0, 0.0); } } MLTRenderer::MLTRenderer() { } MLTRenderer::~MLTRenderer() { } int MLTRenderer::render(const Scene& scene, const Camera& camera) { } } // namespace spica <commit_msg>Implementing MLT.<commit_after>#define SPICA_MLT_RENDERER_EXPORT #include "mlt_renderer.h" #include <algorithm> #include <vector> #include <stack> namespace spica { namespace { struct PrimarySample { int modify_time; double value; PrimarySample() { modify_time = 0; value = rng.randReal(); } }; struct KelemenMLT { private: inline double mutate(const double x) { const double r = rng.randReal(); const double s1 = 1.0 / 512.0; const double s2 = 1.0 / 16.0; const double dx = s1 / (s1 / s2 + abs(2.0 * r - 1.0)) - s1 / (s1 / s2 + 1.0); if (r < 0.5) { const double x1 = x + dx; return (x1 < 1.0) ? x1 : x1 - 1.0; } else { const double x1 = x - dx; return (x1 < 0.0) ? x1 + 1.0 : x1; } } public: int global_time; int large_step; int large_step_time; int used_rand_coords; std::vector<PrimarySample> primary_samples; std::stack<PrimarySample> primary_samples_stack; KelemenMLT() { global_time = large_step = large_step_time = used_rand_coords = 0; primary_samples.resize(128); } void initUsedRandCoords() { used_rand_coords = 0; } inline double nextSample() { if (primary_samples.size() <= used_rand_coords) { primary_samples.resize(primary_samples.size() * 1.5); } if (primary_samples[used_rand_coords].modify_time < global_time) { if (large_step > 0) { primary_samples_stack.push(primary_samples[used_rand_coords]); primary_samples[used_rand_coords].modify_time = global_time; primary_samples[used_rand_coords].value = rng.randReal(); } else { if (primary_samples[used_rand_coords].modify_time < large_step_time) { primary_samples[used_rand_coords].modify_time = large_step_time; primary_samples[used_rand_coords].value = rng.randReal(); } while (primary_samples[used_rand_coords].modify_time < global_time - 1) { primary_samples[used_rand_coords].value = mutate(primary_samples[used_rand_coords].value); primary_samples[used_rand_coords].modify_time++; } primary_samples_stack.push(primary_samples[used_rand_coords]); primary_samples[used_rand_coords].value = mutate(primary_samples[used_rand_coords].value); primary_samples[used_rand_coords].modify_time = global_time; } used_rand_coords++; return primary_samples[used_rand_coords - 1].value; } } }; Color radiance(const Scene& scene, const Ray& ray, const int depth, KelemenMLT& mlt) { Intersection intersection; if (!scene.intersect(ray, intersection)) { return Color(0.0, 0.0, 0.0); } const Primitive* obj_ptr = scene.getObjectPtr(intersection.objectId()); const HitPoint& hitpoint = intersection.hitPoint(); const Vector3 orient_normal = hitpoint.normal().dot(ray.direction()) < 0.0 ? hitpoint.normal() : -hitpoint.normal(); const Color& light_color = obj_ptr->color(); double roulette_probability = std::max(light_color.red(), std::max(light_color.green(), light_color.blue())); if (depth > maxDepth) { if (mlt.nextSample() >= roulette_probability) { return Color(0.0, 0.0, 0.0); } } else { roulette_probability = 1.0; } if (obj_ptr->reftype() == REFLECTION_DIFFUSE) { if (intersection.objectId() != scene.lightId()) { const int shadow_ray = 1; Vector3 direct_light; for (int i = 0; i < shadow_ray; i++) { direct_light = direct_light + direct_radiance_sample(hitpoint.position(), orient_normal, intersection.objectId(), mlt) / shadow_ray; } Vector3 w, u, v; w = orient_normal; if (abs(w.x()) > EPS) { u = Vector3(0.0, 1.0, 0.0).cross(w).normalize(); } else { u = Vector3(1.0, 0.0, 0.0).cross(w).normalize(); } v = w.cross(u); const double r1 = 2.0 * PI * mlt.nextSample(); const double r2 = mlt.nextSample(); const double r2s = sqrt(r2); Vector3 next_dir = (u * cos(r1) * r2s + v * sin(r1) * r2s + w * sqrt(1.0 - r2)).normalize(); const Color next_bounce_color = radiance(scene, Ray(hitpoint.position(), next_dir), depth + 1, mlt); return direct_light + light_color.cwiseMultiply(next_bounce_color) / roulette_probability; } else if (depth == 0) { return obj_ptr->emission(); } else { return Color(0.0, 0.0, 0.0); } } else if (obj_ptr->reftype() == REFLECTION_SPECULAR) { Intersection light_intersect; Ray reflection_ray = Ray(hitpoint.position(), ray.direction() - hitpoint.normal() * 2.0 * hitpoint.normal().dot(ray.direction())); scene.intersect(reflection_ray, light_intersect); Vector3 direct_light; if (light_intersect.objectId() == scene.lightId()) { direct_light = scene.getObjectPtr(scene.lightId())->emission(); } const Color next_bounce_color = radiance(scene, reflection_ray, depth + 1, mlt); return direct_light + obj_ptr->color().cwiseMultiply(next_bounce_color) / roulette_probability; } else if (obj_ptr->reftype() == REFLECTION_REFRACTION) { Intersection light_intersect; Ray reflection_ray = Ray(hitpoint.position(), ray.direction() - hitpoint.normal() * 2.0 * hitpoint.normal().dot(ray.direction())); scene.intersect(reflection_ray, light_intersect); Vector3 direct_light; if (light_intersect.objectId() == scene.lightId()) { direct_light = scene.getObjectPtr(scene.lightId())->emission(); } bool is_incoming = hitpoint.normal().dot(orient_normal) > 0.0; // Snell const double nc = 1.0; const double nt = 1.5; const double nnt = is_incoming ? nc / nt : nt / nc; const double ddn = ray.direction().dot(orient_normal); const double cos2t = 1.0 - nnt * nnt * (1.0 - ddn * ddn); if (cos2t < 0.0) { const Color next_bounce_color = radiance(scene, reflection_ray, depth + 1, mlt); return direct_light + obj_ptr->color().cwiseMultiply(next_bounce_color) / roulette_probability; } Vector3 tdir = (ray.direction() * nnt - hitpoint.normal() * (is_incoming ? 1.0 : -1.0) * (ddn * nnt + sqrt(cos2t))); // Schlick const double a = nt - nc; const double b = nt + nc; const double R0 = (a * a) / (b * b); const double c = 1.0 - (is_incoming ? -ddn : tdir.dot(hitpoint.normal())); const double Re = R0 + (1.0 - R0) * pow(c, 5.0); const double Tr = 1.0 - Re; const double probability = 0.25 + 0.5 * Re; Ray refraction_ray = Ray(hitpoint.position(), tdir); scene.intersect(reflection_ray, light_intersect); Vector3 direct_light_refraction; if (light_intersect.objectId() == scene.lightId()) { direct_light_refraction = scene.getObjectPtr(scene.lightId())->emission(); } if (depth > 2) { if (mlt.nextSample() < probability) { const Color next_bounce_color = radiance(scene, reflection_ray, depth + 1, mlt); return obj_ptr->color().cwiseMultiply(direct_light + Re * next_bounce_color) / (probability * roulette_probability); } else { const Color next_bounce_color = radiance(scene, refraction_ray, depth + 1, mlt); return obj_ptr->color().cwiseMultiply(direct_light_refraction + Tr * next_bounce_color) / ((1.0 - probability) * roulette_probability); } } else { const Color next_bounce_color_reflect = radiance(scene, reflection_ray, depth + 1, mlt); const Color next_bounce_color_refract = radiance(scene, refraction_ray, depth + 1, mlt); const Color next_bounce_color = Re * next_bounce_color_reflect + Tr * next_bounce_color_refract; return obj_ptr->color().cwiseMultiply(direct_light + next_bounce_color) / roulette_probability; } } return Color(0.0, 0.0, 0.0); } struct PathSample { int x, y; Color F; double weight; PathSample(const int x_ = 0, const int y_ = 0, const Color& F_ = Color(), const double weight_ = 1.0) : x(x_) , y(y_) , F(F_) , weight(weight_) { } }; PathSample generate_new_path(const Ray& camera, const Vector3& cx, const Vector3& cy, const int width, const int height, KelemenMLT& mlt, int x, int y) { double weight = 4.0; if (x < 0) { weight *= width; x = mlt.nextSample() * width; if (x == width) { x = 0; } } if (y < 0) { weight *= height; y = mlt.nextSample() * height; if (y == height) { y = 0; } } int sx = mlt.nextSample() < 0.5 ? 0 : 1; int sy = mlt.nextSample() < 0.5 ? 0 : 1; const double r1 = 2.0 * mlt.nextSample(); const double r2 = 2.0 * mlt.nextSample(); const double dx = r1 < 1.0 ? sqrt(r1) - 1.0 : 1.0 - sqrt(2.0 - r1); const double dy = r2 < 1.0 ? sqrt(r2) - 1.0 : 1.0 - sqrt(2.0 - r2); Vector3 dir = cx * (((sx + 0.5 + dx) / 2.0 + x) / width - 0.5) + cy * (((sy + 0.5 + dy) / 2.0 + y) / height - 0.5) + camera.direction(); const Ray ray = Ray(camera.origin() + camera.direction() * 130.0, dir.normalize()); Color c = radiance(scene, ray, 0, mlt); return PathSample(x, y, c, weight); } } // anonymous namespace MLTRenderer::MLTRenderer() { } MLTRenderer::~MLTRenderer() { } int MLTRenderer::render(const Scene& scene, const Camera& camera) { const int width = camera.imageWidth(); const int height = camera.imageHeight(); const int mlt_num = width * height; // TODO: Revise Image image(width, height); for (int mi = 0; mi < mlt_num; mi++) { KelemenMLT mlt; int seed_path_max = width * height; if (seed_path_max <= 0) { seed_path_max = 1; } std::vector<PathSample> seed_paths(seed_path_max); double sumI = 0.0; mlt.large_step = 1; for (int i = 0; i < seed_path_max; i++) { mlt.initUsedRandCoords(); PathSample smaple = generate_new_path(scene, camera.lens().normal(), cx, cy, width, height, mlt, -1, -1); mlt.global_time++; while (!mlt.primary_samples_stack.empty()) { mlt.primary_samples_stack.pop(); } sumI += luminance(sample.F); seed_paths[i] = sample; } } } } // namespace spica <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* common headers */ #include "common.h" /* interface header */ #include "WinJoystick.h" /* implementation headers */ #include <mmsystem.h> #include "ErrorHandler.h" #include "TextUtils.h" WinJoystick::WinJoystick() { } WinJoystick::~WinJoystick() { } void WinJoystick::initJoystick(const char* joystickName) { inited = false; if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) { return; } if (strlen(joystickName) < 11) { printError("Invalid joystick name."); return; } if (joystickName[10] == '1') JoystickID = JOYSTICKID1; else if (joystickName[10] == '2') JoystickID = JOYSTICKID2; JOYINFO joyInfo; JOYCAPS joyCaps; if ((joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) || (joyGetDevCaps(JoystickID, &joyCaps, sizeof(joyCaps)) != JOYERR_NOERROR)) { printError("Unable to initialize joystick. Perhaps it is not plugged in?"); return; } xMin = (float)joyCaps.wXmin; xMax = (float)joyCaps.wXmax; yMin = (float)joyCaps.wYmin; yMax = (float)joyCaps.wYmax; inited = true; } bool WinJoystick::joystick() const { return inited; } void WinJoystick::getJoy(int& x, int& y) const { if (!inited) return; JOYINFOEX joyInfo; // we're only interested in position joyInfo.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_USEDEADZONE; // check for errors if (joyGetPosEx(JoystickID, &joyInfo) != JOYERR_NOERROR) { printError("Could not get extended info from joystick"); return; } // adjust X and Y to scale x = (joyInfo.dwXpos / xMax) * 2000 - 1000; y = (joyInfo.dwYpos / yMax) * 2000 - 1000; // ballistic x = (x * abs(x)) / 1000; y = (y * abs(y)) / 1000; } unsigned long WinJoystick::getJoyButtons() const { if (!inited) return 0; // FIXME - Should use joyGetPosEx and JOYINFOEX, to get the rest of the buttons, // but wasn't working for me. JOYINFO joyInfo; // check for errors if (joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) { printError("Could not get extended info from joystick"); return 0; } unsigned long retbuts = joyInfo.wButtons; unsigned long buttons = 0; if (retbuts & JOY_BUTTON1) buttons = buttons | 0x00001; if (retbuts & JOY_BUTTON2) buttons = buttons | 0x00002; if (retbuts & JOY_BUTTON3) buttons = buttons | 0x00004; if (retbuts & JOY_BUTTON4) buttons = buttons | 0x00008; /* if (retbuts & JOY_BUTTON5) buttons = buttons | 0x00010; if (retbuts & JOY_BUTTON6) buttons = buttons | 0x00020; if (retbuts & JOY_BUTTON7) buttons = buttons | 0x00040; if (retbuts & JOY_BUTTON8) buttons = buttons | 0x00080; if (retbuts & JOY_BUTTON9) buttons = buttons | 0x00100; if (retbuts & JOY_BUTTON10) buttons = buttons | 0x00200; */ return buttons; } void WinJoystick::getJoyDevices(std::vector<std::string> &list) const { list.clear(); if (joyGetNumDevs() != 0) { // we have at least one joystick driver, get the name of both joystick IDs if they exist. JOYCAPS joyCaps; if (joyGetDevCaps(JOYSTICKID1, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) { list.push_back(string_util::format("Joystick 1 (%s)", joyCaps.szOEMVxD)); } if (joyGetDevCaps(JOYSTICKID2, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) { list.push_back(string_util::format("Joystick 2 (%s)", joyCaps.szOEMVxD)); } } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Make native windows MMSystem joystick use up to ten buttons<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* common headers */ #include "common.h" /* interface header */ #include "WinJoystick.h" /* implementation headers */ #include <mmsystem.h> #include "ErrorHandler.h" #include "TextUtils.h" WinJoystick::WinJoystick() { } WinJoystick::~WinJoystick() { } void WinJoystick::initJoystick(const char* joystickName) { inited = false; if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) { return; } if (strlen(joystickName) < 11) { printError("Invalid joystick name."); return; } if (joystickName[10] == '1') JoystickID = JOYSTICKID1; else if (joystickName[10] == '2') JoystickID = JOYSTICKID2; JOYINFO joyInfo; JOYCAPS joyCaps; if ((joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) || (joyGetDevCaps(JoystickID, &joyCaps, sizeof(joyCaps)) != JOYERR_NOERROR)) { printError("Unable to initialize joystick. Perhaps it is not plugged in?"); return; } xMin = (float)joyCaps.wXmin; xMax = (float)joyCaps.wXmax; yMin = (float)joyCaps.wYmin; yMax = (float)joyCaps.wYmax; inited = true; } bool WinJoystick::joystick() const { return inited; } void WinJoystick::getJoy(int& x, int& y) const { if (!inited) return; JOYINFOEX joyInfo; // we're only interested in position joyInfo.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_USEDEADZONE; joyInfo.dwSize = sizeof(joyInfo); // check for errors if (joyGetPosEx(JoystickID, &joyInfo) != JOYERR_NOERROR) { printError("Could not get extended info from joystick"); return; } // adjust X and Y to scale x = (joyInfo.dwXpos / xMax) * 2000 - 1000; y = (joyInfo.dwYpos / yMax) * 2000 - 1000; // ballistic x = (x * abs(x)) / 1000; y = (y * abs(y)) / 1000; } unsigned long WinJoystick::getJoyButtons() const { if (!inited) return 0; JOYINFOEX joyInfo; // we're only interested in buttons joyInfo.dwFlags = JOY_RETURNBUTTONS; joyInfo.dwSize = sizeof(joyInfo); // check for errors if (joyGetPosEx(JoystickID, &joyInfo) != JOYERR_NOERROR) { printError("Could not get extended info from joystick"); return 0; } unsigned long retbuts = joyInfo.dwButtons; unsigned long buttons = 0; if (retbuts & JOY_BUTTON1) buttons = buttons | 0x00001; if (retbuts & JOY_BUTTON2) buttons = buttons | 0x00002; if (retbuts & JOY_BUTTON3) buttons = buttons | 0x00004; if (retbuts & JOY_BUTTON4) buttons = buttons | 0x00008; if (retbuts & JOY_BUTTON5) buttons = buttons | 0x00010; if (retbuts & JOY_BUTTON6) buttons = buttons | 0x00020; if (retbuts & JOY_BUTTON7) buttons = buttons | 0x00040; if (retbuts & JOY_BUTTON8) buttons = buttons | 0x00080; if (retbuts & JOY_BUTTON9) buttons = buttons | 0x00100; if (retbuts & JOY_BUTTON10) buttons = buttons | 0x00200; return buttons; } void WinJoystick::getJoyDevices(std::vector<std::string> &list) const { list.clear(); if (joyGetNumDevs() != 0) { // we have at least one joystick driver, get the name of both joystick IDs if they exist. JOYCAPS joyCaps; if (joyGetDevCaps(JOYSTICKID1, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) { list.push_back(string_util::format("Joystick 1 (%s)", joyCaps.szOEMVxD)); } if (joyGetDevCaps(JOYSTICKID2, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) { list.push_back(string_util::format("Joystick 2 (%s)", joyCaps.szOEMVxD)); } } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // 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 GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // // Original author of this file is Jan Boelsche ([email protected]). // #include "PluginManager.h" #include "NodeDefinition.h" #include "../base/DlfcnWrapper.h" #include "../base/FileHelper.h" #include "../base/Logger.h" #include "../base/OSHelper.h" #include <iostream> #include <string> using namespace std; using namespace avg; #ifdef _WIN32 #define PATH_DELIMITER ";" #define PLUGIN_EXTENSION ".dll" #else #define PATH_DELIMITER ":" #define PLUGIN_EXTENSION ".so" #endif PluginManager::PluginNotFound::PluginNotFound(const string& sMessage) : Exception(AVG_ERR_FILEIO, sMessage) {} PluginManager::PluginCorrupted::PluginCorrupted(const string& sMessage) : Exception(AVG_ERR_CORRUPT_PLUGIN, sMessage) {} PluginManager& PluginManager::get() { static PluginManager s_Instance; return s_Instance; } PluginManager::PluginManager() { setSearchPath(string("."PATH_DELIMITER) + "./plugin"PATH_DELIMITER + getAvgLibPath() + "plugin"); } void PluginManager::setSearchPath(const string& sNewPath) { m_sCurrentSearchPath = sNewPath; parsePath(m_sCurrentSearchPath); } string PluginManager::getSearchPath() const { return m_sCurrentSearchPath; } boost::python::object PluginManager::loadPlugin(const std::string& sPluginName) { // is it loaded aready? PluginMap::iterator i = m_LoadedPlugins.find(sPluginName); if (i == m_LoadedPlugins.end()) { // no, let's try to load it! string sFullpath = locateSharedObject(sPluginName+PLUGIN_EXTENSION); void *handle = internalLoadPlugin(sFullpath); // add to map of loaded plugins m_LoadedPlugins[sPluginName] = make_pair(handle, 1); } else { // yes, just increase the reference count int referenceCount = i->second.second; ++referenceCount; m_LoadedPlugins[sPluginName] = make_pair(i->second.first, referenceCount); } boost::python::object sysModule(boost::python::handle<>(PyImport_ImportModule("sys"))); return sysModule.attr("modules")[sPluginName]; } string PluginManager::locateSharedObject(const string& sFilename) { vector<string>::iterator i = m_PathComponents.begin(); string sFullpath; while (i != m_PathComponents.end()) { sFullpath = *i + sFilename; if (fileExists(sFullpath)) { return sFullpath; } ++i; } string sMessage = "Unable to locate plugin file '" + sFilename + "'. Was looking in " + m_sCurrentSearchPath; AVG_TRACE(Logger::PLUGIN, sMessage); throw PluginNotFound(sMessage); } string PluginManager::checkDirectory(const string& sDirectory) { string sFixedDirectory; char lastChar = *sDirectory.rbegin(); if (lastChar != '/' && lastChar != '\\') { sFixedDirectory = sDirectory + "/"; } else { sFixedDirectory = sDirectory; } return sFixedDirectory; } void PluginManager::parsePath(const string& sPath) { // break the string into colon separated components // and make sure each component has a trailing slash // warn about non-existing directories m_PathComponents.clear(); string sRemaining = sPath; string::size_type i; do { i = sRemaining.find(PATH_DELIMITER); string sDirectory; if (i == string::npos) { sDirectory = sRemaining; sRemaining = ""; } else { sDirectory = sRemaining.substr(0, i); sRemaining = sRemaining.substr(i+1); } sDirectory = checkDirectory(sDirectory); m_PathComponents.push_back(sDirectory); } while (!sRemaining.empty()); AVG_TRACE(Logger::PLUGIN, "Plugin search path set to '" << sPath << "'"); } void* PluginManager::internalLoadPlugin(const string& sFullpath) { void *handle = dlopen(sFullpath.c_str(), RTLD_LOCAL | RTLD_NOW); if (!handle) { string sMessage(dlerror()); AVG_TRACE(Logger::PLUGIN, "Could not load plugin. dlopen failed with message '" << sMessage << "'"); throw PluginCorrupted(sMessage); } try { registerPlugin(handle); } catch(PluginCorrupted& e) { dlclose(handle); throw e; } AVG_TRACE(Logger::PLUGIN, "Loaded plugin '" << sFullpath << "'"); return handle; } void PluginManager::registerPlugin(void* handle) { typedef void (*RegisterPluginPtr)(); RegisterPluginPtr registerPlugin = reinterpret_cast<RegisterPluginPtr>(dlsym(handle, "registerPlugin")); if (registerPlugin) { registerPlugin(); } else { AVG_TRACE(Logger::PLUGIN, "No plugin registration function detected"); throw PluginCorrupted("No plugin registration function detected"); } } <commit_msg>Fixed default plugin search path on linux.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // 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 GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // // Original author of this file is Jan Boelsche ([email protected]). // #include "PluginManager.h" #include "NodeDefinition.h" #include "../base/DlfcnWrapper.h" #include "../base/FileHelper.h" #include "../base/Logger.h" #include "../base/OSHelper.h" #include <iostream> #include <string> using namespace std; using namespace avg; #ifdef _WIN32 #define PATH_DELIMITER ";" #define PLUGIN_EXTENSION ".dll" #else #define PATH_DELIMITER ":" #define PLUGIN_EXTENSION ".so" #endif PluginManager::PluginNotFound::PluginNotFound(const string& sMessage) : Exception(AVG_ERR_FILEIO, sMessage) {} PluginManager::PluginCorrupted::PluginCorrupted(const string& sMessage) : Exception(AVG_ERR_CORRUPT_PLUGIN, sMessage) {} PluginManager& PluginManager::get() { static PluginManager s_Instance; return s_Instance; } PluginManager::PluginManager() { setSearchPath(string("."PATH_DELIMITER) + "./plugin"PATH_DELIMITER + getPath(getAvgLibPath()) + "plugin"); } void PluginManager::setSearchPath(const string& sNewPath) { m_sCurrentSearchPath = sNewPath; parsePath(m_sCurrentSearchPath); } string PluginManager::getSearchPath() const { return m_sCurrentSearchPath; } boost::python::object PluginManager::loadPlugin(const std::string& sPluginName) { // is it loaded aready? PluginMap::iterator i = m_LoadedPlugins.find(sPluginName); if (i == m_LoadedPlugins.end()) { // no, let's try to load it! string sFullpath = locateSharedObject(sPluginName+PLUGIN_EXTENSION); void *handle = internalLoadPlugin(sFullpath); // add to map of loaded plugins m_LoadedPlugins[sPluginName] = make_pair(handle, 1); } else { // yes, just increase the reference count int referenceCount = i->second.second; ++referenceCount; m_LoadedPlugins[sPluginName] = make_pair(i->second.first, referenceCount); } boost::python::object sysModule(boost::python::handle<>(PyImport_ImportModule("sys"))); return sysModule.attr("modules")[sPluginName]; } string PluginManager::locateSharedObject(const string& sFilename) { vector<string>::iterator i = m_PathComponents.begin(); string sFullpath; while (i != m_PathComponents.end()) { sFullpath = *i + sFilename; if (fileExists(sFullpath)) { return sFullpath; } ++i; } string sMessage = "Unable to locate plugin file '" + sFilename + "'. Was looking in " + m_sCurrentSearchPath; AVG_TRACE(Logger::PLUGIN, sMessage); throw PluginNotFound(sMessage); } string PluginManager::checkDirectory(const string& sDirectory) { string sFixedDirectory; char lastChar = *sDirectory.rbegin(); if (lastChar != '/' && lastChar != '\\') { sFixedDirectory = sDirectory + "/"; } else { sFixedDirectory = sDirectory; } return sFixedDirectory; } void PluginManager::parsePath(const string& sPath) { // break the string into colon separated components // and make sure each component has a trailing slash // warn about non-existing directories m_PathComponents.clear(); string sRemaining = sPath; string::size_type i; do { i = sRemaining.find(PATH_DELIMITER); string sDirectory; if (i == string::npos) { sDirectory = sRemaining; sRemaining = ""; } else { sDirectory = sRemaining.substr(0, i); sRemaining = sRemaining.substr(i+1); } sDirectory = checkDirectory(sDirectory); m_PathComponents.push_back(sDirectory); } while (!sRemaining.empty()); AVG_TRACE(Logger::PLUGIN, "Plugin search path set to '" << sPath << "'"); } void* PluginManager::internalLoadPlugin(const string& sFullpath) { void *handle = dlopen(sFullpath.c_str(), RTLD_LOCAL | RTLD_NOW); if (!handle) { string sMessage(dlerror()); AVG_TRACE(Logger::PLUGIN, "Could not load plugin. dlopen failed with message '" << sMessage << "'"); throw PluginCorrupted(sMessage); } try { registerPlugin(handle); } catch(PluginCorrupted& e) { dlclose(handle); throw e; } AVG_TRACE(Logger::PLUGIN, "Loaded plugin '" << sFullpath << "'"); return handle; } void PluginManager::registerPlugin(void* handle) { typedef void (*RegisterPluginPtr)(); RegisterPluginPtr registerPlugin = reinterpret_cast<RegisterPluginPtr>(dlsym(handle, "registerPlugin")); if (registerPlugin) { registerPlugin(); } else { AVG_TRACE(Logger::PLUGIN, "No plugin registration function detected"); throw PluginCorrupted("No plugin registration function detected"); } } <|endoftext|>
<commit_before>/* * Copyright 2012 Matthias Fuchs * * 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 "ZipFileInput.h" #include <zip.h> #include "Exception.h" namespace stromx { namespace core { ZipFileInput::ZipFileInput(const std::string& archive) : m_archiveHandle(0), m_initialized(false), m_archive(archive), m_currentFile(0) { int error = 0; m_archiveHandle = zip_open(m_archive.c_str(), 0, &error); if(! m_archiveHandle) throw FileAccessFailed(m_archive, "Failed to open zip archive."); } ZipFileInput::~ZipFileInput() { if(m_archiveHandle) zip_close(m_archiveHandle); } void ZipFileInput::initialize(const std::string& text, const std::string& filename) { m_currentText.clear(); m_currentText.str(text); if(m_currentFile) { delete m_currentFile; m_currentFile = 0; } m_currentFilename = filename; m_initialized = true; } const bool ZipFileInput::hasFile() const { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); return ! m_currentFilename.empty(); } std::istream& ZipFileInput::text() { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); return m_currentText; } std::istream& ZipFileInput::openFile(const stromx::core::InputProvider::OpenMode mode) { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); if(m_currentFile) throw WrongState("File has already been opened."); if(! hasFile()) throw NoInputFile(); std::ios_base::openmode iosmode = std::ios_base::in; if(mode == BINARY) iosmode |= std::ios_base::binary; struct zip_stat stat; if(zip_stat(m_archiveHandle, m_currentFilename.c_str(), 0, &stat) < 0) throw FileAccessFailed(m_currentFilename, m_archive, "Failed to access file in zip archive."); int fileSize = stat.size; char* content = new char[fileSize]; zip_file* file = zip_fopen(m_archiveHandle, m_currentFilename.c_str(), 0); if(! file) throw FileAccessFailed(m_currentFilename, m_archive, "Failed to open file in zip archive."); if(zip_fread(file, content, fileSize) != fileSize) throw FileAccessFailed(m_currentFilename, m_archive, "Failed to read file in zip archive."); m_currentFile = new std::istringstream(std::string(content, fileSize), iosmode); return *m_currentFile; } std::istream& ZipFileInput::file() { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); if(! m_currentFile) throw WrongState("File has not been opened."); return *m_currentFile; } } } <commit_msg>Fixed Visual studion warning<commit_after>/* * Copyright 2012 Matthias Fuchs * * 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 "ZipFileInput.h" #include <zip.h> #include "Exception.h" namespace stromx { namespace core { ZipFileInput::ZipFileInput(const std::string& archive) : m_archiveHandle(0), m_initialized(false), m_archive(archive), m_currentFile(0) { int error = 0; m_archiveHandle = zip_open(m_archive.c_str(), 0, &error); if(! m_archiveHandle) throw FileAccessFailed(m_archive, "Failed to open zip archive."); } ZipFileInput::~ZipFileInput() { if(m_archiveHandle) zip_close(m_archiveHandle); } void ZipFileInput::initialize(const std::string& text, const std::string& filename) { m_currentText.clear(); m_currentText.str(text); if(m_currentFile) { delete m_currentFile; m_currentFile = 0; } m_currentFilename = filename; m_initialized = true; } const bool ZipFileInput::hasFile() const { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); return ! m_currentFilename.empty(); } std::istream& ZipFileInput::text() { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); return m_currentText; } std::istream& ZipFileInput::openFile(const stromx::core::InputProvider::OpenMode mode) { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); if(m_currentFile) throw WrongState("File has already been opened."); if(! hasFile()) throw NoInputFile(); std::ios_base::openmode iosmode = std::ios_base::in; if(mode == BINARY) iosmode |= std::ios_base::binary; struct zip_stat stat; if(zip_stat(m_archiveHandle, m_currentFilename.c_str(), 0, &stat) < 0) throw FileAccessFailed(m_currentFilename, m_archive, "Failed to access file in zip archive."); unsigned int fileSize = (unsigned int)(stat.size); char* content = new char[fileSize]; zip_file* file = zip_fopen(m_archiveHandle, m_currentFilename.c_str(), 0); if(! file) throw FileAccessFailed(m_currentFilename, m_archive, "Failed to open file in zip archive."); if(zip_fread(file, content, fileSize) != fileSize) throw FileAccessFailed(m_currentFilename, m_archive, "Failed to read file in zip archive."); m_currentFile = new std::istringstream(std::string(content, fileSize), iosmode); return *m_currentFile; } std::istream& ZipFileInput::file() { if(! m_initialized) throw WrongState("Zip file input has not been initialized."); if(! m_currentFile) throw WrongState("File has not been opened."); return *m_currentFile; } } } <|endoftext|>
<commit_before>/** * projectM-qt -- Qt4 based projectM GUI * Copyright (C)2003-2004 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #ifndef NULLABLE_HPP #define NULLABLE_HPP template <class Value> class Nullable { public: Nullable(const Value & value) : m_value(value), m_hasValue(true) {} Nullable() :m_hasValue(false) {} Nullable & operator=(const Value & value) { m_value = value; m_hasValue = true; } void nullify() { m_hasValue = false; } const Value & value() const { return m_value;} bool hasValue() const { return m_hasValue;} private: Value m_value; bool m_hasValue; }; #endif <commit_msg>Add return value to non-void function template<commit_after>/** * projectM-qt -- Qt4 based projectM GUI * Copyright (C)2003-2004 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #ifndef NULLABLE_HPP #define NULLABLE_HPP template <class Value> class Nullable { public: Nullable(const Value & value) : m_value(value), m_hasValue(true) {} Nullable() :m_hasValue(false) {} Nullable & operator=(const Value & value) { m_value = value; m_hasValue = true; static Nullable tmp = 0; return tmp; } void nullify() { m_hasValue = false; } const Value & value() const { return m_value;} bool hasValue() const { return m_hasValue;} private: Value m_value; bool m_hasValue; }; #endif <|endoftext|>
<commit_before>/** * message.cpp * * Created on: 11 окт. 2015 г. * Author: zmij */ #include <pushkin/l10n/message.hpp> #include <pushkin/l10n/message_io.hpp> #include <pushkin/l10n/message_util.hpp> #include <boost/lexical_cast.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <sstream> #include <map> #include <algorithm> namespace psst { namespace l10n { ::std::locale::id domain_name_facet::id; ::std::locale::id context_name_facet::id; ::std::locale::id locale_name_facet::id; namespace detail { format::format(localized_message const& msg) : fmt_{ new formatted_message{ msg } } { } format::format(localized_message&& msg) : fmt_{ new formatted_message{ ::std::move(msg) } } { } format::format(formatted_message_ptr&& fmt) : fmt_{ ::std::move(fmt) } { } message_args::message_args(message_args const& rhs) : args_{} { args_.reserve(rhs.args_.size()); ::std::transform(rhs.args_.begin(), rhs.args_.end(), ::std::back_inserter(args_), [](arg_holder const& arg) { return arg->clone(); }); } message_args::message_args(message_args&& rhs) : args_{::std::move(rhs.args_)} { } } /* namespace detail */ namespace { const std::map< message::message_type, std::string > TYPE_TO_STRING { { message::message_type::empty, "" }, { message::message_type::simple, "L10N" }, { message::message_type::plural, "L10NN" }, { message::message_type::context, "L10NC" }, { message::message_type::context_plural, "L10NNC" }, }; // TYPE_TO_STRING const std::map< std::string, message::message_type > STRING_TO_TYPE { { "L10N", message::message_type::simple }, { "L10NN", message::message_type::plural }, { "L10NC", message::message_type::context }, { "L10NNC", message::message_type::context_plural }, }; // STRING_TO_TYPE const ::std::string DEFAULT_DOMAIN = ""; } // namespace // Generated output operator std::ostream& operator << (std::ostream& out, message::message_type val) { std::ostream::sentry s (out); if (s) { auto f = TYPE_TO_STRING.find(val); if (f != TYPE_TO_STRING.end()) { out << f->second; } else { out << "Unknown type " << (int)val; } } return out; } // Generated input operator std::istream& operator >> (std::istream& in, message::message_type& val) { std::istream::sentry s (in); if (!s) return in; std::string name; if (in >> name) { auto f = STRING_TO_TYPE.find(name); if (f != STRING_TO_TYPE.end()) { val = f->second; } else { val = message::message_type::empty; in.setstate(std::ios_base::failbit); } } return in; } message::message() : type_(message_type::empty), n_(0) { } message::message(optional_string const& domain) : type_(message_type::empty), domain_(domain), n_(0) { } message::message(std::string const& id, optional_string const& domain) : type_(message_type::simple), msgid_(id), msgstr_(id), domain_(domain), n_(0) { } message::message(id_str_pair const& id_n_str, domain_type const& domain) : type_(message_type::simple), msgid_(id_n_str.first), msgstr_(id_n_str.second), domain_(domain), n_(0) { if(msgstr_.find("{1}") != std::string::npos) set_plural(); } message::message(std::string const& context_str, std::string const& id, optional_string const& domain) : type_(message_type::context), msgid_(id), msgstr_(id), context_(context_str), domain_(domain), n_(0) { } message::message(std::string const& context_str, id_str_pair const& id_n_str, domain_type const& domain) : type_(message_type::context), msgid_(id_n_str.first), msgstr_(id_n_str.second), context_(context_str), domain_(domain), n_(0) { if(msgstr_.find("{1}") != std::string::npos) set_plural(); } message::message(std::string const& singular, std::string const& plural_str, int n, optional_string const& domain) : type_(message_type::plural), msgid_(singular), msgstr_(singular), plural_(plural_str), domain_(domain), n_(n) { } message::message(std::string const& context, std::string const& singular, std::string const& plural, int n, optional_string const& domain) : type_(message_type::context_plural), msgid_(singular), msgstr_(singular), context_(context), plural_(plural), domain_(domain), n_(n) { } void message::swap(message& rhs) noexcept { using std::swap; swap(type_, rhs.type_); swap(msgid_, rhs.msgid_); swap(msgstr_, rhs.msgstr_); swap(plural_, rhs.plural_); swap(context_, rhs.context_); swap(n_, rhs.n_); swap(domain_, rhs.domain_); swap(args_, rhs.args_); } ::std::string const& message::plural() const { if (!plural_.is_initialized()) throw ::std::runtime_error{ "Message msgid '" + msgid_ + "' doesn't contain a plural form" }; return *plural_; } ::std::string const& message::context() const { if (!context_.is_initialized()) throw ::std::runtime_error{ "Message msgid '" + msgid_ + "' doesn't have context" }; return *context_; } ::std::string const& message::domain() const { if (!domain_.is_initialized()) return DEFAULT_DOMAIN; return *domain_; } void message::domain( std::string const& domain) { domain_ = domain; } void message::set_plural() { switch (type_) { case message_type::simple: case message_type::plural: type_ = message_type::plural; break; case message_type::context: case message_type::context_plural: type_ = message_type::context_plural; break; default: throw ::std::runtime_error{"Cannot convert message to a plural form"}; } plural_ = msgid_; } void message::set_plural(int n) { set_plural(); n_ = n; } message::localized_message message::translate(int n) const { switch (type_) { case message_type::empty: return localized_message(); case message_type::simple: return localized_message(msgid_); case message_type::context: return localized_message(context_.value(), msgid_); case message_type::plural: return localized_message(msgid_, plural_.value(), n); case message_type::context_plural: return localized_message(context_.value(), msgid_, plural_.value(), n); default: throw std::runtime_error("Unknown message type"); } } detail::format message::format(int n, bool feed_plural) const { detail::format fmt{translate(n)}; if (has_plural() && feed_plural) fmt % n; fmt % args_; return fmt; } void message::write(std::ostream& os) const { namespace locn = boost::locale; if (domain_.is_initialized()) { os << locn::as::domain(domain_.value()); } if(has_format_args()) { os << format(); } else { os << translate(n_); } } void message::collect(message_list& messages) const { for (auto const& arg : args_) { arg->collect(messages); } } message message::create_message(::std::string const& id, get_named_param_func f, domain_type const& domain) { auto id_phs = extract_named_placeholders(id); message msg{id_phs.first, domain}; for (auto const& ph : id_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); f(msg, nm); } return msg; } message message::create_message(std::string const& context, std::string const& id, get_named_param_func f, domain_type const& domain) { auto id_phs = extract_named_placeholders(id); message msg{context, id_phs.first, domain}; for (auto const& ph : id_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); f(msg, nm); } return msg; } message message::create_message(std::string const& singular, std::string const& plural, get_named_param_func f, get_n_func get_n, int n, domain_type const& domain) { auto singular_phs = extract_named_placeholders(singular); auto plural_phs = extract_named_placeholders(plural); message msg{singular_phs.first, plural_phs.first, n, domain}; for (auto const& ph : singular_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); if (ph.is_pluralizer) { if (get_n) { msg.set_n(get_n(nm)); } else { f(msg, nm); } } else { f(msg, nm); } } return msg; } message message::create_message(std::string const& context, std::string const& singular, std::string const& plural, get_named_param_func f, get_n_func get_n, int n, domain_type const& domain) { auto singular_phs = extract_named_placeholders(singular); auto plural_phs = extract_named_placeholders(plural); message msg{context, singular_phs.first, plural_phs.first, n, domain}; for (auto const& ph : singular_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); if (ph.is_pluralizer) { if (get_n) { msg.set_n(get_n(nm)); } if (ph.uses > 1) f(msg, nm); } else { f(msg, nm); } } return msg; } std::ostream& operator << (std::ostream& out, message const& val) { std::ostream::sentry s(out); if (s) { val.write(out); } return out; } ::std::istream& operator >> (::std::istream& is, message& val) { ::std::istream::sentry s(is); if(!s) return is; ::std::string msgstr; char c; while(is.get(c)) msgstr.push_back(c); message::id_str_pair id_n_str{ (val.id().empty() ? msgstr : val.id()), msgstr }; message::optional_string domain; message::optional_string context; auto loc = is.getloc(); if (::std::has_facet<domain_name_facet>(loc)) { domain = ::std::use_facet<domain_name_facet>(loc).domain(); } if (::std::has_facet<context_name_facet>(loc)) { context = ::std::use_facet<context_name_facet>(loc).context(); } if (context.is_initialized()) { val = message{*context, id_n_str, domain}; } else { val = message{id_n_str, domain}; } if(val.msgstr().find("{1}") != std::string::npos) val.set_plural(); return is; } } /* namespace l10n */ } /* namespace psst */ <commit_msg>AWM-8562 format() if has_plural<commit_after>/** * message.cpp * * Created on: 11 окт. 2015 г. * Author: zmij */ #include <pushkin/l10n/message.hpp> #include <pushkin/l10n/message_io.hpp> #include <pushkin/l10n/message_util.hpp> #include <boost/lexical_cast.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <sstream> #include <map> #include <algorithm> namespace psst { namespace l10n { ::std::locale::id domain_name_facet::id; ::std::locale::id context_name_facet::id; ::std::locale::id locale_name_facet::id; namespace detail { format::format(localized_message const& msg) : fmt_{ new formatted_message{ msg } } { } format::format(localized_message&& msg) : fmt_{ new formatted_message{ ::std::move(msg) } } { } format::format(formatted_message_ptr&& fmt) : fmt_{ ::std::move(fmt) } { } message_args::message_args(message_args const& rhs) : args_{} { args_.reserve(rhs.args_.size()); ::std::transform(rhs.args_.begin(), rhs.args_.end(), ::std::back_inserter(args_), [](arg_holder const& arg) { return arg->clone(); }); } message_args::message_args(message_args&& rhs) : args_{::std::move(rhs.args_)} { } } /* namespace detail */ namespace { const std::map< message::message_type, std::string > TYPE_TO_STRING { { message::message_type::empty, "" }, { message::message_type::simple, "L10N" }, { message::message_type::plural, "L10NN" }, { message::message_type::context, "L10NC" }, { message::message_type::context_plural, "L10NNC" }, }; // TYPE_TO_STRING const std::map< std::string, message::message_type > STRING_TO_TYPE { { "L10N", message::message_type::simple }, { "L10NN", message::message_type::plural }, { "L10NC", message::message_type::context }, { "L10NNC", message::message_type::context_plural }, }; // STRING_TO_TYPE const ::std::string DEFAULT_DOMAIN = ""; } // namespace // Generated output operator std::ostream& operator << (std::ostream& out, message::message_type val) { std::ostream::sentry s (out); if (s) { auto f = TYPE_TO_STRING.find(val); if (f != TYPE_TO_STRING.end()) { out << f->second; } else { out << "Unknown type " << (int)val; } } return out; } // Generated input operator std::istream& operator >> (std::istream& in, message::message_type& val) { std::istream::sentry s (in); if (!s) return in; std::string name; if (in >> name) { auto f = STRING_TO_TYPE.find(name); if (f != STRING_TO_TYPE.end()) { val = f->second; } else { val = message::message_type::empty; in.setstate(std::ios_base::failbit); } } return in; } message::message() : type_(message_type::empty), n_(0) { } message::message(optional_string const& domain) : type_(message_type::empty), domain_(domain), n_(0) { } message::message(std::string const& id, optional_string const& domain) : type_(message_type::simple), msgid_(id), msgstr_(id), domain_(domain), n_(0) { } message::message(id_str_pair const& id_n_str, domain_type const& domain) : type_(message_type::simple), msgid_(id_n_str.first), msgstr_(id_n_str.second), domain_(domain), n_(0) { if(msgstr_.find("{1}") != std::string::npos) set_plural(); } message::message(std::string const& context_str, std::string const& id, optional_string const& domain) : type_(message_type::context), msgid_(id), msgstr_(id), context_(context_str), domain_(domain), n_(0) { } message::message(std::string const& context_str, id_str_pair const& id_n_str, domain_type const& domain) : type_(message_type::context), msgid_(id_n_str.first), msgstr_(id_n_str.second), context_(context_str), domain_(domain), n_(0) { if(msgstr_.find("{1}") != std::string::npos) set_plural(); } message::message(std::string const& singular, std::string const& plural_str, int n, optional_string const& domain) : type_(message_type::plural), msgid_(singular), msgstr_(singular), plural_(plural_str), domain_(domain), n_(n) { } message::message(std::string const& context, std::string const& singular, std::string const& plural, int n, optional_string const& domain) : type_(message_type::context_plural), msgid_(singular), msgstr_(singular), context_(context), plural_(plural), domain_(domain), n_(n) { } void message::swap(message& rhs) noexcept { using std::swap; swap(type_, rhs.type_); swap(msgid_, rhs.msgid_); swap(msgstr_, rhs.msgstr_); swap(plural_, rhs.plural_); swap(context_, rhs.context_); swap(n_, rhs.n_); swap(domain_, rhs.domain_); swap(args_, rhs.args_); } ::std::string const& message::plural() const { if (!plural_.is_initialized()) throw ::std::runtime_error{ "Message msgid '" + msgid_ + "' doesn't contain a plural form" }; return *plural_; } ::std::string const& message::context() const { if (!context_.is_initialized()) throw ::std::runtime_error{ "Message msgid '" + msgid_ + "' doesn't have context" }; return *context_; } ::std::string const& message::domain() const { if (!domain_.is_initialized()) return DEFAULT_DOMAIN; return *domain_; } void message::domain( std::string const& domain) { domain_ = domain; } void message::set_plural() { switch (type_) { case message_type::simple: case message_type::plural: type_ = message_type::plural; break; case message_type::context: case message_type::context_plural: type_ = message_type::context_plural; break; default: throw ::std::runtime_error{"Cannot convert message to a plural form"}; } plural_ = msgid_; } void message::set_plural(int n) { set_plural(); n_ = n; } message::localized_message message::translate(int n) const { switch (type_) { case message_type::empty: return localized_message(); case message_type::simple: return localized_message(msgid_); case message_type::context: return localized_message(context_.value(), msgid_); case message_type::plural: return localized_message(msgid_, plural_.value(), n); case message_type::context_plural: return localized_message(context_.value(), msgid_, plural_.value(), n); default: throw std::runtime_error("Unknown message type"); } } detail::format message::format(int n, bool feed_plural) const { detail::format fmt{translate(n)}; if (has_plural() && feed_plural) fmt % n; fmt % args_; return fmt; } void message::write(std::ostream& os) const { namespace locn = boost::locale; if (domain_.is_initialized()) { os << locn::as::domain(domain_.value()); } if(has_plural() || has_format_args()) { os << format(); } else { os << translate(n_); } } void message::collect(message_list& messages) const { for (auto const& arg : args_) { arg->collect(messages); } } message message::create_message(::std::string const& id, get_named_param_func f, domain_type const& domain) { auto id_phs = extract_named_placeholders(id); message msg{id_phs.first, domain}; for (auto const& ph : id_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); f(msg, nm); } return msg; } message message::create_message(std::string const& context, std::string const& id, get_named_param_func f, domain_type const& domain) { auto id_phs = extract_named_placeholders(id); message msg{context, id_phs.first, domain}; for (auto const& ph : id_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); f(msg, nm); } return msg; } message message::create_message(std::string const& singular, std::string const& plural, get_named_param_func f, get_n_func get_n, int n, domain_type const& domain) { auto singular_phs = extract_named_placeholders(singular); auto plural_phs = extract_named_placeholders(plural); message msg{singular_phs.first, plural_phs.first, n, domain}; for (auto const& ph : singular_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); if (ph.is_pluralizer) { if (get_n) { msg.set_n(get_n(nm)); } else { f(msg, nm); } } else { f(msg, nm); } } return msg; } message message::create_message(std::string const& context, std::string const& singular, std::string const& plural, get_named_param_func f, get_n_func get_n, int n, domain_type const& domain) { auto singular_phs = extract_named_placeholders(singular); auto plural_phs = extract_named_placeholders(plural); message msg{context, singular_phs.first, plural_phs.first, n, domain}; for (auto const& ph : singular_phs.second) { auto const& nm = ::boost::get<::std::string>(ph.id); if (ph.is_pluralizer) { if (get_n) { msg.set_n(get_n(nm)); } if (ph.uses > 1) f(msg, nm); } else { f(msg, nm); } } return msg; } std::ostream& operator << (std::ostream& out, message const& val) { std::ostream::sentry s(out); if (s) { val.write(out); } return out; } ::std::istream& operator >> (::std::istream& is, message& val) { ::std::istream::sentry s(is); if(!s) return is; ::std::string msgstr; char c; while(is.get(c)) msgstr.push_back(c); message::id_str_pair id_n_str{ (val.id().empty() ? msgstr : val.id()), msgstr }; message::optional_string domain; message::optional_string context; auto loc = is.getloc(); if (::std::has_facet<domain_name_facet>(loc)) { domain = ::std::use_facet<domain_name_facet>(loc).domain(); } if (::std::has_facet<context_name_facet>(loc)) { context = ::std::use_facet<context_name_facet>(loc).context(); } if (context.is_initialized()) { val = message{*context, id_n_str, domain}; } else { val = message{id_n_str, domain}; } if(val.msgstr().find("{1}") != std::string::npos) val.set_plural(); return is; } } /* namespace l10n */ } /* namespace psst */ <|endoftext|>
<commit_before>// RUN: clang -shared %S/call_lib.c -olibcall_lib%shlibext // RUN: cat %s | %cling | FileCheck %s .L libcall_lib extern "C" int cling_testlibrary_function(); int i = cling_testlibrary_function(); extern "C" int printf(const char* fmt, ...); printf("got i=%d\n", i); // CHECK: got i=66 .q <commit_msg>Try to fix intermittent test failure (library not yet built)<commit_after>// RUN: clang -shared %S/call_lib.c -olibcall_lib%shlibext && cat %s | %cling | FileCheck %s .L libcall_lib extern "C" int cling_testlibrary_function(); int i = cling_testlibrary_function(); extern "C" int printf(const char* fmt, ...); printf("got i=%d\n", i); // CHECK: got i=66 .q <|endoftext|>
<commit_before>#include "pch.h" #include "axl_rtl_BoyerMooreFind.h" #include "axl_rtl_BoyerMooreAccessor.h" namespace axl { namespace rtl { //............................................................................. bool BinaryBoyerMooreFind::setPattern ( const void* p, size_t size, uint_t flags ) { if (!size) { clear (); return true; } bool result = (flags & Flag_Reverse) ? m_pattern.copyReverse ((const char*) p, size) : m_pattern.copy ((const char*) p, size); if (!result) return false; m_flags = flags; buildBadSkipTable (); return !(flags & Flag_Horspool) ? buildGoodSkipTable () : true; } void BinaryBoyerMooreFind::buildBadSkipTable () { size_t patternSize = m_pattern.getCount (); m_badSkipTable.setCount (256); for (size_t i = 0; i < 256; i++) m_badSkipTable [i] = patternSize; size_t last = patternSize - 1; for (size_t i = 0, j = last; i < last; i++, j--) m_badSkipTable [(uchar_t) m_pattern [i]] = j; } size_t BinaryBoyerMooreFind::find ( const void* p, size_t size ) { size_t patternSize = m_pattern.getCount (); if (!patternSize || size < patternSize) return -1; size_t result = (m_flags & Flag_Reverse) ? findImpl (BinaryBoyerMooreReverseAccessor ((const char*) p + size - 1), size) : findImpl (BinaryBoyerMooreAccessor ((const char*) p), size); if (result == -1) return -1; if (m_flags & Flag_Reverse) result = size - result - patternSize; return result; } size_t BinaryBoyerMooreFind::find ( IncrementalContext* incrementalContext, size_t offset, const void* p, size_t size ) { size_t patternSize = m_pattern.getCount (); if (!patternSize) return -1; size_t tailSize = incrementalContext->m_tail.getCount (); size_t fullSize = size + tailSize; if (fullSize < patternSize) { if (m_flags & Flag_Reverse) incrementalContext->m_tail.appendReverse ((const char*) p, size); else incrementalContext->m_tail.append ((const char*) p, size); return -1; } size_t result = (m_flags & Flag_Reverse) ? findImpl (BinaryBoyerMooreIncrementalReverseAccessor ((const char*) p + size - 1, incrementalContext), fullSize) : findImpl (BinaryBoyerMooreIncrementalAccessor ((const char*) p, incrementalContext), fullSize); if (result == -1) return -1; incrementalContext->reset (); result -= tailSize; if (m_flags & Flag_Reverse) result = size - result - patternSize; return offset + result; } template <typename Accessor> size_t BinaryBoyerMooreFind::findImpl ( const Accessor& accessor, size_t size ) { size_t patternSize = m_pattern.getCount (); ASSERT (patternSize && size >= patternSize); size_t last = patternSize - 1; size_t i = last; if (m_flags & Flag_Horspool) while (i < size) { intptr_t j = last; uchar_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) return i; i--; j--; } i += m_badSkipTable [c]; } else while (i < size) { intptr_t j = last; uchar_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) return i; i--; j--; } size_t badSkip = m_badSkipTable [c]; size_t goodSkip = m_goodSkipTable [j]; i += AXL_MAX (badSkip, goodSkip); } ASSERT (i > last && i - last <= size); i -= last; accessor.saveTail (i, size - i); return -1; } //............................................................................. bool TextBoyerMooreFind::setPattern ( size_t badSkipTableSize, enc::CharCodec* codec, const void* p, size_t size, uint_t flags ) { size_t length = codec->decodeToUtf32 (&m_pattern, p, size); if (!length) { clear (); return true; } if (flags & Flag_CaseInsensitive) for (size_t i = 0; i < length; i++) m_pattern [i] = enc::utfToCaseFold (m_pattern [i]); if (flags & Flag_Reverse) m_pattern.reverse (); m_flags = flags; bool result = buildBadSkipTable (badSkipTableSize); if (!result) return false; return !(flags & Flag_Horspool) ? buildGoodSkipTable () : true; } bool TextBoyerMooreFind::buildBadSkipTable (size_t tableSize) { size_t patternSize = m_pattern.getCount (); bool result = m_badSkipTable.setCount (tableSize); if (!result) return false; for (size_t i = 0; i < tableSize; i++) m_badSkipTable [i] = patternSize; size_t last = patternSize - 1; if (m_flags & Flag_CaseInsensitive) for (size_t i = 0, j = last; i < last; i++, j--) { uint32_t c = enc::utfToCaseFold (m_pattern [i]); m_badSkipTable [c % tableSize] = j; } else for (size_t i = 0, j = last; i < last; i++, j--) { uint32_t c = m_pattern [i]; m_badSkipTable [c % tableSize] = j; } return true; } size_t TextBoyerMooreFind::find ( enc::CharCodec* codec, const void* p, size_t size ) { size_t patternLength = m_pattern.getCount (); if (!patternLength) return -1; size_t length = codec->decodeToUtf32 (&m_buffer, p, size); if (length == -1) return -1; if (length < patternLength) return -1; if (m_flags & Flag_WholeWord) m_buffer.append (' '); size_t result = (m_flags & Flag_CaseInsensitive) ? (m_flags & Flag_Reverse) ? findImpl (TextBoyerMooreCaseFoldReverseAccessor (m_buffer + length - 1), length, length) : findImpl (TextBoyerMooreCaseFoldAccessor (m_buffer), length, length) : (m_flags & Flag_Reverse) ? findImpl (TextBoyerMooreReverseAccessor (m_buffer + length - 1), length, length) : findImpl (TextBoyerMooreAccessor (m_buffer), length, length); if (result == -1) return -1; if (m_flags & Flag_Reverse) result = size - result - patternLength; ASSERT (result <= length); return codec->calcRequiredBufferSizeToEncodeFromUtf32 (m_buffer, result); } size_t TextBoyerMooreFind::find ( IncrementalContext* incrementalContext, enc::CharCodec* codec, size_t offset, const void* p, size_t size ) { size_t patternLength = m_pattern.getCount (); if (!patternLength) return -1; size_t chunkLength = codec->decodeToUtf32 (&m_buffer, p, size); if (chunkLength == -1 || chunkLength == 0) return -1; size_t tailLength = incrementalContext->m_tail.getCount (); size_t fullLength = chunkLength + tailLength; size_t end = fullLength; if (m_flags & Flag_WholeWord) end--; if (end < patternLength) { if (m_flags & Flag_Reverse) incrementalContext->m_tail.appendReverse (m_buffer, chunkLength); else incrementalContext->m_tail.append (m_buffer, chunkLength); return -1; } size_t result = (m_flags & Flag_CaseInsensitive) ? (m_flags & Flag_Reverse) ? findImpl ( TextBoyerMooreCaseFoldIncrementalReverseAccessor (m_buffer + chunkLength - 1, incrementalContext), end, fullLength ) : findImpl ( TextBoyerMooreCaseFoldIncrementalAccessor (m_buffer, incrementalContext), end, fullLength ) : (m_flags & Flag_Reverse) ? findImpl ( TextBoyerMooreIncrementalReverseAccessor (m_buffer + chunkLength - 1, incrementalContext), end, fullLength ) : findImpl ( TextBoyerMooreIncrementalAccessor (m_buffer, incrementalContext), end, fullLength ); if (result == -1) return -1; result -= tailLength; if (m_flags & Flag_Reverse) result = size - result - patternLength; if ((intptr_t) result < 0) { ASSERT (-result <= tailLength); result = -codec->calcRequiredBufferSizeToEncodeFromUtf32 (incrementalContext->m_tail, -result); } else if (result) { ASSERT (result <= chunkLength); result = codec->calcRequiredBufferSizeToEncodeFromUtf32 (m_buffer, result); } incrementalContext->reset (); return offset + result; } template <typename Accessor> size_t TextBoyerMooreFind::findImpl ( const Accessor& accessor, size_t end, size_t size ) { size_t badSkipTableSize = m_badSkipTable.getCount (); size_t patternSize = m_pattern.getCount (); ASSERT (patternSize && end >= patternSize); size_t last = patternSize - 1; size_t i = last; if (m_flags & Flag_Horspool) while (i < end) { intptr_t j = last; uint32_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) { if ((m_flags & Flag_WholeWord) && (!accessor.isDelimChar (i - 1) || !accessor.isDelimChar (i + patternSize))) { break; } return i; } i--; j--; } i += m_badSkipTable [c % badSkipTableSize]; } else while (i < end) { intptr_t j = last; uint32_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) { if ((m_flags & Flag_WholeWord) && (!accessor.isDelimChar (i - 1) || !accessor.isDelimChar (i + patternSize))) { break; } return i; } i--; j--; } size_t badSkip = m_badSkipTable [c % badSkipTableSize]; size_t goodSkip = m_goodSkipTable [j]; i += AXL_MAX (badSkip, goodSkip); } ASSERT (i > last && i - last <= size); i -= last; accessor.saveTail (i, size - i); return -1; } //............................................................................. } // namespace rtl } // namespace axl <commit_msg>[axl] boyer-moore find should actually succeed on empty pattern<commit_after>#include "pch.h" #include "axl_rtl_BoyerMooreFind.h" #include "axl_rtl_BoyerMooreAccessor.h" namespace axl { namespace rtl { //............................................................................. bool BinaryBoyerMooreFind::setPattern ( const void* p, size_t size, uint_t flags ) { if (!size) { clear (); return true; } bool result = (flags & Flag_Reverse) ? m_pattern.copyReverse ((const char*) p, size) : m_pattern.copy ((const char*) p, size); if (!result) return false; m_flags = flags; buildBadSkipTable (); return !(flags & Flag_Horspool) ? buildGoodSkipTable () : true; } void BinaryBoyerMooreFind::buildBadSkipTable () { size_t patternSize = m_pattern.getCount (); m_badSkipTable.setCount (256); for (size_t i = 0; i < 256; i++) m_badSkipTable [i] = patternSize; size_t last = patternSize - 1; for (size_t i = 0, j = last; i < last; i++, j--) m_badSkipTable [(uchar_t) m_pattern [i]] = j; } size_t BinaryBoyerMooreFind::find ( const void* p, size_t size ) { size_t patternSize = m_pattern.getCount (); if (!patternSize) return 0; if (size < patternSize) return -1; size_t result = (m_flags & Flag_Reverse) ? findImpl (BinaryBoyerMooreReverseAccessor ((const char*) p + size - 1), size) : findImpl (BinaryBoyerMooreAccessor ((const char*) p), size); if (result == -1) return -1; if (m_flags & Flag_Reverse) result = size - result - patternSize; return result; } size_t BinaryBoyerMooreFind::find ( IncrementalContext* incrementalContext, size_t offset, const void* p, size_t size ) { size_t patternSize = m_pattern.getCount (); if (!patternSize) return 0; size_t tailSize = incrementalContext->m_tail.getCount (); size_t fullSize = size + tailSize; if (fullSize < patternSize) { if (m_flags & Flag_Reverse) incrementalContext->m_tail.appendReverse ((const char*) p, size); else incrementalContext->m_tail.append ((const char*) p, size); return -1; } size_t result = (m_flags & Flag_Reverse) ? findImpl (BinaryBoyerMooreIncrementalReverseAccessor ((const char*) p + size - 1, incrementalContext), fullSize) : findImpl (BinaryBoyerMooreIncrementalAccessor ((const char*) p, incrementalContext), fullSize); if (result == -1) return -1; incrementalContext->reset (); result -= tailSize; if (m_flags & Flag_Reverse) result = size - result - patternSize; return offset + result; } template <typename Accessor> size_t BinaryBoyerMooreFind::findImpl ( const Accessor& accessor, size_t size ) { size_t patternSize = m_pattern.getCount (); ASSERT (patternSize && size >= patternSize); size_t last = patternSize - 1; size_t i = last; if (m_flags & Flag_Horspool) while (i < size) { intptr_t j = last; uchar_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) return i; i--; j--; } i += m_badSkipTable [c]; } else while (i < size) { intptr_t j = last; uchar_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) return i; i--; j--; } size_t badSkip = m_badSkipTable [c]; size_t goodSkip = m_goodSkipTable [j]; i += AXL_MAX (badSkip, goodSkip); } ASSERT (i > last && i - last <= size); i -= last; accessor.saveTail (i, size - i); return -1; } //............................................................................. bool TextBoyerMooreFind::setPattern ( size_t badSkipTableSize, enc::CharCodec* codec, const void* p, size_t size, uint_t flags ) { size_t length = codec->decodeToUtf32 (&m_pattern, p, size); if (!length) { clear (); return true; } if (flags & Flag_CaseInsensitive) for (size_t i = 0; i < length; i++) m_pattern [i] = enc::utfToCaseFold (m_pattern [i]); if (flags & Flag_Reverse) m_pattern.reverse (); m_flags = flags; bool result = buildBadSkipTable (badSkipTableSize); if (!result) return false; return !(flags & Flag_Horspool) ? buildGoodSkipTable () : true; } bool TextBoyerMooreFind::buildBadSkipTable (size_t tableSize) { size_t patternSize = m_pattern.getCount (); bool result = m_badSkipTable.setCount (tableSize); if (!result) return false; for (size_t i = 0; i < tableSize; i++) m_badSkipTable [i] = patternSize; size_t last = patternSize - 1; if (m_flags & Flag_CaseInsensitive) for (size_t i = 0, j = last; i < last; i++, j--) { uint32_t c = enc::utfToCaseFold (m_pattern [i]); m_badSkipTable [c % tableSize] = j; } else for (size_t i = 0, j = last; i < last; i++, j--) { uint32_t c = m_pattern [i]; m_badSkipTable [c % tableSize] = j; } return true; } size_t TextBoyerMooreFind::find ( enc::CharCodec* codec, const void* p, size_t size ) { size_t patternLength = m_pattern.getCount (); if (!patternLength) return 0; size_t length = codec->decodeToUtf32 (&m_buffer, p, size); if (length == -1) return -1; if (length < patternLength) return -1; if (m_flags & Flag_WholeWord) m_buffer.append (' '); size_t result = (m_flags & Flag_CaseInsensitive) ? (m_flags & Flag_Reverse) ? findImpl (TextBoyerMooreCaseFoldReverseAccessor (m_buffer + length - 1), length, length) : findImpl (TextBoyerMooreCaseFoldAccessor (m_buffer), length, length) : (m_flags & Flag_Reverse) ? findImpl (TextBoyerMooreReverseAccessor (m_buffer + length - 1), length, length) : findImpl (TextBoyerMooreAccessor (m_buffer), length, length); if (result == -1) return -1; if (m_flags & Flag_Reverse) result = size - result - patternLength; ASSERT (result <= length); return codec->calcRequiredBufferSizeToEncodeFromUtf32 (m_buffer, result); } size_t TextBoyerMooreFind::find ( IncrementalContext* incrementalContext, enc::CharCodec* codec, size_t offset, const void* p, size_t size ) { size_t patternLength = m_pattern.getCount (); if (!patternLength) return 0; size_t chunkLength = codec->decodeToUtf32 (&m_buffer, p, size); if (chunkLength == -1 || chunkLength == 0) return -1; size_t tailLength = incrementalContext->m_tail.getCount (); size_t fullLength = chunkLength + tailLength; size_t end = fullLength; if (m_flags & Flag_WholeWord) end--; if (end < patternLength) { if (m_flags & Flag_Reverse) incrementalContext->m_tail.appendReverse (m_buffer, chunkLength); else incrementalContext->m_tail.append (m_buffer, chunkLength); return -1; } size_t result = (m_flags & Flag_CaseInsensitive) ? (m_flags & Flag_Reverse) ? findImpl ( TextBoyerMooreCaseFoldIncrementalReverseAccessor (m_buffer + chunkLength - 1, incrementalContext), end, fullLength ) : findImpl ( TextBoyerMooreCaseFoldIncrementalAccessor (m_buffer, incrementalContext), end, fullLength ) : (m_flags & Flag_Reverse) ? findImpl ( TextBoyerMooreIncrementalReverseAccessor (m_buffer + chunkLength - 1, incrementalContext), end, fullLength ) : findImpl ( TextBoyerMooreIncrementalAccessor (m_buffer, incrementalContext), end, fullLength ); if (result == -1) return -1; result -= tailLength; if (m_flags & Flag_Reverse) result = size - result - patternLength; if ((intptr_t) result < 0) { ASSERT (-result <= tailLength); result = -codec->calcRequiredBufferSizeToEncodeFromUtf32 (incrementalContext->m_tail, -result); } else if (result) { ASSERT (result <= chunkLength); result = codec->calcRequiredBufferSizeToEncodeFromUtf32 (m_buffer, result); } incrementalContext->reset (); return offset + result; } template <typename Accessor> size_t TextBoyerMooreFind::findImpl ( const Accessor& accessor, size_t end, size_t size ) { size_t badSkipTableSize = m_badSkipTable.getCount (); size_t patternSize = m_pattern.getCount (); ASSERT (patternSize && end >= patternSize); size_t last = patternSize - 1; size_t i = last; if (m_flags & Flag_Horspool) while (i < end) { intptr_t j = last; uint32_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) { if ((m_flags & Flag_WholeWord) && (!accessor.isDelimChar (i - 1) || !accessor.isDelimChar (i + patternSize))) { break; } return i; } i--; j--; } i += m_badSkipTable [c % badSkipTableSize]; } else while (i < end) { intptr_t j = last; uint32_t c; for (;;) { c = accessor.getChar (i); if (c != m_pattern [j]) break; if (j == 0) { if ((m_flags & Flag_WholeWord) && (!accessor.isDelimChar (i - 1) || !accessor.isDelimChar (i + patternSize))) { break; } return i; } i--; j--; } size_t badSkip = m_badSkipTable [c % badSkipTableSize]; size_t goodSkip = m_goodSkipTable [j]; i += AXL_MAX (badSkip, goodSkip); } ASSERT (i > last && i - last <= size); i -= last; accessor.saveTail (i, size - i); return -1; } //............................................................................. } // namespace rtl } // namespace axl <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // 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 GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "regression_serv.hpp" #include <string> #include <utility> #include <vector> #include "jubatus/util/text/json.h" #include "jubatus/util/data/optional.h" #include "jubatus/util/lang/shared_ptr.h" #include "jubatus/core/common/jsonconfig.hpp" #include "jubatus/core/fv_converter/datum.hpp" #include "jubatus/core/fv_converter/datum_to_fv_converter.hpp" #include "jubatus/core/fv_converter/converter_config.hpp" #include "jubatus/core/storage/storage_factory.hpp" #include "jubatus/core/regression/regression_factory.hpp" #include "../framework/mixer/mixer_factory.hpp" using std::string; using std::vector; using std::pair; using jubatus::util::lang::shared_ptr; using jubatus::util::text::json::json; using jubatus::util::lang::lexical_cast; using jubatus::core::fv_converter::datum; using jubatus::server::common::lock_service; using jubatus::server::framework::mixer::create_mixer; namespace jubatus { namespace server { namespace { struct regression_serv_config { std::string method; jubatus::util::data::optional<core::common::jsonconfig::config> parameter; core::fv_converter::converter_config converter; template<typename Ar> void serialize(Ar& ar) { ar & JUBA_MEMBER(method) & JUBA_MEMBER(parameter) & JUBA_MEMBER(converter); } }; shared_ptr<core::storage::storage_base> make_model( const framework::server_argv& arg) { return core::storage::storage_factory::create_storage( (arg.is_standalone()) ? "local" : "local_mixture"); } } // namespace regression_serv::regression_serv( const framework::server_argv& a, const jubatus::util::lang::shared_ptr<lock_service>& zk) : server_base(a), mixer_(create_mixer(a, zk, rw_mutex(), user_data_version())) { } regression_serv::~regression_serv() { } void regression_serv::get_status(status_t& status) const { status_t my_status; regression_->get_status(my_status); status.insert(my_status.begin(), my_status.end()); } uint64_t regression_serv::user_data_version() const { return 1; // should be inclemented when model data is modified } void regression_serv::set_config(const string& config) { core::common::jsonconfig::config config_root(lexical_cast<json>(config)); regression_serv_config conf = core::common::jsonconfig::config_cast_check<regression_serv_config>( config_root); config_ = config; core::common::jsonconfig::config param; if (conf.parameter) { param = *conf.parameter; } shared_ptr<core::storage::storage_base> model = make_model(argv()); regression_.reset( new core::driver::regression( model, core::regression::regression_factory::create_regression( conf.method, param, model), core::fv_converter::make_fv_converter(conf.converter, &so_loader_))); mixer_->set_driver(regression_.get()); // TODO(kuenishi): switch the function when set_config is done // because mixing method differs btwn PA, CW, etc... LOG(INFO) << "config loaded: " << config; } string regression_serv::get_config() const { check_set_config(); return config_; } int regression_serv::train(const vector<scored_datum>& data) { check_set_config(); int count = 0; core::fv_converter::datum d; for (size_t i = 0; i < data.size(); ++i) { // TODO(unno): change interface of driver? regression_->train(std::make_pair(data[i].score, data[i].data)); DLOG(INFO) << "trained: " << data[i].score; count++; } // TODO(kuenishi): send count incrementation to mixer return count; } vector<float> regression_serv::estimate( const vector<datum>& data) const { check_set_config(); vector<float> ret; for (size_t i = 0; i < data.size(); ++i) { ret.push_back(regression_->estimate(data[i])); } return ret; // vector<estimate_results> >::ok(ret); } bool regression_serv::clear() { check_set_config(); regression_->clear(); LOG(INFO) << "model cleared: " << argv().name; return true; } void regression_serv::check_set_config() const { if (!regression_) { throw JUBATUS_EXCEPTION(core::common::config_not_set()); } } } // namespace server } // namespace jubatus <commit_msg>remove unnecessary argument in regression driver<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // 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 GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "regression_serv.hpp" #include <string> #include <utility> #include <vector> #include "jubatus/util/text/json.h" #include "jubatus/util/data/optional.h" #include "jubatus/util/lang/shared_ptr.h" #include "jubatus/core/common/jsonconfig.hpp" #include "jubatus/core/fv_converter/datum.hpp" #include "jubatus/core/fv_converter/datum_to_fv_converter.hpp" #include "jubatus/core/fv_converter/converter_config.hpp" #include "jubatus/core/storage/storage_factory.hpp" #include "jubatus/core/regression/regression_factory.hpp" #include "../framework/mixer/mixer_factory.hpp" using std::string; using std::vector; using std::pair; using jubatus::util::lang::shared_ptr; using jubatus::util::text::json::json; using jubatus::util::lang::lexical_cast; using jubatus::core::fv_converter::datum; using jubatus::server::common::lock_service; using jubatus::server::framework::mixer::create_mixer; namespace jubatus { namespace server { namespace { struct regression_serv_config { std::string method; jubatus::util::data::optional<core::common::jsonconfig::config> parameter; core::fv_converter::converter_config converter; template<typename Ar> void serialize(Ar& ar) { ar & JUBA_MEMBER(method) & JUBA_MEMBER(parameter) & JUBA_MEMBER(converter); } }; shared_ptr<core::storage::storage_base> make_model( const framework::server_argv& arg) { return core::storage::storage_factory::create_storage( (arg.is_standalone()) ? "local" : "local_mixture"); } } // namespace regression_serv::regression_serv( const framework::server_argv& a, const jubatus::util::lang::shared_ptr<lock_service>& zk) : server_base(a), mixer_(create_mixer(a, zk, rw_mutex(), user_data_version())) { } regression_serv::~regression_serv() { } void regression_serv::get_status(status_t& status) const { status_t my_status; regression_->get_status(my_status); status.insert(my_status.begin(), my_status.end()); } uint64_t regression_serv::user_data_version() const { return 1; // should be inclemented when model data is modified } void regression_serv::set_config(const string& config) { core::common::jsonconfig::config config_root(lexical_cast<json>(config)); regression_serv_config conf = core::common::jsonconfig::config_cast_check<regression_serv_config>( config_root); config_ = config; core::common::jsonconfig::config param; if (conf.parameter) { param = *conf.parameter; } shared_ptr<core::storage::storage_base> model = make_model(argv()); regression_.reset( new core::driver::regression( core::regression::regression_factory::create_regression( conf.method, param, model), core::fv_converter::make_fv_converter(conf.converter, &so_loader_))); mixer_->set_driver(regression_.get()); // TODO(kuenishi): switch the function when set_config is done // because mixing method differs btwn PA, CW, etc... LOG(INFO) << "config loaded: " << config; } string regression_serv::get_config() const { check_set_config(); return config_; } int regression_serv::train(const vector<scored_datum>& data) { check_set_config(); int count = 0; core::fv_converter::datum d; for (size_t i = 0; i < data.size(); ++i) { // TODO(unno): change interface of driver? regression_->train(std::make_pair(data[i].score, data[i].data)); DLOG(INFO) << "trained: " << data[i].score; count++; } // TODO(kuenishi): send count incrementation to mixer return count; } vector<float> regression_serv::estimate( const vector<datum>& data) const { check_set_config(); vector<float> ret; for (size_t i = 0; i < data.size(); ++i) { ret.push_back(regression_->estimate(data[i])); } return ret; // vector<estimate_results> >::ok(ret); } bool regression_serv::clear() { check_set_config(); regression_->clear(); LOG(INFO) << "model cleared: " << argv().name; return true; } void regression_serv::check_set_config() const { if (!regression_) { throw JUBATUS_EXCEPTION(core::common::config_not_set()); } } } // namespace server } // namespace jubatus <|endoftext|>
<commit_before>#include "rubymotion.h" #include "motion-game.h" #include <dlfcn.h> /// @class Scene < Node /// This class represents a scene, an independent screen or stage of the /// application workflow. A scene is responsible for handling events from the /// device, providing a physics world for the sprites, and also starting the /// game loop. /// An application must have at least one scene, and the +Scene+ class is /// designed to be subclassed. VALUE rb_cScene = Qnil; #if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR extern "C" { void rb_repl_new(VALUE); } #endif enum mc_Scene_EventType { ON_BEGIN, ON_MOVE, ON_END, ON_CANCEL }; class mc_Scene : public cocos2d::LayerColor { public: cocos2d::Scene *scene; VALUE obj; SEL update_sel; cocos2d::EventListenerTouchOneByOne *touch_listener; mc_Scene() { obj = Qnil; touch_listener = NULL; #if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV update_sel = rb_selector("update:"); #else update_sel = rb_selector("update"); #endif } static mc_Scene *create(void) { auto scene = new mc_Scene(); scene->initWithColor(cocos2d::Color4B::BLACK); return scene; } virtual void update(float delta) { LayerColor::update(delta); VALUE arg = DBL2NUM(delta); rb_send(obj, update_sel, 1, &arg); } void setBackgroundColor(cocos2d::Color3B color) { setColor(color); updateColor(); } #if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR virtual void onEnter() { cocos2d::LayerColor::onEnter(); rb_repl_new(this->obj); } #endif }; #define SCENE(obj) _COCOS_WRAP_GET(obj, mc_Scene) extern "C" cocos2d::Scene * rb_any_to_scene(VALUE obj) { if (rb_obj_is_kind_of(obj, rb_cScene)) { return SCENE(obj)->scene; } rb_raise(rb_eArgError, "expected Scene object"); } static VALUE scene_alloc(VALUE rcv, SEL sel) { auto layer = mc_Scene::create(); auto scene = cocos2d::Scene::createWithPhysics(); scene->addChild(layer); layer->scene = scene; VALUE obj = rb_cocos2d_object_new(layer, rcv); layer->obj = rb_retain(obj); return obj; } /// @group Constructors /// @method #initialize /// The default initializer. Subclasses can construct the scene interface in /// this method, as well as providing an implementation for {#update}, then /// run the update loop by calling {#start_update}. /// @return [Scene] the receiver. static VALUE scene_initialize(VALUE rcv, SEL sel) { return rcv; } /// @group Update Loop /// @method #start_update /// Starts the update loop. The +#update+ method will be called on this object /// for every frame. /// @return [self] the receiver. static VALUE scene_start_update(VALUE rcv, SEL sel) { SCENE(rcv)->scheduleUpdate(); return rcv; } /// @method #stop_update /// Stops the update loop. The +#update+ method will no longer be called on /// this object. /// @return [self] the receiver. static VALUE scene_stop_update(VALUE rcv, SEL sel) { SCENE(rcv)->unscheduleUpdate(); return rcv; } /// @method #update(delta) /// The update loop method. Subclasses can provide a custom implementation of /// this method. The default implementation is empty. /// @param delta [Float] a value representing the amount of time, in seconds, /// since the last time this method was called. /// @return [self] the receiver. static VALUE scene_update(VALUE rcv, SEL sel, VALUE delta) { // Do nothing. return rcv; } /// @group Events static VALUE scene_add_listener(VALUE rcv, cocos2d::EventListener *listener) { auto scene = SCENE(rcv); scene->getEventDispatcher()->addEventListenerWithSceneGraphPriority( listener, scene); return rcv; } static bool scene_onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) { return true; } static VALUE scene_on_touch_event(VALUE rcv, SEL sel, mc_Scene_EventType type) { VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... auto scene = SCENE(rcv); if (scene->touch_listener == NULL) { scene->touch_listener = cocos2d::EventListenerTouchOneByOne::create(); } else { scene->getEventDispatcher()->removeEventListener(scene->touch_listener); } auto lambda = [block](cocos2d::Touch *touch, cocos2d::Event *event) -> bool { VALUE touch_obj = rb_cocos2d_object_new(touch, rb_cTouch); return RTEST(rb_block_call(block, 1, &touch_obj)); }; switch (type) { case ON_BEGIN: scene->touch_listener->onTouchBegan = lambda; break; case ON_MOVE: scene->touch_listener->onTouchMoved = lambda; break; case ON_END: scene->touch_listener->onTouchEnded = lambda; break; case ON_CANCEL: scene->touch_listener->onTouchCancelled = lambda; break; } if (scene->touch_listener->onTouchBegan == NULL) { // EventDispatcher will use the return value of 'onTouchBegan' to determine whether to pass following 'move', 'end' // message to 'EventListenerTouchOneByOne' or not. So 'onTouchBegan' needs to be set. scene->touch_listener->onTouchBegan = scene_onTouchBegan; } return scene_add_listener(rcv, scene->touch_listener); } /// @method #on_touch_begin /// Starts listening for touch begin events on the receiver. /// @yield [Events::Touch] the given block will be yield when a touch begin /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_begin(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_BEGIN); } /// @method #on_touch_end /// Starts listening for touch end events on the receiver. /// This method requires {#on_touch_begin} calling in order to catch the event. /// @yield [Events::Touch] the given block will be yield when a touch end /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_end(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_END); } /// @method #on_touch_move /// Starts listening for touch move events on the receiver. /// This method requires {#on_touch_begin} calling in order to catch the event. /// @yield [Events::Touch] the given block will be yield when a touch move /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_move(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_MOVE); } /// @method #on_touch_cancel /// Starts listening for touch cancel events on the receiver. /// This method requires {#on_touch_begin} calling in order to catch the event. /// @yield [Events::Touch] the given block will be yield when a touch cancel /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_cancel(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_CANCEL); } /// @method #on_accelerate /// Starts listening for accelerometer events on the receiver. /// @yield [Events::Acceleration] the given block will be yield when an /// accelerometer event is received from the device. /// @return [self] the receiver. static VALUE scene_on_accelerate(VALUE rcv, SEL sel) { #if CC_TARGET_OS_APPLETV rb_raise(rb_eRuntimeError, "Not supported in tvOS"); #else VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... cocos2d::Device::setAccelerometerEnabled(true); auto listener = cocos2d::EventListenerAcceleration::create( [block](cocos2d::Acceleration *acc, cocos2d::Event *event) { VALUE acc_obj = rb_cocos2d_object_new(acc, rb_cAcceleration); rb_block_call(block, 1, &acc_obj); }); return scene_add_listener(rcv, listener); #endif } /// @method #on_contact_begin /// Starts listening for contact begin events from the physics engine. /// @yield [Events::PhysicsContact] the given block will be yield when a /// contact event is received from the physics engine. /// @return [self] the receiver. static VALUE scene_on_contact_begin(VALUE rcv, SEL sel) { VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... auto listener = cocos2d::EventListenerPhysicsContact::create(); listener->onContactBegin = [block](cocos2d::PhysicsContact &contact) -> bool { return RTEST(rb_block_call(block, 0, NULL)); }; return scene_add_listener(rcv, listener); } /// @endgroup /// @property #gravity /// @return [Point] the gravity of the scene's physics world. static VALUE scene_gravity(VALUE rcv, SEL sel) { return rb_ccvec2_to_obj(SCENE(rcv)->scene->getPhysicsWorld()->getGravity()); } static VALUE scene_gravity_set(VALUE rcv, SEL sel, VALUE arg) { SCENE(rcv)->scene->getPhysicsWorld()->setGravity(rb_any_to_ccvec2(arg)); return rcv; } /// @method #debug_physics? /// @return [Boolean] whether the physics engine should draw debug lines. static VALUE scene_debug_physics(VALUE rcv, SEL sel) { return SCENE(rcv)->scene->getPhysicsWorld()->getDebugDrawMask() == cocos2d::PhysicsWorld::DEBUGDRAW_NONE ? Qfalse : Qtrue; } /// @method #debug_physics=(value) /// Set to draw the debug line. /// @param value [Boolean] true if draw debug lines. static VALUE scene_debug_physics_set(VALUE rcv, SEL sel, VALUE arg) { SCENE(rcv)->scene->getPhysicsWorld()->setDebugDrawMask(RTEST(arg) ? cocos2d::PhysicsWorld::DEBUGDRAW_ALL : cocos2d::PhysicsWorld::DEBUGDRAW_NONE); return arg; } /// @method #background_color=(color) /// Set background color for scene. /// @param color [Color] background color for scene. static VALUE scene_background_color_set(VALUE rcv, SEL sel, VALUE val) { SCENE(rcv)->setBackgroundColor(rb_any_to_cccolor3(val)); return val; } extern "C" void Init_Layer(void) { rb_cScene = rb_define_class_under(rb_mMC, "Scene", rb_cNode); // rb_register_cocos2d_object_finalizer(rb_cScene); removed because rb_cScene inherits rb_cNode and it already has finalizer. rb_define_singleton_method(rb_cScene, "alloc", scene_alloc, 0); rb_define_method(rb_cScene, "initialize", scene_initialize, 0); rb_define_method(rb_cScene, "start_update", scene_start_update, 0); rb_define_method(rb_cScene, "stop_update", scene_stop_update, 0); rb_define_method(rb_cScene, "update", scene_update, 1); rb_define_method(rb_cScene, "on_touch_begin", scene_on_touch_begin, 0); rb_define_method(rb_cScene, "on_touch_end", scene_on_touch_end, 0); rb_define_method(rb_cScene, "on_touch_move", scene_on_touch_move, 0); rb_define_method(rb_cScene, "on_touch_cancel", scene_on_touch_cancel, 0); rb_define_method(rb_cScene, "on_accelerate", scene_on_accelerate, 0); rb_define_method(rb_cScene, "on_contact_begin", scene_on_contact_begin, 0); rb_define_method(rb_cScene, "gravity", scene_gravity, 0); rb_define_method(rb_cScene, "gravity=", scene_gravity_set, 1); rb_define_method(rb_cScene, "debug_physics?", scene_debug_physics, 0); rb_define_method(rb_cScene, "debug_physics=", scene_debug_physics_set, 1); rb_define_method(rb_cScene, "background_color=", scene_background_color_set, 1); rb_define_method(rb_cScene, "color=", scene_background_color_set, 1); // depricated } <commit_msg>Revert "[#69] add the note in documents"<commit_after>#include "rubymotion.h" #include "motion-game.h" #include <dlfcn.h> /// @class Scene < Node /// This class represents a scene, an independent screen or stage of the /// application workflow. A scene is responsible for handling events from the /// device, providing a physics world for the sprites, and also starting the /// game loop. /// An application must have at least one scene, and the +Scene+ class is /// designed to be subclassed. VALUE rb_cScene = Qnil; #if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR extern "C" { void rb_repl_new(VALUE); } #endif enum mc_Scene_EventType { ON_BEGIN, ON_MOVE, ON_END, ON_CANCEL }; class mc_Scene : public cocos2d::LayerColor { public: cocos2d::Scene *scene; VALUE obj; SEL update_sel; cocos2d::EventListenerTouchOneByOne *touch_listener; mc_Scene() { obj = Qnil; touch_listener = NULL; #if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV update_sel = rb_selector("update:"); #else update_sel = rb_selector("update"); #endif } static mc_Scene *create(void) { auto scene = new mc_Scene(); scene->initWithColor(cocos2d::Color4B::BLACK); return scene; } virtual void update(float delta) { LayerColor::update(delta); VALUE arg = DBL2NUM(delta); rb_send(obj, update_sel, 1, &arg); } void setBackgroundColor(cocos2d::Color3B color) { setColor(color); updateColor(); } #if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR virtual void onEnter() { cocos2d::LayerColor::onEnter(); rb_repl_new(this->obj); } #endif }; #define SCENE(obj) _COCOS_WRAP_GET(obj, mc_Scene) extern "C" cocos2d::Scene * rb_any_to_scene(VALUE obj) { if (rb_obj_is_kind_of(obj, rb_cScene)) { return SCENE(obj)->scene; } rb_raise(rb_eArgError, "expected Scene object"); } static VALUE scene_alloc(VALUE rcv, SEL sel) { auto layer = mc_Scene::create(); auto scene = cocos2d::Scene::createWithPhysics(); scene->addChild(layer); layer->scene = scene; VALUE obj = rb_cocos2d_object_new(layer, rcv); layer->obj = rb_retain(obj); return obj; } /// @group Constructors /// @method #initialize /// The default initializer. Subclasses can construct the scene interface in /// this method, as well as providing an implementation for {#update}, then /// run the update loop by calling {#start_update}. /// @return [Scene] the receiver. static VALUE scene_initialize(VALUE rcv, SEL sel) { return rcv; } /// @group Update Loop /// @method #start_update /// Starts the update loop. The +#update+ method will be called on this object /// for every frame. /// @return [self] the receiver. static VALUE scene_start_update(VALUE rcv, SEL sel) { SCENE(rcv)->scheduleUpdate(); return rcv; } /// @method #stop_update /// Stops the update loop. The +#update+ method will no longer be called on /// this object. /// @return [self] the receiver. static VALUE scene_stop_update(VALUE rcv, SEL sel) { SCENE(rcv)->unscheduleUpdate(); return rcv; } /// @method #update(delta) /// The update loop method. Subclasses can provide a custom implementation of /// this method. The default implementation is empty. /// @param delta [Float] a value representing the amount of time, in seconds, /// since the last time this method was called. /// @return [self] the receiver. static VALUE scene_update(VALUE rcv, SEL sel, VALUE delta) { // Do nothing. return rcv; } /// @group Events static VALUE scene_add_listener(VALUE rcv, cocos2d::EventListener *listener) { auto scene = SCENE(rcv); scene->getEventDispatcher()->addEventListenerWithSceneGraphPriority( listener, scene); return rcv; } static bool scene_onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) { return true; } static VALUE scene_on_touch_event(VALUE rcv, SEL sel, mc_Scene_EventType type) { VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... auto scene = SCENE(rcv); if (scene->touch_listener == NULL) { scene->touch_listener = cocos2d::EventListenerTouchOneByOne::create(); } else { scene->getEventDispatcher()->removeEventListener(scene->touch_listener); } auto lambda = [block](cocos2d::Touch *touch, cocos2d::Event *event) -> bool { VALUE touch_obj = rb_cocos2d_object_new(touch, rb_cTouch); return RTEST(rb_block_call(block, 1, &touch_obj)); }; switch (type) { case ON_BEGIN: scene->touch_listener->onTouchBegan = lambda; break; case ON_MOVE: scene->touch_listener->onTouchMoved = lambda; break; case ON_END: scene->touch_listener->onTouchEnded = lambda; break; case ON_CANCEL: scene->touch_listener->onTouchCancelled = lambda; break; } if (scene->touch_listener->onTouchBegan == NULL) { // EventDispatcher will use the return value of 'onTouchBegan' to determine whether to pass following 'move', 'end' // message to 'EventListenerTouchOneByOne' or not. So 'onTouchBegan' needs to be set. scene->touch_listener->onTouchBegan = scene_onTouchBegan; } return scene_add_listener(rcv, scene->touch_listener); } /// @method #on_touch_begin /// Starts listening for touch begin events on the receiver. /// @yield [Events::Touch] the given block will be yield when a touch begin /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_begin(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_BEGIN); } /// @method #on_touch_end /// Starts listening for touch end events on the receiver. /// @yield [Events::Touch] the given block will be yield when a touch end /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_end(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_END); } /// @method #on_touch_move /// Starts listening for touch move events on the receiver. /// @yield [Events::Touch] the given block will be yield when a touch move /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_move(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_MOVE); } /// @method #on_touch_cancel /// Starts listening for touch cancel events on the receiver. /// @yield [Events::Touch] the given block will be yield when a touch cancel /// event is received. /// @return [self] the receiver. static VALUE scene_on_touch_cancel(VALUE rcv, SEL sel) { return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_CANCEL); } /// @method #on_accelerate /// Starts listening for accelerometer events on the receiver. /// @yield [Events::Acceleration] the given block will be yield when an /// accelerometer event is received from the device. /// @return [self] the receiver. static VALUE scene_on_accelerate(VALUE rcv, SEL sel) { #if CC_TARGET_OS_APPLETV rb_raise(rb_eRuntimeError, "Not supported in tvOS"); #else VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... cocos2d::Device::setAccelerometerEnabled(true); auto listener = cocos2d::EventListenerAcceleration::create( [block](cocos2d::Acceleration *acc, cocos2d::Event *event) { VALUE acc_obj = rb_cocos2d_object_new(acc, rb_cAcceleration); rb_block_call(block, 1, &acc_obj); }); return scene_add_listener(rcv, listener); #endif } /// @method #on_contact_begin /// Starts listening for contact begin events from the physics engine. /// @yield [Events::PhysicsContact] the given block will be yield when a /// contact event is received from the physics engine. /// @return [self] the receiver. static VALUE scene_on_contact_begin(VALUE rcv, SEL sel) { VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... auto listener = cocos2d::EventListenerPhysicsContact::create(); listener->onContactBegin = [block](cocos2d::PhysicsContact &contact) -> bool { return RTEST(rb_block_call(block, 0, NULL)); }; return scene_add_listener(rcv, listener); } /// @endgroup /// @property #gravity /// @return [Point] the gravity of the scene's physics world. static VALUE scene_gravity(VALUE rcv, SEL sel) { return rb_ccvec2_to_obj(SCENE(rcv)->scene->getPhysicsWorld()->getGravity()); } static VALUE scene_gravity_set(VALUE rcv, SEL sel, VALUE arg) { SCENE(rcv)->scene->getPhysicsWorld()->setGravity(rb_any_to_ccvec2(arg)); return rcv; } /// @method #debug_physics? /// @return [Boolean] whether the physics engine should draw debug lines. static VALUE scene_debug_physics(VALUE rcv, SEL sel) { return SCENE(rcv)->scene->getPhysicsWorld()->getDebugDrawMask() == cocos2d::PhysicsWorld::DEBUGDRAW_NONE ? Qfalse : Qtrue; } /// @method #debug_physics=(value) /// Set to draw the debug line. /// @param value [Boolean] true if draw debug lines. static VALUE scene_debug_physics_set(VALUE rcv, SEL sel, VALUE arg) { SCENE(rcv)->scene->getPhysicsWorld()->setDebugDrawMask(RTEST(arg) ? cocos2d::PhysicsWorld::DEBUGDRAW_ALL : cocos2d::PhysicsWorld::DEBUGDRAW_NONE); return arg; } /// @method #background_color=(color) /// Set background color for scene. /// @param color [Color] background color for scene. static VALUE scene_background_color_set(VALUE rcv, SEL sel, VALUE val) { SCENE(rcv)->setBackgroundColor(rb_any_to_cccolor3(val)); return val; } extern "C" void Init_Layer(void) { rb_cScene = rb_define_class_under(rb_mMC, "Scene", rb_cNode); // rb_register_cocos2d_object_finalizer(rb_cScene); removed because rb_cScene inherits rb_cNode and it already has finalizer. rb_define_singleton_method(rb_cScene, "alloc", scene_alloc, 0); rb_define_method(rb_cScene, "initialize", scene_initialize, 0); rb_define_method(rb_cScene, "start_update", scene_start_update, 0); rb_define_method(rb_cScene, "stop_update", scene_stop_update, 0); rb_define_method(rb_cScene, "update", scene_update, 1); rb_define_method(rb_cScene, "on_touch_begin", scene_on_touch_begin, 0); rb_define_method(rb_cScene, "on_touch_end", scene_on_touch_end, 0); rb_define_method(rb_cScene, "on_touch_move", scene_on_touch_move, 0); rb_define_method(rb_cScene, "on_touch_cancel", scene_on_touch_cancel, 0); rb_define_method(rb_cScene, "on_accelerate", scene_on_accelerate, 0); rb_define_method(rb_cScene, "on_contact_begin", scene_on_contact_begin, 0); rb_define_method(rb_cScene, "gravity", scene_gravity, 0); rb_define_method(rb_cScene, "gravity=", scene_gravity_set, 1); rb_define_method(rb_cScene, "debug_physics?", scene_debug_physics, 0); rb_define_method(rb_cScene, "debug_physics=", scene_debug_physics_set, 1); rb_define_method(rb_cScene, "background_color=", scene_background_color_set, 1); rb_define_method(rb_cScene, "color=", scene_background_color_set, 1); // depricated } <|endoftext|>
<commit_before>#include "augs/enums/callback_result.h" #include "game/cosmos/specific_entity_handle.h" #include "application/intercosm.h" #include "application/setups/editor/editor_folder.h" #include "application/setups/editor/editor_command_input.h" #include "application/setups/editor/commands/change_entity_property_command.h" #include "application/setups/editor/commands/change_flavour_property_command.h" #include "application/setups/editor/commands/change_common_state_command.h" #include "application/setups/editor/commands/change_grouping_command.h" #include "application/setups/editor/commands/change_property_command.h" #include "application/setups/editor/commands/asset_commands.h" #include "application/setups/editor/commands/detail/editor_property_accessors.h" #include "augs/readwrite/byte_readwrite.h" template <class D> std::string change_property_command<D>::describe() const { return built_description; } template <class D> void change_property_command<D>::refresh_other_state(const editor_command_input in) { (void)in; if constexpr(std::is_same_v<D, change_asset_property_command<assets::image_id>>) { auto& self = *static_cast<D*>(this); for (const auto& i : self.affected_assets) { in.folder.work->update_offsets_of(i, changer_callback_result::DONT_REFRESH); } if (!self.affected_assets.empty()) { /* Only for refreshing */ in.folder.work->update_offsets_of(self.affected_assets.front()); } } } template <class D> void change_property_command<D>::rewrite_change( const std::vector<std::byte>& new_value, const editor_command_input in ) { auto& self = *static_cast<D*>(this); common.reset_timestamp(); /* At this point, the command can only be undone or rewritten, so it makes sense that the storage for value after change is empty. */ ensure(value_after_change.empty()); editor_property_accessors::access_each_property( self, in, [&](auto& field) { augs::from_bytes(new_value, field); return callback_result::CONTINUE; } ); refresh_other_state(in); } template <class Archive, class T> static void write_object_or_trivial_marker(Archive& ar, const T& from, const std::size_t bytes_count) { if constexpr(std::is_same_v<T, augs::trivial_type_marker>) { const std::byte* location = reinterpret_cast<const std::byte*>(std::addressof(from)); ar.write(location, bytes_count); } else { (void)bytes_count; augs::write_bytes(ar, from); } } template <class Archive, class T> static void read_object_or_trivial_marker(Archive& ar, T& to, const std::size_t bytes_count) { if constexpr(std::is_same_v<T, augs::trivial_type_marker>) { std::byte* location = reinterpret_cast<std::byte*>(std::addressof(to)); ar.read(location, bytes_count); } else { (void)bytes_count; augs::read_bytes(ar, to); } } template <class D> void change_property_command<D>::redo(const editor_command_input in) { auto& self = *static_cast<D*>(this); ensure(values_before_change.empty()); const auto trivial_element_size = value_after_change.size(); auto before_change_data = augs::ref_memory_stream(values_before_change); auto after_change_data = augs::cref_memory_stream(value_after_change); editor_property_accessors::access_each_property( self, in, [&](auto& field) { write_object_or_trivial_marker(before_change_data, field, trivial_element_size); read_object_or_trivial_marker(after_change_data, field, trivial_element_size); after_change_data.set_read_pos(0u); return callback_result::CONTINUE; } ); value_after_change.clear(); if constexpr(std::is_same_v<D, change_asset_property_command<assets::image_id>>) { for (const auto& i : self.affected_assets) { in.folder.work->update_offsets_of(i, changer_callback_result::DONT_REFRESH); } if (!self.affected_assets.empty()) { /* Only for refreshing */ in.folder.work->update_offsets_of(self.affected_assets.front()); } } } template <class D> void change_property_command<D>::undo(const editor_command_input in) { auto& self = *static_cast<D*>(this); bool read_once = true; ensure(value_after_change.empty()); const auto trivial_element_size = values_before_change.size() / self.count_affected(); auto before_change_data = augs::cref_memory_stream(values_before_change); auto after_change_data = augs::ref_memory_stream(value_after_change); editor_property_accessors::access_each_property( self, in, [&](auto& field) { if (read_once) { write_object_or_trivial_marker(after_change_data, field, trivial_element_size); read_once = false; } read_object_or_trivial_marker(before_change_data, field, trivial_element_size); return callback_result::CONTINUE; } ); values_before_change.clear(); refresh_other_state(in); } template class change_property_command<change_flavour_property_command>; template class change_property_command<change_entity_property_command>; template class change_property_command<change_common_state_command>; template class change_property_command<change_group_property_command>; template class change_property_command<change_current_mode_property_command>; template class change_property_command<change_mode_vars_property_command>; template class change_property_command<change_asset_property_command<assets::image_id>>; template class change_property_command<change_asset_property_command<assets::sound_id>>; template class change_property_command<change_asset_property_command<assets::plain_animation_id>>; template class change_property_command<change_asset_property_command<assets::particle_effect_id>>; <commit_msg>Simplified change_property_command to not clear after value data<commit_after>#include "augs/enums/callback_result.h" #include "game/cosmos/specific_entity_handle.h" #include "application/intercosm.h" #include "application/setups/editor/editor_folder.h" #include "application/setups/editor/editor_command_input.h" #include "application/setups/editor/commands/change_entity_property_command.h" #include "application/setups/editor/commands/change_flavour_property_command.h" #include "application/setups/editor/commands/change_common_state_command.h" #include "application/setups/editor/commands/change_grouping_command.h" #include "application/setups/editor/commands/change_property_command.h" #include "application/setups/editor/commands/asset_commands.h" #include "application/setups/editor/commands/detail/editor_property_accessors.h" #include "augs/readwrite/byte_readwrite.h" template <class D> std::string change_property_command<D>::describe() const { return built_description; } template <class D> void change_property_command<D>::refresh_other_state(const editor_command_input in) { (void)in; if constexpr(std::is_same_v<D, change_asset_property_command<assets::image_id>>) { auto& self = *static_cast<D*>(this); for (const auto& i : self.affected_assets) { in.folder.work->update_offsets_of(i, changer_callback_result::DONT_REFRESH); } if (!self.affected_assets.empty()) { /* Only for refreshing */ in.folder.work->update_offsets_of(self.affected_assets.front()); } } } template <class D> void change_property_command<D>::rewrite_change( const std::vector<std::byte>& new_value, const editor_command_input in ) { auto& self = *static_cast<D*>(this); common.reset_timestamp(); editor_property_accessors::access_each_property( self, in, [&](auto& field) { augs::from_bytes(new_value, field); return callback_result::CONTINUE; } ); refresh_other_state(in); } template <class Archive, class T> static void write_object_or_trivial_marker(Archive& ar, const T& from, const std::size_t bytes_count) { if constexpr(std::is_same_v<T, augs::trivial_type_marker>) { const std::byte* location = reinterpret_cast<const std::byte*>(std::addressof(from)); ar.write(location, bytes_count); } else { (void)bytes_count; augs::write_bytes(ar, from); } } template <class Archive, class T> static void read_object_or_trivial_marker(Archive& ar, T& to, const std::size_t bytes_count) { if constexpr(std::is_same_v<T, augs::trivial_type_marker>) { std::byte* location = reinterpret_cast<std::byte*>(std::addressof(to)); ar.read(location, bytes_count); } else { (void)bytes_count; augs::read_bytes(ar, to); } } template <class D> void change_property_command<D>::redo(const editor_command_input in) { auto& self = *static_cast<D*>(this); ensure(values_before_change.empty()); const auto trivial_element_size = value_after_change.size(); auto before_change_data = augs::ref_memory_stream(values_before_change); auto after_change_data = augs::cref_memory_stream(value_after_change); editor_property_accessors::access_each_property( self, in, [&](auto& field) { write_object_or_trivial_marker(before_change_data, field, trivial_element_size); read_object_or_trivial_marker(after_change_data, field, trivial_element_size); after_change_data.set_read_pos(0u); return callback_result::CONTINUE; } ); if constexpr(std::is_same_v<D, change_asset_property_command<assets::image_id>>) { for (const auto& i : self.affected_assets) { in.folder.work->update_offsets_of(i, changer_callback_result::DONT_REFRESH); } if (!self.affected_assets.empty()) { /* Only for refreshing */ in.folder.work->update_offsets_of(self.affected_assets.front()); } } } template <class D> void change_property_command<D>::undo(const editor_command_input in) { auto& self = *static_cast<D*>(this); const auto trivial_element_size = values_before_change.size() / self.count_affected(); auto before_change_data = augs::cref_memory_stream(values_before_change); editor_property_accessors::access_each_property( self, in, [&](auto& field) { read_object_or_trivial_marker(before_change_data, field, trivial_element_size); return callback_result::CONTINUE; } ); values_before_change.clear(); refresh_other_state(in); } template class change_property_command<change_flavour_property_command>; template class change_property_command<change_entity_property_command>; template class change_property_command<change_common_state_command>; template class change_property_command<change_group_property_command>; template class change_property_command<change_current_mode_property_command>; template class change_property_command<change_mode_vars_property_command>; template class change_property_command<change_asset_property_command<assets::image_id>>; template class change_property_command<change_asset_property_command<assets::sound_id>>; template class change_property_command<change_asset_property_command<assets::plain_animation_id>>; template class change_property_command<change_asset_property_command<assets::particle_effect_id>>; <|endoftext|>