hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
a16f72d14ec77d9b41e3cd7e269a78b0f9452883
5,686
cpp
C++
src/DebugReportCallback.cpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
src/DebugReportCallback.cpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
src/DebugReportCallback.cpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
#include <gbVk/DebugReportCallback.hpp> #include <gbVk/Exceptions.hpp> #include <gbVk/Instance.hpp> namespace GHULBUS_VULKAN_NAMESPACE { DebugReportCallback::DebugReportCallback(Instance& instance, VkDebugReportFlagsEXT flags) :m_debugReportCallback(nullptr), m_instance(instance.getVkInstance()) { m_vkCreateDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>( vkGetInstanceProcAddr(m_instance, "vkCreateDebugReportCallbackEXT")); m_vkDestroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>( vkGetInstanceProcAddr(m_instance, "vkDestroyDebugReportCallbackEXT")); if ((!m_vkCreateDebugReportCallback) || (!m_vkDestroyDebugReportCallback)) { GHULBUS_THROW(Exceptions::VulkanError{} << Exception_Info::vulkan_error_code(VK_ERROR_EXTENSION_NOT_PRESENT), "Extension VK_EXT_debug_report was not loaded correctly."); } VkDebugReportCallbackCreateInfoEXT create_info; create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; create_info.pNext = nullptr; create_info.flags = flags; create_info.pfnCallback = static_callback; create_info.pUserData = this; VkResult const res = m_vkCreateDebugReportCallback(m_instance, &create_info, nullptr, &m_debugReportCallback); checkVulkanError(res, "Error in vkCreateDebugReportCallbackEXT."); } DebugReportCallback::~DebugReportCallback() { if (m_debugReportCallback) { m_vkDestroyDebugReportCallback(m_instance, m_debugReportCallback, nullptr); } } DebugReportCallback::DebugReportCallback(DebugReportCallback&& rhs) :m_debugReportCallback(rhs.m_debugReportCallback), m_instance(rhs.m_instance) { rhs.m_debugReportCallback = nullptr; } void DebugReportCallback::addCallback(Callback callback_function) { m_userCallbacks.emplace_back(std::move(callback_function)); } VkBool32 DebugReportCallback::callback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT object_type, uint64_t object, size_t location, int32_t message_code, const char* layer_prefix, const char* message) { for (auto const& f : m_userCallbacks) { if (f(flags, object_type, object, location, message_code, layer_prefix, message) == Return::Abort) { return VK_TRUE; } } return VK_FALSE; } VkBool32 DebugReportCallback::static_callback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT object_type, uint64_t object, size_t location, int32_t message_code, const char* layer_prefix, const char* message, void* user_data) { DebugReportCallback* thisptr = reinterpret_cast<DebugReportCallback*>(user_data); return thisptr->callback(flags, object_type, object, location, message_code, layer_prefix, message); } char const* DebugReportCallback::translateFlags(VkDebugReportFlagsEXT flags) { switch (flags) { case VK_DEBUG_REPORT_INFORMATION_BIT_EXT: return "Information"; case VK_DEBUG_REPORT_WARNING_BIT_EXT: return "Warning"; case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT: return "Performance"; case VK_DEBUG_REPORT_ERROR_BIT_EXT: return "Error"; case VK_DEBUG_REPORT_DEBUG_BIT_EXT: return "Debug"; default: return ""; } } char const* DebugReportCallback::translateObjectType(VkDebugReportObjectTypeEXT object_type) { switch (object_type) { default: case VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT: return "Unknown"; case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: return "Instance"; case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: return "PhysicalDevice"; case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: return "Device"; case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: return "Queue"; case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: return "Semaphore"; case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: return "CommandBuffer"; case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: return "Fence"; case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: return "DeviceMemory"; case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: return "Buffer"; case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: return "Image"; case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: return "Event"; case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: return "QueryPool"; case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: return "BufferView"; case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: return "ImageView"; case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: return "ShaderModule"; case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: return "PipelineCache"; case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: return "PipelineLayout"; case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: return "RenderPass"; case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: return "Pipeline"; case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: return "DescriptorSetLayout"; case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: return "Sampler"; case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: return "DescriptorPool"; case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: return "DescriptorSet"; case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: return "Framebuffer"; case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "CommandPool"; case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "Surface"; case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "Swapchain"; case VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT: return "DebugReport"; } } }
48.598291
117
0.780162
[ "object" ]
a175f5836450af521a90bdf857f27c47eaa95ecc
3,976
cc
C++
Engine/app/guifeature/androidguiinputhandler.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
26
2015-01-15T12:57:40.000Z
2022-02-16T10:07:12.000Z
Engine/app/guifeature/androidguiinputhandler.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
null
null
null
Engine/app/guifeature/androidguiinputhandler.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
17
2015-02-18T07:51:31.000Z
2020-06-01T01:10:12.000Z
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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. ****************************************************************************/ #if __ANDROID__ #include "input/input_stdneb.h" #include "androidguiinputhandler.h" #include "input/inputserver.h" #include "myguiplatforms/include/MyGUI_GenesisInput.h" #include "gui.h" #include "myguiplatforms/include/MyGUI_GenesisInput.h" namespace Input { __ImplementClass(Input::AndroidGuiInputHandler, 'AGIH', Input::InputTouchScreen); using namespace Input; //------------------------------------------------------------------------ AndroidGuiInputHandler::AndroidGuiInputHandler() { } //------------------------------------------------------------------------ AndroidGuiInputHandler::~AndroidGuiInputHandler() { } //------------------------------------------------------------------------ bool AndroidGuiInputHandler::OnEvent( const Input::InputEvent& inputEvent ) { MyGUI::GenesisInputManager* gui_input = MyGUI::GenesisInputManager::getInstancePtr(); if (!gui_input) { return false; } bool ret = false; static int mouse_z = 0; switch (inputEvent.GetType()) { // reset input handler if another one begins to capture case InputEvent::TouchMotionDown: { IndexT idxTouch(0); // force to produce a move event const SizeT count = inputEvent.GetPointersCount(); for (IndexT i = 0; i < count; ++i) { const IndexT id = inputEvent.GetPointerId(i); const Math::float2& pos_n = inputEvent.GetNormTouchPos(id); m_FingerStates[id].down = true; if ( i < 1 && !(pos_n.x() < 0.0f || pos_n.x() > 1.0f || pos_n.y() < 0.0f || pos_n.y() > 1.0f)) { gui_input->injectMouseMove(pos_n.x(), pos_n.y(), mouse_z); } ret |= gui_input->injectMousePress(pos_n.x(), pos_n.y(), MyGUI::MouseButton::Left); } } break; case InputEvent::TouchMotionUp: { const SizeT count = inputEvent.GetPointersCount(); for (IndexT i = 0; i < count; ++i) { const IndexT id = inputEvent.GetPointerId(i); m_FingerStates[id].up = true; const Math::float2& pos_n = inputEvent.GetNormTouchPos(id); ret |= gui_input->injectMouseRelease(pos_n.x(), pos_n.y(), MyGUI::MouseButton::Left); } } break; case InputEvent::TouchMotionMove: { const SizeT count = inputEvent.GetPointersCount(); for (IndexT i = 0; i < count && i < 1; ++i) { const IndexT id = inputEvent.GetPointerId(i); m_FingerStates[id].pressed = true; const Math::float2& pos_n = inputEvent.GetNormTouchPos(id); if ( !(pos_n.x() < 0.0f || pos_n.x() > 1.0f || pos_n.y() < 0.0f || pos_n.y() > 1.0f)) { ret |= gui_input->injectMouseMove(pos_n.x(), pos_n.y(), mouse_z); } } } break; default: break; } return !ret; } } #endif
30.584615
99
0.624748
[ "3d" ]
a176443fa480a5a1da32fa47b85d0d9773905390
535
cpp
C++
chapters/11/ch11.cpp
tmdefreitas/cpp4e
1e034bb0fa849903b6a2efe31e7817ebd6f5173e
[ "MIT" ]
null
null
null
chapters/11/ch11.cpp
tmdefreitas/cpp4e
1e034bb0fa849903b6a2efe31e7817ebd6f5173e
[ "MIT" ]
null
null
null
chapters/11/ch11.cpp
tmdefreitas/cpp4e
1e034bb0fa849903b6a2efe31e7817ebd6f5173e
[ "MIT" ]
null
null
null
// Ch. 11 - Select Operations //11.2 Free Store // free store == the heap == dynamic memory //C++ implementation does not guarantee the presence of a garbace collector //Good strategy to avoid "naked new" //Can overload new operator to allocate space other than the free store. //Use nothrow in this overload to avoid throwing exceptions when allocation fails. //Lambda expressions void print_modulo(const vector<int>& v, ostream& os, int m) { for_each(begin(v), end(v), [&os,m](int x) {if (x%m==0) os << x << '\n';} ); }
28.157895
82
0.691589
[ "vector" ]
a17946b70fdeea84ceb09c18ec9274e467d30109
6,644
cpp
C++
ds/security/gina/samples/gptdemo/gptdemo.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/gina/samples/gptdemo/gptdemo.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/gina/samples/gptdemo/gptdemo.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "main.h" #include <initguid.h> #include <gptdemo.h> #include <gpedit.h> // // Global variables for this DLL // LONG g_cRefThisDll = 0; HINSTANCE g_hInstance; ///////////////////////////////////////////////////////////////////////////// // DLL Entry Point extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) { if (dwReason == DLL_PROCESS_ATTACH) { g_hInstance = hInstance; DisableThreadLibraryCalls(hInstance); InitNameSpace(); #if DBG InitDebugSupport(); #endif } return TRUE; // ok } ///////////////////////////////////////////////////////////////////////////// // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { return (g_cRefThisDll == 0 ? S_OK : S_FALSE); } ///////////////////////////////////////////////////////////////////////////// // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return (CreateComponentDataClassFactory (rclsid, riid, ppv)); } ///////////////////////////////////////////////////////////////////////////// // DllRegisterServer - Adds entries to the system registry const TCHAR szSnapInLocation[] = TEXT("%SystemRoot%\\System32\\GPTDemo.dll"); STDAPI DllRegisterServer(void) { TCHAR szSnapInKey[50]; TCHAR szSubKey[200]; TCHAR szSnapInName[100]; TCHAR szGUID[50]; DWORD dwDisp, dwIndex; LONG lResult; HKEY hKey; StringFromGUID2 (CLSID_GPTDemoSnapIn, szSnapInKey, 50); // // Register SnapIn in HKEY_CLASSES_ROOT // LoadString (g_hInstance, IDS_SNAPIN_NAME, szSnapInName, 100); wsprintf (szSubKey, TEXT("CLSID\\%s"), szSnapInKey); lResult = RegCreateKeyEx (HKEY_CLASSES_ROOT, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult != ERROR_SUCCESS) { return SELFREG_E_CLASS; } RegSetValueEx (hKey, NULL, 0, REG_SZ, (LPBYTE)szSnapInName, (lstrlen(szSnapInName) + 1) * sizeof(TCHAR)); RegCloseKey (hKey); wsprintf (szSubKey, TEXT("CLSID\\%s\\InProcServer32"), szSnapInKey); lResult = RegCreateKeyEx (HKEY_CLASSES_ROOT, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult != ERROR_SUCCESS) { return SELFREG_E_CLASS; } RegSetValueEx (hKey, NULL, 0, REG_EXPAND_SZ, (LPBYTE)szSnapInLocation, (lstrlen(szSnapInLocation) + 1) * sizeof(TCHAR)); RegCloseKey (hKey); // // Register SnapIn with MMC // wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\SnapIns\\%s"), szSnapInKey); lResult = RegCreateKeyEx (HKEY_LOCAL_MACHINE, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult != ERROR_SUCCESS) { return SELFREG_E_CLASS; } RegSetValueEx (hKey, TEXT("NameString"), 0, REG_SZ, (LPBYTE)szSnapInName, (lstrlen(szSnapInName) + 1) * sizeof(TCHAR)); RegCloseKey (hKey); for (dwIndex = 0; dwIndex < NUM_NAMESPACE_ITEMS; dwIndex++) { StringFromGUID2 (*g_NameSpace[dwIndex].pNodeID, szGUID, 50); wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\SnapIns\\%s\\NodeTypes\\%s"), szSnapInKey, szGUID); lResult = RegCreateKeyEx (HKEY_LOCAL_MACHINE, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult != ERROR_SUCCESS) { return SELFREG_E_CLASS; } RegCloseKey (hKey); } // // Register in the NodeTypes key // for (dwIndex = 0; dwIndex < NUM_NAMESPACE_ITEMS; dwIndex++) { StringFromGUID2 (*g_NameSpace[dwIndex].pNodeID, szGUID, 50); wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\NodeTypes\\%s"), szGUID); lResult = RegCreateKeyEx (HKEY_LOCAL_MACHINE, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult != ERROR_SUCCESS) { return SELFREG_E_CLASS; } RegCloseKey (hKey); } // // Register as an extension for various nodes // StringFromGUID2 (NODEID_User, szGUID, 50); wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\NodeTypes\\%s\\Extensions\\NameSpace"), szGUID); lResult = RegCreateKeyEx (HKEY_LOCAL_MACHINE, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult != ERROR_SUCCESS) { return SELFREG_E_CLASS; } RegSetValueEx (hKey, szSnapInKey, 0, REG_SZ, (LPBYTE)szSnapInName, (lstrlen(szSnapInName) + 1) * sizeof(TCHAR)); RegCloseKey (hKey); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // DllUnregisterServer - Removes entries from the system registry STDAPI DllUnregisterServer(void) { TCHAR szSnapInKey[50]; TCHAR szSubKey[200]; TCHAR szGUID[50]; DWORD dwIndex; LONG lResult; HKEY hKey; DWORD dwDisp; StringFromGUID2 (CLSID_GPTDemoSnapIn, szSnapInKey, 50); wsprintf (szSubKey, TEXT("CLSID\\%s"), szSnapInKey); RegDelnode (HKEY_CLASSES_ROOT, szSubKey); wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\SnapIns\\%s"), szSnapInKey); RegDelnode (HKEY_LOCAL_MACHINE, szSubKey); for (dwIndex = 0; dwIndex < NUM_NAMESPACE_ITEMS; dwIndex++) { StringFromGUID2 (*g_NameSpace[dwIndex].pNodeID, szGUID, 50); wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\NodeTypes\\%s"), szGUID); RegDelnode (HKEY_LOCAL_MACHINE, szSubKey); } StringFromGUID2 (NODEID_User, szGUID, 50); wsprintf (szSubKey, TEXT("Software\\Microsoft\\MMC\\NodeTypes\\%s\\Extensions\\NameSpace"), szGUID); lResult = RegOpenKeyEx (HKEY_LOCAL_MACHINE, szSubKey, 0, KEY_WRITE, &hKey); if (lResult == ERROR_SUCCESS) { RegDeleteValue (hKey, szSnapInKey); RegCloseKey (hKey); } return S_OK; }
29.0131
105
0.559452
[ "object" ]
a1796ce11a8b7d00613426093f4e4d0ed52bfbc5
2,219
hpp
C++
include/bcm-compressor.hpp
waYne1337/tbwt
e6c24549f38e0961b39b42ffb3cf56bd2c747e48
[ "MIT" ]
12
2018-04-06T06:07:18.000Z
2021-03-04T16:10:23.000Z
include/bcm-compressor.hpp
waYne1337/tbwt
e6c24549f38e0961b39b42ffb3cf56bd2c747e48
[ "MIT" ]
1
2018-04-06T14:35:23.000Z
2018-04-06T14:35:23.000Z
include/bcm-compressor.hpp
waYne1337/tbwt
e6c24549f38e0961b39b42ffb3cf56bd2c747e48
[ "MIT" ]
1
2018-05-19T11:56:16.000Z
2018-05-19T11:56:16.000Z
/* * bcm-compressor.hpp for bwt tunneling * Copyright (c) 2017 Uwe Baier All Rights Reserved. * * 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. */ #ifndef BCM_COMPRESSOR_HPP #define BCM_COMPRESSOR_HPP #include "bwt-compressor.hpp" #include "tbwt-compressor.hpp" #include "bcm-ss.hpp" #include "block-scores-rle-model.hpp" #include <istream> #include <limits> #include <ostream> #include <stdexcept> //! class which encodes a BWT with second stage by Ilya Muravyov class BW_SS_BCM : public block_scores_rle_model { public: //! encodes the transform t using MTF + RLE0 + Entropy template<class T> static void encode( T &t, std::ostream &out ) { bcm::CM cm; for (t_idx_t i = 0; i < t.size(); i++) { cm.Encode( t[i], out ); } cm.Flush(out); } //! decodes the transform and stores it in t using MTF + RLE0 + Entropy (t must have length of output) template<class T> static void decode( std::istream &in, T &t ) { bcm::CM cm; cm.Init(in); for (t_idx_t i = 0; i < t.size(); i++) { t[i] = cm.Decode(in); } } }; //typedefs defining compressors typedef bwt_compressor<BW_SS_BCM> bwt_compressor_bcm; typedef tbwt_compressor<BW_SS_BCM> tbwt_compressor_bcm; #endif
32.632353
103
0.729157
[ "model", "transform" ]
a17deb6ce8edcd9510736519f05f2c0dc569af11
3,008
cpp
C++
src/loaders/json_game_loader.cpp
dfyx/jumping-cubes-tactics
30a96816ebe698302f3cc0a8d4971f68689508a0
[ "WTFPL" ]
1
2015-08-26T12:12:38.000Z
2015-08-26T12:12:38.000Z
src/loaders/json_game_loader.cpp
dfyx/jumping-cubes-tactics
30a96816ebe698302f3cc0a8d4971f68689508a0
[ "WTFPL" ]
null
null
null
src/loaders/json_game_loader.cpp
dfyx/jumping-cubes-tactics
30a96816ebe698302f3cc0a8d4971f68689508a0
[ "WTFPL" ]
null
null
null
#include "json_game_loader.h" #include "json_game_loader_p.h" #include "../gamedata/game.h" #include "../gamedata/node.h" #include "../gamedata/edge.h" #include "../graphics/node_sprite.h" #include "../graphics/edge_sprite.h" #include <vector> #include <json/json.h> #include <iostream> #include <fstream> namespace JCT_SFML { namespace Loaders { JsonGameLoader::JsonGameLoader(const std::string &filename) { d = new JsonGameLoaderPrivate(); d->filename = filename; d->game = NULL; } JsonGameLoader::~JsonGameLoader() { delete d; } Gamedata::Game *JsonGameLoader::game() { if(d->game == NULL) { loadGame(); } return d->game; } std::vector<Graphics::NodeSprite*> JsonGameLoader::nodeSprites() { if(d->game == NULL) { loadGame(); } return d->nodeSprites; } std::vector<Graphics::EdgeSprite*> JsonGameLoader::edgeSprites() { if(d->game == NULL) { loadGame(); } return d->edgeSprites; } void JsonGameLoader::loadGame() { d->game = new Gamedata::Game(); std::ifstream filestream(d->filename, std::ifstream::in); Json::Value root; Json::Reader reader; if(!reader.parse(filestream, root)) { std::cout << reader.getFormattedErrorMessages(); return; } std::vector<Gamedata::Node*> nodes; std::vector<Gamedata::Edge*> edges; const Json::Value jsonNodes = root["nodes"]; for(int index = 0; index < jsonNodes.size(); index++) { const Json::Value jsonNode = jsonNodes[index]; float x = jsonNode["x"].asFloat(); float y = jsonNode["y"].asFloat(); Gamedata::Node* node = new Gamedata::Node(); Graphics::NodeSprite* nodeSprite = new Graphics::NodeSprite(node); nodeSprite->setPosition(sf::Vector2f(x, y)); d->game->addNode(node); nodes.push_back(node); d->nodeSprites.push_back(nodeSprite); } const Json::Value jsonEdges = root["edges"]; for(int index = 0; index < jsonEdges.size(); index++) { const Json::Value jsonEdge = jsonEdges[index]; unsigned int to = jsonEdge["to"].asInt(); unsigned int from = jsonEdge["from"].asInt(); bool invisible = jsonEdge["invisible"].asBool(); bool bidirectional = jsonEdge["bidirectional"].asBool(); Gamedata::Node* fromNode = nodes[from]; Gamedata::Node* toNode = nodes[to]; Gamedata::Edge* edge = new Gamedata::Edge(fromNode, toNode); fromNode->addEdge(edge); if(bidirectional) { edge = new Gamedata::Edge(toNode, fromNode); toNode->addEdge(edge); } if(!invisible) { Graphics::EdgeSprite* edgeSprite = new Graphics::EdgeSprite(d->nodeSprites[from], d->nodeSprites[to]); d->edgeSprites.push_back(edgeSprite); } } } } }
25.277311
98
0.580452
[ "vector" ]
a182b03caf7f7a8423e36a57260dbd26066027ac
7,396
cpp
C++
level_zero/tools/test/unit_tests/sources/sysman/temperature/windows/test_zes_temperature.cpp
againull/compute-runtime
3ef1ab88a4d9fad5c72e343f349365817c54da17
[ "Intel", "MIT" ]
1
2019-04-25T23:21:01.000Z
2019-04-25T23:21:01.000Z
level_zero/tools/test/unit_tests/sources/sysman/temperature/windows/test_zes_temperature.cpp
ConnectionMaster/compute-runtime
ea373d2664251b10e55aa237555e4ba9221ace0f
[ "Intel", "MIT" ]
null
null
null
level_zero/tools/test/unit_tests/sources/sysman/temperature/windows/test_zes_temperature.cpp
ConnectionMaster/compute-runtime
ea373d2664251b10e55aa237555e4ba9221ace0f
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2020-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/tools/source/sysman/temperature/windows/os_temperature_imp.h" #include "level_zero/tools/test/unit_tests/sources/sysman/temperature/windows/mock_temperature.h" #include "level_zero/tools/test/unit_tests/sources/sysman/windows/mock_sysman_fixture.h" extern bool sysmanUltsEnable; namespace L0 { namespace ult { constexpr uint32_t temperatureHandleComponentCount = 3u; class SysmanDeviceTemperatureFixture : public SysmanDeviceFixture { protected: Mock<TemperatureKmdSysManager> *pKmdSysManager = nullptr; KmdSysManager *pOriginalKmdSysManager = nullptr; std::vector<ze_device_handle_t> deviceHandles; void SetUp() override { if (!sysmanUltsEnable) { GTEST_SKIP(); } SysmanDeviceFixture::SetUp(); pKmdSysManager = new Mock<TemperatureKmdSysManager>; EXPECT_CALL(*pKmdSysManager, escape(_, _, _, _, _)) .WillRepeatedly(::testing::Invoke(pKmdSysManager, &Mock<TemperatureKmdSysManager>::mock_escape)); pOriginalKmdSysManager = pWddmSysmanImp->pKmdSysManager; pWddmSysmanImp->pKmdSysManager = pKmdSysManager; for (auto handle : pSysmanDeviceImp->pTempHandleContext->handleList) { delete handle; } pSysmanDeviceImp->pTempHandleContext->handleList.clear(); uint32_t subDeviceCount = 0; // We received a device handle. Check for subdevices in this device Device::fromHandle(device->toHandle())->getSubDevices(&subDeviceCount, nullptr); if (subDeviceCount == 0) { deviceHandles.resize(1, device->toHandle()); } else { deviceHandles.resize(subDeviceCount, nullptr); Device::fromHandle(device->toHandle())->getSubDevices(&subDeviceCount, deviceHandles.data()); } pSysmanDeviceImp->pTempHandleContext->init(deviceHandles); } void TearDown() override { if (!sysmanUltsEnable) { GTEST_SKIP(); } SysmanDeviceFixture::TearDown(); pWddmSysmanImp->pKmdSysManager = pOriginalKmdSysManager; if (pKmdSysManager != nullptr) { delete pKmdSysManager; pKmdSysManager = nullptr; } } std::vector<zes_temp_handle_t> get_temp_handles(uint32_t count) { std::vector<zes_temp_handle_t> handles(count, nullptr); EXPECT_EQ(zesDeviceEnumTemperatureSensors(device->toHandle(), &count, handles.data()), ZE_RESULT_SUCCESS); return handles; } }; TEST_F(SysmanDeviceTemperatureFixture, GivenComponentCountZeroWhenEnumeratingTemperatureSensorsThenValidCountIsReturnedAndVerifySysmanPowerGetCallSucceeds) { uint32_t count = 0; EXPECT_EQ(zesDeviceEnumTemperatureSensors(device->toHandle(), &count, nullptr), ZE_RESULT_SUCCESS); EXPECT_EQ(count, temperatureHandleComponentCount); } TEST_F(SysmanDeviceTemperatureFixture, GivenInvalidComponentCountWhenEnumeratingTemperatureSensorsThenValidCountIsReturnedAndVerifySysmanPowerGetCallSucceeds) { uint32_t count = 0; EXPECT_EQ(zesDeviceEnumTemperatureSensors(device->toHandle(), &count, nullptr), ZE_RESULT_SUCCESS); EXPECT_EQ(count, temperatureHandleComponentCount); count = count + 1; EXPECT_EQ(zesDeviceEnumTemperatureSensors(device->toHandle(), &count, nullptr), ZE_RESULT_SUCCESS); EXPECT_EQ(count, temperatureHandleComponentCount); } TEST_F(SysmanDeviceTemperatureFixture, GivenComponentCountZeroWhenEnumeratingTemperatureSensorsThenValidPowerHandlesIsReturned) { uint32_t count = 0; EXPECT_EQ(zesDeviceEnumTemperatureSensors(device->toHandle(), &count, nullptr), ZE_RESULT_SUCCESS); EXPECT_EQ(count, temperatureHandleComponentCount); std::vector<zes_temp_handle_t> handles(count, nullptr); EXPECT_EQ(zesDeviceEnumTemperatureSensors(device->toHandle(), &count, handles.data()), ZE_RESULT_SUCCESS); for (auto handle : handles) { EXPECT_NE(handle, nullptr); } } TEST_F(SysmanDeviceTemperatureFixture, GivenValidPowerHandleWhenGettingTemperaturePropertiesAllowSetToTrueThenCallSucceeds) { auto handles = get_temp_handles(temperatureHandleComponentCount); uint32_t sensorTypeIndex = 0; for (auto handle : handles) { zes_temp_properties_t properties; ze_result_t result = zesTemperatureGetProperties(handle, &properties); EXPECT_EQ(ZE_RESULT_SUCCESS, result); EXPECT_FALSE(properties.onSubdevice); EXPECT_EQ(properties.subdeviceId, 0); EXPECT_FALSE(properties.isCriticalTempSupported); EXPECT_FALSE(properties.isThreshold1Supported); EXPECT_FALSE(properties.isThreshold2Supported); EXPECT_EQ(properties.maxTemperature, pKmdSysManager->mockMaxTemperature); EXPECT_EQ(properties.type, pKmdSysManager->mockSensorTypes[sensorTypeIndex++]); } } TEST_F(SysmanDeviceTemperatureFixture, GivenValidTempHandleWhenGettingMemoryTemperatureThenValidTemperatureReadingsRetrieved) { auto handles = get_temp_handles(temperatureHandleComponentCount); double temperature; ASSERT_EQ(ZE_RESULT_SUCCESS, zesTemperatureGetState(handles[ZES_TEMP_SENSORS_MEMORY], &temperature)); EXPECT_EQ(temperature, static_cast<double>(pKmdSysManager->mockTempMemory)); } TEST_F(SysmanDeviceTemperatureFixture, GivenValidTempHandleWhenGettingGPUTemperatureThenValidTemperatureReadingsRetrieved) { auto handles = get_temp_handles(temperatureHandleComponentCount); double temperature; ASSERT_EQ(ZE_RESULT_SUCCESS, zesTemperatureGetState(handles[ZES_TEMP_SENSORS_GPU], &temperature)); EXPECT_EQ(temperature, static_cast<double>(pKmdSysManager->mockTempGPU)); } TEST_F(SysmanDeviceTemperatureFixture, GivenValidTempHandleWhenGettingGlobalTemperatureThenValidTemperatureReadingsRetrieved) { auto handles = get_temp_handles(temperatureHandleComponentCount); double temperature; ASSERT_EQ(ZE_RESULT_SUCCESS, zesTemperatureGetState(handles[ZES_TEMP_SENSORS_GLOBAL], &temperature)); EXPECT_EQ(temperature, static_cast<double>(pKmdSysManager->mockTempGlobal)); } TEST_F(SysmanDeviceTemperatureFixture, GivenValidTempHandleWhenGettingUnsupportedSensorsTemperatureThenUnsupportedReturned) { auto pTemperatureImpMemory = std::make_unique<TemperatureImp>(deviceHandles[0], pOsSysman, ZES_TEMP_SENSORS_GLOBAL_MIN); auto pWddmTemperatureImp = static_cast<WddmTemperatureImp *>(pTemperatureImpMemory->pOsTemperature.get()); double pTemperature = 0; EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pWddmTemperatureImp->getSensorTemperature(&pTemperature)); } TEST_F(SysmanDeviceTemperatureFixture, GivenValidTempHandleWhenGettingTemperatureConfigThenUnsupportedIsReturned) { auto handles = get_temp_handles(temperatureHandleComponentCount); for (auto handle : handles) { zes_temp_config_t config = {}; EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, zesTemperatureGetConfig(handle, &config)); } } TEST_F(SysmanDeviceTemperatureFixture, GivenValidTempHandleWhenSettingTemperatureConfigThenUnsupportedIsReturned) { auto handles = get_temp_handles(temperatureHandleComponentCount); for (auto handle : handles) { zes_temp_config_t config = {}; EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, zesTemperatureSetConfig(handle, &config)); } } } // namespace ult } // namespace L0
44.554217
160
0.768388
[ "vector" ]
08514af3651fdd95a53f8fc97f8f1607fc07acd0
8,543
cpp
C++
libhail/src/hail/query/backend/compile.cpp
MariusDanner/hail
5ca0305f8243b5888931b1afaa1fbfb617dee097
[ "MIT" ]
null
null
null
libhail/src/hail/query/backend/compile.cpp
MariusDanner/hail
5ca0305f8243b5888931b1afaa1fbfb617dee097
[ "MIT" ]
null
null
null
libhail/src/hail/query/backend/compile.cpp
MariusDanner/hail
5ca0305f8243b5888931b1afaa1fbfb617dee097
[ "MIT" ]
null
null
null
#include <hail/query/backend/compile.hpp> #include <hail/query/backend/svalue.hpp> #include <llvm/IR/Verifier.h> #include <llvm/Support/raw_ostream.h> namespace hail { CompileModule::CompileModule(TypeContext &tc, STypeContext &stc, Module *module, const std::vector<EmitType> &param_types, EmitType return_type, llvm::LLVMContext &llvm_context, llvm::Module *llvm_module) : tc(tc), stc(stc), llvm_context(llvm_context), llvm_module(llvm_module) { auto main = module->get_function("main"); // FIXME assert(main); CompileFunction(tc, stc, main, param_types, return_type, llvm_context, llvm_module); } CompileFunction::CompileFunction(TypeContext &tc, STypeContext &stc, Function *function, const std::vector<EmitType> &param_types, EmitType return_type, llvm::LLVMContext &llvm_context, llvm::Module *llvm_module) : tc(tc), stc(stc), function(function), param_types(param_types), return_type(return_type), llvm_context(llvm_context), llvm_ir_builder(llvm_context), llvm_module(llvm_module), ir_type(tc, function) { auto llvm_ft = llvm::FunctionType::get(llvm::Type::getVoidTy(llvm_context), {llvm::Type::getInt8PtrTy(llvm_context), llvm::Type::getInt8PtrTy(llvm_context), llvm::Type::getInt8PtrTy(llvm_context)}, false); llvm_function = llvm::Function::Create(llvm_ft, llvm::Function::ExternalLinkage, "__hail_f", llvm_module); auto entry = llvm::BasicBlock::Create(llvm_context, "entry", llvm_function); llvm_ir_builder.SetInsertPoint(entry); auto result = emit(function->get_body()).cast_to(*this, return_type).as_data(*this); std::vector<llvm::Value *> result_llvm_values; result.get_constituent_values(result_llvm_values); assert(result_llvm_values.size() == 2); auto return_address = llvm_function->getArg(1); llvm_ir_builder.CreateStore(result_llvm_values[0], return_address); llvm::Value *value_address = llvm_ir_builder.CreateGEP(return_address, llvm::ConstantInt::get(llvm_context, llvm::APInt(64, 8))); value_address = llvm_ir_builder.CreateBitCast(value_address, llvm::PointerType::get(result_llvm_values[1]->getType(), 0)); llvm_ir_builder.CreateStore(result_llvm_values[1], value_address); llvm_ir_builder.CreateRetVoid(); verifyFunction(*llvm_function, &llvm::errs()); llvm_function->print(llvm::errs(), nullptr); } llvm::Type * CompileFunction::get_llvm_type(PrimitiveType pt) const { switch (pt) { case PrimitiveType::VOID: return llvm::Type::getVoidTy(llvm_context); case PrimitiveType::INT8: return llvm::Type::getInt8Ty(llvm_context); case PrimitiveType::INT32: return llvm::Type::getInt32Ty(llvm_context); case PrimitiveType::INT64: return llvm::Type::getInt64Ty(llvm_context); case PrimitiveType::FLOAT32: return llvm::Type::getFloatTy(llvm_context); case PrimitiveType::FLOAT64: return llvm::Type::getDoubleTy(llvm_context); case PrimitiveType::POINTER: return llvm::Type::getInt8PtrTy(llvm_context); default: abort(); } } llvm::AllocaInst * CompileFunction::make_entry_alloca(llvm::Type *llvm_type) { llvm::IRBuilder<> builder(&llvm_function->getEntryBlock(), llvm_function->getEntryBlock().begin()); return builder.CreateAlloca(llvm_type); } EmitValue CompileFunction::emit(Block *x) { assert(x->get_children().size() == 1); return emit(x->get_child(0)); } EmitValue CompileFunction::emit(Input *x) { if (x->get_parent()->get_function_parent()) { auto param_type = param_types[x->index]; std::vector<PrimitiveType> constituent_types; param_type.get_constituent_types(constituent_types); assert(constituent_types.size() == 2); assert(constituent_types[0] == PrimitiveType::INT8); auto params_address = llvm_function->getArg(2); auto param_address = llvm_ir_builder.CreateGEP(params_address, {llvm::ConstantInt::get(llvm_context, llvm::APInt(64, x->index * 16))}); auto m = llvm_ir_builder.CreateLoad(get_llvm_type(constituent_types[0]), param_address); llvm::Type *value_llvm_type = get_llvm_type(constituent_types[1]); llvm::Value *value_address = llvm_ir_builder.CreateGEP(param_address, {llvm::ConstantInt::get(llvm_context, llvm::APInt(64, 8))}); value_address = llvm_ir_builder.CreateBitCast(value_address, llvm::PointerType::get(value_llvm_type, 0)); auto llvm_value = llvm_ir_builder.CreateLoad(value_llvm_type, value_address); std::vector<llvm::Value *> param_llvm_values{m, llvm_value}; return param_type.from_llvm_values(param_llvm_values, 0); } abort(); } const SType * CompileFunction::get_default_stype(const Type *t) { switch (t->tag) { case Type::Tag::BOOL: return stc.sbool; case Type::Tag::INT32: return stc.sint32; case Type::Tag::INT64: return stc.sint64; case Type::Tag::FLOAT32: return stc.sfloat32; case Type::Tag::FLOAT64: return stc.sfloat64; default: abort(); } } EmitValue CompileFunction::emit(Literal *x) { auto t = ir_type(x); if (x->value.get_missing()) return EmitType(get_default_stype(t)).make_na(*this); switch (ir_type(x)->tag) { case Type::Tag::BOOL: { auto m = llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0); auto c = llvm::ConstantInt::get(llvm_context, llvm::APInt(1, x->value.as_bool())); return EmitValue(m, new SBoolValue(stc.sbool, c)); } case Type::Tag::INT32: { auto m = llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0); auto c = llvm::ConstantInt::get(llvm_context, llvm::APInt(32, x->value.as_int32())); return EmitValue(m, new SInt32Value(stc.sint32, c)); } case Type::Tag::INT64: { auto m = llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0); auto c = llvm::ConstantInt::get(llvm_context, llvm::APInt(64, x->value.as_int64())); return EmitValue(m, new SInt64Value(stc.sint64, c)); } case Type::Tag::FLOAT32: { auto m = llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0); auto c = llvm::ConstantFP::get(llvm_context, llvm::APFloat(x->value.as_float32())); return EmitValue(m, new SFloat32Value(stc.sfloat32, c)); } case Type::Tag::FLOAT64: { auto m = llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0); auto c = llvm::ConstantFP::get(llvm_context, llvm::APFloat(x->value.as_float64())); return EmitValue(m, new SFloat64Value(stc.sfloat64, c)); } default: abort(); } } EmitValue CompileFunction::emit(NA *x) { return EmitType(get_default_stype(x->type)).make_na(*this); } EmitValue CompileFunction::emit(IsNA *x) { auto cond = emit(x->get_child(0)).as_control(*this); llvm::AllocaInst *l = make_entry_alloca(llvm::Type::getInt8Ty(llvm_context)); auto merge_bb = llvm::BasicBlock::Create(llvm_context, "isna_merge", llvm_function); // present llvm_ir_builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0), l); llvm_ir_builder.CreateBr(merge_bb); llvm_ir_builder.SetInsertPoint(cond.missing_block); llvm_ir_builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 1), l); llvm_ir_builder.CreateBr(merge_bb); llvm_ir_builder.SetInsertPoint(merge_bb); llvm::Value *v = llvm_ir_builder.CreateLoad(l); auto m = llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0); return EmitValue(m, new SBoolValue(stc.sbool, v)); } EmitValue CompileFunction::emit(MakeTuple *x) { std::vector<EmitType> element_stypes; std::vector<EmitDataValue> element_emit_values; for (auto c : x->get_children()) { auto cv = emit(c).as_data(*this); element_stypes.push_back(cv.get_type()); element_emit_values.push_back(cv); } return EmitValue(llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm_context), 0), new SStackTupleValue(stc.stack_stuple(ir_type(x), element_stypes), element_emit_values)); } EmitValue CompileFunction::emit(GetTupleElement *x) { auto t = emit(x->get_child(0)).as_control(*this); // FIXME any tuple value auto elem = cast<SCanonicalTupleValue>(t.svalue)->get_element(*this, x->index).as_control(*this); llvm_ir_builder.SetInsertPoint(elem.missing_block); llvm_ir_builder.CreateBr(t.missing_block); return EmitValue(t.missing_block, elem.svalue); } EmitValue CompileFunction::emit(IR *x) { return x->dispatch([this](auto x) { return emit(x); }); } }
32.48289
99
0.705724
[ "vector" ]
08556e2b0d2d1f73890d82fd8ecaa33a6b9c47c9
12,331
cpp
C++
JEBString/JEBString/Utf8/Utf8String.cpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
1
2019-12-25T05:30:20.000Z
2019-12-25T05:30:20.000Z
JEBString/JEBString/Utf8/Utf8String.cpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
JEBString/JEBString/Utf8/Utf8String.cpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
#include "Utf8String.hpp" #include "JEBString/JEBStringMacros.hpp" #include "JEBString/EncodedStrings/EncodedString.hpp" #include "JEBString/EncodedStrings/CodePageEncoding.hpp" #include "JEBString/EncodedStrings/Utf8Encoding.hpp" #include "JEBString/RawStrings/EscapedString.hpp" #include "JEBString/Utf16/Utf16Utilities.hpp" namespace JEBString { namespace Utf8 { using JEBString::EncodedStrings::EncodedRange; using JEBString::EncodedStrings::Utf8Encoding; std::string& append(std::string& str, uint32_t chr) { EncodedStrings::addUtf8(std::back_inserter(str), chr); return str; } int32_t caseInsensitiveCompare(const std::string& str, const std::string& cmp) { return EncodedStrings::caseInsensitiveCompare(utf8Range(str), utf8Range(cmp)); } bool caseInsensitiveEqual(const std::string& str, const std::string& cmp) { return EncodedStrings::caseInsensitiveEqual(utf8Range(str), utf8Range(cmp)); } bool caseInsensitiveLess(const std::string& str, const std::string& cmp) { return EncodedStrings::caseInsensitiveLess(utf8Range(str), utf8Range(cmp)); } bool contains(const std::string& str, uint32_t chr) { return EncodedStrings::contains(utf8Range(str), chr); } bool endsWith(const std::string& str, const std::string& cmp, FindFlags_t flags /*= FindFlags::Defaults*/) { return EncodedStrings::endsWith(utf8Range(str), utf8Range(cmp), flags); } std::string escape(const std::string& str) { return RawStrings::escapeControlCharacters(str); } StringRange findSubstring(const std::string& str, const std::string& sub, FindFlags_t flags /*= FindFlags::Defaults*/) { auto r = EncodedStrings::find(utf8Range(str), utf8Range(sub), flags); return std::make_pair(begin(r), end(r)); } MutableStringRange findSubstring(std::string& str, const std::string& sub, FindFlags_t flags /*= FindFlags::Defaults*/) { auto r = EncodedStrings::find(utf8Range(str), utf8Range(sub), flags); return std::make_pair(begin(r), end(r)); } StringRange findSubstring(StringRange str, const std::string& sub, FindFlags_t flags /*= FindFlags::Defaults*/) { auto r = EncodedStrings::find(utf8Range(str.first, str.second), utf8Range(sub), flags); return std::make_pair(begin(r), end(r)); } MutableStringRange findSubstring(MutableStringRange str, const std::string& sub, FindFlags_t flags /*= FindFlags::Defaults*/) { auto r = EncodedStrings::find(utf8Range(str.first, str.second), utf8Range(sub), flags); return std::make_pair(begin(r), end(r)); } std::string insert(const std::string& str, ptrdiff_t pos, const std::string& sub) { auto it = nthCharacter(str, pos); std::string result(begin(str), it); result.append(sub); result.append(it, end(str)); return result; } std::string insert(const std::string& str, ptrdiff_t pos, uint32_t chr) { auto it = nthCharacter(str, pos); std::string result(begin(str), it); append(result, chr); result.append(it, end(str)); return result; } std::string& insertInPlace(std::string& str, ptrdiff_t pos, const std::string& sub) { str.insert(nthCharacter(str, pos), begin(sub), end(sub)); return str; } bool isAlphaNumeric(const std::string& str) { return isAlphaNumeric(begin(str), end(str)); } bool isValidUtf8(const std::string& str) { return EncodedStrings::isValidUtf8(begin(str), end(str)); } std::string join(const std::vector<std::string>& strings, const std::string& separator) { return join(begin(strings), end(strings), separator); } std::string lower(const std::string& str) { std::string result; result.reserve(str.size()); EncodedStrings::forEachLower( utf8Range(str), [&](uint32_t c) {EncodedStrings::addUtf8(back_inserter(result), c);}); return result; } std::string::iterator nthCharacter(std::string& str, ptrdiff_t n) { return EncodedStrings::nthCharacter(utf8Range(str), n); } std::string::const_iterator nthCharacter(const std::string& str, ptrdiff_t n) { return EncodedStrings::nthCharacter(utf8Range(str), n); } std::string replace(const std::string& str, ptrdiff_t first, ptrdiff_t last, const std::string& repl) { auto strRange = utf8Range(str); auto fIt = EncodedStrings::nthCharacter(strRange, first); auto lIt = EncodedStrings::nthCharacter(strRange, last); std::string result(begin(str), fIt); result.append(repl); return result.append(lIt, end(str)); } std::string replace(const std::string& str, const std::string& cmp, const std::string& subst, size_t max, FindFlags_t flags) { std::string result; return EncodedStrings::replace(result, utf8Range(str), utf8Range(cmp), utf8Range(subst), max, flags); } std::string replaceCodePoint(const std::string& s, uint32_t fromChar, uint32_t toChar, size_t max) { char fromBuffer[EncodedStrings::MAX_ENCODED_UTF8_LENGTH]; size_t fromSize = EncodedStrings::encodeUtf8(fromBuffer, fromChar); char toBuffer[EncodedStrings::MAX_ENCODED_UTF8_LENGTH]; auto toSize = EncodedStrings::encodeUtf8(toBuffer, toChar); std::string result; EncodedStrings::replace(result, utf8Range(s), utf8Range(fromBuffer, fromBuffer + fromSize), utf8Range(toBuffer, toBuffer + toSize), max, FindFlags::Defaults); return result; } std::string& replaceInPlace(std::string& str, ptrdiff_t first, ptrdiff_t last, const std::string& repl) { auto strRange = utf8Range(str); auto fIt = EncodedStrings::nthCharacter(strRange, first); auto lIt = EncodedStrings::nthCharacter(strRange, last); return str.replace(fIt, lIt, repl); } std::string replaceInvalidUtf8(const std::string& str, uint32_t chr) { std::string result; result.reserve(str.size()); auto beg = str.begin(); auto it = str.begin(); while (it != str.end()) { uint32_t cp; if (EncodedStrings::nextUtf8CodePoint(cp, it, str.end()) != DecodeResult::Ok) { result.append(beg, it); beg = ++it; append(result, chr); } } result.append(beg, str.end()); return result; } std::string& replaceInvalidUtf8InPlace(std::string& str, char chr) { assert(chr > 0); auto it = str.begin(); while (it != str.end()) { uint32_t cp; if (EncodedStrings::nextUtf8CodePoint(cp, it, str.end()) != DecodeResult::Ok) *it++ = chr; } return str; } std::string reverse(const std::string& str) { std::string result; result.reserve(str.size()); EncodedStrings::reverse(utf8Range(str), utf8Encoder(result)); return result; } std::vector<std::string> split( const std::string& str, size_t maxParts /*= 0*/, SplitFlags_t flags /*= SplitFlags::IgnoreEmpty*/) { std::vector<std::string> parts; EncodedStrings::forEachToken(utf8Range(str), Unicode::isWhitespace, rangePushBacker(parts), maxParts, flags); return parts; } std::vector<std::string> split( const std::string& str, const std::string& sep, size_t maxParts /*= 0*/, SplitFlags_t flags /*= SplitFlags::Defaults*/) { std::vector<std::string> parts; EncodedStrings::forEachToken(utf8Range(str), utf8Range(sep), rangePushBacker(parts), maxParts, flags); return parts; } std::vector<std::string> splitLines( const std::string& str, size_t maxParts /*= 0*/, SplitFlags_t flags /*= SplitFlags::Defaults*/) { std::vector<std::string> parts; EncodedStrings::forEachLine(utf8Range(str), rangePushBacker(parts), maxParts, flags); return parts; } bool startsWith(const std::string& str, const std::string& cmp, FindFlags_t flags /*= FindFlags::Defaults*/) { return EncodedStrings::startsWith(utf8Range(str), utf8Range(cmp), flags); } size_t stringLength(const std::string& str) { return stringLength(begin(str), end(str)); } std::string substring( const std::string& str, ptrdiff_t startIndex, ptrdiff_t endIndex /*= std::numeric_limits<ptrdiff_t>::max()*/) { return toString(EncodedStrings::substring(utf8Range(str), startIndex, endIndex)); } std::string title(const std::string& str) { std::string result; result.reserve(str.size()); EncodedStrings::forEachTitle( utf8Range(str), [&](uint32_t c) {EncodedStrings::addUtf8(back_inserter(result), c);}); return result; } std::string toString(uint32_t chr) { char buffer[EncodedStrings::MAX_ENCODED_UTF8_LENGTH]; size_t n = EncodedStrings::encodeUtf8(buffer, chr); return std::string(buffer, buffer + n); } std::string toUtf8(const std::string& str, Encoding_t encoding) { std::string result; result.reserve(str.size()); switch (encoding) { case Encoding::Utf8: EncodedStrings::copy(utf8Range(str), utf8Encoder(result)); break; case Encoding::Latin1: EncodedStrings::copy( makeEncodedRange(str, EncodedStrings::Latin1Encoding()), utf8Encoder(result)); break; case Encoding::Windows1252: EncodedStrings::copy( makeEncodedRange(str, EncodedStrings::Windows1252Encoding()), utf8Encoder(result)); break; default: throw std::logic_error( FORMAT_STRING("Convert to UTF-8: unsupported encoding " << encoding << ".")); } return result; } std::string toUtf8(const std::wstring& str, Encoding_t encoding /*= Encoding::Utf16*/) { std::string result; result.reserve(str.size()); switch (encoding) { case Encoding::Utf16: EncodedStrings::copy(Utf16::utf16Range(str), utf8Encoder(result)); break; default: throw std::logic_error( FORMAT_STRING("Convert to UTF-8: unsupported encoding " << encoding << ".")); } return result; } std::string trim(const std::string& str) { return toString(EncodedStrings::trim(utf8Range(str), Unicode::isWhitespace)); } std::string trimFront(const std::string& str) { return toString(EncodedStrings::trimFront(utf8Range(str), Unicode::isWhitespace)); } std::string trimBack(const std::string& str) { return toString(EncodedStrings::trimBack(utf8Range(str), Unicode::isWhitespace)); } std::string unescape(const std::string& str) { return RawStrings::unescapeString(str, [](std::string& s, uint32_t c) {EncodedStrings::addUtf8(back_inserter(s), c);}); } std::string upper(const std::string& str) { std::string result; result.reserve(str.size()); EncodedStrings::forEachUpper( utf8Range(str), [&](uint32_t c) {EncodedStrings::addUtf8(back_inserter(result), c);}); return result; } }}
30.8275
83
0.587544
[ "vector" ]
08580ce57e24070b1aab0397533d40b7b25af6fc
15,274
cpp
C++
Source/SystemQOR/MSWindows/WinQL/System/Devices/Battery/WinQLBattery.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQL/System/Devices/Battery/WinQLBattery.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQL/System/Devices/Battery/WinQLBattery.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//WinQLBattery.cpp // Copyright Querysoft Limited 2013, 2017 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "WinQL/CodeServices/WinQLPolicy.h" #include "WinQL/Application/Threading/WinQLCriticalSection.h" #include "WinQL/Definitions/Constants.h" #include "WinQL/Application/ErrorSystem/WinQLError.h" #include "WinQL/CodeServices/Text/WinString.h" #include "WinQL/System/Devices/Battery/WinQLBattery.h" #include "WinQL/System/Devices/Interfaces/WinQLDeviceInterfaceClass.h" #include "WinQL/System/WinQLSystem.h" //-------------------------------------------------------------------------------- namespace nsWin32 { __QOR_IMPLEMENT_OCLASS_GUID( CBattery, 0x72631E54, 0x78A4, 0x11D0, 0xBC, 0xF7, 0x00, 0xAA, 0x00, 0xB7, 0xB3, 0x2A ); nsCodeQOR::CTExternalRegEntry< CBattery > CBattery::RegEntry; //-------------------------------------------------------------------------------- CBattery::CBattery() : CDeviceInterface() , m_bTagAcquired( false ) , m_bAcquiredInfo( false ) , m_ucGranularityCount( 0 ) , m_bPresent( true ) { _WINQ_FCONTEXT( "CBattery::CBattery" ); m_BQI.AtRate = 0; m_BQI.BatteryTag = 0; m_BQI.InformationLevel = BatteryInformation; m_Status.Capacity = 0; m_Status.PowerState = 0; m_Status.Voltage = 0; m_Status.Rate = 0; } //-------------------------------------------------------------------------------- CBattery::CBattery( unsigned long ulBatteryIndex ) : CDeviceInterface() , m_bTagAcquired( false ) , m_bAcquiredInfo( false ) , m_ucGranularityCount( 0 ) , m_bPresent( false ) { _WINQ_FCONTEXT( "CBattery::CBattery" ); /*TODO: restore this to wokring order unsigned long ulCountDevicesWithBatteryInterface = System().Devices(QOR_PP_SHARED_OBJECT_ACCESS).RegisteredLocalInterfaceClasses()[CDeviceInterfaceClassCollection::Battery]->Interfaces().Size(); if( ulCountDevicesWithBatteryInterface > ulBatteryIndex ) { CBattery::refType RefBattery( System().Devices(QOR_PP_SHARED_OBJECT_ACCESS).RegisteredLocalInterfaceClasses()[ CDeviceInterfaceClassCollection::Battery ]->Interfaces()[ulBatteryIndex] ); if( !RefBattery.IsNull() ) { *this = *RefBattery; m_bPresent = true; } } */ } //-------------------------------------------------------------------------------- CBattery::CBattery( const CBattery& src ) : CDeviceInterface( src ) { _WINQ_FCONTEXT( "CBattery::CBattery" ); *this = src; } //-------------------------------------------------------------------------------- CBattery& CBattery::operator = ( const CBattery& src ) { _WINQ_FCONTEXT( "CBattery::operator =" ); if( &src != this ) { CDeviceInterface::operator=( src ); m_bPresent = src.m_bPresent; m_bTagAcquired = src.m_bTagAcquired; m_bAcquiredInfo = src.m_bAcquiredInfo; m_ucGranularityCount = src.m_ucGranularityCount; m_BQI = src.m_BQI; m_BI = src.m_BI; m_Status = src.m_Status; for( unsigned char ucCount = 0; ucCount < m_ucGranularityCount; ucCount++ ) { m_Scales[ ucCount ] = src.m_Scales[ ucCount ]; } //m_pIODevice = src.m_pIODevice; m_ulTemperature = src.m_ulTemperature; } return *this; } //-------------------------------------------------------------------------------- CBattery::~CBattery() { _WINQ_FCONTEXT( "CBattery::~CBattery" ); m_Session.Dispose(); } //-------------------------------------------------------------------------------- unsigned long CBattery::GetTag() { _WINQ_FCONTEXT( "CBattery::GetTag" ); if( !m_bTagAcquired ) { InternalGetTag(); } return m_BQI.BatteryTag; } //-------------------------------------------------------------------------------- bool CBattery::IsSystemBattery() { _WINQ_FCONTEXT( "CBattery::IsSystemBattery" ); if( !m_bAcquiredInfo ) { InternalGetInfo(); } return ( m_BI.Capabilities & System_Battery ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsCapacityRelative() { _WINQ_FCONTEXT( "CBattery::IsCapacityRelative" ); if( !m_bAcquiredInfo ) { InternalGetInfo(); } return ( m_BI.Capabilities & Capacity_Relative ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsShortTerm() { _WINQ_FCONTEXT( "CBattery::IsShortTerm" ); if( !m_bAcquiredInfo ) { InternalGetInfo(); } return ( m_BI.Capabilities & Is_Short_Tem ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsSetChargeSupported() { _WINQ_FCONTEXT( "CBattery::IsSetChargeSupported" ); if( !m_bAcquiredInfo ) { InternalGetInfo(); } return ( m_BI.Capabilities & Set_Charge_Supported ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsSetDischargeSupported() { _WINQ_FCONTEXT( "CBattery::IsSetDischargeSupported" ); if( !m_bAcquiredInfo ) { InternalGetInfo(); } return ( m_BI.Capabilities & Set_Discharge_Supported ) ? true : false; } //-------------------------------------------------------------------------------- unsigned long CBattery::GetPowerState() { _WINQ_FCONTEXT( "CBattery::GetPowerState" ); InternalGetStatus(); return m_Status.PowerState; } //-------------------------------------------------------------------------------- unsigned long CBattery::GetCapacity() { _WINQ_FCONTEXT( "CBattery::GetCapacity" ); InternalGetStatus(); return m_Status.Capacity; } //-------------------------------------------------------------------------------- unsigned long CBattery::GetVoltage() { _WINQ_FCONTEXT( "CBattery::GetVoltage" ); InternalGetStatus(); return m_Status.Voltage; } //-------------------------------------------------------------------------------- long CBattery::GetRate() { _WINQ_FCONTEXT( "CBattery::GetRate" ); InternalGetStatus(); return m_Status.Rate; } //-------------------------------------------------------------------------------- bool CBattery::IsOnLine() { _WINQ_FCONTEXT( "CBattery::IsOnLine" ); InternalGetStatus(); return ( m_Status.PowerState & PowerStatus_On_Line ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsDischarging() { _WINQ_FCONTEXT( "CBattery::IsDischarging" ); InternalGetStatus(); return ( m_Status.PowerState & PowerStatus_Discharging ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsCharging() { _WINQ_FCONTEXT( "CBattery::IsCharging" ); InternalGetStatus(); return ( m_Status.PowerState & PowerStatus_Charging ) ? true : false; } //-------------------------------------------------------------------------------- bool CBattery::IsCritical() { _WINQ_FCONTEXT( "CBattery::IsCritical" ); InternalGetStatus(); return ( m_Status.PowerState & PowerStatus_Critical ) ? true : false; } //-------------------------------------------------------------------------------- double CBattery::GetTemperatureDegreesC() { _WINQ_FCONTEXT( "CBattery::GetTemperatureDegreesC" ); InternalGetTemperature(); double dResult = ((double)m_ulTemperature) - 273.15; dResult /= 10; return dResult; } //-------------------------------------------------------------------------------- unsigned long CBattery::EstimateTimeInSeconds( unsigned long ulRate ) { _WINQ_FCONTEXT( "CBattery::EstimateTimeInSeconds" ); if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryEstimatedTime; m_BQI.AtRate = ulRate; unsigned long ulOut = 0; unsigned long ulEstimate = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), &ulEstimate, sizeof( ulEstimate) , &ulOut, 0 ) ) { } return ulEstimate; } //-------------------------------------------------------------------------------- CWString CBattery::GetSerialNumber() { _WINQ_FCONTEXT( "CBattery::GetSerialNumber" ); CWString strSerialNumber; if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatterySerialNumber; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), strSerialNumber.GetBufferSetLength( MaxPath ), MaxPath, &ulOut, 0 ) ) { strSerialNumber.ValidateBuffer( static_cast< unsigned short >( ulOut ) ); } return strSerialNumber; } //-------------------------------------------------------------------------------- CWString CBattery::GetManufacturerName() { _WINQ_FCONTEXT( "CBattery::GetManufacturerName" ); CWString strManufacturerName; if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryManufactureName; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), strManufacturerName.GetBufferSetLength( MaxPath ), MaxPath, &ulOut, 0 ) ) { strManufacturerName.ValidateBuffer( static_cast< unsigned short >( ulOut ) ); } return strManufacturerName; } //-------------------------------------------------------------------------------- CTString CBattery::GetManufactureDate() { _WINQ_FCONTEXT( "CBattery::GetManufactureDate" ); CTString strManufactureDate; if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryManufactureDate; Battery_Manufacture_Date Date; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), &Date, sizeof(Date), &ulOut, 0 ) ) { //TOOD: Use current locale information to turn the date into a string strManufactureDate = CTString( _TXT( "Date of manufacture" ) ); } return strManufactureDate; } //-------------------------------------------------------------------------------- CWString CBattery::GetDeviceName() { _WINQ_FCONTEXT( "CBattery::GetDeviecName" ); CWString strDeviceName; if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryDeviceName; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), strDeviceName.GetBufferSetLength( MaxPath ), MaxPath, &ulOut, 0 ) ) { strDeviceName.ValidateBuffer( static_cast< unsigned short >( ulOut ) ); } return strDeviceName; } //-------------------------------------------------------------------------------- void CBattery::InternalGetTag() { _WINQ_FCONTEXT( "CBattery::InternalGetTag" ); unsigned long ulWait = 0; unsigned long ulOut = 0; if (m_Session.IsNull()) { m_Session = Open(Generic_Read | Generic_Write, File_Share_Read | File_Share_Write, File_Attribute_Normal); } if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Tag, Method_Buffered, File_Read_Access ), &ulWait, sizeof( ulWait ), &m_BQI.BatteryTag, sizeof( m_BQI.BatteryTag ), &ulOut, 0 ) ) { m_bTagAcquired = true; } } //-------------------------------------------------------------------------------- void CBattery::InternalGetTemperature() { _WINQ_FCONTEXT( "CBattery::InternalGetTemperature" ); if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryTemperature; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), &m_ulTemperature, sizeof( m_ulTemperature ), &ulOut, 0 ) ) { } } //-------------------------------------------------------------------------------- void CBattery::InternalGetGranularity() { _WINQ_FCONTEXT( "CBattery::InternalGetGranularity" ); if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryGranularityInformation; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), m_Scales, sizeof( Battery_Reporting_Scale ) * 4, &ulOut, 0 ) ) { m_ucGranularityCount = static_cast< unsigned char >( ulOut / sizeof( Battery_Reporting_Scale ) ); } } //-------------------------------------------------------------------------------- void CBattery::InternalGetInfo() { _WINQ_FCONTEXT( "CBattery::InternalGetInfo" ); if( !m_bTagAcquired ) { InternalGetTag(); } m_BQI.InformationLevel = BatteryInformation; unsigned long ulOut = 0; if(m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Information, Method_Buffered, File_Read_Access ), &m_BQI, sizeof( m_BQI ), &m_BI, sizeof( m_BI ), &ulOut, 0 ) ) { m_bAcquiredInfo = true; } } //-------------------------------------------------------------------------------- void CBattery::InternalGetStatus() { _WINQ_FCONTEXT( "CBattery::InternalGetStatus" ); if( !m_bTagAcquired ) { InternalGetTag(); } Battery_Wait_Status WaitStatus = {0}; WaitStatus.BatteryTag = m_BQI.BatteryTag; unsigned long ulOut = 0; m_Session->Control( __WINQL_DEVICE_CONTROL_CODE( File_Device_Battery, Query_Status, Method_Buffered, File_Read_Access ), &WaitStatus, sizeof( WaitStatus ), &m_Status, sizeof( m_Status ), &ulOut, 0 ); } //-------------------------------------------------------------------------------- //Call to ensure cached data is requeryed after a change of Tag void CBattery::OnTagChange( void ) { _WINQ_FCONTEXT( "CBattery::OnTagChange" ); m_bTagAcquired = false; m_bAcquiredInfo = false; m_ucGranularityCount = 0; } }//nsWin32
31.820833
229
0.600629
[ "object" ]
08588a443e7910ec15660d700bef89f13d87e78d
40,851
hpp
C++
libs/pika/schedulers/include/pika/schedulers/queue_holder_thread.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
13
2022-01-17T12:01:48.000Z
2022-03-16T10:03:14.000Z
libs/pika/schedulers/include/pika/schedulers/queue_holder_thread.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
163
2022-01-17T17:36:45.000Z
2022-03-31T17:42:57.000Z
libs/pika/schedulers/include/pika/schedulers/queue_holder_thread.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
4
2022-01-19T08:44:22.000Z
2022-01-31T23:16:21.000Z
// Copyright (c) 2019 John Biddiscombe // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <pika/config.hpp> #include <pika/assert.hpp> #include <pika/datastructures/tuple.hpp> #include <pika/debugging/print.hpp> #include <pika/schedulers/lockfree_queue_backends.hpp> #include <pika/threading_base/print.hpp> #include <pika/threading_base/scheduler_base.hpp> #include <pika/threading_base/thread_data.hpp> #include <pika/threading_base/thread_data_stackful.hpp> #include <pika/threading_base/thread_data_stackless.hpp> #include <pika/threading_base/thread_queue_init_parameters.hpp> #include <pika/type_support/unused.hpp> #include <atomic> #include <cmath> #include <cstddef> #include <cstdint> #include <exception> #include <functional> #include <iomanip> #include <list> #include <map> #include <memory> #include <mutex> #include <string> #include <unordered_set> #include <utility> #include <vector> #if !defined(QUEUE_HOLDER_THREAD_DEBUG) #if defined(PIKA_DEBUG) #define QUEUE_HOLDER_THREAD_DEBUG false #else #define QUEUE_HOLDER_THREAD_DEBUG false #endif #endif namespace pika { static pika::debug::enable_print<QUEUE_HOLDER_THREAD_DEBUG> tq_deb( "QH_THRD"); } // ------------------------------------------------------------ namespace pika { namespace threads { namespace policies { // apply the modulo operator only when needed // (i.e. when the input is greater than the ceiling) // NB: the numbers must be positive PIKA_FORCEINLINE std::size_t fast_mod( std::size_t const input, std::size_t const ceil) { return input >= ceil ? input % ceil : input; } enum : std::size_t { max_thread_count = 1000 }; enum : std::size_t { round_robin_rollover = 1 }; // ---------------------------------------------------------------- // Helper class to hold a set of queues. // ---------------------------------------------------------------- template <typename QueueType> struct queue_holder_thread { using thread_holder_type = queue_holder_thread<QueueType>; // Queues that will store actual work for this thread // They might be shared between cores, so we use a pointer to // reference them QueueType* const bp_queue_; QueueType* const hp_queue_; QueueType* const np_queue_; QueueType* const lp_queue_; // these are the domain and local thread queue ids for the container const std::size_t domain_index_; const std::size_t queue_index_; const std::size_t thread_num_; // a mask that hold a bit per queue to indicate ownership of the queue const std::size_t owner_mask_; // we must use OS mutexes here because we cannot suspend a pika // thread whilst processing the Queues for that thread, this code // is running at the OS level in effect. using mutex_type = std::mutex; using scoped_lock = std::unique_lock<mutex_type>; // mutex protecting the thread map mutable util::cache_line_data<mutex_type> thread_map_mtx_; // every thread maintains lists of free thread data objects // sorted by their stack sizes using thread_heap_type = std::list<thread_id_type, pika::detail::internal_allocator<thread_id_type>>; thread_heap_type thread_heap_small_; thread_heap_type thread_heap_medium_; thread_heap_type thread_heap_large_; thread_heap_type thread_heap_huge_; thread_heap_type thread_heap_nostack_; // these ought to be atomic, but if we get a race and assign a thread // to queue N instead of N+1 it doesn't really matter mutable util::cache_line_data<std::tuple<std::size_t, std::size_t>> rollover_counters_; // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- static pika::detail::internal_allocator<threads::thread_data> thread_alloc_; using task_description = thread_init_data; // ------------------------------------- // thread map stores every task in this queue set // this is the type of a map holding all threads (except depleted/terminated) using thread_map_type = std::unordered_set<thread_id_type, std::hash<thread_id_type>, std::equal_to<thread_id_type>, pika::detail::internal_allocator<thread_id_type>>; thread_map_type thread_map_; mutable util::cache_line_data<std::atomic<std::int32_t>> thread_map_count_; // ------------------------------------- // terminated tasks // completed tasks that can be reused (stack space etc) using terminated_items_type = lockfree_fifo::apply<thread_data*>::type; terminated_items_type terminated_items_; mutable util::cache_line_data<std::atomic<std::int32_t>> terminated_items_count_; thread_queue_init_parameters parameters_; std::thread::id owner_id_; // ------------------------------------------------------------ struct queue_mc_print { const QueueType* const q_; explicit queue_mc_print(const QueueType* const q) : q_(q) { } // friend std::ostream& operator<<( std::ostream& os, const queue_mc_print& d) { os << "n " << debug::dec<3>(d.q_->new_tasks_count_.data_) << " w " << debug::dec<3>(d.q_->work_items_count_.data_); return os; } }; struct queue_data_print { const queue_holder_thread* q_; explicit queue_data_print(const queue_holder_thread* q) : q_(q) { } // friend std::ostream& operator<<( std::ostream& os, const queue_data_print& d) { os << "D " << debug::dec<2>(d.q_->domain_index_) << " Q " << debug::dec<3>(d.q_->queue_index_) << " TM " << debug::dec<3>(d.q_->thread_map_count_.data_) << " [BP " << queue_mc_print(d.q_->bp_queue_) << "] [HP " << queue_mc_print(d.q_->hp_queue_) << "] [NP " << queue_mc_print(d.q_->np_queue_) << "] [LP " << queue_mc_print(d.q_->lp_queue_) << "] T " << debug::dec<3>(d.q_->terminated_items_count_.data_); return os; } }; // ------------------------------------------------------------ // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // NOLINTBEGIN(bugprone-easily-swappable-parameters) queue_holder_thread(QueueType* bp_queue, QueueType* hp_queue, QueueType* np_queue, QueueType* lp_queue, std::size_t domain, std::size_t queue, std::size_t thread_num, std::size_t owner, const thread_queue_init_parameters& init, std::thread::id owner_id) // NOLINTEND(bugprone-easily-swappable-parameters) : bp_queue_(bp_queue) , hp_queue_(hp_queue) , np_queue_(np_queue) , lp_queue_(lp_queue) , domain_index_(domain) , queue_index_(queue) , thread_num_(thread_num) , owner_mask_(owner) , terminated_items_(max_thread_count) , parameters_(init) , owner_id_(owner_id) { rollover_counters_.data_ = std::make_tuple(queue_index_, round_robin_rollover); tq_deb.debug(debug::str<>("construct"), "D", debug::dec<2>(domain_index_), "Q", debug::dec<3>(queue_index_), "Rollover counter", debug::dec<>(std::get<0>(rollover_counters_.data_)), debug::dec<>(std::get<1>(rollover_counters_.data_))); thread_map_count_.data_ = 0; terminated_items_count_.data_ = 0; if (bp_queue_) bp_queue_->set_holder(this); if (hp_queue_) hp_queue_->set_holder(this); if (np_queue_) np_queue_->set_holder(this); if (lp_queue_) lp_queue_->set_holder(this); } // ---------------------------------------------------------------- ~queue_holder_thread() { if (owns_bp_queue()) delete bp_queue_; if (owns_hp_queue()) delete hp_queue_; if (owns_np_queue()) delete np_queue_; if (owns_lp_queue()) delete lp_queue_; // for (auto t : thread_heap_small_) deallocate(get_thread_id_data(t)); for (auto t : thread_heap_medium_) deallocate(get_thread_id_data(t)); for (auto t : thread_heap_large_) deallocate(get_thread_id_data(t)); for (auto t : thread_heap_huge_) deallocate(get_thread_id_data(t)); for (auto t : thread_heap_nostack_) deallocate(get_thread_id_data(t)); } // ---------------------------------------------------------------- inline bool owns_bp_queue() const { return bp_queue_ && ((owner_mask_ & 1) != 0); } // ---------------------------------------------------------------- inline bool owns_hp_queue() const { return hp_queue_ && ((owner_mask_ & 2) != 0); } // ---------------------------------------------------------------- inline bool owns_np_queue() const { return ((owner_mask_ & 4) != 0); } // ---------------------------------------------------------------- inline bool owns_lp_queue() const { return lp_queue_ && ((owner_mask_ & 8) != 0); } // ------------------------------------------------------------ // return the next round robin thread index across all workers // using a batching of N per worker before incrementing inline std::size_t worker_next(std::size_t const workers) const { tq_deb.debug(debug::str<>("worker_next"), "Rollover counter ", debug::dec<4>(std::get<0>(rollover_counters_.data_)), debug::dec<4>(std::get<1>(rollover_counters_.data_)), "workers", debug::dec<4>(workers)); if (--std::get<1>(rollover_counters_.data_) == 0) { std::get<1>(rollover_counters_.data_) = round_robin_rollover; std::get<0>(rollover_counters_.data_) = fast_mod( std::get<0>(rollover_counters_.data_) + 1, workers); } return std::get<0>(rollover_counters_.data_); } // ------------------------------------------------------------ void schedule_thread(threads::thread_id_ref_type thrd, thread_priority priority, bool other_end = false) { if (bp_queue_ && (priority == thread_priority::bound)) { tq_deb.debug(debug::str<>("schedule_thread"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "queueing thread_priority::bound"); bp_queue_->schedule_work(PIKA_MOVE(thrd), other_end); } else if (hp_queue_ && (priority == thread_priority::high || priority == thread_priority::high_recursive || priority == thread_priority::boost)) { tq_deb.debug(debug::str<>("schedule_thread"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "queueing thread_priority::high"); hp_queue_->schedule_work(PIKA_MOVE(thrd), other_end); } else if (lp_queue_ && (priority == thread_priority::low)) { tq_deb.debug(debug::str<>("schedule_thread"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "queueing thread_priority::low"); lp_queue_->schedule_work(PIKA_MOVE(thrd), other_end); } else { tq_deb.debug(debug::str<>("schedule_thread"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "queueing thread_priority::normal"); np_queue_->schedule_work(PIKA_MOVE(thrd), other_end); } } // ---------------------------------------------------------------- bool cleanup_terminated(std::size_t thread_num, bool delete_all) { // clang-format off if (thread_num!=thread_num_) { tq_deb.error(debug::str<>("assertion fail") , "thread_num", thread_num , "thread_num_", thread_num_ , "queue_index_", queue_index_ , queue_data_print(this) ); } // clang-format on PIKA_ASSERT(thread_num == thread_num_); if (terminated_items_count_.data_.load(std::memory_order_relaxed) == 0) return true; scoped_lock lk(thread_map_mtx_.data_); if (delete_all) { // delete all threads thread_data* todelete; while (terminated_items_.pop(todelete)) { --terminated_items_count_.data_; tq_deb.debug(debug::str<>("cleanup"), "delete", queue_data_print(this), debug::threadinfo<thread_data*>(todelete)); thread_id_type tid(todelete); remove_from_thread_map(tid, true); } } else { // delete only this many threads std::int64_t delete_count = static_cast<std::int64_t>( terminated_items_count_.data_.load( std::memory_order_relaxed) / 2); tq_deb.debug(debug::str<>("cleanup"), "recycle", "delete_count", debug::dec<3>(delete_count)); thread_data* todelete; while (delete_count && terminated_items_.pop(todelete)) { thread_id_type tid(todelete); --terminated_items_count_.data_; remove_from_thread_map(tid, false); tq_deb.debug(debug::str<>("cleanup"), "recycle", queue_data_print(this), debug::threadinfo<thread_id_type*>(&tid)); recycle_thread(tid); --delete_count; } } return terminated_items_count_.data_.load( std::memory_order_relaxed) == 0; } // ---------------------------------------------------------------- void create_thread(thread_init_data& data, thread_id_ref_type* tid, std::size_t thread_num, error_code& ec) { PIKA_ASSERT( (!data.run_now || (data.run_now && thread_num == thread_num_))); if (data.run_now && thread_num != thread_num_) { data.run_now = false; } // create the thread using priority to select queue if (data.priority == thread_priority::normal) { tq_deb.debug(debug::str<>("create_thread "), queue_data_print(this), "thread_priority::normal", "run_now ", data.run_now); return np_queue_->create_thread(data, tid, ec); } else if (bp_queue_ && (data.priority == thread_priority::bound)) { tq_deb.debug(debug::str<>("create_thread "), queue_data_print(this), "thread_priority::bound", "run_now ", data.run_now); return bp_queue_->create_thread(data, tid, ec); } else if (hp_queue_ && (data.priority == thread_priority::high || data.priority == thread_priority::high_recursive || data.priority == thread_priority::boost)) { // boosted threads return to normal after being queued if (data.priority == thread_priority::boost) { data.priority = thread_priority::normal; } tq_deb.debug(debug::str<>("create_thread "), queue_data_print(this), "thread_priority::high", "run_now ", data.run_now); return hp_queue_->create_thread(data, tid, ec); } else if (lp_queue_ && (data.priority == thread_priority::low)) { tq_deb.debug(debug::str<>("create_thread "), queue_data_print(this), "thread_priority::low", "run_now ", data.run_now); return lp_queue_->create_thread(data, tid, ec); } tq_deb.error(debug::str<>("create_thread "), "priority?"); std::terminate(); } // ---------------------------------------------------------------- // Not thread safe. This function must only be called by the // thread that owns the holder object. // Creates a thread_data object using information from // thread_init_data . // If a thread data object is available on one of the heaps // it will use that, otherwise a new one is created. // Heaps store data ordered/sorted by stack size void create_thread_object( threads::thread_id_ref_type& tid, threads::thread_init_data& data) { PIKA_ASSERT(data.stacksize >= thread_stacksize::minimal); PIKA_ASSERT(data.stacksize <= thread_stacksize::nostack); std::ptrdiff_t const stacksize = data.scheduler_base->get_stack_size(data.stacksize); thread_heap_type* heap = nullptr; if (stacksize == parameters_.small_stacksize_) { heap = &thread_heap_small_; } else if (stacksize == parameters_.medium_stacksize_) { heap = &thread_heap_medium_; } else if (stacksize == parameters_.large_stacksize_) { heap = &thread_heap_large_; } else if (stacksize == parameters_.huge_stacksize_) { heap = &thread_heap_huge_; } else if (stacksize == parameters_.nostack_stacksize_) { heap = &thread_heap_nostack_; } PIKA_ASSERT(heap); if (data.initial_state == thread_schedule_state::pending_do_not_schedule || data.initial_state == thread_schedule_state::pending_boost) { data.initial_state = thread_schedule_state::pending; } // ASAN gets confused by reusing threads/stacks #if !defined(PIKA_HAVE_ADDRESS_SANITIZER) // Check for an unused thread object. if (!heap->empty()) { // Take ownership of the thread object and rebind it. tid = heap->front(); heap->pop_front(); get_thread_id_data(tid)->rebind(data); tq_deb.debug(debug::str<>("create_thread_object"), "rebind", queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&tid)); } else #endif { // Allocate a new thread object. threads::thread_data* p = nullptr; if (stacksize == parameters_.nostack_stacksize_) { p = threads::thread_data_stackless::create( data, this, stacksize); } else { p = threads::thread_data_stackful::create( data, this, stacksize); } tid = thread_id_ref_type(p, thread_id_addref::no); tq_deb.debug(debug::str<>("create_thread_object"), "new", queue_data_print(this), debug::threadinfo<threads::thread_data*>(p)); } } // ---------------------------------------------------------------- void recycle_thread(thread_id_type tid) { std::ptrdiff_t stacksize = get_thread_id_data(tid)->get_stack_size(); if (stacksize == parameters_.small_stacksize_) { thread_heap_small_.push_front(tid); } else if (stacksize == parameters_.medium_stacksize_) { thread_heap_medium_.push_front(tid); } else if (stacksize == parameters_.large_stacksize_) { thread_heap_large_.push_front(tid); } else if (stacksize == parameters_.huge_stacksize_) { thread_heap_huge_.push_front(tid); } else if (stacksize == parameters_.nostack_stacksize_) { thread_heap_nostack_.push_front(tid); } else { PIKA_ASSERT_MSG( false, util::format("Invalid stack size {1}", stacksize)); } } // ---------------------------------------------------------------- static void deallocate(threads::thread_data* p) { using threads::thread_data; p->~thread_data(); thread_alloc_.deallocate(p, 1); } // ---------------------------------------------------------------- void add_to_thread_map(threads::thread_id_type tid) { scoped_lock lk(thread_map_mtx_.data_); // add a new entry in the map for this thread std::pair<thread_map_type::iterator, bool> p = thread_map_.insert(tid); if (/*PIKA_UNLIKELY*/ (!p.second)) { std::string map_size = std::to_string(thread_map_.size()); // threads::thread_id_type tid2 = *(p.first); // threads::thread_data* td = get_thread_id_data(tid2); // std::string prev = pika::util::format("{}", td); tq_deb.error(debug::str<>("map add"), "Couldn't add new thread to the thread map", queue_data_print(this), debug::threadinfo<thread_id_type*>(&tid)); lk.unlock(); PIKA_THROW_EXCEPTION(pika::out_of_memory, "queue_holder_thread::add_to_thread_map", "Couldn't add new thread to the thread map {}", map_size); } ++thread_map_count_.data_; tq_deb.debug(debug::str<>("map add"), queue_data_print(this), debug::threadinfo<thread_id_type*>(&tid)); // this thread has to be in the map now PIKA_ASSERT(thread_map_.find(tid) != thread_map_.end()); } // ---------------------------------------------------------------- void remove_from_thread_map(threads::thread_id_type tid, bool dealloc) { // this thread has to be in this map PIKA_ASSERT(thread_map_.find(tid) != thread_map_.end()); PIKA_ASSERT(thread_map_count_.data_ >= 0); bool deleted = thread_map_.erase(tid) != 0; PIKA_ASSERT(deleted); (void) deleted; tq_deb.debug(debug::str<>("map remove"), queue_data_print(this), debug::threadinfo<thread_id_type*>(&tid)); if (dealloc) { deallocate(get_thread_id_data(tid)); } --thread_map_count_.data_; } // ---------------------------------------------------------------- bool get_next_thread_HP(threads::thread_id_ref_type& thrd, bool stealing, bool check_new) PIKA_HOT { // only take from BP queue if we are not stealing if (!stealing && bp_queue_ && bp_queue_->get_next_thread(thrd, stealing, check_new)) { tq_deb.debug(debug::str<>("next_thread_BP"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "thread_priority::bound"); return true; } if (hp_queue_ && hp_queue_->get_next_thread(thrd, stealing, check_new)) { tq_deb.debug(debug::str<>("get_next_thread_HP"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "thread_priority::high"); return true; } // if we're out of work in the main queues, debug_queues("get_next_thread"); return false; } // ---------------------------------------------------------------- bool get_next_thread( threads::thread_id_ref_type& thrd, bool stealing) PIKA_HOT { if (np_queue_->get_next_thread(thrd, stealing)) { tq_deb.debug(debug::str<>("next_thread_NP"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "thread_priority::normal"); return true; } if (lp_queue_ && lp_queue_->get_next_thread(thrd, stealing)) { tq_deb.debug(debug::str<>("next_thread_LP"), queue_data_print(this), debug::threadinfo<threads::thread_id_ref_type*>(&thrd), "thread_priority::low"); return true; } // if we're out of work in the main queues, debug_queues("get_next_thread"); return false; } // ---------------------------------------------------------------- std::size_t add_new_HP( std::int64_t add_count, thread_holder_type* addfrom, bool stealing) { std::size_t added; if (owns_bp_queue() && !stealing) { added = bp_queue_->add_new(add_count, addfrom->bp_queue_, stealing); if (added > 0) return added; } if (owns_hp_queue()) { added = hp_queue_->add_new(add_count, addfrom->hp_queue_, stealing); if (added > 0) return added; } return 0; } // ---------------------------------------------------------------- std::size_t add_new( std::int64_t add_count, thread_holder_type* addfrom, bool stealing) { std::size_t added; if (owns_np_queue()) { added = np_queue_->add_new(add_count, addfrom->np_queue_, stealing); if (added > 0) return added; } if (owns_lp_queue()) { added = lp_queue_->add_new(add_count, addfrom->lp_queue_, stealing); if (added > 0) return added; } // static auto an_timed = tq_deb.make_timer(1, debug::str<>("add_new")); tq_deb.timed(an_timed, "add", debug::dec<3>(add_count), "owns bp, hp, np, lp", owns_bp_queue(), owns_hp_queue(), owns_np_queue(), owns_lp_queue(), "this", queue_data_print(this), "from", queue_data_print(addfrom)); // return 0; } // ---------------------------------------------------------------- inline std::size_t get_queue_length() { std::size_t count = 0; count += owns_bp_queue() ? bp_queue_->get_queue_length() : 0; count += owns_hp_queue() ? hp_queue_->get_queue_length() : 0; count += owns_np_queue() ? np_queue_->get_queue_length() : 0; count += owns_lp_queue() ? lp_queue_->get_queue_length() : 0; debug_queues("get_queue_length"); return count; } // ---------------------------------------------------------------- inline std::size_t get_thread_count_staged( thread_priority priority) const { // Return thread count of one specific queue. switch (priority) { case thread_priority::default_: { std::int64_t count = 0; count += owns_bp_queue() ? bp_queue_->get_queue_length_staged() : 0; count += owns_hp_queue() ? hp_queue_->get_queue_length_staged() : 0; count += owns_np_queue() ? np_queue_->get_queue_length_staged() : 0; count += owns_lp_queue() ? lp_queue_->get_queue_length_staged() : 0; return count; } case thread_priority::bound: { return owns_bp_queue() ? bp_queue_->get_queue_length_staged() : 0; } case thread_priority::low: { return owns_lp_queue() ? lp_queue_->get_queue_length_staged() : 0; } case thread_priority::normal: { return owns_np_queue() ? np_queue_->get_queue_length_staged() : 0; } case thread_priority::boost: case thread_priority::high: case thread_priority::high_recursive: { return owns_hp_queue() ? hp_queue_->get_queue_length_staged() : 0; } default: case thread_priority::unknown: { PIKA_THROW_EXCEPTION(bad_parameter, "queue_holder_thread::get_thread_count_staged", "unknown thread priority value (thread_priority::unknown)"); } } return 0; } // ---------------------------------------------------------------- inline std::size_t get_thread_count_pending( thread_priority priority) const { // Return thread count of one specific queue. switch (priority) { case thread_priority::default_: { std::int64_t count = 0; count += owns_hp_queue() ? hp_queue_->get_queue_length_pending() : 0; count += owns_np_queue() ? np_queue_->get_queue_length_pending() : 0; count += owns_lp_queue() ? lp_queue_->get_queue_length_pending() : 0; return count; } case thread_priority::bound: { return owns_bp_queue() ? bp_queue_->get_queue_length_pending() : 0; } case thread_priority::low: { return owns_lp_queue() ? lp_queue_->get_queue_length_pending() : 0; } case thread_priority::normal: { return owns_np_queue() ? np_queue_->get_queue_length_pending() : 0; } case thread_priority::boost: case thread_priority::high: case thread_priority::high_recursive: { return owns_hp_queue() ? hp_queue_->get_queue_length_pending() : 0; } default: case thread_priority::unknown: { PIKA_THROW_EXCEPTION(bad_parameter, "queue_holder_thread::get_thread_count_pending", "unknown thread priority value (thread_priority::unknown)"); } } return 0; } // ---------------------------------------------------------------- inline std::size_t get_thread_count( thread_schedule_state state = thread_schedule_state::unknown, thread_priority priority = thread_priority::default_) const { if (thread_schedule_state::terminated == state) return terminated_items_count_.data_.load( std::memory_order_relaxed); if (thread_schedule_state::staged == state) return get_thread_count_staged(priority); if (thread_schedule_state::pending == state) return get_thread_count_pending(priority); if (thread_schedule_state::unknown == state) return thread_map_count_.data_.load(std::memory_order_relaxed) + get_thread_count_staged(priority) - terminated_items_count_.data_.load( std::memory_order_relaxed); // acquire lock only if absolutely necessary scoped_lock lk(thread_map_mtx_.data_); std::int64_t num_threads = 0; thread_map_type::const_iterator end = thread_map_.end(); for (thread_map_type::const_iterator it = thread_map_.begin(); it != end; ++it) { if (get_thread_id_data(*it)->get_state().state() == state) ++num_threads; } return num_threads; } // ------------------------------------------------------------ /// Destroy the passed thread as it has been terminated void destroy_thread( threads::thread_data* thrd, std::size_t thread_num, bool xthread) { // the thread must be destroyed by the same queue holder that created it PIKA_ASSERT(&thrd->get_queue<queue_holder_thread>() == this); // tq_deb.debug(debug::str<>("destroy"), "terminated_items push", "xthread", xthread, queue_data_print(this), debug::threadinfo<threads::thread_data*>(thrd)); terminated_items_.push(thrd); std::int64_t count = ++terminated_items_count_.data_; if (!xthread && (count > parameters_.max_terminated_threads_)) { cleanup_terminated( thread_num, false); // clean up all terminated threads } } // ------------------------------------------------------------ void abort_all_suspended_threads() { scoped_lock lk(thread_map_mtx_.data_); thread_map_type::iterator end = thread_map_.end(); for (thread_map_type::iterator it = thread_map_.begin(); it != end; ++it) { if (get_thread_id_data(*it)->get_state().state() == thread_schedule_state::suspended) { get_thread_id_data(*it)->set_state( thread_schedule_state::pending, thread_restart_state::abort); // np queue always exists so use that as priority doesn't matter np_queue_->schedule_work(*it, true); } } throw std::runtime_error("This function needs to be reimplemented"); } // ------------------------------------------------------------ bool enumerate_threads(util::function<bool(thread_id_type)> const& f, thread_schedule_state state = thread_schedule_state::unknown) const { std::uint64_t count = thread_map_count_.data_; if (state == thread_schedule_state::terminated) { count = terminated_items_count_.data_; } else if (state == thread_schedule_state::staged) { PIKA_THROW_EXCEPTION(bad_parameter, "queue_holder_thread::iterate_threads", "can't iterate over thread ids of staged threads"); return false; } std::vector<thread_id_type> tids; tids.reserve(static_cast<std::size_t>(count)); if (state == thread_schedule_state::unknown) { scoped_lock lk(thread_map_mtx_.data_); thread_map_type::const_iterator end = thread_map_.end(); for (thread_map_type::const_iterator it = thread_map_.begin(); it != end; ++it) { tids.push_back(*it); } } else { scoped_lock lk(thread_map_mtx_.data_); thread_map_type::const_iterator end = thread_map_.end(); for (thread_map_type::const_iterator it = thread_map_.begin(); it != end; ++it) { if (get_thread_id_data(*it)->get_state().state() == state) tids.push_back(*it); } } // now invoke callback function for all matching threads for (thread_id_type const& id : tids) { if (!f(id)) return false; // stop iteration } return true; } // ------------------------------------------------------------ void debug_info() { tq_deb.debug(debug::str<>("details"), "owner_mask_", debug::bin<8>(owner_mask_), "D", debug::dec<2>(domain_index_), "Q", debug::dec<3>(queue_index_)); tq_deb.debug(debug::str<>("bp_queue"), debug::hex<12, void*>(bp_queue_), "holder", debug::hex<12, void*>( bp_queue_->holder_ ? bp_queue_->holder_ : nullptr)); tq_deb.debug(debug::str<>("hp_queue"), debug::hex<12, void*>(hp_queue_), "holder", debug::hex<12, void*>( hp_queue_->holder_ ? hp_queue_->holder_ : nullptr)); tq_deb.debug(debug::str<>("np_queue"), debug::hex<12, void*>(np_queue_), "holder", debug::hex<12, void*>( np_queue_->holder_ ? np_queue_->holder_ : nullptr)); tq_deb.debug(debug::str<>("lp_queue"), debug::hex<12, void*>(lp_queue_), "holder", debug::hex<12, void*>( lp_queue_->holder_ ? lp_queue_->holder_ : nullptr)); } // ------------------------------------------------------------ void debug_queues(const char* prefix) { static auto deb_queues = tq_deb.make_timer(1, debug::str<>("debug_queues")); // tq_deb.timed(deb_queues, prefix, queue_data_print(this)); } }; template <typename QueueType> pika::detail::internal_allocator<threads::thread_data> queue_holder_thread<QueueType>::thread_alloc_; }}} // namespace pika::threads::policies
39.431467
85
0.489241
[ "object", "vector" ]
08625331506f2c70572194ab5de3b04d45538790
391
hpp
C++
include/Bomberman/GameBase/RenderGroup.hpp
PoetaKodu/bomberman
339f01e28afea0fde05f2b2c4e8e40a0d878945b
[ "MIT" ]
null
null
null
include/Bomberman/GameBase/RenderGroup.hpp
PoetaKodu/bomberman
339f01e28afea0fde05f2b2c4e8e40a0d878945b
[ "MIT" ]
null
null
null
include/Bomberman/GameBase/RenderGroup.hpp
PoetaKodu/bomberman
339f01e28afea0fde05f2b2c4e8e40a0d878945b
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace bmb { class Actor; class IRenderable; class RenderGroup { public: using RenderableContainer = std::vector< IRenderable* >; bool addUnique( IRenderable& renderable_ ); RenderableContainer const& getRenderables() const { return _renderables; } protected: RenderableContainer _renderables; }; }
15.64
61
0.672634
[ "vector" ]
08672d88833e658e9147a78298b8d69d3bf3aa5c
1,058
hpp
C++
libs/geometry/test/point_concept/function_requiring_a_point.hpp
Ron2014/boost_1_48_0
19673f69677ffcba7c7bd6e08ec07ee3962f161c
[ "BSL-1.0" ]
null
null
null
libs/geometry/test/point_concept/function_requiring_a_point.hpp
Ron2014/boost_1_48_0
19673f69677ffcba7c7bd6e08ec07ee3962f161c
[ "BSL-1.0" ]
null
null
null
libs/geometry/test/point_concept/function_requiring_a_point.hpp
Ron2014/boost_1_48_0
19673f69677ffcba7c7bd6e08ec07ee3962f161c
[ "BSL-1.0" ]
null
null
null
// Boost.Geometry (aka GGL, Generic Geometry Library) Point concept unit tests // // Copyright (c) 2008-2011 Bruno Lalande, Paris, France. // Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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) #ifndef GEOMETRY_TEST_POINT_CONCEPT_FUNCTION_REQUIRING_A_POINT_HPP #define GEOMETRY_TEST_POINT_CONCEPT_FUNCTION_REQUIRING_A_POINT_HPP #include <boost/concept/requires.hpp> #include <boost/geometry/geometries/concepts/point_concept.hpp> namespace bg = boost::geometry; namespace test { template <typename P, typename C> inline BOOST_CONCEPT_REQUIRES( ((bg::concept::Point<P>)) ((bg::concept::ConstPoint<C>)), (void)) function_requiring_a_point(P& p1, const C& p2) { bg::set<0>(p1, bg::get<0>(p2)); } } #endif // GEOMETRY_TEST_POINT_CONCEPT_FUNCTION_REQUIRING_A_POINT_HPP
32.060606
80
0.716446
[ "geometry" ]
0867c3ee655585f12a3b5452d1b2fc3acedefce3
6,479
cpp
C++
private/shell/ext/netplwiz/advanced.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/netplwiz/advanced.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/netplwiz/advanced.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#include "stdafx.h" #include "advanced.h" BOOL CAdvancedDialog::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwndDlg, WM_INITDIALOG, OnInitDialog); HANDLE_MSG(hwndDlg, WM_COMMAND, OnCommand); default: break; } return FALSE; } BOOL CAdvancedDialog::OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) { // Create the message for the advanced dialog that informs the user // of the purpose of the dialog, etc. TCHAR szUsername[UNLEN + 1]; TCHAR szDomainname[UNCLEN + 1]; TCHAR szMessage[UNLEN + UNCLEN + MAX_STATIC + 1]; TCHAR szFormat[MAX_STATIC + 1]; TCHAR szUserAndDomain[UNLEN + UNCLEN + 1]; // Load the current user name ULONG cchUsername = ARRAYSIZE(szUsername); ULONG cchDomainname = ARRAYSIZE(szDomainname); if (GetCurrentUserAndDomainName(szUsername, &cchUsername, szDomainname, &cchDomainname)) { // Create the server\username form wsprintf(szUserAndDomain, TEXT("%s\\%s"), szDomainname, szUsername); // Create the message LoadString(g_hInstance, IDS_CONNECTASUSER_MESSAGE, szFormat, ARRAYSIZE(szFormat)); _sntprintf(szMessage, ARRAYSIZE(szMessage), szFormat, m_pdata->szResourceName, szUserAndDomain); SetDlgItemText(hwnd, IDC_LOGGEDIN_STATIC, szMessage); } // Load the current alternate user name into the text box SetDlgItemText(hwnd, IDC_USER, m_pdata->szUsername); Edit_LimitText(GetDlgItem(hwnd, IDC_USER), UNLEN); // If there is no DC, disable "find user" function if (!GetEnvironmentVariable(TEXT("USERDNSDOMAIN"), NULL, 0) ) { // DS isn't available, disable browse EnableWindow(GetDlgItem(hwnd, IDC_FINDUSER_BUTTON), FALSE); } // Load the current alternate user password into the text box SetDlgItemText(hwnd, IDC_PASSWORD, m_pdata->szPassword); Edit_LimitText(GetDlgItem(hwnd, IDC_PASSWORD), PWLEN); // Set the reconnect check box if needed Button_SetCheck(GetDlgItem(hwnd, IDC_COMPLETION_RECONNECT_CHECK), (m_pdata->fReconnect ? BST_CHECKED : BST_UNCHECKED)); return TRUE; } BOOL CAdvancedDialog::OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { switch (id) { case IDC_FINDUSER_BUTTON: // User wants to look up a username FindUser(hwnd, IDC_USER); return TRUE; case IDOK: // User has click OK, save the username they've entered GetDlgItemText(hwnd, IDC_USER, m_pdata->szUsername, ARRAYSIZE(m_pdata->szUsername)); GetDlgItemText(hwnd, IDC_PASSWORD, m_pdata->szPassword, ARRAYSIZE(m_pdata->szPassword)); // See if the user wants to reconnect to the share on startup m_pdata->fReconnect = IsDlgButtonChecked(hwnd, IDC_COMPLETION_RECONNECT_CHECK); // Fall through case IDCANCEL: EndDialog(hwnd, id); return TRUE; default: break; } return FALSE; } void CAdvancedDialog::FindUser(HWND hwndDlg, UINT uiTextLocation) // This routine activates the appropriate Object Picker to allow // the user to select a user // uiTextLocation -- The resource ID of the Edit control where the selected // object should be printed { static const TCHAR c_szObjectSid[] = TEXT("ObjectSid"); static const TCHAR* aszAttributes[] = { c_szObjectSid, }; HRESULT hr; PDSSELECTIONLIST pDsSelectionList; GETUSERGROUPSELECTIONINFO gui = {0}; gui.cbSize = sizeof(gui); gui.ptzComputerName = NULL; gui.flDsObjectPicker = DSOP_SCOPE_DIRECTORY | DSOP_SCOPE_DOMAIN_TREE | DSOP_SCOPE_EXTERNAL_TRUSTED_DOMAINS | DSOP_RESTRICT_NAMES_TO_KNOWN_DOMAINS; gui.flStartingScope = DSOP_SCOPE_SPECIFIED_DOMAIN; gui.flUserGroupObjectPickerOtherDomains = UGOP_USERS; gui.cRequestedAttributes = ARRAYSIZE(aszAttributes); gui.aptzRequestedAttributes = aszAttributes; gui.ppDsSelList = &pDsSelectionList; gui.hwndParent = hwndDlg; // // List users and groups, with this computer as the focus // hr = GetUserGroupSelection(&gui); // // Note: If the object picker dialog is cancelled, it returns S_FALSE, // so we must check for that as well. Technically, we could just check // (hr == S_OK), but this way, we're safe if COM adds more success codes. // Also, note that the NULL check for pDsSelectionList is a workaround // for a bug in the Object Picker where it returns S_OK with no selection. // if (SUCCEEDED(hr) && hr != S_FALSE && pDsSelectionList) { // Fill in the edit box with the user name LPVARIANT pvarSid = pDsSelectionList->aDsSelection[0].pvarOtherAttributes; if (NULL != pvarSid && (VT_ARRAY | VT_UI1) == V_VT(pvarSid)) { PSID pSid; // = (PSID)(V_ARRAY(pvarSid)->pvData); if (SUCCEEDED(SafeArrayAccessData(V_ARRAY(pvarSid), &pSid))) { TCHAR szDomain[DNLEN + 1]; TCHAR szUser[UNLEN + 1]; DWORD cchDomain = ARRAYSIZE(szDomain); DWORD cchUser = ARRAYSIZE(szUser); SID_NAME_USE sUse; // Lookup the domain and user name for this SID BOOL fSuccess = LookupAccountSid(NULL, pSid, szUser, &cchUser, szDomain, &cchDomain, &sUse); if (fSuccess) { TCHAR szDomainUser[UNLEN + DNLEN + 2]; wnsprintf(szDomainUser, ARRAYSIZE(szDomainUser), TEXT("%s\\%s"), szDomain, szUser); SetDlgItemText(hwndDlg, uiTextLocation, szDomainUser); } else { // Lookupaccountsid failed } SafeArrayUnaccessData(V_ARRAY(pvarSid)); } } else { TraceMsg("SID wasn't returned from GetUserGroupSelection"); } } else { // MPRUI_LOG0(TRACE, "Object picker was closed with no selection made\n"); } if (pDsSelectionList) FreeDsSelectionList(pDsSelectionList); }
33.921466
93
0.617688
[ "object" ]
086a9d2a589b89210dca62c4f3298622b83dfcdc
11,696
inl
C++
modules/SofaBoundaryCondition/AffineMovementConstraint.inl
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
modules/SofaBoundaryCondition/AffineMovementConstraint.inl
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
modules/SofaBoundaryCondition/AffineMovementConstraint.inl
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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) 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_AFFINEMOVEMENTCONSTRAINT_INL #define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_AFFINEMOVEMENTCONSTRAINT_INL #include <SofaBoundaryCondition/AffineMovementConstraint.h> #include <sofa/core/visual/VisualParams.h> #include <SofaBaseTopology/TopologySubsetData.inl> #include <sofa/simulation/Simulation.h> #include <iostream> #include <sofa/helper/cast.h> namespace sofa { namespace component { namespace projectiveconstraintset { // Define TestFunction template< class DataTypes> bool AffineMovementConstraint<DataTypes>::FCPointHandler::applyTestCreateFunction(unsigned int, const sofa::helper::vector<unsigned int> &, const sofa::helper::vector<double> &) { return fc != 0; } // Define RemovalFunction template< class DataTypes> void AffineMovementConstraint<DataTypes>::FCPointHandler::applyDestroyFunction(unsigned int pointIndex, core::objectmodel::Data<value_type>&) { if (fc) { fc->removeConstraint((unsigned int) pointIndex); } } template <class DataTypes> AffineMovementConstraint<DataTypes>::AffineMovementConstraint() : core::behavior::ProjectiveConstraintSet<DataTypes>(NULL) , data(new AffineMovementConstraintInternalData<DataTypes>) , m_meshIndices( initData(&m_meshIndices,"meshIndices","Indices of the mesh") ) , m_indices( initData(&m_indices,"indices","Indices of the constrained points") ) , m_beginConstraintTime( initData(&m_beginConstraintTime,"beginConstraintTime","Begin time of the bilinear constraint") ) , m_endConstraintTime( initData(&m_endConstraintTime,"endConstraintTime","End time of the bilinear constraint") ) , m_rotation( initData(&m_rotation,"rotation","rotation applied to border points") ) , m_quaternion( initData(&m_quaternion,"quaternion","quaternion applied to border points") ) , m_translation( initData(&m_translation,"translation","translation applied to border points") ) , m_drawConstrainedPoints( initData(&m_drawConstrainedPoints,"drawConstrainedPoints","draw constrained points") ) { pointHandler = new FCPointHandler(this, &m_indices); if(!m_beginConstraintTime.isSet()) m_beginConstraintTime = 0; if(!m_endConstraintTime.isSet()) m_endConstraintTime = 20; } template <class DataTypes> AffineMovementConstraint<DataTypes>::~AffineMovementConstraint() { if (pointHandler) delete pointHandler; } template <class DataTypes> void AffineMovementConstraint<DataTypes>::clearConstraints() { m_indices.beginEdit()->clear(); m_indices.endEdit(); } template <class DataTypes> void AffineMovementConstraint<DataTypes>::addConstraint(unsigned int index) { m_indices.beginEdit()->push_back(index); m_indices.endEdit(); } template <class DataTypes> void AffineMovementConstraint<DataTypes>::removeConstraint(unsigned int index) { removeValue(*m_indices.beginEdit(),index); m_indices.endEdit(); } // -- Constraint interface template <class DataTypes> void AffineMovementConstraint<DataTypes>::init() { this->core::behavior::ProjectiveConstraintSet<DataTypes>::init(); topology = this->getContext()->getMeshTopology(); // Initialize functions and parameters m_indices.createTopologicalEngine(topology, pointHandler); m_indices.registerTopologicalData(); const SetIndexArray & indices = m_indices.getValue(); unsigned int maxIndex=this->mstate->getSize(); for (unsigned int i=0; i<indices.size(); ++i) { const unsigned int index=indices[i]; if (index >= maxIndex) { serr << "Index " << index << " not valid!" << sendl; removeConstraint(index); } } } template <class DataTypes> template <class DataDeriv> void AffineMovementConstraint<DataTypes>::projectResponseT(const core::MechanicalParams* /*mparams*/, DataDeriv& dx) { const SetIndexArray & indices = m_indices.getValue(); for (size_t i = 0; i< indices.size(); ++i) { dx[indices[i]]=Deriv(); } } template <class DataTypes> void AffineMovementConstraint<DataTypes>::projectResponse(const core::MechanicalParams* mparams, DataVecDeriv& resData) { helper::WriteAccessor<DataVecDeriv> res = resData; projectResponseT<VecDeriv>(mparams, res.wref()); } template <class DataTypes> void AffineMovementConstraint<DataTypes>::projectVelocity(const core::MechanicalParams* mparams, DataVecDeriv& vData) { helper::WriteAccessor<DataVecDeriv> res = vData; projectResponseT<VecDeriv>(mparams, res.wref()); } template <class DataTypes> void AffineMovementConstraint<DataTypes>::projectPosition(const core::MechanicalParams* /*mparams*/, DataVecCoord& xData) { sofa::simulation::Node::SPtr root = down_cast<sofa::simulation::Node>( this->getContext()->getRootContext() ); helper::WriteAccessor<DataVecCoord> x = xData; const SetIndexArray & indices = m_indices.getValue(); // Time SReal beginTime = m_beginConstraintTime.getValue(); SReal endTime = m_endConstraintTime.getValue(); SReal totalTime = endTime - beginTime; //initialize initial mesh Dofs positions, if it's not done if(meshPointsX0.size()==0) this->initializeInitialPositions(m_meshIndices.getValue(),xData,meshPointsX0); //initialize final mesh Dofs positions, if it's not done if(meshPointsXf.size()==0) this->initializeFinalPositions(m_meshIndices.getValue(),xData, meshPointsX0, meshPointsXf); //initialize initial constrained Dofs positions, if it's not done if(x0.size() == 0) this->initializeInitialPositions(indices,xData,x0); //initialize final constrained Dofs positions, if it's not done if (xf.size() == 0) this->initializeFinalPositions(indices,xData,x0,xf); // Update the intermediate Dofs positions computed by linear interpolation SReal time = root->getTime(); if( time > beginTime && time <= endTime && totalTime > 0) { for (size_t i = 0; i< indices.size(); ++i) { x[indices[i]] = ((xf[indices[i]]-x0[indices[i]])*time + (x0[indices[i]]*endTime - xf[indices[i]]*beginTime))/totalTime; } } else if (time > endTime) { for (size_t i = 0; i< indices.size(); ++i) { x[indices[i]] = xf[indices[i]]; } } } template <class DataTypes> void AffineMovementConstraint<DataTypes>::projectMatrix( sofa::defaulttype::BaseMatrix* M, unsigned /*offset*/ ) { // clears the rows and columns associated with constrained particles unsigned blockSize = DataTypes::deriv_total_size; for(SetIndexArray::const_iterator it= m_indices.getValue().begin(), iend=m_indices.getValue().end(); it!=iend; it++ ) { M->clearRowsCols((*it) * blockSize,(*it+1) * (blockSize) ); } } template <class DataTypes> void AffineMovementConstraint<DataTypes>::getFinalPositions( VecCoord& finalPos,DataVecCoord& xData) { // Indices of mesh points const SetIndexArray & meshIndices = m_meshIndices.getValue(); // Initialize final positions if(meshPointsXf.size()==0) {this->initializeFinalPositions(meshIndices,xData,meshPointsX0,meshPointsXf);} // Set final positions finalPos.resize(meshIndices.size()); for (size_t i=0; i < meshIndices.size() ; ++i) { finalPos[meshIndices[i]] = meshPointsXf[meshIndices[i]]; } } template <class DataTypes> void AffineMovementConstraint<DataTypes>::initializeInitialPositions (const SetIndexArray & indices, DataVecCoord& xData, VecCoord& x0) { helper::WriteAccessor<DataVecCoord> x = xData; x0.resize(x.size()); for (size_t i=0; i < indices.size() ; ++i) { x0[indices[i]] = x[indices[i]]; } } template <class DataTypes> void AffineMovementConstraint<DataTypes>::transform(const SetIndexArray & indices, VecCoord& x0, VecCoord& xf) { Vector3 translation = m_translation.getValue(); for (size_t i=0; i < indices.size() ; ++i) { DataTypes::setCPos(xf[indices[i]], (m_rotation.getValue())*DataTypes::getCPos(x0[indices[i]]) + translation); } } template <> void AffineMovementConstraint<defaulttype::Rigid3Types>::transform(const SetIndexArray & indices, defaulttype::Rigid3Types::VecCoord& x0, defaulttype::Rigid3Types::VecCoord& xf) { // Get quaternion and translation values RotationMatrix rotationMat(0); Quat quat = m_quaternion.getValue(); quat.toMatrix(rotationMat); Vector3 translation = m_translation.getValue(); // Apply transformation for (size_t i=0; i < indices.size() ; ++i) { // Translation xf[indices[i]].getCenter() = rotationMat*(x0[indices[i]].getCenter()) + translation; // Rotation xf[indices[i]].getOrientation() = (quat)+x0[indices[i]].getOrientation(); } } template <class DataTypes> void AffineMovementConstraint<DataTypes>::initializeFinalPositions (const SetIndexArray & indices, DataVecCoord& xData, VecCoord& x0, VecCoord& xf) { Deriv displacement; helper::WriteAccessor<DataVecCoord> x = xData; xf.resize(x.size()); // if the positions were not initialized if(x0.size() == 0) this->initializeInitialPositions(indices,xData,x0); transform(indices,x0,xf); } template <class DataTypes> void AffineMovementConstraint<DataTypes>::draw(const core::visual::VisualParams* vparams) { const SetIndexArray & indices = m_indices.getValue(); std::vector< Vector3 > points; const VecCoord& x = this->mstate->read(core::ConstVecCoordId::position())->getValue(); Vector3 point; if(m_drawConstrainedPoints.getValue()) { for (SetIndexArray::const_iterator it = indices.begin();it != indices.end();++it) { point = DataTypes::getCPos(x[*it]); points.push_back(point); } vparams->drawTool()->drawPoints(points, 10, defaulttype::Vec<4,float>(1,0.5,0.5,1)); } } } // namespace constraint } // namespace component } // namespace sofa #endif
34.60355
177
0.660568
[ "mesh", "vector", "transform" ]
086d8d41b06e1381d1a7c669d459444948ed6ba8
754
hpp
C++
od_mstar3/mstar_utils.hpp
ct2034/PRIMAL2
1bd44cba6f674e37e78b893a323d35a348dfb759
[ "MIT" ]
75
2018-10-08T00:53:44.000Z
2021-09-17T12:26:21.000Z
od_mstar3/mstar_utils.hpp
544211707/distributedRL_MAPF
b7ea7a4accdb9593207ae30cc1d79d4c93965865
[ "MIT" ]
8
2020-11-20T07:41:03.000Z
2021-12-14T08:36:42.000Z
od_mstar3/mstar_utils.hpp
544211707/distributedRL_MAPF
b7ea7a4accdb9593207ae30cc1d79d4c93965865
[ "MIT" ]
36
2018-09-28T09:07:56.000Z
2021-09-20T14:10:29.000Z
#ifndef MSTAR_UTILS_H #define MSTAR_UTILS_H /** * Defines convinence functions for testing or other purposes not directly * related to the actual planning */ #include <iostream> #include "mstar_type_defs.hpp" namespace mstar{ void print_od_path(const OdPath &path){ for (const OdCoord &pos: path){ std::cout << "{"; for (const RobCoord &i: pos.coord){ std::cout << i << " "; } std::cout << "}" << std::endl; } }; void print_path(const std::vector<std::vector<std::pair<int, int>>> &path){ for (const auto &coord: path){ std::cout << "{"; for (const auto &c: coord){ std::cout << "(" << c.first << ", " << c.second << ") "; } std::cout << "}" << std::endl; } }; }; #endif
20.944444
77
0.566313
[ "vector" ]
086fabab35a835e13ff973dd716a1d1f3d041c41
5,179
hpp
C++
Forest_Steiner.hpp
d5storm/Steiner-Forest
34f2656c0f2bad230f4c5fff20aca2a93de52bf8
[ "MIT" ]
2
2021-06-02T17:32:49.000Z
2021-11-22T20:17:34.000Z
Forest_Steiner.hpp
d5storm/Steiner-Forest
34f2656c0f2bad230f4c5fff20aca2a93de52bf8
[ "MIT" ]
null
null
null
Forest_Steiner.hpp
d5storm/Steiner-Forest
34f2656c0f2bad230f4c5fff20aca2a93de52bf8
[ "MIT" ]
null
null
null
// // Forest_Steiner.hpp // Steiner_Tree // // Created by sergio junior on 12/11/19. // Copyright © 2019 sergio junior. All rights reserved. // #ifndef Forest_Steiner_hpp #define Forest_Steiner_hpp #include <string> #include <vector> #include <iostream> #include <limits.h> #include <fstream> #include <cstdlib> #include <iomanip> #include <sstream> #include <list> #include <algorithm> #include <stack> #include <dirent.h> #include <ostream> #include <chrono> #include <queue> #include "./src/spgsolver.h" #include "./src/graph.h" #include "./src/rfw_random.h" using namespace std; class Edge { public: int id; int vertex_a, vertex_b; double weight; double tempWeight; bool usedEdge; int appearance; Edge(int id, int vertex_a, int vertex_b, double weight){ this->id = id; usedEdge = false; this->vertex_a = vertex_a; this->vertex_b = vertex_b; this->weight = weight; this->tempWeight = weight; this->appearance = 0; } void useEdgeAsPattern(){ this->usedEdge = true; } void useEdge(){ this->usedEdge = true; this->appearance++; } void forceUnUseEdge(){ this->appearance = 0; this->usedEdge = false; } void unUseEdge(){ if(this->appearance == 1){ this->appearance = 0; this->usedEdge = false; } else if(this->appearance > 1) this->appearance--; } }; class Nugget { public: int vertex_a, vertex_b; list<Edge*> * pathEdges; vector<bool> * isEdgeIdUsed; Nugget(int vertex_a, int vertex_b, list<Edge*> * pathEdges, int totalEdges){ this->vertex_a = vertex_a; this->vertex_b = vertex_b; this->pathEdges = pathEdges; this->isEdgeIdUsed = new vector<bool>(totalEdges, false); list<Edge *>::iterator it = this->pathEdges->begin(); int e; for(e = 0; e < this->pathEdges->size(); it++){ Edge * edge = *it; // cout << "EdgeID: " << edge->id << " isEdgeUsedSize: " << isEdgeIdUsed->size() << endl; // cin.get(); this->isEdgeIdUsed->at(edge->id) = true; e++; } } }; class Grafo { public: int V,E; // list<int> *adj; // adjacent list Grafo(string path); // constructor double solvePrim(RFWLocalRandom * random, int seed, int iter); double solveLuidi(RFWLocalRandom * random, int perturbation, int * totalEdgeLS, double alpha, bool usePattern, vector<vector<int>*> * elem, bool useTarget, int target); void printGraph(); Edge* getEdge(int id); Edge* getEdge(int vertex_a, int vertex_b); vector<Edge*> * getEdges() {return edges;}; vector<vector<int>*> getTerminalGroup(int pos); int totalUsedEdges() { return usedEdges->size();} int patternSize() { return usedPatternSize; } int getSolutionCost(); bool isFeasible(){ return detectCicle() && checkTerminalsMeet()?true:false; } private: bool detectCicle(); bool DFS(int start, int father, vector<int> * visited); bool checkTerminalsMeet(); int usedPatternSize = 0; list<Nugget*> * solution; vector<vector<int>*> * terminals; vector<vector<int>*> * adj; vector<vector<int>*> * steinerForest; vector<vector<int>*> * perturbationAux; vector<Edge*>* edges; list<Edge*>* usedEdges; vector<Graph> * treeGraphs; bool relocateLocalSearch(); bool relocateHardLocalSearch(); // TODO: VERSÃO DO RELOCATE QUE REALMENTE TENTA A "NOVA" ORDEM ESTABELECIDA. bool removeEdgeLocalSearch(bool firstImprovement); bool reDoNugget(); // TODO: DE TEMPOS EM TEMPOS COMEÇAR DE NOVO A SOLUÇÃO COM A ORDEM ESTABELECIDA. void removeAndInsertPerturbation(int percentage, RFWLocalRandom * random); void pushNugget(int vertex_a, int vertex_b, list<Edge*> * path, int totalEdges); void insertNugget(int pos, int vertex_a, int vertex_b, list<Edge*> * path, int totalEdges); Nugget * removeNugget(int pos); void createSteinerForestAdj(); void updatePerturbationAux(); void clearSteinerForestAdj(); void addEdge(int id, int vertex_a, int vertex_b, double weight); void useEdge(int e); void unUseEdge(int e); void useEdge(Edge * e); void unUseEdge(Edge * e); void clearUnusedPatternEdges(); vector<int>* addTerminalGroup(); vector<vector<Edge*>*>* getConnectedComponents(); void removeCiclesWithPrim(vector<vector<Edge*>*>* components); void solveByPath(RFWLocalRandom * random, bool usePattern, vector<vector<int>*> * elem); void GRASP(RFWLocalRandom * random, double alpha); void construct(vector<std::pair<int,int>> * pairs, vector<vector<int>*> * adj, RFWLocalRandom * random); void constructGrasp(vector<std::pair<int,int>> * pairs, RFWLocalRandom * random, double alpha); list<Edge*> * connectTwoVertexDijkstra(int vertex_source, int vertex_dest, vector<vector<int>*> * matrix); int minDistance(vector<int> dist, vector<bool> sptSet); void addToPath(vector<int> parent, int j, list<Edge*>* usedEdgesOnPath); }; #endif
30.110465
172
0.640278
[ "vector" ]
0874b4d06df5b2c5390858140ef901ac03bee894
6,606
cpp
C++
kern/drivers/pci/pci.cpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
44
2018-01-28T20:07:48.000Z
2022-02-11T22:58:49.000Z
kern/drivers/pci/pci.cpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
2
2017-09-12T15:38:16.000Z
2017-11-05T12:19:01.000Z
kern/drivers/pci/pci.cpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
8
2018-08-17T13:30:57.000Z
2021-06-25T16:56:12.000Z
/* pci.cpp Copyright (c) 05 Yann BOUCHER (yann) 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 "pci.hpp" #include "pci_vendors.hpp" #include "io.hpp" #include "utils/logging.hpp" std::vector<pci::PciDevice> pci::devices; inline uint32_t devaddr(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset) { return (uint32_t)(bus << 16) | (uint32_t)(slot << 11 ) | (uint32_t)(func << 8 ) | (uint32_t)(offset & ~0x3) | 0x80000000u; } uint32_t pci::read32(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset) { assert((offset & 0x3) == 0); // only aligned accesses outl(0xCF8, devaddr(bus, slot, func, offset)); return inl(0xCFC); } uint16_t pci::read16(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset) { assert((offset % 0x1) == 0); // only aligned accesses uint32_t val = read32(bus, slot, func, offset & ~0x3); if (offset & 0x3) return val & 0xFFFF; else return val >> 16; } uint8_t pci::read8(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset) { uint32_t val = read32(bus, slot, func, offset & ~0x3); return (val >> 8*(offset&0x3)) & 0xFF; } void pci::write32(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset, uint32_t val) { assert((offset & 0x3) == 0); outl(0xCF8, devaddr(bus, slot, func, offset)); outl(0xCFC, val); } void pci::write16(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset, uint16_t val) { assert((offset & 0x1) == 0); uint32_t src_val = read32(bus, slot, func, offset & ~0x3); uint32_t mask = (0x0000FFFF << 8*(offset&0x3)); src_val &= mask; src_val |= (val << (16 - 8*(offset&0x3))); write32(bus, slot, func, offset & ~0x3, src_val); } void pci::write8(uint16_t bus, uint16_t slot, uint16_t func, uint16_t offset, uint8_t val) { assert((offset & 0x1) == 0); uint32_t src_val = read32(bus, slot, func, offset & ~0x3); uint32_t mask = (0x000000FF << 8*(offset&0x3)); src_val &= mask; src_val |= (val << (32 - 8*(offset&0x3))); write32(bus, slot, func, offset & ~0x3, src_val); } uint16_t pci::device_id(uint16_t bus, uint16_t slot, uint16_t func) { return read16(bus, slot, func, 0); } uint16_t pci::vendor_id(uint16_t bus, uint16_t slot, uint16_t func) { return read16(bus, slot, func, 2); } uint8_t pci::header_type(uint16_t bus, uint16_t slot, uint16_t func) { return read8(bus, slot, func, 0xD); } void pci::check_device(uint8_t bus, uint8_t device) { uint8_t function = 0; uint16_t vendorID = vendor_id(bus, device, function); if(vendorID == 0xFFFF) return; // Device doesn't exist check_function(bus, device, function); uint8_t headerType = header_type(bus, device, function); if( (headerType & 0x80) != 0 || true) { /* It is a multi-function device, so check remaining functions */ for(function = 1; function < 8; function++) { if(vendor_id(bus, device, function) != 0xFFFF) { check_function(bus, device, function); } } } } void pci::check_function(uint8_t bus, uint8_t device, uint8_t function) { auto dev = get_dev(bus, device, function); pci::devices.emplace_back(dev); } void pci::scan() { for(uint16_t bus = 0; bus < 256; bus++) { for (uint8_t device = 0; device < 32; device++) { check_device(bus, device); } } } uint8_t pci::base_class(uint16_t bus, uint16_t slot, uint16_t func) { return read8(bus, slot, func, 0x8); } uint8_t pci::sub_class(uint16_t bus, uint16_t slot, uint16_t func) { return read8(bus, slot, func, 0x9); } uint8_t pci::prog_if(uint16_t bus, uint16_t slot, uint16_t func) { return read8(bus, slot, func, 0xA); } pci::PciDevice pci::get_dev(uint16_t bus, uint16_t slot, uint16_t func) { PciDevice dev; for (size_t i { 0 }; i < sizeof(dev) / sizeof(uint32_t); ++i) { uint32_t dword = read32(bus, slot, func, i*sizeof(uint32_t)); reinterpret_cast<uint32_t*>(&dev)[i] = dword; } dev.bus = bus; dev.slot = slot; dev.func = func; return dev; } std::vector<pci::PciDevice> pci::find_devices(uint8_t class_code, uint8_t sub_class) { std::vector<pci::PciDevice> devices; for (const auto& device : pci::devices) { if (device.classCode == class_code && device.subclass == sub_class) { devices.emplace_back(device); } } return devices; } std::vector<pci::PciDevice> pci::find_devices(uint8_t class_code, uint8_t sub_class, uint8_t interface) { std::vector<pci::PciDevice> devices; for (const auto& device : pci::devices) { if (device.classCode == class_code && device.subclass == sub_class && device.progIF == interface) { devices.emplace_back(device); } } return devices; } uint64_t pci::get_bar_val(const pci::PciDevice& dev, size_t bar_idx) { assert(bar_idx <= 6); auto type = bar_type(dev.bar[bar_idx]); switch (type) { case BARType::IO16: return dev.bar[bar_idx] & 0xFFFFFFFC; case BARType::Mem16: return dev.bar[bar_idx] & 0xFFF0; case BARType::Mem32: return dev.bar[bar_idx] & 0xFFFFFFF0; case BARType::Mem64: return (dev.bar[bar_idx] & 0xFFFFFFF0) + (uint64_t(dev.bar[bar_idx+1] & 0xFFFFFFFF) << 32); case BARType::Invalid: assert(false); } return 0; } uint8_t get_irq(const pci::PciDevice &dev) { // TODO : IO APIC return dev.int_line; }
27.07377
105
0.651226
[ "vector" ]
0878f4ed2b7d3c4b7eb193d74f4e267c6e3db79a
2,040
cpp
C++
leetcode.com/0236 Lowest Common Ancestor of a Binary Tree/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0236 Lowest Common Ancestor of a Binary Tree/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0236 Lowest Common Ancestor of a Binary Tree/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { private: TreeNode *result, *p, *q; // if result != null, we've found our LCA bool _helper(TreeNode *root) { if (result) return false; int found_cnt = 0; if (root == p) ++found_cnt; // found p if (root == q) ++found_cnt; // use if, instead of else if, in case: p == q // if we have found_cnt = 2, root is our LCA // if found_cnt = 2, no need to traverse another sub tree if (found_cnt !=2 && root->left) if (_helper(root->left)) ++found_cnt; if (found_cnt !=2 && root->right) if (_helper(root->right)) ++found_cnt; // we may have found our LCA in the above sub routines, return then if (result) return false; // for the first time, we have found_cnt = 2, root is our LCA if (found_cnt == 2) { result = root; return false; } // found_cnt could be 1: means we have found one of p, q; or we have found LCA in the sub routines // found_cnt could be 0: means we have found none of p, q return found_cnt; } public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { // don't know if below four cases are legal if (!root) return nullptr; // case 1: root == null, return null if (p) { if (!q) return p; // case 2: p != null && q == null, return p } else if (q) { return q; // case 3: p == null && q != null, return q } else { while (root->left) root = root->left; return root; // case 4: p == null && q == null, return the left most node (silly...) } // root != nullptr && p != nullptr && q != nullptr result = nullptr; // haven't found LCA yet this->p = p; this->q = q; _helper(root); return result; } };
37.090909
106
0.552941
[ "vector" ]
087dd197fc23847ee4a310a78b45b451c3afaf8f
1,929
hpp
C++
stan/math/prim/scal/fun/promote_scalar.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/scal/fun/promote_scalar.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/scal/fun/promote_scalar.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_SCAL_FUN_PROMOTE_SCALAR_HPP #define STAN_MATH_PRIM_SCAL_FUN_PROMOTE_SCALAR_HPP #include <stan/math/prim/scal/fun/promote_scalar_type.hpp> #include <stan/math/prim/scal/meta/index_type.hpp> namespace stan { namespace math { /** * General struct to hold static function for promoting underlying * scalar types. * * @tparam T return type of nested static function. * @tparam S input type for nested static function, whose underlying * scalar type must be assignable to T. */ template <typename T, typename S> struct promote_scalar_struct { /** * Return the value of the input argument promoted to the type * specified by the template parameter. * * This is the base case for mismatching template parameter * types in which the underlying scalar type of template * parameter <code>S</code> is assignable to type <code>T</code>. * * @param x input of type S. * @return input promoted to have scalars of type T. */ static T apply(S x) { return T(x); } }; /** * Struct to hold static function for promoting underlying scalar * types. This specialization is for equal input and output types * of function types. * * @tparam T input and return type of nested static function. */ template <typename T> struct promote_scalar_struct<T, T> { /** * Return the unmodified input. * * @param x input of type T. * @return input unmodified. */ static T apply(const T& x) { return x; } }; /** * This is the top-level function to call to promote the scalar * types of an input of type S to type T. * * @tparam T scalar type of output. * @tparam S input type. * @param x input vector. * @return input vector with scalars promoted to type T. */ template <typename T, typename S> typename promote_scalar_type<T, S>::type promote_scalar(const S& x) { return promote_scalar_struct<T, S>::apply(x); } } // namespace math } // namespace stan #endif
27.956522
69
0.712805
[ "vector" ]
0881b2020760c05dd514edcf2ce8549c9c77d5c8
1,006
cpp
C++
LeetCode/Others/Matrix/DetermineWhetherMatrixCanBeObtainedByRotation.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/Others/Matrix/DetermineWhetherMatrixCanBeObtainedByRotation.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/Others/Matrix/DetermineWhetherMatrixCanBeObtainedByRotation.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 1886 Determine Whether Matrix Can Be Obtained By Rotation * Easy * Jiawei Wang * 2021 10.4 */ #include <vector> using namespace::std; class Solution { public: bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) { for (int i = 0; i < 4; i++) { rotate(mat); if (mat == target) return true; } return false; } private: // From LeetCode 48 Rotate Image: void rotate(vector<vector<int>>& matrix) { if (matrix.empty()) return; int top = 0; int left = 0; int right = matrix.size() - 1; int bottom = matrix.size() - 1; int n = matrix.size(); // number of cells in one line while (n > 1) { for (int i = 0; i < n - 1; i++) { int tmp = matrix[top][left+i]; matrix[top][left+i] = matrix[bottom-i][left]; matrix[bottom-i][left] = matrix[bottom][right-i]; matrix[bottom][right-i] = matrix[top+i][right]; matrix[top+i][right] = tmp; } top++; bottom--; left++; right--; n -= 2; } } };
19.346154
78
0.578529
[ "vector" ]
0885160082731e7153ef2c2895b62908c35e69c8
5,928
cpp
C++
flashlight/fl/dataset/Utils.cpp
imaginary-person/flashlight
30d45c1c8c0fbe335a2a9d1e4bab57847316b157
[ "BSD-3-Clause" ]
1
2021-09-29T06:24:41.000Z
2021-09-29T06:24:41.000Z
flashlight/fl/dataset/Utils.cpp
pkassotis/flashlight
1061e1727c77fac644713047be4c2fb95c02fd55
[ "BSD-3-Clause" ]
5
2021-06-20T23:58:27.000Z
2021-07-09T17:45:07.000Z
flashlight/fl/dataset/Utils.cpp
pkassotis/flashlight
1061e1727c77fac644713047be4c2fb95c02fd55
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "flashlight/fl/dataset/Utils.h" #include <algorithm> #include <stdexcept> namespace fl { std::vector<int64_t> partitionByRoundRobin( int64_t numSamples, int64_t partitionId, int64_t numPartitions, int64_t batchSz /* = 1 */, bool allowEmpty /* = false */) { if (partitionId < 0 || partitionId >= numPartitions) { throw std::invalid_argument( "invalid partitionId, numPartitions for partitionByRoundRobin"); } int64_t nSamplesPerGlobalBatch = numPartitions * batchSz; int64_t nGlobalBatches = numSamples / nSamplesPerGlobalBatch; bool includeLast = (numSamples % nSamplesPerGlobalBatch) >= numPartitions; if (allowEmpty && (numSamples % nSamplesPerGlobalBatch) > 0) { includeLast = true; } if (includeLast) { ++nGlobalBatches; } std::vector<int64_t> outSamples; outSamples.reserve(nGlobalBatches * batchSz); for (size_t i = 0; i < nGlobalBatches; i++) { auto offset = i * nSamplesPerGlobalBatch; int64_t nCurSamples; // num samples in current batch if (includeLast && (i == nGlobalBatches - 1)) { nCurSamples = (numSamples - offset) / numPartitions; // min samples per proc int64_t remaining = (numSamples - offset) % numPartitions; offset += nCurSamples * partitionId; if (partitionId < remaining) { nCurSamples += 1; } offset += std::min(partitionId, remaining); } else { offset += batchSz * partitionId; nCurSamples = batchSz; } for (int64_t b = 0; b < nCurSamples; ++b) { outSamples.emplace_back(b + offset); } } return outSamples; } std::pair<std::vector<int64_t>, std::vector<int64_t>> dynamicPartitionByRoundRobin( const std::vector<float>& samplesSize, int64_t partitionId, int64_t numPartitions, int64_t maxSizePerBatch, bool allowEmpty /* = false */) { if (partitionId < 0 || partitionId >= numPartitions) { throw std::invalid_argument( "[dynamicPartitionByRoundRobin] invalid partitionId, numPartitions"); } std::vector<int64_t> batchSizes, batchOffsets; int64_t sampleIdx = 0, batchStartSampleIdx = 0; float maxSampleLen = 0; while (sampleIdx < samplesSize.size()) { if (samplesSize[sampleIdx] > maxSizePerBatch) { throw std::invalid_argument( "[dynamicPartitionByRoundRobin] invalid samples length: each sample " "should have size <= maxSizePerBatch, either filter data or set larger maxSizePerBatch. " "maxSizePerBatch were set to " + std::to_string(maxSizePerBatch) + " sample size is " + std::to_string(samplesSize[sampleIdx])); } float maxSampleLenOld = maxSampleLen; maxSampleLen = std::max(maxSampleLen, samplesSize[sampleIdx]); if ((sampleIdx - batchStartSampleIdx + 1) * maxSampleLen > maxSizePerBatch) { if (maxSampleLenOld * (sampleIdx - batchStartSampleIdx) > maxSizePerBatch) { throw std::invalid_argument( "dynamicPartitionByRoundRobin is doing wrong packing"); } batchSizes.push_back(sampleIdx - batchStartSampleIdx); batchOffsets.push_back(batchStartSampleIdx); batchStartSampleIdx = sampleIdx; maxSampleLen = samplesSize[sampleIdx]; } else { sampleIdx++; } } // process last batch with sampleIdx == numSamples, batchStartSampleIdx < // numSamples if ((sampleIdx - batchStartSampleIdx) * maxSampleLen < maxSizePerBatch) { batchSizes.push_back(sampleIdx - batchStartSampleIdx); batchOffsets.push_back(batchStartSampleIdx); } int64_t nGlobalBatches = batchSizes.size() / numPartitions; if (allowEmpty && (batchSizes.size() % numPartitions) > 0) { ++nGlobalBatches; } std::vector<int64_t> outSamples, outBatchSizes; for (size_t i = 0; i < nGlobalBatches; i++) { int index = i * numPartitions + partitionId; if (index < batchSizes.size()) { outBatchSizes.emplace_back(batchSizes[index]); for (int64_t b = 0; b < batchSizes[index]; ++b) { outSamples.emplace_back(b + batchOffsets[index]); } } } return {outSamples, outBatchSizes}; } std::vector<af::array> makeBatchFromRange( std::shared_ptr<const Dataset> dataset, std::vector<Dataset::BatchFunction> batchFns, int64_t start, int64_t end) { std::vector<std::vector<af::array>> buffer; for (int64_t batchidx = start; batchidx < end; ++batchidx) { auto fds = dataset->get(batchidx); if (buffer.size() < fds.size()) { buffer.resize(fds.size()); } for (int64_t i = 0; i < fds.size(); ++i) { buffer[i].emplace_back(fds[i]); } } std::vector<af::array> result(buffer.size()); for (int64_t i = 0; i < buffer.size(); ++i) { result[i] = makeBatch(buffer[i], (i < batchFns.size()) ? batchFns[i] : nullptr); } return result; } af::array makeBatch( const std::vector<af::array>& data, const Dataset::BatchFunction& batchFn) { if (batchFn) { return batchFn(data); } // Using default batching function if (data.empty()) { return af::array(); } auto dims = data[0].dims(); for (const auto& d : data) { if (d.dims() != dims) { throw std::invalid_argument("dimension mismatch while batching dataset"); } } int ndims = (data[0].elements() > 1) ? dims.ndims() : 0; if (ndims >= 4) { throw std::invalid_argument("# of dims must be < 4 for batching"); } dims[ndims] = data.size(); auto batcharr = af::array(dims, data[0].type()); for (size_t i = 0; i < data.size(); ++i) { std::array<af::seq, 4> sel{af::span, af::span, af::span, af::span}; sel[ndims] = af::seq(i, i); batcharr(sel[0], sel[1], sel[2], sel[3]) = data[i]; } return batcharr; } } // namespace fl
32.751381
99
0.652834
[ "vector" ]
088772bcba7c70ed242ff1f18513f38fee48807a
50,752
cc
C++
src/nnet3/nnet-example-utils.cc
zhuhuifeng/kaldi-zhf
8986d408fc51d0d804a064d3d0d450624f6a583c
[ "Apache-2.0" ]
5
2017-08-02T17:19:16.000Z
2019-05-13T05:03:24.000Z
src/nnet3/nnet-example-utils.cc
aashishyadavally/Working-with-Kaldi
38530efb23fc0f57a1d139d27b797be93ecb41b2
[ "Apache-2.0" ]
2
2015-11-11T14:51:47.000Z
2018-02-07T21:27:36.000Z
src/nnet3/nnet-example-utils.cc
aashishyadavally/Working-with-Kaldi
38530efb23fc0f57a1d139d27b797be93ecb41b2
[ "Apache-2.0" ]
2
2020-06-24T08:11:31.000Z
2021-11-30T13:10:11.000Z
// nnet3/nnet-example-utils.cc // Copyright 2012-2015 Johns Hopkins University (author: Daniel Povey) // 2014 Vimal Manohar // See ../../COPYING for clarification regarding multiple authors // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "nnet3/nnet-example-utils.h" #include "lat/lattice-functions.h" #include "hmm/posterior.h" #include "util/text-utils.h" #include <numeric> #include <iomanip> namespace kaldi { namespace nnet3 { // get a sorted list of all NnetIo names in all examples in the list (will // normally be just the strings "input" and "output", but maybe also "ivector"). static void GetIoNames(const std::vector<NnetExample> &src, std::vector<std::string> *names_vec) { std::set<std::string> names; std::vector<NnetExample>::const_iterator iter = src.begin(), end = src.end(); for (; iter != end; ++iter) { std::vector<NnetIo>::const_iterator iter2 = iter->io.begin(), end2 = iter->io.end(); for (; iter2 != end2; ++iter2) names.insert(iter2->name); } CopySetToVector(names, names_vec); } // Get feature "sizes" for each NnetIo name, which are the total number of // Indexes for that NnetIo (needed to correctly size the output matrix). Also // make sure the dimensions are consistent for each name. static void GetIoSizes(const std::vector<NnetExample> &src, const std::vector<std::string> &names, std::vector<int32> *sizes) { std::vector<int32> dims(names.size(), -1); // just for consistency checking. sizes->clear(); sizes->resize(names.size(), 0); std::vector<std::string>::const_iterator names_begin = names.begin(), names_end = names.end(); std::vector<NnetExample>::const_iterator iter = src.begin(), end = src.end(); for (; iter != end; ++iter) { std::vector<NnetIo>::const_iterator iter2 = iter->io.begin(), end2 = iter->io.end(); for (; iter2 != end2; ++iter2) { const NnetIo &io = *iter2; std::vector<std::string>::const_iterator names_iter = std::lower_bound(names_begin, names_end, io.name); KALDI_ASSERT(*names_iter == io.name); int32 i = names_iter - names_begin; int32 this_dim = io.features.NumCols(); if (dims[i] == -1) dims[i] = this_dim; else if(dims[i] != this_dim) { KALDI_ERR << "Merging examples with inconsistent feature dims: " << dims[i] << " vs. " << this_dim << " for '" << io.name << "'."; } KALDI_ASSERT(io.features.NumRows() == io.indexes.size()); int32 this_size = io.indexes.size(); (*sizes)[i] += this_size; } } } // Do the final merging of NnetIo, once we have obtained the names, dims and // sizes for each feature/supervision type. static void MergeIo(const std::vector<NnetExample> &src, const std::vector<std::string> &names, const std::vector<int32> &sizes, bool compress, NnetExample *merged_eg) { int32 num_feats = names.size(); std::vector<int32> cur_size(num_feats, 0); std::vector<std::vector<GeneralMatrix const*> > output_lists(num_feats); merged_eg->io.clear(); merged_eg->io.resize(num_feats); for (int32 f = 0; f < num_feats; f++) { NnetIo &io = merged_eg->io[f]; int32 size = sizes[f]; KALDI_ASSERT(size > 0); io.name = names[f]; io.indexes.resize(size); } std::vector<std::string>::const_iterator names_begin = names.begin(), names_end = names.end(); std::vector<NnetExample>::const_iterator iter = src.begin(), end = src.end(); for (int32 n = 0; iter != end; ++iter,++n) { std::vector<NnetIo>::const_iterator iter2 = iter->io.begin(), end2 = iter->io.end(); for (; iter2 != end2; ++iter2) { const NnetIo &io = *iter2; std::vector<std::string>::const_iterator names_iter = std::lower_bound(names_begin, names_end, io.name); KALDI_ASSERT(*names_iter == io.name); int32 f = names_iter - names_begin; int32 this_size = io.indexes.size(), &this_offset = cur_size[f]; KALDI_ASSERT(this_size + this_offset <= sizes[f]); output_lists[f].push_back(&(io.features)); NnetIo &output_io = merged_eg->io[f]; std::copy(io.indexes.begin(), io.indexes.end(), output_io.indexes.begin() + this_offset); std::vector<Index>::iterator output_iter = output_io.indexes.begin(); // Set the n index to be different for each of the original examples. for (int32 i = this_offset; i < this_offset + this_size; i++) { // we could easily support merging already-merged egs, but I don't see a // need for it right now. KALDI_ASSERT(output_iter[i].n == 0 && "Merging already-merged egs? Not currentlysupported."); output_iter[i].n = n; } this_offset += this_size; // note: this_offset is a reference. } } KALDI_ASSERT(cur_size == sizes); for (int32 f = 0; f < num_feats; f++) { AppendGeneralMatrixRows(output_lists[f], &(merged_eg->io[f].features)); if (compress) { // the following won't do anything if the features were sparse. merged_eg->io[f].features.Compress(); } } } void MergeExamples(const std::vector<NnetExample> &src, bool compress, NnetExample *merged_eg) { KALDI_ASSERT(!src.empty()); std::vector<std::string> io_names; GetIoNames(src, &io_names); // the sizes are the total number of Indexes we have across all examples. std::vector<int32> io_sizes; GetIoSizes(src, io_names, &io_sizes); MergeIo(src, io_names, io_sizes, compress, merged_eg); } void ShiftExampleTimes(int32 t_offset, const std::vector<std::string> &exclude_names, NnetExample *eg) { if (t_offset == 0) return; std::vector<NnetIo>::iterator iter = eg->io.begin(), end = eg->io.end(); for (; iter != end; iter++) { bool name_is_excluded = false; std::vector<std::string>::const_iterator exclude_iter = exclude_names.begin(), exclude_end = exclude_names.end(); for (; exclude_iter != exclude_end; ++exclude_iter) { if (iter->name == *exclude_iter) { name_is_excluded = true; break; } } if (!name_is_excluded) { // name is not something like "ivector" that we exclude from shifting. std::vector<Index>::iterator index_iter = iter->indexes.begin(), index_end = iter->indexes.end(); for (; index_iter != index_end; ++index_iter) index_iter->t += t_offset; } } } void GetComputationRequest(const Nnet &nnet, const NnetExample &eg, bool need_model_derivative, bool store_component_stats, ComputationRequest *request) { request->inputs.clear(); request->inputs.reserve(eg.io.size()); request->outputs.clear(); request->outputs.reserve(eg.io.size()); request->need_model_derivative = need_model_derivative; request->store_component_stats = store_component_stats; for (size_t i = 0; i < eg.io.size(); i++) { const NnetIo &io = eg.io[i]; const std::string &name = io.name; int32 node_index = nnet.GetNodeIndex(name); if (node_index == -1 && !nnet.IsInputNode(node_index) && !nnet.IsOutputNode(node_index)) KALDI_ERR << "Nnet example has input or output named '" << name << "', but no such input or output node is in the network."; std::vector<IoSpecification> &dest = nnet.IsInputNode(node_index) ? request->inputs : request->outputs; dest.resize(dest.size() + 1); IoSpecification &io_spec = dest.back(); io_spec.name = name; io_spec.indexes = io.indexes; io_spec.has_deriv = nnet.IsOutputNode(node_index) && need_model_derivative; } // check to see if something went wrong. if (request->inputs.empty()) KALDI_ERR << "No inputs in computation request."; if (request->outputs.empty()) KALDI_ERR << "No outputs in computation request."; } void WriteVectorAsChar(std::ostream &os, bool binary, const VectorBase<BaseFloat> &vec) { if (binary) { int32 dim = vec.Dim(); std::vector<unsigned char> char_vec(dim); const BaseFloat *data = vec.Data(); for (int32 i = 0; i < dim; i++) { BaseFloat value = data[i]; KALDI_ASSERT(value >= 0.0 && value <= 1.0); // below, the adding 0.5 is done so that we round to the closest integer // rather than rounding down (since static_cast will round down). char_vec[i] = static_cast<unsigned char>(255.0 * value + 0.5); } WriteIntegerVector(os, binary, char_vec); } else { // the regular floating-point format will be more readable for text mode. vec.Write(os, binary); } } void ReadVectorAsChar(std::istream &is, bool binary, Vector<BaseFloat> *vec) { if (binary) { BaseFloat scale = 1.0 / 255.0; std::vector<unsigned char> char_vec; ReadIntegerVector(is, binary, &char_vec); int32 dim = char_vec.size(); vec->Resize(dim, kUndefined); BaseFloat *data = vec->Data(); for (int32 i = 0; i < dim; i++) data[i] = scale * char_vec[i]; } else { vec->Read(is, binary); } } void RoundUpNumFrames(int32 frame_subsampling_factor, int32 *num_frames, int32 *num_frames_overlap) { if (*num_frames % frame_subsampling_factor != 0) { int32 new_num_frames = frame_subsampling_factor * (*num_frames / frame_subsampling_factor + 1); KALDI_LOG << "Rounding up --num-frames=" << (*num_frames) << " to a multiple of --frame-subsampling-factor=" << frame_subsampling_factor << ", now --num-frames=" << new_num_frames; *num_frames = new_num_frames; } if (*num_frames_overlap % frame_subsampling_factor != 0) { int32 new_num_frames_overlap = frame_subsampling_factor * (*num_frames_overlap / frame_subsampling_factor + 1); KALDI_LOG << "Rounding up --num-frames-overlap=" << (*num_frames_overlap) << " to a multiple of --frame-subsampling-factor=" << frame_subsampling_factor << ", now --num-frames-overlap=" << new_num_frames_overlap; *num_frames_overlap = new_num_frames_overlap; } if (*num_frames_overlap < 0 || *num_frames_overlap >= *num_frames) { KALDI_ERR << "--num-frames-overlap=" << (*num_frames_overlap) << " < " << "--num-frames=" << (*num_frames); } } void ExampleGenerationConfig::ComputeDerived() { if (!SplitStringToIntegers(num_frames_str, ",", false, &num_frames) || num_frames.empty()) { KALDI_ERR << "Invalid option (expected comma-separated list of integers): " << "--num-frames=" << num_frames_str; } int32 m = frame_subsampling_factor; if (m < 1) { KALDI_ERR << "Invalid value --frame-subsampling-factor=" << m; } bool changed = false; for (size_t i = 0; i < num_frames.size(); i++) { int32 value = num_frames[i]; if (value <= 0) { KALDI_ERR << "Invalid option --num-frames=" << num_frames_str; } if (value % m != 0) { value = m * ((value / m) + 1); changed = true; } num_frames[i] = value; } if (changed) { std::ostringstream rounded_num_frames_str; for (size_t i = 0; i < num_frames.size(); i++) { if (i > 0) rounded_num_frames_str << ','; rounded_num_frames_str << num_frames[i]; } KALDI_LOG << "Rounding up --num-frames=" << num_frames_str << " to multiples of --frame-subsampling-factor=" << m << ", to: " << rounded_num_frames_str.str(); } } UtteranceSplitter::UtteranceSplitter(const ExampleGenerationConfig &config): config_(config), total_num_utterances_(0), total_input_frames_(0), total_frames_overlap_(0), total_num_chunks_(0), total_frames_in_chunks_(0) { if (config.num_frames.empty()) { KALDI_ERR << "You need to call ComputeDerived() on the " "ExampleGenerationConfig()."; } InitSplitForLength(); } UtteranceSplitter::~UtteranceSplitter() { KALDI_LOG << "Split " << total_num_utterances_ << " utts, with " << "total length " << total_input_frames_ << " frames (" << (total_input_frames_ / 360000.0) << " hours assuming " << "100 frames per second)"; float average_chunk_length = total_frames_in_chunks_ * 1.0 / total_num_chunks_, overlap_percent = total_frames_overlap_ * 100.0 / total_input_frames_, output_percent = total_frames_in_chunks_ * 100.0 / total_input_frames_, output_percent_no_overlap = output_percent - overlap_percent; KALDI_LOG << "Average chunk length was " << average_chunk_length << " frames; overlap between adjacent chunks was " << overlap_percent << "% of input length; length of output was " << output_percent << "% of input length (minus overlap = " << output_percent_no_overlap << "%)."; if (chunk_size_to_count_.size() > 1) { std::ostringstream os; os << std::setprecision(4); for (std::map<int32, int32>::iterator iter = chunk_size_to_count_.begin(); iter != chunk_size_to_count_.end(); ++iter) { int32 chunk_size = iter->first, num_frames = chunk_size * iter->second; float percent_of_total = num_frames * 100.0 / total_frames_in_chunks_; if (iter != chunk_size_to_count_.begin()) os << ", "; os << chunk_size << " = " << percent_of_total << "%"; } KALDI_LOG << "Output frames are distributed among chunk-sizes as follows: " << os.str(); } } float UtteranceSplitter::DefaultDurationOfSplit( const std::vector<int32> &split) const { if (split.empty()) // not a valid split, but useful to handle this case. return 0.0; float principal_num_frames = config_.num_frames[0], num_frames_overlap = config_.num_frames_overlap; KALDI_ASSERT(num_frames_overlap < principal_num_frames && "--num-frames-overlap value is too high"); float overlap_proportion = num_frames_overlap / principal_num_frames; float ans = std::accumulate(split.begin(), split.end(), int32(0)); for (size_t i = 0; i + 1 < split.size(); i++) { float min_adjacent_chunk_length = std::min(split[i], split[i + 1]), overlap = overlap_proportion * min_adjacent_chunk_length; ans -= overlap; } KALDI_ASSERT(ans > 0.0); return ans; } /* This comment describes the idea behind what InitChunkSize() is supposed to do, and how it relates to the purpose of class UtteranceSplitter. Class UtteranceSplitter is supposed to tell us, for a given utterance length, what chunk sizes to use. The chunk sizes it may choose are: - zero or more chunks of the 'principal' size (the first-listed value in --num-frames option) - at most two chunks of 'alternative' num-frames (meaning, any but the first-listed choice in the --num-frames option). (note: an empty list of chunks is not allowed as a split). A split is a list of chunk-sizes in increasing order (we when we actually split the utterance into chunks, we may, at random, reverse the order. The choice of split to use for a given utterance-length is determined as follows. Firstly, for each split we compute a 'default duration' (see DefaultDurationOfSplit()... if --num-frames-overlap is zero, this is just the sum of the chunk sizes). We then use by a cost-function that depends on default-duration and the length of the utterance: the idea is that these two should be as close as possible, but penalizing the default-duration being larger than the utterance-length (which in the normal case of --num-frames-overlap=0 would lead to gaps between the segments), twice as much as the other sign of difference. Specifically: cost(default_duration, utt_length) = (default_duration > utt_length ? default_duration - utt_length : 2.0 * (utt_length - default_duration)) [but as a special case, set c to infinity if the largest chunk size in the split is longer than the utterance length; we couldn't, in that case, use this split for this utterance]. We want to make sure a good variety of combinations of chunk sizes are chosen in case there are ties from the cost function. For each utterance length we store the set of splits, whose costs are within 2 of the best cost available for that utterance length. When asked to find chunks for a particular utterance of that length, we will choose randomly from that pool of splits. */ void UtteranceSplitter::InitSplitForLength() { int32 max_utterance_length = MaxUtteranceLength(); // The 'splits' vector is a list of possible splits (a split being // a sorted vector of chunk-sizes). // The vector 'splits' is itself sorted. std::vector<std::vector<int32> > splits; InitSplits(&splits); // Define a split-index 0 <= s < splits.size() as index into the 'splits' // vector, and let a cost c >= 0 represent the mismatch between an // utterance length and the total length of the chunk sizes in a split: // c(default_duration, utt_length) = (default_duration > utt_length ? // default_duration - utt_length : // 2.0 * (utt_length - default_duration)) // [but as a special case, set c to infinity if the largest chunk size in the // split is longer than the utterance length; we couldn't, in that case, use // this split for this utterance]. // 'costs_for_length[u][s]', indexed by utterance-length u and then split, // contains the cost for utterance-length u and split s. std::vector<std::vector<float> > costs_for_length( max_utterance_length + 1); int32 num_splits = splits.size(); for (int32 u = 0; u <= max_utterance_length; u++) costs_for_length[u].reserve(num_splits); for (int32 s = 0; s < num_splits; s++) { const std::vector<int32> &split = splits[s]; float default_duration = DefaultDurationOfSplit(split); int32 max_chunk_size = *std::max_element(split.begin(), split.end()); for (int32 u = 0; u <= max_utterance_length; u++) { // c is the cost for this utterance length and this split. We penalize // gaps twice as strongly as overlaps, based on the intuition that // completely throwing out frames of data is worse than counting them // twice. float c = (default_duration > float(u) ? default_duration - float(u) : 2.0 * (u - default_duration)); if (u < max_chunk_size) // can't fit the largest of the chunks in this // utterance c = std::numeric_limits<float>::max(); KALDI_ASSERT(c >= 0); costs_for_length[u].push_back(c); } } splits_for_length_.resize(max_utterance_length + 1); for (int32 u = 0; u <= max_utterance_length; u++) { const std::vector<float> &costs = costs_for_length[u]; float min_cost = *std::min_element(costs.begin(), costs.end()); if (min_cost == std::numeric_limits<float>::max()) { // All costs were infinity, becaues this utterance-length u is shorter // than the smallest chunk-size. Leave splits_for_length_[u] as empty // for this utterance-length, meaning we will not be able to choose any // split, and such utterances will be discarded. continue; } float cost_threshold = 1.9999; // We will choose pseudo-randomly from splits // that are within this distance from the // best cost. Make the threshold just // slightly less than 2... this will // hopefully make the behavior more // deterministic for ties. std::vector<int32> possible_splits; std::vector<float>::const_iterator iter = costs.begin(), end = costs.end(); int32 s = 0; for (; iter != end; ++iter,++s) if (*iter < min_cost + cost_threshold) splits_for_length_[u].push_back(splits[s]); } if (GetVerboseLevel() >= 3) { std::ostringstream os; for (int32 u = 0; u <= max_utterance_length; u++) { if (!splits_for_length_[u].empty()) { os << u << "=("; std::vector<std::vector<int32 > >::const_iterator iter1 = splits_for_length_[u].begin(), end1 = splits_for_length_[u].end(); while (iter1 != end1) { std::vector<int32>::const_iterator iter2 = iter1->begin(), end2 = iter1->end(); while (iter2 != end2) { os << *iter2; ++iter2; if (iter2 != end2) os << ","; } ++iter1; if (iter1 != end1) os << "/"; } os << ")"; if (u < max_utterance_length) os << ", "; } } KALDI_VLOG(3) << "Utterance-length-to-splits map is: " << os.str(); } } bool UtteranceSplitter::LengthsMatch(const std::string &utt, int32 utterance_length, int32 supervision_length) const { int32 sf = config_.frame_subsampling_factor, expected_supervision_length = (utterance_length + sf - 1) / sf; if (supervision_length == expected_supervision_length) { return true; } else { if (sf == 1) { KALDI_WARN << "Supervision does not have expected length for utterance " << utt << ": expected length = " << utterance_length << ", got " << supervision_length; } else { KALDI_WARN << "Supervision does not have expected length for utterance " << utt << ": expected length = (" << utterance_length << " + " << sf << " - 1) / " << sf << " = " << expected_supervision_length << ", got: " << supervision_length << " (note: --frame-subsampling-factor=" << sf << ")"; } return false; } } void UtteranceSplitter::GetChunkSizesForUtterance( int32 utterance_length, std::vector<int32> *chunk_sizes) const { KALDI_ASSERT(!splits_for_length_.empty()); // 'primary_length' is the first-specified num-frames. // It's the only chunk that may be repeated an arbitrary number // of times. int32 primary_length = config_.num_frames[0], num_frames_overlap = config_.num_frames_overlap, max_tabulated_length = splits_for_length_.size() - 1, num_primary_length_repeats = 0; KALDI_ASSERT(primary_length - num_frames_overlap > 0); KALDI_ASSERT(utterance_length >= 0); while (utterance_length > max_tabulated_length) { utterance_length -= (primary_length - num_frames_overlap); num_primary_length_repeats++; } KALDI_ASSERT(utterance_length >= 0); const std::vector<std::vector<int32> > &possible_splits = splits_for_length_[utterance_length]; if (possible_splits.empty()) { chunk_sizes->clear(); return; } int32 num_possible_splits = possible_splits.size(), randomly_chosen_split = RandInt(0, num_possible_splits - 1); *chunk_sizes = possible_splits[randomly_chosen_split]; for (int32 i = 0; i < num_primary_length_repeats; i++) chunk_sizes->push_back(primary_length); std::sort(chunk_sizes->begin(), chunk_sizes->end()); if (RandInt(0, 1) == 0) { std::reverse(chunk_sizes->begin(), chunk_sizes->end()); } } int32 UtteranceSplitter::MaxUtteranceLength() const { int32 num_lengths = config_.num_frames.size(); KALDI_ASSERT(num_lengths > 0); // 'primary_length' is the first-specified num-frames. // It's the only chunk that may be repeated an arbitrary number // of times. int32 primary_length = config_.num_frames[0], max_length = primary_length; for (int32 i = 0; i < num_lengths; i++) { KALDI_ASSERT(config_.num_frames[i] > 0); max_length = std::max(config_.num_frames[i], max_length); } return 2 * max_length + primary_length; } void UtteranceSplitter::InitSplits(std::vector<std::vector<int32> > *splits) const { // we consider splits whose default duration (as returned by // DefaultDurationOfSplit()) is up to MaxUtteranceLength() + primary_length. // We can be confident without doing a lot of math, that splits above this // length will never be chosen for any utterance-length up to // MaxUtteranceLength() (which is the maximum we use). int32 primary_length = config_.num_frames[0], default_duration_ceiling = MaxUtteranceLength() + primary_length; typedef unordered_set<std::vector<int32>, VectorHasher<int32> > SetType; SetType splits_set; int32 num_lengths = config_.num_frames.size(); // The splits we are allow are: zero to two 'alternate' lengths, plus // an arbitrary number of repeats of the 'primary' length. The repeats // of the 'primary' length are handled by the inner loop over n. // The zero to two 'alternate' lengths are handled by the loops over // i and j. i == 0 and j == 0 are special cases; they mean, no // alternate is chosen. for (int32 i = 0; i < num_lengths; i++) { for (int32 j = 0; j < num_lengths; j++) { std::vector<int32> vec; if (i > 0) vec.push_back(config_.num_frames[i]); if (j > 0) vec.push_back(config_.num_frames[j]); int32 n = 0; while (DefaultDurationOfSplit(vec) <= default_duration_ceiling) { if (!vec.empty()) // Don't allow the empty vector as a split. splits_set.insert(vec); n++; vec.push_back(primary_length); std::sort(vec.begin(), vec.end()); } } } for (SetType::const_iterator iter = splits_set.begin(); iter != splits_set.end(); ++iter) splits->push_back(*iter); std::sort(splits->begin(), splits->end()); // make the order deterministic, // for consistency of output // between runs and C libraries. } // static void UtteranceSplitter::DistributeRandomlyUniform(int32 n, std::vector<int32> *vec) { KALDI_ASSERT(!vec->empty()); int32 size = vec->size(); if (n < 0) { DistributeRandomlyUniform(-n, vec); for (int32 i = 0; i < size; i++) (*vec)[i] *= -1; return; } // from this point we know n >= 0. int32 common_part = n / size, remainder = n % size, i; for (i = 0; i < remainder; i++) { (*vec)[i] = common_part + 1; } for (; i < size; i++) { (*vec)[i] = common_part; } std::random_shuffle(vec->begin(), vec->end()); KALDI_ASSERT(std::accumulate(vec->begin(), vec->end(), int32(0)) == n); } // static void UtteranceSplitter::DistributeRandomly(int32 n, const std::vector<int32> &magnitudes, std::vector<int32> *vec) { KALDI_ASSERT(!vec->empty() && vec->size() == magnitudes.size()); int32 size = vec->size(); if (n < 0) { DistributeRandomly(-n, magnitudes, vec); for (int32 i = 0; i < size; i++) (*vec)[i] *= -1; return; } float total_magnitude = std::accumulate(magnitudes.begin(), magnitudes.end(), int32(0)); KALDI_ASSERT(total_magnitude > 0); // note: 'partial_counts' contains the negative of the partial counts, so // when we sort the larger partial counts come first. std::vector<std::pair<float, int32> > partial_counts; int32 total_count = 0; for (int32 i = 0; i < size; i++) { float this_count = n * float(magnitudes[i]) / total_magnitude; // note: cast of float to int32 rounds towards zero (down, in this // case, since this_count >= 0). int32 this_whole_count = static_cast<int32>(this_count), this_partial_count = this_count - this_whole_count; (*vec)[i] = this_whole_count; total_count += this_whole_count; partial_counts.push_back(std::pair<float, int32>(-this_partial_count, i)); } KALDI_ASSERT(total_count <= n && total_count + size >= n); std::sort(partial_counts.begin(), partial_counts.end()); int32 i = 0; // Increment by one the elements of the vector that has the largest partial // count, then the next largest partial count, and so on... until we reach the // desired total-count 'n'. for(; total_count < n; i++,total_count++) { (*vec)[partial_counts[i].second]++; } KALDI_ASSERT(std::accumulate(vec->begin(), vec->end(), int32(0)) == n); } void UtteranceSplitter::GetGapSizes(int32 utterance_length, bool enforce_subsampling_factor, const std::vector<int32> &chunk_sizes, std::vector<int32> *gap_sizes) const { if (chunk_sizes.empty()) { gap_sizes->clear(); return; } if (enforce_subsampling_factor && config_.frame_subsampling_factor > 1) { int32 sf = config_.frame_subsampling_factor, size = chunk_sizes.size(); int32 utterance_length_reduced = (utterance_length + (sf - 1)) / sf; std::vector<int32> chunk_sizes_reduced(chunk_sizes); for (int32 i = 0; i < size; i++) { KALDI_ASSERT(chunk_sizes[i] % config_.frame_subsampling_factor == 0); chunk_sizes_reduced[i] /= config_.frame_subsampling_factor; } GetGapSizes(utterance_length_reduced, false, chunk_sizes_reduced, gap_sizes); KALDI_ASSERT(gap_sizes->size() == static_cast<size_t>(size)); for (int32 i = 0; i < size; i++) (*gap_sizes)[i] *= config_.frame_subsampling_factor; return; } int32 num_chunks = chunk_sizes.size(), total_of_chunk_sizes = std::accumulate(chunk_sizes.begin(), chunk_sizes.end(), int32(0)), total_gap = utterance_length - total_of_chunk_sizes; gap_sizes->resize(num_chunks); if (total_gap < 0) { // there is an overlap. Overlaps can only go between chunks, not at the // beginning or end of the utterance. Also, we try to make the length of // overlap proportional to the size of the smaller of the two chunks // that the overlap is between. if (num_chunks == 1) { // there needs to be an overlap, but there is only one chunk... this means // the chunk-size exceeds the utterance length, which is not allowed. KALDI_ERR << "Chunk size is " << chunk_sizes[0] << " but utterance length is only " << utterance_length; } // note the elements of 'overlaps' will be <= 0. std::vector<int32> magnitudes(num_chunks - 1), overlaps(num_chunks - 1); // the 'magnitudes' vector will contain the minimum of the lengths of the // two adjacent chunks between which are are going to consider having an // overlap. These will be used to assign the overlap proportional to that // size. for (int32 i = 0; i + 1 < num_chunks; i++) { magnitudes[i] = std::min<int32>(chunk_sizes[i], chunk_sizes[i + 1]); } DistributeRandomly(total_gap, magnitudes, &overlaps); for (int32 i = 0; i + 1 < num_chunks; i++) { // If the following condition does not hold, it's possible we // could get chunk start-times less than zero. I don't believe // it's possible for this condition to fail, but we're checking // for it at this level to make debugging easier, just in case. KALDI_ASSERT(overlaps[i] <= magnitudes[i]); } (*gap_sizes)[0] = 0; // no gap before 1st chunk. for (int32 i = 1; i < num_chunks; i++) (*gap_sizes)[i] = overlaps[i-1]; } else { // There may be a gap. Gaps can go at the start or end of the utterance, or // between segments. We try to distribute the gaps evenly. std::vector<int32> gaps(num_chunks + 1); DistributeRandomlyUniform(total_gap, &gaps); // the last element of 'gaps', the one at the end of the utterance, is // implicit and doesn't have to be written to the output. for (int32 i = 0; i < num_chunks; i++) (*gap_sizes)[i] = gaps[i]; } } void UtteranceSplitter::GetChunksForUtterance( int32 utterance_length, std::vector<ChunkTimeInfo> *chunk_info) { std::vector<int32> chunk_sizes; GetChunkSizesForUtterance(utterance_length, &chunk_sizes); std::vector<int32> gaps(chunk_sizes.size()); GetGapSizes(utterance_length, true, chunk_sizes, &gaps); int32 num_chunks = chunk_sizes.size(); chunk_info->resize(num_chunks); int32 t = 0; for (int32 i = 0; i < num_chunks; i++) { t += gaps[i]; ChunkTimeInfo &info = (*chunk_info)[i]; info.first_frame = t; info.num_frames = chunk_sizes[i]; info.left_context = (i == 0 && config_.left_context_initial >= 0 ? config_.left_context_initial : config_.left_context); info.right_context = (i == 0 && config_.right_context_final >= 0 ? config_.right_context_final : config_.right_context); t += chunk_sizes[i]; } SetOutputWeights(utterance_length, chunk_info); AccStatsForUtterance(utterance_length, *chunk_info); // check that the end of the last chunk doesn't go more than // 'config_.frame_subsampling_factor - 1' frames past the end // of the utterance. That amount, we treat as rounding error. KALDI_ASSERT(t - utterance_length < config_.frame_subsampling_factor); } void UtteranceSplitter::AccStatsForUtterance( int32 utterance_length, const std::vector<ChunkTimeInfo> &chunk_info) { total_num_utterances_ += 1; total_input_frames_ += utterance_length; for (size_t c = 0; c < chunk_info.size(); c++) { int32 chunk_size = chunk_info[c].num_frames; if (c > 0) { int32 last_chunk_end = chunk_info[c-1].first_frame + chunk_info[c-1].num_frames; if (last_chunk_end > chunk_info[c].first_frame) total_frames_overlap_ += last_chunk_end - chunk_info[c].first_frame; } std::map<int32, int32>::iterator iter = chunk_size_to_count_.find( chunk_size); if (iter == chunk_size_to_count_.end()) chunk_size_to_count_[chunk_size] = 1; else iter->second++; total_num_chunks_ += 1; total_frames_in_chunks_ += chunk_size; } } void UtteranceSplitter::SetOutputWeights( int32 utterance_length, std::vector<ChunkTimeInfo> *chunk_info) const { int32 sf = config_.frame_subsampling_factor; int32 num_output_frames = (utterance_length + sf - 1) / sf; // num_output_frames is the number of frames of supervision. 'count[t]' will // be the number of chunks that this output-frame t appears in. Note: the // 'first_frame' and 'num_frames' members of ChunkTimeInfo will always be // multiples of frame_subsampling_factor. std::vector<int32> count(num_output_frames, 0); int32 num_chunks = chunk_info->size(); for (int32 i = 0; i < num_chunks; i++) { ChunkTimeInfo &chunk = (*chunk_info)[i]; for (int32 t = chunk.first_frame / sf; t < (chunk.first_frame + chunk.num_frames) / sf; t++) count[t]++; } for (int32 i = 0; i < num_chunks; i++) { ChunkTimeInfo &chunk = (*chunk_info)[i]; chunk.output_weights.resize(chunk.num_frames / sf); int32 t_start = chunk.first_frame / sf; for (int32 t = t_start; t < (chunk.first_frame + chunk.num_frames) / sf; t++) chunk.output_weights[t - t_start] = 1.0 / count[t]; } } int32 ExampleMergingConfig::IntSet::LargestValueInRange(int32 max_value) const { KALDI_ASSERT(!ranges.empty()); int32 ans = 0, num_ranges = ranges.size(); for (int32 i = 0; i < num_ranges; i++) { int32 possible_ans = 0; if (max_value >= ranges[i].first) { if (max_value >= ranges[i].second) possible_ans = ranges[i].second; else possible_ans = max_value; } if (possible_ans > ans) ans = possible_ans; } return ans; } // static bool ExampleMergingConfig::ParseIntSet(const std::string &str, ExampleMergingConfig::IntSet *int_set) { std::vector<std::string> split_str; SplitStringToVector(str, ",", false, &split_str); if (split_str.empty()) return false; int_set->largest_size = 0; int_set->ranges.resize(split_str.size()); for (size_t i = 0; i < split_str.size(); i++) { std::vector<int32> split_range; SplitStringToIntegers(split_str[i], ":", false, &split_range); if (split_range.size() < 1 || split_range.size() > 2 || split_range[0] > split_range.back() || split_range[0] <= 0) return false; int_set->ranges[i].first = split_range[0]; int_set->ranges[i].second = split_range.back(); int_set->largest_size = std::max<int32>(int_set->largest_size, split_range.back()); } return true; } void ExampleMergingConfig::ComputeDerived() { if (measure_output_frames != "deprecated") { KALDI_WARN << "The --measure-output-frames option is deprecated " "and will be ignored."; } if (discard_partial_minibatches != "deprecated") { KALDI_WARN << "The --discard-partial-minibatches option is deprecated " "and will be ignored."; } std::vector<std::string> minibatch_size_split; SplitStringToVector(minibatch_size, "/", false, &minibatch_size_split); if (minibatch_size_split.empty()) { KALDI_ERR << "Invalid option --minibatch-size=" << minibatch_size; } rules.resize(minibatch_size_split.size()); for (size_t i = 0; i < minibatch_size_split.size(); i++) { int32 &eg_size = rules[i].first; IntSet &int_set = rules[i].second; // 'this_rule' will be either something like "256" or like "64-128,256" // (but these two only if minibatch_size_split.size() == 1, or something with // an example-size specified, like "256=64-128,256" std::string &this_rule = minibatch_size_split[i]; if (this_rule.find('=') != std::string::npos) { std::vector<std::string> rule_split; // split on '=' SplitStringToVector(this_rule, "=", false, &rule_split); if (rule_split.size() != 2) { KALDI_ERR << "Could not parse option --minibatch-size=" << minibatch_size; } if (!ConvertStringToInteger(rule_split[0], &eg_size) || !ParseIntSet(rule_split[1], &int_set)) KALDI_ERR << "Could not parse option --minibatch-size=" << minibatch_size; } else { if (minibatch_size_split.size() != 1) { KALDI_ERR << "Could not parse option --minibatch-size=" << minibatch_size << " (all rules must have " << "eg-size specified if >1 rule)"; } if (!ParseIntSet(this_rule, &int_set)) KALDI_ERR << "Could not parse option --minibatch-size=" << minibatch_size; } } { // check that no size is repeated. std::vector<int32> all_sizes(minibatch_size_split.size()); for (size_t i = 0; i < minibatch_size_split.size(); i++) all_sizes[i] = rules[i].first; std::sort(all_sizes.begin(), all_sizes.end()); if (!IsSortedAndUniq(all_sizes)) { KALDI_ERR << "Invalid --minibatch-size=" << minibatch_size << " (repeated example-sizes)"; } } } int32 ExampleMergingConfig::MinibatchSize(int32 size_of_eg, int32 num_available_egs, bool input_ended) const { KALDI_ASSERT(num_available_egs > 0 && size_of_eg > 0); int32 num_rules = rules.size(); if (num_rules == 0) KALDI_ERR << "You need to call ComputeDerived() before calling " "MinibatchSize()."; int32 min_distance = std::numeric_limits<int32>::max(), closest_rule_index = 0; for (int32 i = 0; i < num_rules; i++) { int32 distance = std::abs(size_of_eg - rules[i].first); if (distance < min_distance) { min_distance = distance; closest_rule_index = i; } } if (!input_ended) { // until the input ends, we can only use the largest available // minibatch-size (otherwise, we could expect more later). int32 largest_size = rules[closest_rule_index].second.largest_size; if (largest_size <= num_available_egs) return largest_size; else return 0; } else { int32 s = rules[closest_rule_index].second.LargestValueInRange( num_available_egs); KALDI_ASSERT(s <= num_available_egs); return s; } } void ExampleMergingStats::WroteExample(int32 example_size, size_t structure_hash, int32 minibatch_size) { std::pair<int32, size_t> p(example_size, structure_hash); unordered_map<int32, int32> &h = stats_[p].minibatch_to_num_written; unordered_map<int32, int32>::iterator iter = h.find(minibatch_size); if (iter == h.end()) h[minibatch_size] = 1; else iter->second += 1; } void ExampleMergingStats::DiscardedExamples(int32 example_size, size_t structure_hash, int32 num_discarded) { std::pair<int32, size_t> p(example_size, structure_hash); stats_[p].num_discarded += num_discarded; } void ExampleMergingStats::PrintStats() const { PrintSpecificStats(); PrintAggregateStats(); } void ExampleMergingStats::PrintAggregateStats() const { // First print some aggregate stats. int64 num_distinct_egs_types = 0, // number of distinct types of input egs // (differing in size or structure). total_discarded_egs = 0, // total number of discarded egs. total_discarded_egs_size = 0, // total number of discarded egs each multiplied by size // of that eg total_non_discarded_egs = 0, // total over all minibatches written, of // minibatch-size, equals number of input egs // that were not discarded. total_non_discarded_egs_size = 0, // total over all minibatches of size-of-eg // * minibatch-size. num_minibatches = 0, // total number of minibatches num_distinct_minibatch_types = 0; // total number of combination of // (type-of-eg, number of distinct // minibatch-sizes for that eg-type)- // reflects the number of time we have // to compile. StatsType::const_iterator eg_iter = stats_.begin(), eg_end = stats_.end(); for (; eg_iter != eg_end; ++eg_iter) { int32 eg_size = eg_iter->first.first; const StatsForExampleSize &stats = eg_iter->second; num_distinct_egs_types++; total_discarded_egs += stats.num_discarded; total_discarded_egs_size += stats.num_discarded * eg_size; unordered_map<int32, int32>::const_iterator mb_iter = stats.minibatch_to_num_written.begin(), mb_end = stats.minibatch_to_num_written.end(); for (; mb_iter != mb_end; ++mb_iter) { int32 mb_size = mb_iter->first, num_written = mb_iter->second; num_distinct_minibatch_types++; num_minibatches += num_written; total_non_discarded_egs += num_written * mb_size; total_non_discarded_egs_size += num_written * mb_size * eg_size; } } // the averages are written as integers- we don't really need more precision // than that. int64 total_input_egs = total_discarded_egs + total_non_discarded_egs, total_input_egs_size = total_discarded_egs_size + total_non_discarded_egs_size; float avg_input_egs_size = total_input_egs_size * 1.0 / total_input_egs; float percent_discarded = total_discarded_egs * 100.0 / total_input_egs; // note: by minibatch size we mean the number of egs per minibatch, it // does not take note of the size of the input egs. float avg_minibatch_size = total_non_discarded_egs * 1.0 / num_minibatches; std::ostringstream os; os << std::setprecision(4); os << "Processed " << total_input_egs << " egs of avg. size " << avg_input_egs_size << " into " << num_minibatches << " minibatches, discarding " << percent_discarded << "% of egs. Avg minibatch size was " << avg_minibatch_size << ", #distinct types of egs/minibatches " << "was " << num_distinct_egs_types << "/" << num_distinct_minibatch_types; KALDI_LOG << os.str(); } void ExampleMergingStats::PrintSpecificStats() const { KALDI_LOG << "Merged specific eg types as follows [format: <eg-size1>=" "{<mb-size1>-><num-minibatches1>,<mbsize2>-><num-minibatches2>.../d=<num-discarded>}" ",<egs-size2>={...},... (note,egs-size == number of input " "frames including context)."; std::ostringstream os; // copy from unordered map to map to get sorting, for consistent output. typedef std::map<std::pair<int32, size_t>, StatsForExampleSize> SortedMapType; SortedMapType stats; stats.insert(stats_.begin(), stats_.end()); SortedMapType::const_iterator eg_iter = stats.begin(), eg_end = stats.end(); for (; eg_iter != eg_end; ++eg_iter) { int32 eg_size = eg_iter->first.first; if (eg_iter != stats.begin()) os << ","; os << eg_size << "={"; const StatsForExampleSize &stats = eg_iter->second; unordered_map<int32, int32>::const_iterator mb_iter = stats.minibatch_to_num_written.begin(), mb_end = stats.minibatch_to_num_written.end(); for (; mb_iter != mb_end; ++mb_iter) { int32 mb_size = mb_iter->first, num_written = mb_iter->second; if (mb_iter != stats.minibatch_to_num_written.begin()) os << ","; os << mb_size << "->" << num_written; } os << ",d=" << stats.num_discarded << "}"; } KALDI_LOG << os.str(); } int32 GetNnetExampleSize(const NnetExample &a) { int32 ans = 0; for (size_t i = 0; i < a.io.size(); i++) { int32 s = a.io[i].indexes.size(); if (s > ans) ans = s; } return ans; } ExampleMerger::ExampleMerger(const ExampleMergingConfig &config, NnetExampleWriter *writer): finished_(false), num_egs_written_(0), config_(config), writer_(writer) { } void ExampleMerger::AcceptExample(NnetExample *eg) { KALDI_ASSERT(!finished_); // If an eg with the same structure as 'eg' is already a key in the // map, it won't be replaced, but if it's new it will be made // the key. Also we remove the key before making the vector empty. // This way we ensure that the eg in the key is always the first // element of the vector. std::vector<NnetExample*> &vec = eg_to_egs_[eg]; vec.push_back(eg); int32 eg_size = GetNnetExampleSize(*eg), num_available = vec.size(); bool input_ended = false; int32 minibatch_size = config_.MinibatchSize(eg_size, num_available, input_ended); if (minibatch_size != 0) { // we need to write out a merged eg. KALDI_ASSERT(minibatch_size == num_available); std::vector<NnetExample*> vec_copy(vec); eg_to_egs_.erase(eg); // MergeExamples() expects a vector of NnetExample, not of pointers, // so use swap to create that without doing any real work. std::vector<NnetExample> egs_to_merge(minibatch_size); for (int32 i = 0; i < minibatch_size; i++) { egs_to_merge[i].Swap(vec_copy[i]); delete vec_copy[i]; // we owned those pointers. } WriteMinibatch(egs_to_merge); } } void ExampleMerger::WriteMinibatch(const std::vector<NnetExample> &egs) { KALDI_ASSERT(!egs.empty()); int32 eg_size = GetNnetExampleSize(egs[0]); NnetExampleStructureHasher eg_hasher; size_t structure_hash = eg_hasher(egs[0]); int32 minibatch_size = egs.size(); stats_.WroteExample(eg_size, structure_hash, minibatch_size); NnetExample merged_eg; MergeExamples(egs, config_.compress, &merged_eg); std::ostringstream key; key << "merged-" << (num_egs_written_++) << "-" << minibatch_size; writer_->Write(key.str(), merged_eg); } void ExampleMerger::Finish() { if (finished_) return; // already finished. finished_ = true; // we'll convert the map eg_to_egs_ to a vector of vectors to avoid // iterator invalidation problems. std::vector<std::vector<NnetExample*> > all_egs; all_egs.reserve(eg_to_egs_.size()); MapType::iterator iter = eg_to_egs_.begin(), end = eg_to_egs_.end(); for (; iter != end; ++iter) all_egs.push_back(iter->second); eg_to_egs_.clear(); for (size_t i = 0; i < all_egs.size(); i++) { int32 minibatch_size; std::vector<NnetExample*> &vec = all_egs[i]; KALDI_ASSERT(!vec.empty()); int32 eg_size = GetNnetExampleSize(*(vec[0])); bool input_ended = true; while (!vec.empty() && (minibatch_size = config_.MinibatchSize(eg_size, vec.size(), input_ended)) != 0) { // MergeExamples() expects a vector of NnetExample, not of pointers, // so use swap to create that without doing any real work. std::vector<NnetExample> egs_to_merge(minibatch_size); for (int32 i = 0; i < minibatch_size; i++) { egs_to_merge[i].Swap(vec[i]); delete vec[i]; // we owned those pointers. } vec.erase(vec.begin(), vec.begin() + minibatch_size); WriteMinibatch(egs_to_merge); } if (!vec.empty()) { int32 eg_size = GetNnetExampleSize(*(vec[0])); NnetExampleStructureHasher eg_hasher; size_t structure_hash = eg_hasher(*(vec[0])); int32 num_discarded = vec.size(); stats_.DiscardedExamples(eg_size, structure_hash, num_discarded); for (int32 i = 0; i < num_discarded; i++) delete vec[i]; vec.clear(); } } stats_.PrintStats(); } } // namespace nnet3 } // namespace kaldi
40.375497
92
0.630655
[ "vector" ]
0887feaf6b53def0b905d79ec70ab745798a06fd
20,666
hpp
C++
applications/SolidMechanicsApplication/custom_solvers/time_integration_methods/bdf_method.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/SolidMechanicsApplication/custom_solvers/time_integration_methods/bdf_method.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/SolidMechanicsApplication/custom_solvers/time_integration_methods/bdf_method.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// // Project Name: KratosSolidMechanicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: April 2018 $ // Revision: $Revision: 0.0 $ // // #if !defined(KRATOS_BDF_METHOD_H_INCLUDED) #define KRATOS_BDF_METHOD_H_INCLUDED // System includes // External includes // Project includes #include "custom_solvers/time_integration_methods/time_integration_method.hpp" namespace Kratos { ///@addtogroup SolidMechanicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. * This class performs predict and update of dofs variables, their time derivatives and time integrals */ template<class TVariableType, class TValueType> class BdfMethod : public TimeIntegrationMethod<TVariableType,TValueType> { public: ///@name Type Definitions ///@{ /// BaseType typedef TimeIntegrationMethod<TVariableType,TValueType> BaseType; /// BasePointerType typedef typename BaseType::Pointer BasePointerType; /// NodeType typedef typename BaseType::NodeType NodeType; /// KratosVariable or KratosVariableComponent typedef typename BaseType::VariablePointer VariablePointer; KRATOS_CLASS_POINTER_DEFINITION( BdfMethod ); ///@} ///@name Life Cycle ///@{ /// Default Constructor. BdfMethod() : BaseType() {} /// Constructor. BdfMethod(const TVariableType& rVariable) : BaseType(rVariable) {} /// Constructor. BdfMethod(const TVariableType& rVariable, const TVariableType& rFirstDerivative, const TVariableType& rSecondDerivative) : BaseType(rVariable,rFirstDerivative,rSecondDerivative) {} /// Constructor. BdfMethod(const TVariableType& rVariable, const TVariableType& rFirstDerivative, const TVariableType& rSecondDerivative, const TVariableType& rPrimaryVariable) : BaseType(rVariable,rFirstDerivative,rSecondDerivative,rPrimaryVariable) {} /// Copy Constructor. BdfMethod(BdfMethod& rOther) :BaseType(rOther) ,mOrder(rOther.mOrder) ,mDeltaTime(rOther.mDeltaTime) ,mBDF(rOther.mBDF) { } /// Clone. BasePointerType Clone() override { return BasePointerType( new BdfMethod(*this) ); } /// Destructor. ~BdfMethod() override{} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ //calculate parameters (to call it once with the original input parameters) void CalculateParameters(ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY const double& delta_time = rCurrentProcessInfo[DELTA_TIME]; if (delta_time < 1.0e-24) { KRATOS_ERROR << " ERROR: detected delta_time = 0 in the Solution Method DELTA_TIME. PLEASE : check if the time step is created correctly for the current model part " << std::endl; } unsigned int order = 1; if (rCurrentProcessInfo.Has(TIME_INTEGRATION_ORDER)) { order = rCurrentProcessInfo[TIME_INTEGRATION_ORDER]; } if (rCurrentProcessInfo.Has(BDF_COEFFICIENTS)) { mBDF = rCurrentProcessInfo[BDF_COEFFICIENTS]; if( mBDF.size() > 1 && (order + 1) != mBDF.size() ) order = mBDF.size()-1; } if (mBDF.size() == 0 ){ //if (mBDF.size() != (order + 1)) mBDF.resize(order + 1,false); // Compute the BDF coefficients from order switch(order) { case 1 : mBDF[0] = 1.0/delta_time; //coefficient for step n+1 (1/Dt if Dt is constant) mBDF[1] = -1.0/delta_time; //coefficient for step n (-1/Dt if Dt is constant) break; case 2 : mBDF[0] = 3.0/( 2.0 * delta_time ); //coefficient for step n+1 (3/2Dt if Dt is constant) mBDF[1] = -2.0/( delta_time ); //coefficient for step n (-4/2Dt if Dt is constant) mBDF[2] = 1.0/( 2.0 * delta_time ); //coefficient for step n-1 (1/2Dt if Dt is constant) break; case 3 : mBDF[0] = 11.0/(6.0 * delta_time); //coefficient for step n+1 (11/6Dt if Dt is constant) mBDF[1] = -18.0/(6.0 * delta_time); //coefficient for step n (-18/6Dt if Dt is constant) mBDF[2] = 9.0/(6.0 * delta_time); //coefficient for step n-1 (9/6Dt if Dt is constant) mBDF[3] = -2.0/(6.0 * delta_time); //coefficient for step n-2 (2/6Dt if Dt is constant) break; case 4 : mBDF[0] = 25.0/(12.0 * delta_time); //coefficient for step n+1 (25/12Dt if Dt is constant) mBDF[1] = -48.0/(12.0 * delta_time); //coefficient for step n (-48/12Dt if Dt is constant) mBDF[2] = 36.0/(12.0 * delta_time); //coefficient for step n-1 (36/12Dt if Dt is constant) mBDF[3] = -16.0/(12.0 * delta_time); //coefficient for step n-2 (16/12Dt if Dt is constant) mBDF[4] = 3.0/(12.0 * delta_time); //coefficient for step n-3 (3/12Dt if Dt is constant) break; case 5 : mBDF[0] = 137.0/(60.0 * delta_time); //coefficient for step n+1 (137/60Dt if Dt is constant) mBDF[1] = -300.0/(60.0 * delta_time); //coefficient for step n (-300/60Dt if Dt is constant) mBDF[2] = 300.0/(60.0 * delta_time); //coefficient for step n-1 (300/60Dt if Dt is constant) mBDF[3] = -200.0/(60.0 * delta_time); //coefficient for step n-2 (-200/60Dt if Dt is constant) mBDF[4] = 75.0/(60.0 * delta_time); //coefficient for step n-3 (75/60Dt if Dt is constant) mBDF[5] = -12.0/(60.0 * delta_time); //coefficient for step n-4 (-12/60Dt if Dt is constant) break; case 6 : mBDF[0] = 147.0/(60.0 * delta_time); //coefficient for step n+1 (147/60Dt if Dt is constant) mBDF[1] = -360.0/(60.0 * delta_time); //coefficient for step n (-360/60Dt if Dt is constant) mBDF[2] = 450.0/(60.0 * delta_time); //coefficient for step n-1 (450/60Dt if Dt is constant) mBDF[3] = -400.0/(60.0 * delta_time); //coefficient for step n-2 (-400/60Dt if Dt is constant) mBDF[4] = 225.0/(60.0 * delta_time); //coefficient for step n-3 (225/60Dt if Dt is constant) mBDF[5] = -72.0/(60.0 * delta_time); //coefficient for step n-4 (-72/60Dt if Dt is constant) mBDF[6] = 10.0/(60.0 * delta_time); //coefficient for step n-5 (10/60Dt if Dt is constant) break; default : KRATOS_ERROR << "Methods with order > 6 are not zero-stable so they cannot be used" << std::endl; } } rCurrentProcessInfo[TIME_INTEGRATION_ORDER] = order; rCurrentProcessInfo[BDF_COEFFICIENTS] = mBDF; this->SetParameters(rCurrentProcessInfo); KRATOS_CATCH( "" ) } // set parameters (do not calculate parameters here, only read them) void SetParameters(const ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY const double& delta_time = rCurrentProcessInfo[DELTA_TIME]; mOrder = 1; if (rCurrentProcessInfo.Has(TIME_INTEGRATION_ORDER)) { mOrder = rCurrentProcessInfo[TIME_INTEGRATION_ORDER]; } if (rCurrentProcessInfo.Has(BDF_COEFFICIENTS)) { mBDF = rCurrentProcessInfo[BDF_COEFFICIENTS]; if( mBDF.size() > 1 && (mOrder + 1) != mBDF.size() ) mOrder = mBDF.size()-1; } mDeltaTime = delta_time; KRATOS_CATCH( "" ) } // set parameters to process info void SetProcessInfoParameters(ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY rCurrentProcessInfo[BDF_COEFFICIENTS] = mBDF; KRATOS_CATCH( "" ) } /** * @brief This function is designed to be called once to perform all the checks needed * @return 0 all ok */ int Check( const ProcessInfo& rCurrentProcessInfo ) override { KRATOS_TRY // Perform base integration method checks int ErrorCode = 0; ErrorCode = BaseType::Check(rCurrentProcessInfo); // Check that all required variables have been registered if( this->mpFirstDerivative == nullptr ){ KRATOS_ERROR << " time integration method FirstDerivative not set " <<std::endl; } if( this->mpSecondDerivative == nullptr ){ KRATOS_ERROR << " time integration method SecondDerivative not set " <<std::endl; } return ErrorCode; KRATOS_CATCH("") } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { std::stringstream buffer; buffer << "BdfMethod"; return buffer.str(); } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "BdfMethod"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << "BdfMethod Data"; } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ unsigned int mOrder; double mDeltaTime; Vector mBDF; ///@} ///@name Protected Operators ///@{ void AssignFromVariable(NodeType& rNode) override { KRATOS_TRY // predict variable from variable TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); // TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); // const TValueType& PreviousVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 1); // const TValueType& PreviousFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); // const TValueType& PreviousSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 1); // CurrentVariable = PreviousVariable + mDeltaTime * PreviousFirstDerivetive + 0.5 * mDeltaTime * mDeltaTime * PreviousSecondDerivative; CurrentFirstDerivative -= CurrentFirstDerivative; CurrentSecondDerivative -= CurrentSecondDerivative; KRATOS_CATCH( "" ) } void AssignFromFirstDerivative(NodeType& rNode) override { KRATOS_TRY // predict variable from first derivative TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); const TValueType& PreviousVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 1); TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); const TValueType& PreviousFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); CurrentVariable = (CurrentFirstDerivative - mBDF[1] * PreviousVariable)/mBDF[0]; TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); CurrentFirstDerivative = PreviousFirstDerivative; CurrentSecondDerivative -= CurrentSecondDerivative; KRATOS_CATCH( "" ) } void AssignFromSecondDerivative(NodeType& rNode) override { KRATOS_TRY // predict variable from second derivative TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); const TValueType& PreviousVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 1); const TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); const TValueType& PreviousFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); CurrentFirstDerivative = (CurrentSecondDerivative - mBDF[1] * PreviousFirstDerivative)/mBDF[0]; CurrentVariable = (CurrentFirstDerivative - mBDF[1] * PreviousVariable)/mBDF[0]; KRATOS_CATCH( "" ) } void PredictFromVariable(NodeType& rNode) override { KRATOS_TRY //if(this->Is(TimeIntegrationLocalFlags::NOT_PREDICT_PRIMARY_VARIABLE)) this->PredictVariable(rNode); this->PredictFirstDerivative(rNode); this->PredictSecondDerivative(rNode); KRATOS_CATCH( "" ) } void PredictFromFirstDerivative(NodeType& rNode) override { KRATOS_TRY this->PredictVariable(rNode); //if(this->Is(TimeIntegrationLocalFlags::NOT_PREDICT_PRIMARY_VARIABLE)) //this->PredictFirstDerivative(rNode); this->PredictSecondDerivative(rNode); KRATOS_CATCH( "" ) } void PredictVariable(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); const TValueType& PreviousVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 1); const TValueType& PreviousFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); const TValueType& PreviousSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 1); CurrentVariable = PreviousVariable + mDeltaTime * PreviousFirstDerivative + 0.5 * mDeltaTime * mDeltaTime * PreviousSecondDerivative; KRATOS_CATCH( "" ) } void PredictFirstDerivative(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); const TValueType& PreviousVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 1); TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); CurrentFirstDerivative = mBDF[0] * CurrentVariable + mBDF[1] * PreviousVariable; KRATOS_CATCH( "" ) } void PredictSecondDerivative(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); const TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); const TValueType& PreviousFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 1); CurrentSecondDerivative = mBDF[0] * CurrentFirstDerivative + mBDF[1] * PreviousFirstDerivative; KRATOS_CATCH( "" ) } void UpdateFromVariable(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); CurrentFirstDerivative = mBDF[0] * rNode.FastGetSolutionStepValue(*this->mpVariable, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentFirstDerivative += mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpVariable, i); TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); CurrentSecondDerivative = mBDF[0] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentSecondDerivative += mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, i); KRATOS_CATCH( "" ) } void UpdateFromFirstDerivative(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentVariable -= mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpVariable, i); CurrentVariable /= mBDF[0]; TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); CurrentSecondDerivative = mBDF[0] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentSecondDerivative += mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, i); KRATOS_CATCH( "" ) } void UpdateFromSecondDerivative(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentFirstDerivative -= mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, i); CurrentFirstDerivative /= mBDF[0]; TValueType& CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpVariable, 0); CurrentVariable = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentVariable -= mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpVariable, i); CurrentVariable /= mBDF[0]; KRATOS_CATCH( "" ) } void UpdateVariable(NodeType& rNode) override { KRATOS_TRY KRATOS_CATCH( "" ) } void UpdateFirstDerivative(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentFirstDerivative = rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); CurrentFirstDerivative = mBDF[0] * rNode.FastGetSolutionStepValue(*this->mpVariable, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentFirstDerivative += mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpVariable, i); KRATOS_CATCH( "" ) } void UpdateSecondDerivative(NodeType& rNode) override { KRATOS_TRY TValueType& CurrentSecondDerivative = rNode.FastGetSolutionStepValue(*this->mpSecondDerivative, 0); CurrentSecondDerivative = mBDF[0] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, 0); for(unsigned int i= 1; i<=mOrder; ++i) CurrentSecondDerivative += mBDF[i] * rNode.FastGetSolutionStepValue(*this->mpFirstDerivative, i); KRATOS_CATCH( "" ) } ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ // get parameters double& GetFirstDerivativeInertialParameter(double& rParameter) override { rParameter = mBDF[0]; return rParameter; } double& GetSecondDerivativeInertialParameter(double& rParameter) override { rParameter = mBDF[0]*mBDF[0]; return rParameter; } ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Serialization ///@{ friend class Serializer; void save(Serializer& rSerializer) const override { KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, BaseType ) rSerializer.save("Order", mOrder); rSerializer.save("DeltaTime", mDeltaTime); rSerializer.save("BDF", mBDF); }; void load(Serializer& rSerializer) override { KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, BaseType ) rSerializer.load("Order", mOrder); rSerializer.load("DeltaTime", mDeltaTime); rSerializer.load("BDF", mBDF); }; ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class BdfMethod ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ template<class TVariableType, class TValueType> inline std::istream & operator >> (std::istream & rIStream, BdfMethod<TVariableType,TValueType>& rThis) { return rIStream; } template<class TVariableType, class TValueType> inline std::ostream & operator << (std::ostream & rOStream, const BdfMethod<TVariableType,TValueType>& rThis) { return rOStream << rThis.Info(); } ///@} ///@} addtogroup block } // namespace Kratos. #endif // KRATOS_BDF_METHOD_H_INCLUDED defined
31.696319
240
0.643956
[ "object", "vector", "model" ]
088c64c12dbdf169de34b889069f0b7ce53d155c
6,827
cpp
C++
TemplePlus/InfinityEngine.cpp
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
69
2015-05-05T14:09:25.000Z
2022-02-15T06:13:04.000Z
TemplePlus/InfinityEngine.cpp
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
457
2015-05-01T22:07:45.000Z
2022-03-31T02:19:10.000Z
TemplePlus/InfinityEngine.cpp
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
25
2016-02-04T21:19:53.000Z
2021-11-15T23:14:51.000Z
#include "stdafx.h" #include "InfinityEngine.h" #include "zlib.h" #include <map> #include <tio/tio.h> InfiniData ieData; void InfiniData::ReadChitin(){ // read header auto chitin_file = tio_fopen("chitin.key", "rb"); if (chitin_file == nullptr) return; tio_fread(&keyHeader, sizeof(ChitinKeyHeader), 1, chitin_file); // Get biff entries (file names really) for (auto i = 0; i<keyHeader.biffCount; i++) { ChitinBifEntry biffTemp; tio_fread(&biffTemp, sizeof(ChitinBifEntry), 1, chitin_file); biffEntries.push_back({ biffTemp }); } auto curPos = tio_ftell(chitin_file); // get the BIF file names for (auto i = 0; i<keyHeader.biffCount; i++) { char tempBuffer[1024]; auto &be = biffEntries[i]; if (tio_ftell(chitin_file) != be.entry.biffFilenameOffset) { logger->warn("oy vey!"); } tio_fread(&tempBuffer, sizeof(char), biffEntries[i].entry.biffFilenameLength, chitin_file); be.fileName = fmt::format("{}", tempBuffer); } // Get resource entries // Consist of string ID, type, and index curPos = tio_ftell(chitin_file); if (curPos > keyHeader.resourceOffset) { logger->warn("oy vey!"); } tio_fseek(chitin_file, keyHeader.resourceOffset, 0); curPos = tio_ftell(chitin_file); for (auto i = 0; i<keyHeader.resourceCount; i++) { ChitinResEntry resTemp; tio_fread(&resTemp, sizeof(ChitinResEntry), 1, chitin_file); resKeyEntries.push_back(resTemp); resMapping[resTemp.resName] = resTemp.resLocator; // special casing for TIS resources (Tilesets) if (resTemp.resType == IeResourceType::IERT_Tileset) { tisKeyEntries.push_back(resTemp); tisMapping[resTemp.resName] = resTemp.resLocator; } } curPos = tio_ftell(chitin_file); // should be 522652 for IWD:EE tio_fclose(chitin_file); } void InfiniData::ReadBifFiles(){ uint32_t curPos; TioFileList fl; tio_filelist_create(&fl, "data/*.BIF"); std::map<int, std::vector<char>> fileCache; std::vector<uint8_t> bifBytes; for (auto i = 0; i< fl.count; i++) { // open the BIF file auto f = tio_fopen(fmt::format("data/{}", fl.files[i].name).c_str(), "rb"); logger->info("Opening BIFF file: {}", f->filename); tio_fseek(f, 0, SEEK_END); auto fSize = tio_ftell(f); tio_fseek(f, 0, SEEK_SET); bifBytes.clear(); bifBytes.resize(fSize); tio_fread(&bifBytes[0], 1, fSize, f); // read the BIFF header char bifSignature[5] = { 0, }; char bifVersion[5] = { 0, }; memcpy(bifSignature, &bifBytes[0],sizeof(char) * 4); memcpy(bifVersion, &bifBytes[4], sizeof(char) * 4); if (!strcmp(bifSignature, "BIFF")) { ReadBif(bifBytes); } else if (!_strcmpi(bifSignature, "BIF ")) { // BIFC V1 file format (zlib compressed BIF file(s), monoblock ) ReadBifcV1(bifBytes); } else if (!strcmp(bifSignature, "BIFC")) { // BIFC V1.0 file format (block-wise compressed BIF file(s) ) ReadBifcV10(bifBytes); } // close file tio_fclose(f); } tio_filelist_destroy(&fl); } void InfiniData::ReadBif( std::vector<uint8_t> &bifBytes){ BiffHeader bifHeader; // get the BIFF header auto bytePtr = 0; auto byteSize = sizeof(BiffHeader); memcpy(&bifHeader, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; if (bifHeader.fileCount > 10000 || bifHeader.fileCount < 0) { // indicates bad data int dummy = 1; } // initialize the BIFF Contents biffContents.push_back({ bifHeader }); auto &bifC = biffContents[biffContents.size()-1]; // read file entries bytePtr = bifHeader.fileEntriesOff; for (auto j = 0; j < bifHeader.fileCount; j++) { BiffFileEntry fe; byteSize = sizeof(BiffFileEntry); memcpy(&fe, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; bifC.files.push_back(fe); } // read tile entries for (auto j = 0; j < bifHeader.tilesetCount; j++) { BiffTileEntry te; byteSize = sizeof(BiffTileEntry); memcpy(&te, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; bifC.tiles.push_back(te); } // read the file data for (auto j = 0; j < bifHeader.fileCount; j++) { auto &fe = bifC.files[j]; bytePtr = fe.dataOffset; // todo } // read the tile data for (auto i = 0; i < bifHeader.tilesetCount; i++) { auto &te = bifC.tiles[i]; bytePtr = te.dataOffset; auto tileCount = te.tilesCount; auto tileSize = te.tileSize; TileData *tiledata = (TileData *)(&bifBytes[bytePtr]); for (auto j = 0; j < tileCount; j++){ IeBitmapFromTile bm(*tiledata); string fname(fmt::format("AR{}.bmp", j)); auto f = tio_fopen(fname.c_str(), "wb"); tio_fwrite(&bm, 1, sizeof(IeBitmapFromTile), f); tio_fclose(f); tiledata++; } } } void InfiniData::ReadBifcV1(std::vector<uint8_t>& bifBytes) { BifCHeader bifCHeader; char fname[1024] = { 0, }; auto bytePtr = 0; // get header auto byteSize = sizeof(BifCHeader); memcpy(&bifCHeader, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; // get filename byteSize = bifCHeader.filenameLen; memcpy(&fname, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; // get data length uint32_t uncompressedDataLen = 0; byteSize = sizeof(uncompressedDataLen); memcpy(&uncompressedDataLen, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; uint32_t compressedDataLen = 0; byteSize = sizeof(compressedDataLen); memcpy(&compressedDataLen, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; // get raw compressed data std::vector<uint8_t> rawData; rawData.resize(compressedDataLen); byteSize = compressedDataLen; memcpy(&rawData[0], &bifBytes[bytePtr], byteSize); std::vector<uint8_t> uncompData; uncompData.resize(uncompressedDataLen); ReadBif(uncompData); } void InfiniData::ReadBifcV10(std::vector<uint8_t>& bifBytes){ auto bytePtr = 0; // get header BifCV10Header bifCHeader; auto byteSize = sizeof(BifCV10Header); memcpy(&bifCHeader, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; std::vector<uint8_t> rawData; std::vector<uint8_t> uncompData; uncompData.resize(bifCHeader.uncompBifSize); auto uncompDataCount = 0; // read compressed blocks while (bytePtr < bifBytes.size()){ uint32_t decompressedBlockSize = 0; uint32_t compressedBlockSize = 0; byteSize = sizeof(decompressedBlockSize); memcpy(&decompressedBlockSize, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; byteSize = sizeof(compressedBlockSize); memcpy(&compressedBlockSize, &bifBytes[bytePtr], byteSize); bytePtr += byteSize; // read raw data block rawData.clear(); rawData.resize(compressedBlockSize); byteSize = compressedBlockSize; memcpy(&rawData[0], &bifBytes[bytePtr], compressedBlockSize); bytePtr += byteSize; // inflate uLongf uncompressedBlockSize; auto uncomResult = uncompress(&uncompData[uncompDataCount], &uncompressedBlockSize, &rawData[0], compressedBlockSize); uncompDataCount += uncompressedBlockSize; } assert(uncompData.size() == uncompDataCount); ReadBif(uncompData); }
25.285185
120
0.698989
[ "vector" ]
088d047ae291270d650013c9b945a55299554915
3,392
cpp
C++
3rdParty/boost/1.71.0/libs/convert/test/has_member.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/convert/test/has_member.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/convert/test/has_member.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Boost.Convert test and usage example // Copyright (c) 2009-2016 Vladimir Batov. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. See http://www.boost.org/LICENSE_1_0.txt. #include "./test.hpp" #if defined(BOOST_CONVERT_IS_NOT_SUPPORTED) int main(int, char const* []) { return 0; } #else #include <boost/convert.hpp> #include <boost/detail/lightweight_test.hpp> #include <vector> #include <iostream> //[has_member_declaration namespace { namespace local { BOOST_DECLARE_HAS_MEMBER(has_begin, begin); BOOST_DECLARE_HAS_MEMBER(has_funop, operator()); }} //] //[has_member_classes_tested namespace { namespace local { struct test01 { int begin; }; struct test02 { char* begin() { return 0; } }; struct test22 { void operator()() {} }; }} //] namespace { namespace local { struct test03 { void begin(int) {} int begin(int, int) { return 0; } }; struct test04 { virtual ~test04() {} private: virtual char* begin() { return 0; } }; struct test05 { virtual char* begin() { return 0; } virtual ~test05() {} }; struct test06 : public test04 {}; struct test07 : private test04 {}; struct test08 : public test05 {}; struct test09 : private test05 {}; struct test11 { int no_begin; }; struct test12 { char* no_begin() { return 0; } }; }} namespace { namespace local { struct test21 { void zoo () {} }; struct test23 { void operator() () const {} }; struct test24 { int operator() (int) { return 0; } }; struct test25 { int operator() (int) const { return 0; } }; struct test26 { int operator() (int) const { return 0; } void operator() () const {} }; }} int main(int, char const* []) { BOOST_TEST(local::has_begin<local::test01>::value == true); BOOST_TEST(local::has_begin<local::test02>::value == true); BOOST_TEST(local::has_begin<local::test03>::value == true); BOOST_TEST(local::has_begin<local::test04>::value == true); BOOST_TEST(local::has_begin<local::test05>::value == true); BOOST_TEST(local::has_begin<local::test06>::value == true); BOOST_TEST(local::has_begin<local::test07>::value == true); BOOST_TEST(local::has_begin<local::test08>::value == true); BOOST_TEST(local::has_begin<local::test09>::value == true); BOOST_TEST(local::has_begin<std::string>::value == true); BOOST_TEST(local::has_begin<std::vector<int> >::value == true); BOOST_TEST(local::has_begin<local::test11>::value == false); BOOST_TEST(local::has_begin<local::test12>::value == false); BOOST_TEST(local::has_begin<std::iostream>::value == false); //[has_member_usage BOOST_TEST(local::has_begin<local::test01>::value == true); BOOST_TEST(local::has_begin<local::test02>::value == true); BOOST_TEST(local::has_funop<local::test22>::value == true); //] BOOST_TEST(local::has_funop<local::test21>::value == false); BOOST_TEST(local::has_funop<local::test22>::value == true); BOOST_TEST(local::has_funop<local::test23>::value == true); BOOST_TEST(local::has_funop<local::test24>::value == true); BOOST_TEST(local::has_funop<local::test25>::value == true); BOOST_TEST(local::has_funop<local::test26>::value == true); return boost::report_errors(); } #endif
32.304762
92
0.642983
[ "vector" ]
08903e5b5472e6f49849b7fb6fd315f5d35fe689
1,936
cpp
C++
CodeForces/501B_Misha_and_changing_handles.cpp
ASM-ATIKUR/Competitive_Programming_Atikur_Rahman
9552e4dca7daad5c07542514d4b8c8baabea1989
[ "MIT" ]
null
null
null
CodeForces/501B_Misha_and_changing_handles.cpp
ASM-ATIKUR/Competitive_Programming_Atikur_Rahman
9552e4dca7daad5c07542514d4b8c8baabea1989
[ "MIT" ]
null
null
null
CodeForces/501B_Misha_and_changing_handles.cpp
ASM-ATIKUR/Competitive_Programming_Atikur_Rahman
9552e4dca7daad5c07542514d4b8c8baabea1989
[ "MIT" ]
null
null
null
/*** ** A S M Atikur Rahman ** Update: 27-10-2019 ***/ #include <bits/stdc++.h> #define sci(x) scanf("%d", &(x)) #define scll(x) scanf("%lld", &(x)) #define scd(x) scanf("%lf", &(x)) #define scstr(x) scanf("%s", x) #define pfi(x) printf("%d", (x)) #define pfll(x) printf("%lld", (x)) #define pfd(x) printf("%f", (x)) #define pfstr(x) printf("%s", (x)) #define ps printf(" ") #define pn printf("\n") #define pfdot printf("..") #define For(i,a,n) for(int i=(a); i<(n); i++) #define rFor(i,n,a) for(int i=n-1; i>=0; i--) #define trav(a,x) for (auto& a : x) #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound #define pi (2*acos(0)) using namespace std; using ll=long long; using pii= pair<int,int>; using pll= pair<long long, long long>; using pcc= pair<char, char>; using pdd= pair<double, double>; using pss= pair<string, string>; #define V(a) vector<a> using vi= vector<int>; using vs= vector<string>; using vll= vector<ll>; using vpii= vector<pii>; using vc= vector<char>; using vd= vector<double>; int main( int argc, char *argv[] ) { int n, i, j, chk[1009]; memset(chk, 0,sizeof(chk)); V(pss) data; string s,s1; cin>>n; for(i=0; i<n; i++) { cin>>s>>s1; data.push_back({s,s1}); } int ans=n; for(i=0; i<n; i++) { for(j=i+1; j<n; j++) { int fg=0; if(data[i].s == data[j].f && !chk[j]) { data[i].s=data[j].s; chk[j]=1; fg=1; } if(data[i].f == data[j].s && !chk[j]) { data[i].f=data[j].f; chk[j]=1; fg=1; } if(fg) ans--; } } pfi(ans);pn; for(i=0; i<n; i++) { if(chk[i]==0) cout<<data[i].f<<" "<<data[i].s<<"\n"; } return 0; }
17.761468
60
0.492252
[ "vector" ]
089232a4498f1a136f834731fc7e92cf9474298f
534
cpp
C++
src/util.cpp
BrunodaSilvaBelo/UltimaCompiler
2120aae040e4d39b3c79fbc5931041ffbcd9bef5
[ "MIT" ]
null
null
null
src/util.cpp
BrunodaSilvaBelo/UltimaCompiler
2120aae040e4d39b3c79fbc5931041ffbcd9bef5
[ "MIT" ]
1
2021-04-12T13:38:27.000Z
2021-04-12T13:38:41.000Z
src/util.cpp
BrunodaSilvaBelo/UltimaCompiler
2120aae040e4d39b3c79fbc5931041ffbcd9bef5
[ "MIT" ]
null
null
null
#include "util.h" #include "token.h" #include <map> #include <utility> std::string uc::show_token_to_alcino(std::vector<Token> const& container) { std::map<unsigned, std::map<unsigned, std::string>> m_map; for (auto& token : container) { auto position = token.get_position(); m_map[position.first][position.second] = token.to_string(); } std::string out = ""; for (auto& i : m_map) { for (auto& j : i.second) { out += j.second + " "; } out += "\n"; } return out; }
22.25
75
0.578652
[ "vector" ]
08938942748433e45ecade5774609c0b1b1c888d
7,541
cpp
C++
src/writer/verilog/verilog_writer.cpp
robtaylor/iroha
e7713910ee64ca98f999b98b0c77c02fcfe2da09
[ "BSD-3-Clause" ]
34
2016-02-07T17:43:55.000Z
2021-12-18T12:01:08.000Z
src/writer/verilog/verilog_writer.cpp
robtaylor/iroha
e7713910ee64ca98f999b98b0c77c02fcfe2da09
[ "BSD-3-Clause" ]
5
2016-04-12T09:27:31.000Z
2021-06-29T10:59:18.000Z
src/writer/verilog/verilog_writer.cpp
robtaylor/iroha
e7713910ee64ca98f999b98b0c77c02fcfe2da09
[ "BSD-3-Clause" ]
5
2015-12-26T10:58:46.000Z
2021-06-25T18:58:40.000Z
#include "writer/verilog/verilog_writer.h" #include "design/design_util.h" #include "iroha/i_design.h" #include "iroha/logging.h" #include "iroha/resource_params.h" #include "iroha/stl_util.h" #include "writer/names.h" #include "writer/verilog/embedded_modules.h" #include "writer/verilog/indent.h" #include "writer/verilog/internal_sram.h" #include "writer/verilog/module.h" #include "writer/verilog/port.h" #include "writer/verilog/port_set.h" #include "writer/verilog/self_shell.h" namespace iroha { namespace writer { namespace verilog { VerilogWriter::VerilogWriter(const IDesign *design, const Connection &conn, const string &flavor, bool debug, ostream &os) : design_(design), conn_(conn), flavor_(flavor), debug_(debug), final_os_(os), embedded_modules_(new EmbeddedModules), with_self_contained_(false), output_vcd_(false), names_root_(new Names(nullptr)), reset_polarity_(false) {} VerilogWriter::~VerilogWriter() {} bool VerilogWriter::Write() { names_root_->ReservePrefix("insn"); names_root_->ReservePrefix("st"); names_root_->ReservePrefix("task"); names_root_->ReservePrefix("S"); // Resource related. names_root_->ReservePrefix("fifo"); names_root_->ReservePrefix("mem"); // e.g. shared_reg names_root_->ReservePrefix("shared"); // SystemVerilog keyword. names_root_->ReservePrefix("always"); DebugMarker::SetEnable(debug_); os_ << "// Generated from " << PACKAGE << "-" << VERSION << ".\n"; IModule *root = DesignUtil::GetRootModule(design_); if (root == nullptr) { LOG(ERROR) << "Failed to determine a root module"; return false; } PrepareModulesRec(root); ResolveResetPolarity(root); BuildModules(root); // * MODULE-NAME-PREFIX is specified. // prefix_rawName // * Not specifed. // shellModuleName_rawName string prefix = design_->GetParams()->GetModuleNamePrefix(); if (prefix.empty()) { prefix = shell_module_name_ + "_"; } for (auto *mod : ordered_modules_) { mod->Write(prefix, os_); } if (!shell_module_name_.empty()) { Module *root_mod = modules_[root]; WriteShellModule(root_mod); } if (!embedded_modules_->Write(GetResetPolarity(), os_)) { LOG(ERROR) << "Failed to write embedded modules."; return false; } STLDeleteSecondElements(&modules_); string s = os_.str(); Indent indent(s); final_os_ << indent.DoIndent(); return true; } void VerilogWriter::SetShellModuleName(const string &n, bool with_self_contained, bool output_vcd) { shell_module_name_ = n; with_self_contained_ = with_self_contained; output_vcd_ = output_vcd; } Module *VerilogWriter::GetByIModule(const IModule *mod) const { auto it = modules_.find(mod); if (it != modules_.end()) { return it->second; } return nullptr; } bool VerilogWriter::GetResetPolarity() const { return reset_polarity_; } void VerilogWriter::ResolveResetPolarity(const IModule *root) { if (root->GetParams()->HasResetPolarity()) { reset_polarity_ = root->GetParams()->GetResetPolarity(); return; } // This may return the default value. reset_polarity_ = design_->GetParams()->GetResetPolarity(); } void VerilogWriter::PrepareModulesRec(const IModule *imod) { vector<IModule *> children = DesignUtil::GetChildModules(imod); for (IModule *child : children) { PrepareModulesRec(child); } Module *mod = new Module(imod, this, conn_, embedded_modules_.get(), names_root_->NewChildNames()); modules_[imod] = mod; ordered_modules_.push_back(mod); } void VerilogWriter::BuildModules(const IModule *imod) { for (auto *mod : ordered_modules_) { const IModule *imod = mod->GetIModule(); IModule *iparent = imod->GetParentModule(); if (iparent != nullptr) { Module *parent = modules_[iparent]; mod->SetParentModule(parent); } } for (auto *mod : ordered_modules_) { mod->PrepareTables(); } for (auto *mod : ordered_modules_) { mod->Build(); } BuildChildModuleSection(); } void VerilogWriter::BuildChildModuleSection() { for (auto *mod : ordered_modules_) { vector<IModule *> child_imods = DesignUtil::GetChildModules(mod->GetIModule()); vector<Module *> mods; for (auto *imod : child_imods) { mods.push_back(modules_[imod]); } mod->BuildChildModuleInstSection(mods); } } void VerilogWriter::WriteShellModule(const Module *root_mod) { const PortSet *ports = root_mod->GetPortSet(); os_ << "`ifndef STRIP_SHELL\n"; os_ << "module " << shell_module_name_ << "("; if (!with_self_contained_) { ports->Output(PortSet::PORT_MODULE_HEAD_DIRECTION, os_); } os_ << ");\n"; if (with_self_contained_) { WriteSelfClockGenerator(root_mod); } std::unique_ptr<SelfShell> shell; if (with_self_contained_) { shell.reset(new SelfShell(design_, ports, reset_polarity_, embedded_modules_.get())); shell->WriteWireDecl(os_); } string name = root_mod->GetName(); if (design_->GetParams()->GetModuleNamePrefix().empty()) { name = shell_module_name_ + "_" + name; } else { name = design_->GetParams()->GetModuleNamePrefix() + name; } os_ << " " << name << " " << name << "_inst("; if (with_self_contained_) { WriteSelfClockConnection(root_mod); shell->WritePortConnection(os_); } else { ports->Output(PortSet::PORT_CONNECTION, os_); } os_ << ");\n"; if (with_self_contained_) { shell->WriteShellFSM(os_); } if (output_vcd_) { os_ << "\n" << "initial begin\n" << " $dumpfile(\"/tmp/" << shell_module_name_ << ".vcd\");\n" << " $dumpvars(0, " << name << "_inst);\n" << " end\n"; } os_ << "\nendmodule // " << shell_module_name_ << "\n"; os_ << "`endif // STRIP_SHELL\n"; os_ << "\n// NOTE: Please copy the follwoing line to your design.\n" << "// " << shell_module_name_ << " " << shell_module_name_ << "_inst("; ports->OutputWithFlavor(PortSet::PORT_CONNECTION_TEMPLATE, flavor_, os_); os_ << ");\n"; os_ << "//"; ports->OutputWithFlavor(PortSet::AXI_USER_ASSIGN_TEMPLATE, flavor_, os_); os_ << "\n"; os_ << "// NOTE: This can be used by your script to auto generate the " "instantiation and connections.\n" << "// :connection: " << shell_module_name_ << ":" << shell_module_name_ << "_inst "; ports->Output(PortSet::PORT_CONNECTION_DATA, os_); os_ << "\n"; } void VerilogWriter::WriteSelfClockGenerator(const Module *root_mod) { const PortSet *ports = root_mod->GetPortSet(); const string &clk = ports->GetClk(); const string &rst = ports->GetReset(); os_ << " reg " << clk << ", " << rst << ";\n\n" << " initial begin\n" << " " << clk << " <= 0;\n" << " " << rst << " <= " << (reset_polarity_ ? "1" : "0") << ";\n" << " #15\n" << " " << rst << " <= ~" << rst << ";\n" << " #10000\n" << " $finish;\n" << " end\n\n"; os_ << " always begin\n" << " #10 " << clk << " = ~" << clk << ";\n" << " end\n\n"; } void VerilogWriter::WriteSelfClockConnection(const Module *root_mod) { const PortSet *ports = root_mod->GetPortSet(); const string &clk = ports->GetClk(); const string &rst = ports->GetReset(); os_ << "." << clk << "(" << clk << "), ." << rst << "(" << rst << ")"; } } // namespace verilog } // namespace writer } // namespace iroha
31.161157
78
0.629757
[ "vector" ]
089a1389cc4abbde68f69705cb6e08ddbeed0915
776
hpp
C++
src/CS2D/Model/Map.hpp
requizm/cs2d_vscode
ff623c0d91a12f690bd0eb4f7ca8cd4130b7a794
[ "MIT" ]
4
2021-02-17T16:52:28.000Z
2022-03-09T15:12:03.000Z
src/CS2D/Model/Map.hpp
requizm/cs2d_vscode
ff623c0d91a12f690bd0eb4f7ca8cd4130b7a794
[ "MIT" ]
10
2021-02-01T13:49:55.000Z
2022-03-06T17:40:42.000Z
src/CS2D/Model/Map.hpp
requizm/cs2d_vscode
ff623c0d91a12f690bd0eb4f7ca8cd4130b7a794
[ "MIT" ]
1
2021-02-01T13:21:37.000Z
2021-02-01T13:21:37.000Z
#ifndef MAP_H #define MAP_H #include <GL/glew.h> #include <cmath> // pow() #include <string> #include <vector> #include "../../Core/Renderer/SpriteRenderer.hpp" #include "Tile.hpp" #include "Weapon.hpp" class Map { public: std::vector<Tile *> tiles; std::vector<Weapon *> weapons; Map() = default; Map(const std::string &path, const std::string &name); ~Map(); std::string GetName() const; void Draw(SpriteRenderer &renderer); Tile *GetTileByCell(int x, int y); Tile *GetTileByCell(Vector2<int> &cellPos); Tile *GetTileByPosition(int x, int y); Tile *GetTileByPosition(Vector2<int> &position); private: void Load(const std::string &file); std::string name; Vector2<int> mapLimit; }; #endif // MAP_H
18.046512
58
0.645619
[ "vector" ]
08a8920503eb95987e37a7b48d08cf0e8d146761
33,827
cpp
C++
packages/monte_carlo/collision/photon/test/tstAdjointPhotoatom.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/photon/test/tstAdjointPhotoatom.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/photon/test/tstAdjointPhotoatom.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file tstAdjointPhotoatom.cpp //! \author Alex Robinson //! \brief Adjoint photoatom unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // FRENSIE Includes #include "MonteCarlo_AdjointPhotoatom.hpp" #include "MonteCarlo_AdjointPhotoatomicReactionNativeFactory.hpp" #include "MonteCarlo_AdjointPhotonProbeState.hpp" #include "Data_AdjointElectronPhotonRelaxationDataContainer.hpp" #include "Utility_StandardHashBasedGridSearcher.hpp" #include "Utility_PhysicalConstants.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" //---------------------------------------------------------------------------// // Testing Variables //---------------------------------------------------------------------------// std::shared_ptr<const MonteCarlo::AdjointPhotoatom> adjoint_photoatom; //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that the atom name can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomName ) { FRENSIE_CHECK( adjoint_photoatom->getAtomName().find( "14" ) < adjoint_photoatom->getAtomName().size() ); } //---------------------------------------------------------------------------// // Check that the nuclide name can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getNuclideName ) { FRENSIE_CHECK( adjoint_photoatom->getAtomName().find( "14" ) < adjoint_photoatom->getAtomName().size() ); } //---------------------------------------------------------------------------// // Check that the atomic number can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicNumber ) { FRENSIE_CHECK_EQUAL( adjoint_photoatom->getAtomicNumber(), 14 ); } //---------------------------------------------------------------------------// // Check that the atomic mass number can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicMassNumber ) { FRENSIE_CHECK_EQUAL( adjoint_photoatom->getAtomicMassNumber(), 0 ); } //---------------------------------------------------------------------------// // Check that the nuclear isomer number can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getIsomerNumber ) { FRENSIE_CHECK_EQUAL( adjoint_photoatom->getIsomerNumber(), 0 ); } //---------------------------------------------------------------------------// // Check that the atomic weight can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicWeight ) { FRENSIE_CHECK_EQUAL( adjoint_photoatom->getAtomicWeight(), 14.0 ); } //---------------------------------------------------------------------------// // Check that the temperature of the atom can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getTemperature ) { FRENSIE_CHECK_EQUAL( adjoint_photoatom->getTemperature(), 0.0 ); } //---------------------------------------------------------------------------// // Check that the core can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getCore ) { const MonteCarlo::AdjointPhotoatomCore& core = adjoint_photoatom->getCore(); FRENSIE_CHECK_EQUAL( core.getScatteringReactions().size(), 2 ); FRENSIE_CHECK_EQUAL( core.getLineEnergyReactions().size(), 1 ); FRENSIE_CHECK_EQUAL( core.getCriticalLineEnergies().size(), 2 ); } //---------------------------------------------------------------------------// // Check that the critical line energies can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getCriticalLineEnergies ) { const std::vector<double>& critical_line_energies = adjoint_photoatom->getCriticalLineEnergies(); FRENSIE_REQUIRE_EQUAL( critical_line_energies.size(), 2 ); FRENSIE_CHECK_EQUAL( critical_line_energies[0], Utility::PhysicalConstants::electron_rest_mass_energy ); FRENSIE_CHECK_EQUAL( critical_line_energies[1], 20.0 ); } //---------------------------------------------------------------------------// // Check if the energy corresponds to a line energy reaction FRENSIE_UNIT_TEST( AdjointPhotoatom, doesEnergyHaveLineEnergyReaction ) { FRENSIE_CHECK( !adjoint_photoatom->doesEnergyHaveLineEnergyReaction( 0.51 ) ); FRENSIE_CHECK( adjoint_photoatom->doesEnergyHaveLineEnergyReaction( Utility::PhysicalConstants::electron_rest_mass_energy ) ); FRENSIE_CHECK( !adjoint_photoatom->doesEnergyHaveLineEnergyReaction( 0.52 ) ); } //---------------------------------------------------------------------------// // Check that the total cross section at the desired energy can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getTotalCrossSection ) { double cross_section = adjoint_photoatom->getTotalCrossSection( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 100.584831294850716, 1e-12 ); cross_section = adjoint_photoatom->getTotalCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 5.51199615670455145, 1e-12 ); cross_section = adjoint_photoatom->getTotalCrossSection( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.96243862843467646e-05, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the total atomic cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicTotalCrossSection ) { double cross_section = adjoint_photoatom->getAtomicTotalCrossSection( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 100.584831294850716, 1e-12 ); cross_section = adjoint_photoatom->getAtomicTotalCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 5.51199615670455145, 1e-12 ); cross_section = adjoint_photoatom->getAtomicTotalCrossSection( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.96243862843467646e-05, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the total nuclear cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getNuclearTotalCrossSection ) { double cross_section = adjoint_photoatom->getNuclearTotalCrossSection( 1e-3 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getNuclearTotalCrossSection( 1.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getNuclearTotalCrossSection( 20.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); } //---------------------------------------------------------------------------// // Check that the total line energy cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getTotalLineEnergyCrossSection ) { double cross_section = adjoint_photoatom->getTotalLineEnergyCrossSection( 0.51 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getTotalLineEnergyCrossSection( Utility::PhysicalConstants::electron_rest_mass_energy ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 15.3615415024052222, 1e-12 ); cross_section = adjoint_photoatom->getTotalLineEnergyCrossSection( 0.52 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); } //---------------------------------------------------------------------------// // Check that the total forward cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getTotalForwardCrossSection ) { double cross_section = adjoint_photoatom->getTotalForwardCrossSection( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 73136.5325778411352, 1e-12 ); cross_section = adjoint_photoatom->getTotalForwardCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 2.96240900282447228, 1e-12 ); cross_section = adjoint_photoatom->getTotalForwardCrossSection( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.08806003440055754, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the total atomic forward cross section at the desired energy // can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicTotalForwardCrossSection ) { double cross_section = adjoint_photoatom->getAtomicTotalForwardCrossSection( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 73136.5325778411352, 1e-12 ); cross_section = adjoint_photoatom->getAtomicTotalForwardCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 2.96240900282447228, 1e-12 ); cross_section = adjoint_photoatom->getAtomicTotalForwardCrossSection( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.08806003440055754, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the nuclear total forward cross section at the desired energy // can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getNuclearTotalForwardCrossSection ) { double cross_section = adjoint_photoatom->getNuclearTotalForwardCrossSection( 1e-3 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getNuclearTotalForwardCrossSection( 1.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getNuclearTotalForwardCrossSection( 20.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); } //---------------------------------------------------------------------------// // Check that the adjoint weight factor at the desired energy can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAdjointWeightFactor ) { double weight_factor = adjoint_photoatom->getAdjointWeightFactor( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 0.00137530216089743699, 1e-12 ); weight_factor = adjoint_photoatom->getAdjointWeightFactor( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 1.86064657224887142, 1e-12 ); weight_factor = adjoint_photoatom->getAdjointWeightFactor( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 1.8036124537152385e-05, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the atomic adjoint weight factor at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicAdjointWeightFactor ) { double weight_factor = adjoint_photoatom->getAtomicAdjointWeightFactor( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 0.00137530216089743699, 1e-12 ); weight_factor = adjoint_photoatom->getAtomicAdjointWeightFactor( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 1.86064657224887142, 1e-12 ); weight_factor = adjoint_photoatom->getAtomicAdjointWeightFactor( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 1.8036124537152385e-05, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the nuclear adjoint weight factor at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getNuclearAdjointWeightFactor ) { double weight_factor = adjoint_photoatom->getNuclearAdjointWeightFactor( 1e-3 ); FRENSIE_CHECK_EQUAL( weight_factor, 1.0 ); weight_factor = adjoint_photoatom->getNuclearAdjointWeightFactor( 1.0 ); FRENSIE_CHECK_EQUAL( weight_factor, 1.0 ); weight_factor = adjoint_photoatom->getNuclearAdjointWeightFactor( 20.0 ); FRENSIE_CHECK_EQUAL( weight_factor, 1.0 ); } //---------------------------------------------------------------------------// // Check that the adjoint line energy weight factor at the desired energy can // be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAdjointLineEnergyWeightFactor ) { double weight_factor = adjoint_photoatom->getAdjointLineEnergyWeightFactor( 0.51 ); FRENSIE_CHECK_EQUAL( weight_factor, 0.0 ); weight_factor = adjoint_photoatom->getAdjointLineEnergyWeightFactor( Utility::PhysicalConstants::electron_rest_mass_energy ); FRENSIE_CHECK_FLOATING_EQUALITY( weight_factor, 3.80493907935216980e+00, 1e-12 ); weight_factor = adjoint_photoatom->getAdjointLineEnergyWeightFactor( 0.52 ); FRENSIE_CHECK_EQUAL( weight_factor, 0.0 ); } //---------------------------------------------------------------------------// // Check that the absorption cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAbsorptionCrossSection ) { double cross_section = adjoint_photoatom->getAbsorptionCrossSection( 1e-3 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getAbsorptionCrossSection( 1.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getAbsorptionCrossSection( 20.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); } //---------------------------------------------------------------------------// // Check that the atomic absorption cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicAbsorptionCrossSection ) { double cross_section = adjoint_photoatom->getAtomicAbsorptionCrossSection( 1e-3 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getAtomicAbsorptionCrossSection( 1.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getAtomicAbsorptionCrossSection( 20.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); } //---------------------------------------------------------------------------// // Check that the nuclear absorption cross section at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getNuclearAbsorptionCrossSection ) { double cross_section = adjoint_photoatom->getNuclearAbsorptionCrossSection( 1e-3 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getNuclearAbsorptionCrossSection( 1.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); cross_section = adjoint_photoatom->getNuclearAbsorptionCrossSection( 20.0 ); FRENSIE_CHECK_EQUAL( cross_section, 0.0 ); } //---------------------------------------------------------------------------// // Check that the survival probability at the desired energy can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getSurvivalProbability ) { double survival_prob = adjoint_photoatom->getSurvivalProbability( 1e-3 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); survival_prob = adjoint_photoatom->getSurvivalProbability( 1.0 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); survival_prob = adjoint_photoatom->getSurvivalProbability( 1.0 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); } //---------------------------------------------------------------------------// // Check that the atomic survival probability at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAtomicSurvivalProbability ) { double survival_prob = adjoint_photoatom->getAtomicSurvivalProbability( 1e-3 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); survival_prob = adjoint_photoatom->getAtomicSurvivalProbability( 1.0 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); survival_prob = adjoint_photoatom->getAtomicSurvivalProbability( 1.0 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); } //---------------------------------------------------------------------------// // Check that the nuclear survival probability at the desired energy can be // returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getNuclearSurvivalProbability ) { double survival_prob = adjoint_photoatom->getNuclearSurvivalProbability( 1e-3 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); survival_prob = adjoint_photoatom->getNuclearSurvivalProbability( 1.0 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); survival_prob = adjoint_photoatom->getNuclearSurvivalProbability( 1.0 ); FRENSIE_CHECK_EQUAL( survival_prob, 1.0 ); } //---------------------------------------------------------------------------// // Check that the cross section for a specific adjoint photoatomic reaction // can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getReactionCrossSection ) { // Check the atomic total cross section double cross_section = adjoint_photoatom->getReactionCrossSection( 1e-3, MonteCarlo::TOTAL_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 100.584831294850716, 1e-12 ); cross_section = adjoint_photoatom->getReactionCrossSection( 1.0, MonteCarlo::TOTAL_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 5.51199615670455145, 1e-12 ); cross_section = adjoint_photoatom->getReactionCrossSection( 20.0, MonteCarlo::TOTAL_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.96243862843467646e-05, 1e-12 ); // Check the total incoherent cross section cross_section = adjoint_photoatom->getReactionCrossSection( 1e-3, MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 0.620920802623559753, 1e-12 ); cross_section = adjoint_photoatom->getReactionCrossSection( 1.0, MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 5.50415974966055277, 1e-12 ); cross_section = adjoint_photoatom->getReactionCrossSection( 20.0, MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_SMALL( cross_section, 1e-12 ); // Check the coherent cross section cross_section = adjoint_photoatom->getReactionCrossSection( 1e-3, MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 99.9639104922271571, 1e-12 ); cross_section = adjoint_photoatom->getReactionCrossSection( 1.0, MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 0.00783640704399895215, 1e-12 ); cross_section = adjoint_photoatom->getReactionCrossSection( 20.0, MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.96243862843467646e-05, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the absorption reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getAbsorptionReactionTypes ) { MonteCarlo::AdjointPhotoatom::ReactionEnumTypeSet reaction_types; adjoint_photoatom->getAbsorptionReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 0 ); } //---------------------------------------------------------------------------// // Check that the scattering reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getScatteringReactionTypes ) { MonteCarlo::AdjointPhotoatom::ReactionEnumTypeSet reaction_types; adjoint_photoatom->getScatteringReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 2 ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); } //---------------------------------------------------------------------------// // Check that the miscellaneous reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getMiscReactionTypes ) { MonteCarlo::AdjointPhotoatom::ReactionEnumTypeSet reaction_types; adjoint_photoatom->getMiscReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 0 ); } //---------------------------------------------------------------------------// // Check that the reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatom, getReactionTypes ) { MonteCarlo::AdjointPhotoatom::ReactionEnumTypeSet reaction_types; adjoint_photoatom->getReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 3 ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::TOTAL_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); } //---------------------------------------------------------------------------// // Check that an analogue collision can be modeled FRENSIE_UNIT_TEST( AdjointPhotoatom, collideAnalogue ) { // Sample the incoherent reaction std::vector<double> fake_stream( 10 ); fake_stream[0] = 0.78; // choose incoherent scattering fake_stream[1] = 0.15; // branch 1 fake_stream[2] = 0.4721647344828152; // select x = 0.9 fake_stream[3] = 0.49; // accept fake_stream[4] = 0.91; // reject based on scattering function fake_stream[5] = 0.15; // branch 1 fake_stream[6] = 0.4721647344828152; // select x = 0.9 fake_stream[7] = 0.49; // accept fake_stream[8] = 0.909; // accept based on scattering function fake_stream[9] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); MonteCarlo::AdjointPhotonState adjoint_photon( 0 ); adjoint_photon.setEnergy( Utility::PhysicalConstants::electron_rest_mass_energy/10.0 ); adjoint_photon.setDirection( 0.0, 0.0, 1.0 ); adjoint_photon.setWeight( 1.0 ); MonteCarlo::ParticleBank bank; adjoint_photoatom->collideAnalogue( adjoint_photon, bank ); FRENSIE_CHECK( !adjoint_photon.isGone() ); FRENSIE_CHECK_FLOATING_EQUALITY( adjoint_photon.getEnergy(), 0.05677765668111111, 1e-15 ); FRENSIE_CHECK_EQUAL( adjoint_photon.getWeight(), 1.0 ); FRENSIE_CHECK_EQUAL( bank.size(), 0 ); // Sample the coherent reaction fake_stream.resize( 6 ); fake_stream[0] = 0.79; fake_stream[1] = 1.00475965594E-03; // sample form factor function squared (y = 1E6 cm) fake_stream[2] = 9.98800000000E-01; // reject the cosine scattering angle form function rejection loop fake_stream[3] = 6.50327467413E-01; // sample form factor function squared (y = 3E7 cm) fake_stream[4] = 5.07800000000E-01; // accept the cosine scattering angle form function rejection loop fake_stream[5] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); adjoint_photon.setEnergy( 4.95936772145E-03 ); adjoint_photon.setDirection( 0.0, 0.0, 1.0 ); adjoint_photon.setWeight( 1.0 ); adjoint_photoatom->collideAnalogue( adjoint_photon, bank ); FRENSIE_CHECK( !adjoint_photon.isGone() ); FRENSIE_CHECK_FLOATING_EQUALITY( adjoint_photon.getEnergy(), 4.95936772145E-03, 1e-15 ); FRENSIE_CHECK_EQUAL( adjoint_photon.getWeight(), 1.0 ); FRENSIE_CHECK_EQUAL( bank.size(), 0 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that a survival biased collision can be modeled FRENSIE_UNIT_TEST( AdjointPhotoatom, collideSurvivalBias ) { // Sample the incoherent reaction std::vector<double> fake_stream( 10 ); fake_stream[0] = 0.78; // choose incoherent scattering fake_stream[1] = 0.15; // branch 1 fake_stream[2] = 0.4721647344828152; // select x = 0.9 fake_stream[3] = 0.49; // accept fake_stream[4] = 0.91; // reject based on scattering function fake_stream[5] = 0.15; // branch 1 fake_stream[6] = 0.4721647344828152; // select x = 0.9 fake_stream[7] = 0.49; // accept fake_stream[8] = 0.909; // accept based on scattering function fake_stream[9] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); MonteCarlo::AdjointPhotonState adjoint_photon( 0 ); adjoint_photon.setEnergy( Utility::PhysicalConstants::electron_rest_mass_energy/10.0 ); adjoint_photon.setDirection( 0.0, 0.0, 1.0 ); adjoint_photon.setWeight( 1.0 ); MonteCarlo::ParticleBank bank; adjoint_photoatom->collideSurvivalBias( adjoint_photon, bank ); FRENSIE_CHECK( !adjoint_photon.isGone() ); FRENSIE_CHECK_FLOATING_EQUALITY( adjoint_photon.getEnergy(), 0.05677765668111111, 1e-15 ); FRENSIE_CHECK_EQUAL( adjoint_photon.getWeight(), 1.0 ); FRENSIE_CHECK_EQUAL( bank.size(), 0 ); // Sample the coherent reaction fake_stream.resize( 6 ); fake_stream[0] = 0.79; fake_stream[1] = 1.00475965594E-03; // sample form factor function squared (y = 1E6 cm) fake_stream[2] = 9.98800000000E-01; // reject the cosine scattering angle form function rejection loop fake_stream[3] = 6.50327467413E-01; // sample form factor function squared (y = 3E7 cm) fake_stream[4] = 5.07800000000E-01; // accept the cosine scattering angle form function rejection loop fake_stream[5] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); adjoint_photon.setEnergy( 4.95936772145E-03 ); adjoint_photon.setDirection( 0.0, 0.0, 1.0 ); adjoint_photon.setWeight( 1.0 ); adjoint_photoatom->collideSurvivalBias( adjoint_photon, bank ); FRENSIE_CHECK( !adjoint_photon.isGone() ); FRENSIE_CHECK_FLOATING_EQUALITY( adjoint_photon.getEnergy(), 4.95936772145E-03, 1e-15 ); FRENSIE_CHECK_EQUAL( adjoint_photon.getWeight(), 1.0 ); FRENSIE_CHECK_EQUAL( bank.size(), 0 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that a line energy collision can be modeled FRENSIE_UNIT_TEST( AdjointPhotoatom, collideAtLineEnergy ) { // Sample the pair production reaction std::vector<double> fake_stream( 4 ); fake_stream[0] = 0.05; // select pair production fake_stream[1] = 0.0; fake_stream[2] = 0.5; fake_stream[3] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); std::unique_ptr<MonteCarlo::AdjointPhotonProbeState> adjoint_photon( new MonteCarlo::AdjointPhotonProbeState( 0 ) ); adjoint_photon->setEnergy( Utility::PhysicalConstants::electron_rest_mass_energy ); adjoint_photon->setDirection( 0.0, 0.0, 1.0 ); adjoint_photon->setWeight( 1.0 ); MonteCarlo::ParticleBank bank; adjoint_photoatom->collideAtLineEnergy( *adjoint_photon, bank ); FRENSIE_CHECK( adjoint_photon->isGone() ); FRENSIE_CHECK_EQUAL( bank.size(), 2 ); FRENSIE_CHECK_FLOATING_EQUALITY( bank.top().getEnergy(), 2*Utility::PhysicalConstants::electron_rest_mass_energy, 1e-15 ); bank.pop(); FRENSIE_CHECK_EQUAL( bank.top().getEnergy(), 20.0 ); FRENSIE_CHECK( bank.top().getWeight() != 1.0 ); bank.pop(); // Sample the triplet production reaction fake_stream[0] = 0.04; // select triplet production fake_stream[1] = 0.0; fake_stream[2] = 0.5; fake_stream[3] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); adjoint_photon.reset( new MonteCarlo::AdjointPhotonProbeState( 0 ) ); adjoint_photon->setEnergy( Utility::PhysicalConstants::electron_rest_mass_energy ); adjoint_photon->setDirection( 0.0, 0.0, 1.0 ); adjoint_photon->setWeight( 1.0 ); adjoint_photoatom->collideAtLineEnergy( *adjoint_photon, bank ); FRENSIE_CHECK( adjoint_photon->isGone() ); FRENSIE_CHECK_EQUAL( bank.size(), 2 ); FRENSIE_CHECK_FLOATING_EQUALITY( bank.top().getEnergy(), 4*Utility::PhysicalConstants::electron_rest_mass_energy, 1e-15 ); bank.pop(); FRENSIE_CHECK_EQUAL( bank.top().getEnergy(), 20.0 ); FRENSIE_CHECK( bank.top().getWeight() != 1.0 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that the atom can be relaxed FRENSIE_UNIT_TEST( AdjointPhotoatom, relaxAtom ) { std::shared_ptr<MonteCarlo::AdjointPhotonState> adjoint_photon( new MonteCarlo::AdjointPhotonState( 0 ) ); adjoint_photon->setEnergy( exp( -1.214969212306E+01 ) ); adjoint_photon->setDirection( 0.0, 0.0, 1.0 ); adjoint_photon->setWeight( 1.0 ); Data::SubshellType vacancy = Data::K_SUBSHELL; MonteCarlo::ParticleBank bank; adjoint_photoatom->relaxAtom( vacancy, *adjoint_photon, bank ); FRENSIE_CHECK_EQUAL( bank.size(), 0 ); } //---------------------------------------------------------------------------// // Custom Setup //---------------------------------------------------------------------------// FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN(); std::string test_native_file_name; FRENSIE_CUSTOM_UNIT_TEST_COMMAND_LINE_OPTIONS() { ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_native_file", test_native_file_name, "", "Test Native file name" ); } FRENSIE_CUSTOM_UNIT_TEST_INIT() { // Create the native data file container Data::AdjointElectronPhotonRelaxationDataContainer data_container( test_native_file_name ); // Create the union energy grid std::shared_ptr<std::vector<double> > energy_grid( new std::vector<double> ); MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createUnionEnergyGrid( data_container, *energy_grid, 20.0 ); // Create the hash based grid searcher std::shared_ptr<const Utility::HashBasedGridSearcher<double> > grid_searcher( new Utility::StandardHashBasedGridSearcher<std::vector<double>,false>( *energy_grid, 100 ) ); // Create the total forward reaction std::shared_ptr<const MonteCarlo::PhotoatomicReaction> total_forward_reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createTotalForwardReaction( data_container, energy_grid, grid_searcher, MonteCarlo::WH_INCOHERENT_ADJOINT_MODEL, total_forward_reaction ); // Create the scattering reactions MonteCarlo::AdjointPhotoatom::ConstReactionMap scattering_reactions; std::shared_ptr<std::vector<double> > critical_line_energies( new std::vector<double>(2) ); (*critical_line_energies)[0] = Utility::PhysicalConstants::electron_rest_mass_energy; (*critical_line_energies)[1] = 20.0; { std::vector<std::shared_ptr<const MonteCarlo::AdjointPhotoatomicReaction> > incoherent_reactions; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createIncoherentReactions( data_container, energy_grid, grid_searcher, incoherent_reactions, MonteCarlo::WH_INCOHERENT_ADJOINT_MODEL, MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING, critical_line_energies ); scattering_reactions[incoherent_reactions[0]->getReactionType()] = incoherent_reactions[0]; } { std::shared_ptr<const MonteCarlo::AdjointPhotoatomicReaction> coherent_reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createCoherentReaction( data_container, energy_grid, grid_searcher, coherent_reaction ); scattering_reactions[coherent_reaction->getReactionType()] = coherent_reaction; } // Create the line energy reactions MonteCarlo::AdjointPhotoatom::ConstLineEnergyReactionMap line_energy_reactions; { MonteCarlo::AdjointPhotoatom::ConstReactionMap& me_line_energy_reactions = line_energy_reactions[Utility::PhysicalConstants::electron_rest_mass_energy]; std::shared_ptr<const MonteCarlo::LineEnergyAdjointPhotoatomicReaction> reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createPairProductionReaction( data_container, energy_grid, grid_searcher, reaction, critical_line_energies ); me_line_energy_reactions[reaction->getReactionType()] = reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createTripletProductionReaction( data_container, energy_grid, grid_searcher, reaction, critical_line_energies ); me_line_energy_reactions[reaction->getReactionType()] = reaction; } // Construct the adjoint photoatom adjoint_photoatom.reset( new MonteCarlo::AdjointPhotoatom( test_native_file_name, data_container.getAtomicNumber(), data_container.getAtomicNumber(), energy_grid, grid_searcher, critical_line_energies, total_forward_reaction, scattering_reactions, MonteCarlo::AdjointPhotoatom::ConstReactionMap(), line_energy_reactions ) ); // Initialize the random number generator Utility::RandomNumberGenerator::createStreams(); } FRENSIE_CUSTOM_UNIT_TEST_SETUP_END(); //---------------------------------------------------------------------------// // end tstAdjointPhotoatom.cpp //---------------------------------------------------------------------------//
39.016148
128
0.650752
[ "vector" ]
08a9a1ed04bef4d43c06cf0be496c0574ef98260
12,303
cc
C++
mars-master4/mars/comm/socket/local_ipstack.cc
zhudong10/MarsLogFrame
1c5d0161a4dbf06f60ef6910256e8950a0e2d75e
[ "MIT" ]
17
2017-09-06T01:30:26.000Z
2022-02-10T09:43:35.000Z
mars-master4/mars/comm/socket/local_ipstack.cc
zhudong10/MarsLogFrame
1c5d0161a4dbf06f60ef6910256e8950a0e2d75e
[ "MIT" ]
null
null
null
mars-master4/mars/comm/socket/local_ipstack.cc
zhudong10/MarsLogFrame
1c5d0161a4dbf06f60ef6910256e8950a0e2d75e
[ "MIT" ]
5
2018-02-05T08:48:55.000Z
2021-02-08T08:04:27.000Z
// Tencent is pleased to support the open source community by making Mars available. // Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. // Licensed under the MIT License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://opensource.org/licenses/MIT // 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. // // IPv6_only.cpp // comm // // Created by yerungui on 16/1/14. // #include "local_ipstack.h" #include <vector> #include "xlogger/xlogger.h" #if (defined(__APPLE__) || defined(ANDROID)) #include <strings.h> #include "socket/unix_socket.h" #include "network/getifaddrs.h" #if defined(__APPLE__) #include "network/getgateway.h" #include "network/getdnssvraddrs.h" #include "platform_comm.h" #endif typedef union sockaddr_union { struct sockaddr generic; struct sockaddr_in in; struct sockaddr_in6 in6; } sockaddr_union; /* * Connect a UDP socket to a given unicast address. This will cause no network * traffic, but will fail fast if the system has no or limited reachability to * the destination (e.g., no IPv4 address, no IPv6 default route, ...). */ static const unsigned int kMaxLoopCount = 10; static int _test_connect(int pf, struct sockaddr *addr, size_t addrlen, struct sockaddr* local_addr, socklen_t local_addr_len) { int s = socket(pf, SOCK_DGRAM, IPPROTO_UDP); if (s < 0) return 0; int ret; unsigned int loop_count = 0; do { ret = connect(s, addr, addrlen); } while (ret < 0 && errno == EINTR && loop_count++<kMaxLoopCount); if (loop_count>=kMaxLoopCount) { xerror2(TSF"connect error. loop_count = %_", loop_count); } int success = (ret == 0); if (success) { memset(local_addr, 0, sizeof(struct sockaddr_storage)); getsockname(s, local_addr, &local_addr_len); } loop_count = 0; do { ret = close(s); } while (ret < 0 && errno == EINTR && loop_count++<kMaxLoopCount); if (loop_count>=kMaxLoopCount) { xerror2(TSF"close error. loop_count = %_", loop_count); } return success; } /* * The following functions determine whether IPv4 or IPv6 connectivity is * available in order to implement AI_ADDRCONFIG. * * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is * available, but whether addresses of the specified family are "configured * on the local system". However, bionic doesn't currently support getifaddrs, * so checking for connectivity is the next best thing. */ static int _have_ipv6(struct sockaddr* local_addr, socklen_t local_addr_len) { #ifdef __APPLE__ static const struct sockaddr_in6 sin6_test = { .sin6_len = sizeof(sockaddr_in6), .sin6_family = AF_INET6, .sin6_port = 80, .sin6_flowinfo = 0, .sin6_scope_id = 0, .sin6_addr.s6_addr = { // 2000:: 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; sockaddr_union addr = { .in6 = sin6_test }; #else static struct sockaddr_in6 sin6_test; sin6_test.sin6_family = AF_INET6; sin6_test.sin6_port = 80; sin6_test.sin6_flowinfo = 0; sin6_test.sin6_scope_id = 0; bzero(sin6_test.sin6_addr.s6_addr, sizeof(sin6_test.sin6_addr.s6_addr)); sin6_test.sin6_addr.s6_addr[0] = 0x20; sockaddr_union addr = { in6:sin6_test }; #endif return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6), local_addr, local_addr_len); } static int _have_ipv4(struct sockaddr* local_addr, socklen_t local_addr_len) { #ifdef __APPLE__ static const struct sockaddr_in sin_test = { .sin_len = sizeof(sockaddr_in), .sin_family = AF_INET, .sin_port = 80, .sin_addr.s_addr = htonl(0x08080808L), // 8.8.8.8 }; sockaddr_union addr = { .in = sin_test }; #else static struct sockaddr_in sin_test = { sin_family:AF_INET, sin_port:80, }; sin_test.sin_addr.s_addr = htonl(0x08080808L); // 8.8.8.8 sockaddr_union addr = { in:sin_test }; #endif return _test_connect(PF_INET, &addr.generic, sizeof(addr.in), local_addr, local_addr_len); } bool two_addrs_on_one_interface(sockaddr* first_addr, sockaddr* second_addr) { char ip1[64] = {0}; char ip2[64] = {0}; std::string ip1_ifname, ip2_ifname; if (AF_INET == first_addr->sa_family) { socket_inet_ntop(AF_INET, &(((sockaddr_in*)first_addr)->sin_addr), ip1, sizeof(ip1)); } else if (AF_INET6 == first_addr->sa_family) { socket_inet_ntop(AF_INET6, &(((sockaddr_in6*)first_addr)->sin6_addr), ip1, sizeof(ip1)); } if (AF_INET == second_addr->sa_family) { socket_inet_ntop(AF_INET, &(((sockaddr_in*)second_addr)->sin_addr), ip2, sizeof(ip2)); } else if (AF_INET6 == second_addr->sa_family) { socket_inet_ntop(AF_INET6, &(((sockaddr_in6*)second_addr)->sin6_addr), ip2, sizeof(ip2)); } std::vector<ifaddrinfo_ip_t> v4_addrs, v6_addrs; if (getifaddrs_ipv4_filter(v4_addrs, 0)) { for (size_t i=0; i<v4_addrs.size(); ++i) { if (!ip1_ifname.empty() && !ip2_ifname.empty()) break; if (0==strncmp(ip1, v4_addrs[i].ip, sizeof(ip1))) { ip1_ifname = v4_addrs[i].ifa_name; } if (0==strncmp(ip2, v4_addrs[i].ip, sizeof(ip2))) { ip2_ifname = v4_addrs[i].ifa_name; } } } if (getifaddrs_ipv6_filter(v6_addrs, 0)) { for (size_t i=0; i<v6_addrs.size(); ++i) { if (!ip1_ifname.empty() && !ip2_ifname.empty()) break; if (0==strncmp(ip1, v6_addrs[i].ip, sizeof(ip1))) { ip1_ifname = v6_addrs[i].ifa_name; } if (0==strncmp(ip2, v6_addrs[i].ip, sizeof(ip2))) { ip2_ifname = v6_addrs[i].ifa_name; } } } if (!ip1_ifname.empty() && !ip2_ifname.empty() && 0==ip1_ifname.compare(ip2_ifname)) return true; return false; } TLocalIPStack __local_ipstack_detect(std::string& _log) { XMessage detail; detail("local_ipstack_detect "); #ifdef __APPLE__ in6_addr addr6_gateway = {0}; if (0 != getdefaultgateway6(&addr6_gateway)){ detail("getdefaultgateway6 fail"); return ELocalIPStack_IPv4; } if (IN6_IS_ADDR_UNSPECIFIED(&addr6_gateway)) { detail("getdefaultgateway6 IN6_IS_ADDR_UNSPECIFIED"); return ELocalIPStack_IPv4; } in_addr addr_gateway = {0}; if (0 != getdefaultgateway(&addr_gateway)) { detail("getdefaultgateway fail"); return ELocalIPStack_IPv6; } if (INADDR_NONE == addr_gateway.s_addr || INADDR_ANY == addr_gateway.s_addr ) { detail("getdefaultgateway INADDR_NONE or INADDR_ANY %d", addr_gateway.s_addr); return ELocalIPStack_IPv6; } #endif sockaddr_storage v4_addr = {0}; sockaddr_storage v6_addr = {0}; int have_ipv4 = _have_ipv4((sockaddr*)&v4_addr, sizeof(v4_addr)); int have_ipv6 = _have_ipv6((sockaddr*)&v6_addr, sizeof(v6_addr)); int local_stack = 0; if (have_ipv4) { local_stack |= ELocalIPStack_IPv4; } if (have_ipv6) { local_stack |= ELocalIPStack_IPv6; } detail("have_ipv4:%d have_ipv6:%d \n", have_ipv4, have_ipv6); #ifdef __APPLE__ if (ELocalIPStack_Dual != local_stack) { detail("ELocalIPStack_Dual != local_stack"); return (TLocalIPStack)local_stack; } // if (two_addrs_on_one_interface((sockaddr*)&v4_addr, (sockaddr*)&v6_addr)) { // detail("two_addrs_on_one_interface: true.v4_addr=%s, v6_addr=%_", socket_address(v4_addr).ip(), ocket_address(v6_addr).ipv6()); // return ELocalIPStack_Dual; // } if (publiccomponent_GetSystemVersion() < 9.0f) { int dns_ip_stack = 0; std::vector<socket_address> dnssvraddrs; getdnssvraddrs(dnssvraddrs); for (size_t i = 0; i < dnssvraddrs.size(); ++i) { if (AF_INET == dnssvraddrs[i].address().sa_family) { dns_ip_stack |= ELocalIPStack_IPv4; } if (AF_INET6 == dnssvraddrs[i].address().sa_family) { dns_ip_stack |= ELocalIPStack_IPv6; } } detail("local_stack:%d dns_ip_stack:%d", local_stack, dns_ip_stack); return (TLocalIPStack)(ELocalIPStack_None==dns_ip_stack? local_stack:dns_ip_stack); } else { xassert2(ELocalIPStack_Dual == local_stack); return (TLocalIPStack)local_stack; } #else return (TLocalIPStack)local_stack; #endif } TLocalIPStack local_ipstack_detect() { #ifdef ANDROID return ELocalIPStack_IPv4; #endif std::string log; return __local_ipstack_detect(log); } static void __local_info(std::string& _log); TLocalIPStack local_ipstack_detect_log(std::string& _log) { __local_info(_log); return __local_ipstack_detect(_log); } #include "network/getifaddrs.h" #include "network/getgateway.h" #include "network/getdnssvraddrs.h" static void __local_info(std::string& _log) { XMessage detail_net_info; in6_addr addr6_gateway; memset(&addr6_gateway, 0, sizeof(addr6_gateway)); if (0 == getdefaultgateway6(&addr6_gateway)) { detail_net_info << "defaultgateway6:" << socket_address(addr6_gateway).ipv6() << "\n"; } else { detail_net_info << "defaultgateway6:failed \n"; } in_addr addr_gateway; memset(&addr_gateway, 0, sizeof(addr_gateway)); if (0 == getdefaultgateway(&addr_gateway)) { detail_net_info << "defaultgateway:" << socket_address(addr_gateway).ip() << "\n"; } else { detail_net_info << "defaultgateway: failed \n"; } std::vector<socket_address> dnssvraddrs; getdnssvraddrs(dnssvraddrs); if (!dnssvraddrs.empty()) { for (size_t i = 0; i < dnssvraddrs.size(); ++i) { if (AF_INET == dnssvraddrs[i].address().sa_family) { detail_net_info << "dns server" << i << ":AF_INET, " << dnssvraddrs[i].ip() << "\n"; } if (AF_INET6 == dnssvraddrs[i].address().sa_family) { detail_net_info << "dns server" << i << ":AF_INET6, " << dnssvraddrs[i].ipv6() << "\n"; } } } else { detail_net_info << "dns server: empty \n"; } std::vector<ifaddrinfo_ip_t> v4_addrs; if (getifaddrs_ipv4_filter(v4_addrs, 0)) { for (size_t i = 0; i < v4_addrs.size(); ++i) { detail_net_info << "interface name:"<<v4_addrs[i].ifa_name << ", " << (v4_addrs[i].ifa_family==AF_INET?"AF_INET":"XX_INET") << ", ip:" << v4_addrs[i].ip << "\n"; } } else { detail_net_info << "getifaddrs_ipv4_filter:false \n"; } std::vector<ifaddrinfo_ip_t> v6_addrs; if (getifaddrs_ipv6_filter(v6_addrs, 0)) { for (size_t i = 0; i < v6_addrs.size(); ++i) { detail_net_info << "interface name:"<<v6_addrs[i].ifa_name << ", " << (v6_addrs[i].ifa_family==AF_INET6?"AF_INET6":"XX_INET") << ", ip:" << v6_addrs[i].ip << "\n"; } } else { detail_net_info << "getifaddrs_ipv6_filter:false \n"; } sockaddr_storage v4_addr = {0}; sockaddr_storage v6_addr = {0}; int have_ipv4 = _have_ipv4((sockaddr*)&v4_addr, sizeof(v4_addr)); int have_ipv6 = _have_ipv6((sockaddr*)&v6_addr, sizeof(v6_addr)); detail_net_info("have_ipv4:%d have_ipv6:%d", have_ipv4, have_ipv6); _log += detail_net_info.Message(); } #else #include <string> TLocalIPStack local_ipstack_detect() { return ELocalIPStack_IPv4; } TLocalIPStack local_ipstack_detect_log(std::string& _log) { _log = "no implement"; return local_ipstack_detect(); } #endif //__APPLE__ //TIPNetworkType IPNetworkTypeDetect_Gateway() { // in6_addr addr6_gateway = {0}; // if (0 != getdefaultgateway6(&addr6_gateway)) // return EIPv4; // // if (IN6_IS_ADDR_UNSPECIFIED(&addr6_gateway)) // return EIPv4; // // in_addr addr_gateway = {0}; // if (0 != getdefaultgateway(&addr_gateway)) // return EIPv6; // // if (INADDR_NONE == addr_gateway.s_addr || INADDR_ANY == addr_gateway.s_addr ) // return EIPv6; // // return EIPv46; //}
35.455331
137
0.653337
[ "vector" ]
08ab325eac3f2bdfee85e9c192c79862b1c92a20
701
hh
C++
transformations/linalg/Transpose.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
5
2019-10-14T01:06:57.000Z
2021-02-02T16:33:06.000Z
transformations/linalg/Transpose.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
transformations/linalg/Transpose.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
#include "GNAObject.hh" class Transpose: public GNAObject, public TransformationBind<Transpose> { public: Transpose() { transformation_("transpose") .input("mat") .output("T") .types([](Transpose* obj, TypesFunctionArgs& fargs){ auto input_shape = fargs.args[0].shape; fargs.rets[0] = DataType().points().shape({input_shape.rbegin(), input_shape.rend()}); }) .func([](Transpose* obj, FunctionArgs& fargs){ fargs.rets[0].mat = fargs.args[0].mat.transpose(); }); } };
35.05
110
0.473609
[ "shape" ]
08b28277578ac0e9d21329c065a75eb21e5b3dec
28,230
cpp
C++
test/quaternions/QuaternionTest.cpp
mcx/kindr
761303a6d82780b3e476473ba66a0c2abc623179
[ "BSD-3-Clause" ]
289
2018-08-06T15:57:18.000Z
2022-03-31T06:52:43.000Z
test/quaternions/QuaternionTest.cpp
mcx/kindr
761303a6d82780b3e476473ba66a0c2abc623179
[ "BSD-3-Clause" ]
15
2018-08-22T09:58:25.000Z
2021-03-26T06:32:14.000Z
test/quaternions/QuaternionTest.cpp
mcx/kindr
761303a6d82780b3e476473ba66a0c2abc623179
[ "BSD-3-Clause" ]
106
2018-08-24T08:39:49.000Z
2022-02-28T15:17:37.000Z
/* * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm * 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 Autonomous Systems Lab, ETH Zurich 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 Christian Gehring, Hannes Sommer, Paul Furgale, * Remo Diethelm 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 <iostream> #include <gtest/gtest.h> #include <kindr/common/assert_macros_eigen.hpp> #include <kindr/common/gtest_eigen.hpp> #include <kindr/quaternions/Quaternion.hpp> namespace quat = kindr; typedef ::testing::Types< quat::QuaternionD, quat::QuaternionF > QuaternionTypes; typedef ::testing::Types< quat::UnitQuaternionD, quat::UnitQuaternionF > UnitQuaternionTypes; typedef ::testing::Types< float, double > PrimTypes; typedef ::testing::Types< std::pair<quat::QuaternionD, quat::QuaternionD>, std::pair<quat::QuaternionD, quat::QuaternionF>, std::pair<quat::QuaternionF, quat::QuaternionF>, std::pair<quat::UnitQuaternionD, quat::UnitQuaternionF>, std::pair<quat::UnitQuaternionD, quat::QuaternionD>, std::pair<quat::UnitQuaternionD, quat::UnitQuaternionD>, std::pair<quat::UnitQuaternionF, quat::QuaternionF>, std::pair<quat::UnitQuaternionD, quat::QuaternionF>, std::pair<quat::UnitQuaternionF, quat::QuaternionD>, std::pair<quat::UnitQuaternionF, quat::UnitQuaternionF> > TypePairs; template <typename QuaternionImplementationPrimeTypePair> struct QuaternionsPairsTest : public ::testing::Test{ typedef typename QuaternionImplementationPrimeTypePair::first_type QuaternionFirstPrimeType; typedef typename QuaternionImplementationPrimeTypePair::second_type QuaternionSecondPrimeType; const QuaternionFirstPrimeType quat1 = QuaternionFirstPrimeType(0.0,0.36,0.48,0.8); const QuaternionSecondPrimeType quat2 = QuaternionSecondPrimeType(0.0,0.36,0.48,0.8); }; template <typename PrimType> struct QuaternionsPrimTypeTest : public ::testing::Test{ typedef quat::Quaternion<PrimType> Quaternion; typedef quat::UnitQuaternion<PrimType> UnitQuaternion; const Quaternion quat = Quaternion(1.0,2.0,3.0,4.0); const UnitQuaternion uquat = UnitQuaternion(0.0,0.36,0.48,0.8); }; template <typename QuaternionImplementation> struct QuaternionsSingleTest : public ::testing::Test{ typedef QuaternionImplementation Quaternion; typedef typename Quaternion::Scalar QuaternionScalar; typedef Eigen::Quaternion<QuaternionScalar> EigenQuat; const EigenQuat eigenQuat1 = EigenQuat(1.0,2.0,3.0,4.0); const EigenQuat eigenQuat2 = EigenQuat(1.23,4.56,7.89,0.12); const EigenQuat eigenQuat1Conj = EigenQuat(1.0,-2.0,-3.0,-4.0); const EigenQuat eigenQuatIdentity = EigenQuat(1.0,0.0,0.0,0.0); const Quaternion quat1 = Quaternion(eigenQuat1); const Quaternion quat2 = Quaternion(eigenQuat2); const Quaternion quatIdentity = Quaternion(eigenQuatIdentity); const QuaternionScalar norm1 = 5.477225575051661; const QuaternionScalar norm2 = 9.196357974763703; }; template <typename UnitQuaternionImplementation> struct UnitQuaternionsSingleTest : public ::testing::Test{ typedef UnitQuaternionImplementation UnitQuaternion; typedef typename UnitQuaternion::Scalar UnitQuaternionScalar; typedef Eigen::Quaternion<UnitQuaternionScalar> EigenQuat; const EigenQuat eigenQuat1 = EigenQuat(0.0,0.36,0.48,0.8); const EigenQuat eigenQuat2 = EigenQuat(-0.48,-0.6,0.0,0.64); const EigenQuat eigenQuat1Conj = EigenQuat(0.0,-0.36,-0.48,-0.8); const EigenQuat eigenQuatIdentity = EigenQuat(1.0,0.0,0.0,0.0); const UnitQuaternion quat1 = UnitQuaternion(eigenQuat1); const UnitQuaternion quat2 = UnitQuaternion(eigenQuat2); const UnitQuaternion quatIdentity = UnitQuaternion(eigenQuatIdentity); }; TYPED_TEST_CASE(QuaternionsSingleTest, QuaternionTypes); TYPED_TEST_CASE(UnitQuaternionsSingleTest, UnitQuaternionTypes); TYPED_TEST_CASE(QuaternionsPairsTest, TypePairs); //QuaternionsPairsTest, TypePairs TYPED_TEST_CASE(QuaternionsPrimTypeTest, PrimTypes); // Testing of Quaternion Constructor and Access Operator TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleConstructor) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; // Default constructor of quaternion needs to set all coefficients to zero Quaternion testQuat; ASSERT_EQ(testQuat.w(),QuaternionScalar(0)); ASSERT_EQ(testQuat.x(),QuaternionScalar(0)); ASSERT_EQ(testQuat.y(),QuaternionScalar(0)); ASSERT_EQ(testQuat.z(),QuaternionScalar(0)); // Constructor of quaternion using 4 scalars Quaternion testQuat1(this->eigenQuat1.w(), this->eigenQuat1.x(), this->eigenQuat1.y(), this->eigenQuat1.z()); ASSERT_EQ(testQuat1.w(),this->eigenQuat1.w()); ASSERT_EQ(testQuat1.x(),this->eigenQuat1.x()); ASSERT_EQ(testQuat1.y(),this->eigenQuat1.y()); ASSERT_EQ(testQuat1.z(),this->eigenQuat1.z()); // Constructor of quaternion using real and imaginary part Quaternion testQuat2(this->eigenQuat1.w(),typename Quaternion::Imaginary(this->eigenQuat1.x(), this->eigenQuat1.y(), this->eigenQuat1.z())); ASSERT_EQ(testQuat2.w(),this->eigenQuat1.w()); ASSERT_EQ(testQuat2.x(),this->eigenQuat1.x()); ASSERT_EQ(testQuat2.y(),this->eigenQuat1.y()); ASSERT_EQ(testQuat2.z(),this->eigenQuat1.z()); ASSERT_EQ(testQuat2.real(),this->eigenQuat1.w()); ASSERT_EQ(testQuat2.imaginary()(0),this->eigenQuat1.x()); ASSERT_EQ(testQuat2.imaginary()(1),this->eigenQuat1.y()); ASSERT_EQ(testQuat2.imaginary()(2),this->eigenQuat1.z()); // Constructor of quaternion using eigen quaternion Quaternion testQuat3(this->eigenQuat1); ASSERT_EQ(testQuat3.w(),this->eigenQuat1.w()); ASSERT_EQ(testQuat3.x(),this->eigenQuat1.x()); ASSERT_EQ(testQuat3.y(),this->eigenQuat1.y()); ASSERT_EQ(testQuat3.z(),this->eigenQuat1.z()); } // Testing of Quaternion multiplication TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleMultiplication) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; Quaternion testQuat; // Check multiplication of two generic quaternions and compare with eigen results Quaternion quat12 = this->quat1*this->quat2; EigenQuat eigenQuat12 = this->eigenQuat1*this->eigenQuat2; ASSERT_EQ(quat12.w(),eigenQuat12.w()); ASSERT_EQ(quat12.x(),eigenQuat12.x()); ASSERT_EQ(quat12.y(),eigenQuat12.y()); ASSERT_EQ(quat12.z(),eigenQuat12.z()); // Check result of multiplication of a generic quaternion with identity testQuat = this->quat1*this->quatIdentity; ASSERT_EQ(testQuat.w(),this->quat1.w()); ASSERT_EQ(testQuat.x(),this->quat1.x()); ASSERT_EQ(testQuat.y(),this->quat1.y()); ASSERT_EQ(testQuat.z(),this->quat1.z()); testQuat = this->quatIdentity*this->quat1; ASSERT_EQ(testQuat.w(),this->quat1.w()); ASSERT_EQ(testQuat.x(),this->quat1.x()); ASSERT_EQ(testQuat.y(),this->quat1.y()); ASSERT_EQ(testQuat.z(),this->quat1.z()); } // Testing of Quaternion conjugation TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleConjugation) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; Quaternion testQuat1; Quaternion testQuat2; // Check conjugation testQuat1 = this->quat1; testQuat2 = testQuat1.conjugated(); ASSERT_NEAR(testQuat1.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->quat1.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->eigenQuat1Conj.z(),1e-6); testQuat2 = testQuat1.conjugate(); ASSERT_NEAR(testQuat1.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->eigenQuat1Conj.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->eigenQuat1Conj.z(),1e-6); } // Testing of Quaternion inversion TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleInversion) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; Quaternion testQuat; Quaternion testQuat1; Quaternion testQuat2; // Check inversion (the inverse is unique and the mutliplication of a quaternion with its inverse gives identity) testQuat1 = this->quat1.inverted(); testQuat = testQuat1*this->quat1; ASSERT_NEAR(testQuat.w(),this->quatIdentity.w(),1e-6); ASSERT_NEAR(testQuat.x(),this->quatIdentity.x(),1e-6); ASSERT_NEAR(testQuat.y(),this->quatIdentity.y(),1e-6); ASSERT_NEAR(testQuat.z(),this->quatIdentity.z(),1e-6); testQuat2 = testQuat1.invert(); ASSERT_NEAR(testQuat1.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->quat1.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->quat1.z(),1e-6); } // Testing of Quaternion comparison (equality) TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleEqualityComparison) { typedef typename TestFixture::Quaternion Quaternion; Quaternion testQuat; // Check equality comparison testQuat = this->quat1; ASSERT_EQ(testQuat==this->quat1,true); ASSERT_EQ(testQuat==this->quat2,false); } // Testing of Quaternion comparison (inequality) TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleInequalityComparison) { typedef typename TestFixture::Quaternion Quaternion; Quaternion testQuat; // Check inequality comparison testQuat = this->quat1; ASSERT_EQ(testQuat!=this->quat1,false); ASSERT_EQ(testQuat!=this->quat2,true); } // Testing of Norm and Normalization TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleNormalization) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; Quaternion testQuat1; Quaternion testQuat2; QuaternionScalar scalar; // Check norm and normalization testQuat1 = this->quat1; scalar = testQuat1.norm(); ASSERT_NEAR(scalar,this->norm1,1e-6); testQuat2 = testQuat1.normalized(); ASSERT_NEAR(testQuat1.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->quat1.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->quat1.w()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.x(),this->quat1.x()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.y(),this->quat1.y()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.z(),this->quat1.z()/this->norm1,1e-6); testQuat2 = testQuat1.normalize(); ASSERT_NEAR(testQuat1.w(),this->quat1.w()/this->norm1,1e-6); ASSERT_NEAR(testQuat1.x(),this->quat1.x()/this->norm1,1e-6); ASSERT_NEAR(testQuat1.y(),this->quat1.y()/this->norm1,1e-6); ASSERT_NEAR(testQuat1.z(),this->quat1.z()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.w(),this->quat1.w()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.x(),this->quat1.x()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.y(),this->quat1.y()/this->norm1,1e-6); ASSERT_NEAR(testQuat2.z(),this->quat1.z()/this->norm1,1e-6); } // Testing of casting to implementation TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleImplementationCast) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; EigenQuat testEigenQuat; // Check casting to implementation testEigenQuat = this->quat1.toImplementation(); ASSERT_EQ(testEigenQuat.w(),this->eigenQuat1.w()); ASSERT_EQ(testEigenQuat.x(),this->eigenQuat1.x()); ASSERT_EQ(testEigenQuat.y(),this->eigenQuat1.y()); ASSERT_EQ(testEigenQuat.z(),this->eigenQuat1.z()); } // Testing vector() and constructor from vector TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleVectorAndVectorConstructor) { typedef typename TestFixture::Quaternion Quaternion; typedef typename TestFixture::QuaternionScalar QuaternionScalar; typedef Eigen::Matrix<QuaternionScalar, 4, 1> Vector4; Quaternion quat = this->quat1; // vector() Vector4 vector = quat.vector(); ASSERT_NEAR(quat.w(),vector(0), 1e-3); ASSERT_NEAR(quat.x(),vector(1), 1e-3); ASSERT_NEAR(quat.y(),vector(2), 1e-3); ASSERT_NEAR(quat.z(),vector(3), 1e-3); // constructor from vector Quaternion quatFromVector(vector); ASSERT_NEAR(quat.w(),quatFromVector.w(), 1e-3); ASSERT_NEAR(quat.x(),quatFromVector.x(), 1e-3); ASSERT_NEAR(quat.y(),quatFromVector.y(), 1e-3); ASSERT_NEAR(quat.z(),quatFromVector.z(), 1e-3); } // Testing of special matrices TYPED_TEST (QuaternionsSingleTest, testQuaternionSingleSpecialMatrices) { typedef typename TestFixture::Quaternion Quaternion; Quaternion quat1 = this->quat1; Quaternion quat2 = this->quat2; // Qleft Quaternion concatenation1 = quat1 * quat2; Quaternion concatenation2(quat1.getQuaternionMatrix() * quat2.vector()); ASSERT_NEAR(concatenation1.w(),concatenation2.w(), 1e-3); ASSERT_NEAR(concatenation1.x(),concatenation2.x(), 1e-3); ASSERT_NEAR(concatenation1.y(),concatenation2.y(), 1e-3); ASSERT_NEAR(concatenation1.z(),concatenation2.z(), 1e-3); // Qright Quaternion concatenation3 = quat1 * quat2; Quaternion concatenation4(quat2.getConjugateQuaternionMatrix() * quat1.vector()); ASSERT_NEAR(concatenation3.w(),concatenation4.w(), 1e-3); ASSERT_NEAR(concatenation3.x(),concatenation4.x(), 1e-3); ASSERT_NEAR(concatenation3.y(),concatenation4.y(), 1e-3); ASSERT_NEAR(concatenation3.z(),concatenation4.z(), 1e-3); } // Test simple casting (()-operator) between type and non-unit and unit quaternions TYPED_TEST (QuaternionsPairsTest, testQuaternionPrimeTypeCasting ) { typedef typename TestFixture::QuaternionFirstPrimeType QuaternionFirstPrimeType; typedef typename TestFixture::QuaternionSecondPrimeType QuaternionSecondPrimeType; QuaternionFirstPrimeType testQuatFirst; QuaternionSecondPrimeType testQuatSecond; // Use ()-operator to cast between different quaternions (float and double primetype, unit and non-unit) // Throws an error if a non-unit quaternion is cast to a unit quaternion // Only tested for unit-quaternion data testQuatFirst(this->quat2); ASSERT_NEAR(testQuatFirst.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuatFirst.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuatFirst.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuatFirst.z(),this->quat1.z(),1e-6); testQuatSecond(this->quat1); ASSERT_NEAR(testQuatSecond.w(),this->quat2.w(),1e-6); ASSERT_NEAR(testQuatSecond.x(),this->quat2.x(),1e-6); ASSERT_NEAR(testQuatSecond.y(),this->quat2.y(),1e-6); ASSERT_NEAR(testQuatSecond.z(),this->quat2.z(),1e-6); } // Test simple casting (=operator) between non-unit and unit quaternions (only unit to non-unit, no primetype casting) TYPED_TEST (QuaternionsPrimTypeTest, testQuaternionAssignmentCasting ) { typename TestFixture::Quaternion testQuat; typename TestFixture::UnitQuaternion testUnitQuat; // Use =operator to cast between different quaternions (must be same primetype, unit and non-unit) testQuat = this->quat; ASSERT_EQ(testQuat.w(),this->quat.w()); ASSERT_EQ(testQuat.x(),this->quat.x()); ASSERT_EQ(testQuat.y(),this->quat.y()); ASSERT_EQ(testQuat.z(),this->quat.z()); testQuat = this->uquat; ASSERT_EQ(testQuat.w(),this->uquat.w()); ASSERT_EQ(testQuat.x(),this->uquat.x()); ASSERT_EQ(testQuat.y(),this->uquat.y()); ASSERT_EQ(testQuat.z(),this->uquat.z()); testUnitQuat = this->uquat; ASSERT_EQ(testUnitQuat.w(),this->uquat.w()); ASSERT_EQ(testUnitQuat.x(),this->uquat.x()); ASSERT_EQ(testUnitQuat.y(),this->uquat.y()); ASSERT_EQ(testUnitQuat.z(),this->uquat.z()); } // Test toUnitquaternion explicit casting TYPED_TEST (QuaternionsPrimTypeTest, testQuaternionToUnitQuaternion ) { typename TestFixture::Quaternion testQuat; typename TestFixture::UnitQuaternion testUnitQuat; // Use toUnitQuaternion method in order normalize and cast a Quaternion to a unit Quaternion testUnitQuat = this->quat.toUnitQuaternion(); // w is 1.0 ASSERT_NEAR(testUnitQuat.norm(),1.0,1e-6); ASSERT_NEAR(testUnitQuat.x()/testUnitQuat.w(),this->quat.x(),1e-6); ASSERT_NEAR(testUnitQuat.y()/testUnitQuat.w(),this->quat.y(),1e-6); ASSERT_NEAR(testUnitQuat.z()/testUnitQuat.w(),this->quat.z(),1e-6); } // Testing of UnitQuaternion Constructor and Access Operator TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleConstructor) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; // Default constructor of quaternion needs to set all coefficients to zero UnitQuaternion testQuat; ASSERT_EQ(testQuat.w(),UnitQuaternionScalar(1)); ASSERT_EQ(testQuat.x(),UnitQuaternionScalar(0)); ASSERT_EQ(testQuat.y(),UnitQuaternionScalar(0)); ASSERT_EQ(testQuat.z(),UnitQuaternionScalar(0)); // Constructor of quaternion using 4 scalars UnitQuaternion testQuat1(this->eigenQuat1.w(), this->eigenQuat1.x(), this->eigenQuat1.y(), this->eigenQuat1.z()); ASSERT_EQ(testQuat1.w(),this->eigenQuat1.w()); ASSERT_EQ(testQuat1.x(),this->eigenQuat1.x()); ASSERT_EQ(testQuat1.y(),this->eigenQuat1.y()); ASSERT_EQ(testQuat1.z(),this->eigenQuat1.z()); // Constructor of quaternion using real and imaginary part UnitQuaternion testQuat2(this->eigenQuat1.w(),typename UnitQuaternion::Imaginary(this->eigenQuat1.x(), this->eigenQuat1.y(), this->eigenQuat1.z())); ASSERT_EQ(testQuat2.w(),this->eigenQuat1.w()); ASSERT_EQ(testQuat2.x(),this->eigenQuat1.x()); ASSERT_EQ(testQuat2.y(),this->eigenQuat1.y()); ASSERT_EQ(testQuat2.z(),this->eigenQuat1.z()); ASSERT_EQ(testQuat2.real(),this->eigenQuat1.w()); ASSERT_EQ(testQuat2.imaginary()(0),this->eigenQuat1.x()); ASSERT_EQ(testQuat2.imaginary()(1),this->eigenQuat1.y()); ASSERT_EQ(testQuat2.imaginary()(2),this->eigenQuat1.z()); // Constructor of quaternion using eigen quaternion UnitQuaternion testQuat3(this->eigenQuat1); ASSERT_EQ(testQuat3.w(),this->eigenQuat1.w()); ASSERT_EQ(testQuat3.x(),this->eigenQuat1.x()); ASSERT_EQ(testQuat3.y(),this->eigenQuat1.y()); ASSERT_EQ(testQuat3.z(),this->eigenQuat1.z()); } // Testing of UnitQuaternion multiplication TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleMultiplication) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; UnitQuaternion testQuat; // Check multiplication of two generic quaternions and compare with eigen results UnitQuaternion quat12 = this->quat1*this->quat2; EigenQuat eigenQuat12 = this->eigenQuat1*this->eigenQuat2; ASSERT_EQ(quat12.w(),eigenQuat12.w()); ASSERT_EQ(quat12.x(),eigenQuat12.x()); ASSERT_EQ(quat12.y(),eigenQuat12.y()); ASSERT_EQ(quat12.z(),eigenQuat12.z()); // Check result of multiplication of a generic quaternion with identity testQuat = this->quat1*this->quatIdentity; ASSERT_EQ(testQuat.w(),this->quat1.w()); ASSERT_EQ(testQuat.x(),this->quat1.x()); ASSERT_EQ(testQuat.y(),this->quat1.y()); ASSERT_EQ(testQuat.z(),this->quat1.z()); testQuat = this->quatIdentity*this->quat1; ASSERT_EQ(testQuat.w(),this->quat1.w()); ASSERT_EQ(testQuat.x(),this->quat1.x()); ASSERT_EQ(testQuat.y(),this->quat1.y()); ASSERT_EQ(testQuat.z(),this->quat1.z()); } // Testing of UnitQuaternion conjugation TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleConjugation) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; UnitQuaternion testQuat1; UnitQuaternion testQuat2; // Check conjugation testQuat1 = this->quat1; testQuat2 = testQuat1.conjugated(); ASSERT_NEAR(testQuat1.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->quat1.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->eigenQuat1Conj.z(),1e-6); testQuat2 = testQuat1.conjugate(); ASSERT_NEAR(testQuat1.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->eigenQuat1Conj.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->eigenQuat1Conj.z(),1e-6); } // Testing of UnitQuaternion inversion TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleInversion) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; UnitQuaternion testQuat1; UnitQuaternion testQuat2; // Check conjugation testQuat1 = this->quat1; testQuat2 = testQuat1.inverted(); ASSERT_NEAR(testQuat1.w(),this->quat1.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->quat1.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->quat1.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->quat1.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->eigenQuat1Conj.z(),1e-6); testQuat2 = testQuat1.invert(); ASSERT_NEAR(testQuat1.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat1.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat1.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat1.z(),this->eigenQuat1Conj.z(),1e-6); ASSERT_NEAR(testQuat2.w(),this->eigenQuat1Conj.w(),1e-6); ASSERT_NEAR(testQuat2.x(),this->eigenQuat1Conj.x(),1e-6); ASSERT_NEAR(testQuat2.y(),this->eigenQuat1Conj.y(),1e-6); ASSERT_NEAR(testQuat2.z(),this->eigenQuat1Conj.z(),1e-6); } // Testing of UnitQuaternion comparison (equality) TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleEqualityComparison) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; UnitQuaternion testQuat; // Check equality comparison testQuat = this->quat1; ASSERT_EQ(testQuat==this->quat1,true); ASSERT_EQ(testQuat==this->quat2,false); } // Testing of UnitQuaternion comparison (inequality) TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleInequalityComparison) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; UnitQuaternion testQuat; // Check inequality comparison testQuat = this->quat1; ASSERT_EQ(testQuat!=this->quat1,false); ASSERT_EQ(testQuat!=this->quat2,true); } // Testing of Norm and Normalization for UnitQuaternion TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleNormalization) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; UnitQuaternion testQuat; UnitQuaternionScalar scalar; // Check norm and normalization testQuat = this->quat1; scalar = testQuat.norm(); ASSERT_NEAR(scalar,1.0,1e-6); } // Testing of casting to implementation for UnitQuaternion TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleImplementationCast) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef typename TestFixture::EigenQuat EigenQuat; EigenQuat testEigenQuat; // Check casting to implementation testEigenQuat = this->quat1.toImplementation(); ASSERT_EQ(testEigenQuat.w(),this->eigenQuat1.w()); ASSERT_EQ(testEigenQuat.x(),this->eigenQuat1.x()); ASSERT_EQ(testEigenQuat.y(),this->eigenQuat1.y()); ASSERT_EQ(testEigenQuat.z(),this->eigenQuat1.z()); } // Testing of special matrices TYPED_TEST (UnitQuaternionsSingleTest, testUnitQuaternionSingleSpecialMatrices) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; UnitQuaternion quat1 = this->quat1; UnitQuaternion quat2 = this->quat2; // Qleft UnitQuaternion concatenation1 = quat1 * quat2; UnitQuaternion concatenation2(quat1.getQuaternionMatrix() * quat2.vector()); ASSERT_NEAR(concatenation1.w(),concatenation2.w(), 1e-3); ASSERT_NEAR(concatenation1.x(),concatenation2.x(), 1e-3); ASSERT_NEAR(concatenation1.y(),concatenation2.y(), 1e-3); ASSERT_NEAR(concatenation1.z(),concatenation2.z(), 1e-3); // Qright UnitQuaternion concatenation3 = quat1 * quat2; UnitQuaternion concatenation4(quat2.getConjugateQuaternionMatrix() * quat1.vector()); ASSERT_NEAR(concatenation3.w(),concatenation4.w(), 1e-3); ASSERT_NEAR(concatenation3.x(),concatenation4.x(), 1e-3); ASSERT_NEAR(concatenation3.y(),concatenation4.y(), 1e-3); ASSERT_NEAR(concatenation3.z(),concatenation4.z(), 1e-3); } // Testing vector() and constructor from vector TYPED_TEST (UnitQuaternionsSingleTest, testQuaternionSingleVectorAndVectorConstructor) { typedef typename TestFixture::UnitQuaternion UnitQuaternion; typedef typename TestFixture::UnitQuaternionScalar UnitQuaternionScalar; typedef Eigen::Matrix<UnitQuaternionScalar, 4, 1> Vector4; UnitQuaternion quat = this->quat1; // vector() Vector4 vector = quat.vector(); ASSERT_NEAR(quat.w(),vector(0), 1e-3); ASSERT_NEAR(quat.x(),vector(1), 1e-3); ASSERT_NEAR(quat.y(),vector(2), 1e-3); ASSERT_NEAR(quat.z(),vector(3), 1e-3); // constructor from vector UnitQuaternion quatFromVector(vector); ASSERT_NEAR(quat.w(),quatFromVector.w(), 1e-3); ASSERT_NEAR(quat.x(),quatFromVector.x(), 1e-3); ASSERT_NEAR(quat.y(),quatFromVector.y(), 1e-3); ASSERT_NEAR(quat.z(),quatFromVector.z(), 1e-3); }
43.69969
150
0.754269
[ "vector" ]
08baf014759f5a8fc39e7bcc5ee0ba76b6bf2541
8,295
cpp
C++
lib/binding/darwin/cpu_meter/process.cpp
Time1ess/StatsGenius
9f6e83d7b6b18aa6ea77b5f795e3473f23530648
[ "MIT" ]
null
null
null
lib/binding/darwin/cpu_meter/process.cpp
Time1ess/StatsGenius
9f6e83d7b6b18aa6ea77b5f795e3473f23530648
[ "MIT" ]
null
null
null
lib/binding/darwin/cpu_meter/process.cpp
Time1ess/StatsGenius
9f6e83d7b6b18aa6ea77b5f795e3473f23530648
[ "MIT" ]
null
null
null
#include <ctime> #include <fstream> #include <iostream> #include <regex> #include <algorithm> #include <stdexcept> #include <unordered_map> #include <unordered_set> #include "process.hpp" namespace { static size_t MaxArgumentLength = 0; // Manually set. size_t GetMaxArgumentLength() { static const size_t MAX_ARGUMENT_LENGTH_UNSET = 0; if (MaxArgumentLength != MAX_ARGUMENT_LENGTH_UNSET) { return MaxArgumentLength; } size_t size = sizeof(size_t); /* Get the maximum process arguments size. */ static int mib[2] = {CTL_KERN, KERN_ARGMAX}; if (sysctl(mib, 2, &MaxArgumentLength, &size, nullptr, 0) == -1) { throw runtime_error{"Failed to get maximum bytes of argument."}; } return MaxArgumentLength; } string GetCommandFromProc(const kinfo_proc* k) { size_t size = GetMaxArgumentLength(); static vector<char> procargs; procargs.resize(size); int mib[3] = {CTL_KERN, KERN_PROCARGS2, k->kp_proc.p_pid}; if (sysctl(mib, 3, procargs.data(), &size, nullptr, 0) == -1) { return string(k->kp_proc.p_comm); } return string(procargs.data() + sizeof(int)); } /* inline bool IsFileExists(const string& path) { struct stat buffer; return stat(path.c_str(), &buffer) == 0; } string ReadFile(const string& path) { std::ifstream t(path); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; } string FindAppIconPath(const string& command) { static const string app_suffix{".app"}; auto it = command.find(app_suffix); if (it == string::npos) { return ""; } const string base_path = command.substr(0, it + app_suffix.length()) + "/Contents"; const string info_plist_path = base_path + "/Info.plist"; if (!IsFileExists(info_plist_path)) { return ""; } const string info_plist_content = ReadFile(info_plist_path); regex re {"<key>CFBundleIconFile</key>[\\s\\S]*<string>(.+)</string>"}; smatch match; if (!regex_search(info_plist_content.begin(), info_plist_content.end(), match, re) or match.size() != 2) { return ""; } string app_icon_path = base_path + "/Resources/" + match.str(1); if (!IsFileExists(app_icon_path)) { const string app_icon_path_with_ext = app_icon_path + ".icns"; if (!IsFileExists(app_icon_path_with_ext)) { return ""; } return app_icon_path_with_ext; } return app_icon_path; } string ReadAndEncodeAppIcon(const string& path) { FILE* in_file {}; icns_family_t* icon_family {}; cout << path << endl; in_file = fopen(path.c_str(), "r"); if (in_file == nullptr) { cout <<"Open Error" << endl; return ""; } int error = icns_read_family_from_file(in_file, &icon_family); fclose(in_file); if (error != 0) { cout <<"Read Error" << endl; return ""; } icns_image_t icon_image; error = icns_get_image32_with_mask_from_family(icon_family, ICNS_128X128_32BIT_DATA, &icon_image); if (error != 0) { cout <<"Image Error" << endl; return ""; } cout << "Width: " << icon_image.imageWidth << endl; cout << "heigth: " << icon_image.imageHeight << endl; return ""; } */ } // namespace namespace StatsGenius { namespace CPUMeter { static unordered_map<int, unique_ptr<Process>> processes; int Process::num_cpus_ = 0; CPUUsage const* Process::total_usage_{}; Process::Process(kinfo_proc proc) : proc_{move(proc)} {} void Process::Prepare() { if (command_.empty()) { command_ = GetCommandFromProc(&proc_); } } vector<const Process*> Process::GetRunningProcesses(int num_cpus, const CPUUsage* total_usage, size_t max_num) { Process::num_cpus_ = num_cpus; Process::total_usage_ = total_usage; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0}; vector<kinfo_proc> procs; size_t count = 0; if (sysctl(mib, 4, nullptr, &count, nullptr, 0) < 0) { throw runtime_error{"Unable to get size of kproc_infos."}; } procs.resize(count / sizeof(kinfo_proc)); if (sysctl(mib, 4, static_cast<void*>(procs.data()), &count, nullptr, 0) < 0) { throw runtime_error{"Unable to get kinfo_procs."}; } unordered_set<int> new_pids; for (kinfo_proc& p : procs) { if (p.kp_proc.p_pid < 1) { continue; } unique_ptr<Process> proc = make_unique<Process>(move(p)); auto pid = proc->GetPid(); new_pids.insert(pid); auto it = processes.find(pid); if (it != processes.end()) { if (it->second->GetCommand() != proc->GetCommand()) { // Replace it->second = move(proc); continue; } // Update it->second->Update(); continue; } // Insert processes[pid] = move(proc); } // Cleanup vector<Process*> cands; for (auto it = processes.begin(); it != processes.end();) { if (new_pids.find(it->first) == new_pids.end()) { it = processes.erase(it); } else { cands.push_back(it->second.get()); it++; } } // Sort by CPU ASC. sort(cands.begin(), cands.end(), [](const Process* a, const Process* b) { return a->GetPercentCPU() > b->GetPercentCPU(); }); vector<const Process*> results; results.resize(max_num); for (size_t i = 0; i < min(max_num, cands.size()); i++) { cands[i]->Prepare(); results[i] = cands[i]; } return results; } void Process::Update() { proc_taskinfo pti; if (sizeof(pti) == proc_pidinfo(GetPid(), PROC_PIDTASKINFO, 0, &pti, sizeof(pti))) { if (0 != utime_ || 0 != stime_) { unsigned int diff = (pti.pti_total_system - stime_) + (pti.pti_total_user - utime_); percent_cpu_ = 1.0 * diff * num_cpus_ / ((total_usage_->user_cpu_ticks + total_usage_->system_cpu_ticks + total_usage_->idle_cpu_ticks) * 100000.0); } utime_ = pti.pti_total_system; stime_ = pti.pti_total_user; } } int Process::GetPid() const { return proc_.kp_proc.p_pid; } string Process::GetCommandName() const { auto it = command_.rfind('/'); if (it == string::npos) { return command_; } return command_.substr(it + 1); } string Process::GetCommand() const { return command_; } float Process::GetPercentCPU() const { return percent_cpu_; } string Process::GetBase64Icon() const { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABz" "enr0AAABSklEQVRYhWNgGAWDBXz++Hnipw+f/nx8//H/h/cf/" "sNoZDaIJkYeA39A0J8+gu2" "YgOGA50+f/3n25Nl/auCnj5/CaWQ2kpo/GA64feP2/" "zs374AxjA2iicHIesDsm7fhNDIbJg" "/CGA5QUNf+T088+B0geEzjv7w5qhh/iRwGpokD5Oy1/" "gtcVv8vla75X0GLzg6QytX6z39f4" "7/wWo3/Aqc1/ovO06SvA0QWaP4X3qbxX0FDG4zlTOgcAjJ+wOC/" "oAHGEnVA3+sMQBqQ19X+" "L1mq+V/wvPp/od0adE4DKVr/ZR0hbMkczf98T9T/K2jS0QGiUyCW8t9Q/y9wW/2/" "RA2dEyE4CgyA5cBZjf9ydloomujmABAe0IIIjHW0yDacOg6gMR51wKgDRh2AxQE6f+" "jnAB3" "MVrGihs5E+jhC54+Spg5mv2AUjFgAAH/+wdnTEexFAAAAAElFTkSuQmCC"; } v8::Local<v8::Object> Process::ToV8Object() const { v8::Local<v8::Object> result = Nan::New<v8::Object>(); v8::Local<v8::String> pid_prop = Nan::New("pid").ToLocalChecked(); v8::Local<v8::String> command_prop = Nan::New("command").ToLocalChecked(); v8::Local<v8::String> command_name_prop = Nan::New("commandName").ToLocalChecked(); v8::Local<v8::String> icon_prop = Nan::New("icon").ToLocalChecked(); v8::Local<v8::String> percent_cpu_prop = Nan::New("percentCPU").ToLocalChecked(); v8::Local<v8::Value> pid_value = Nan::New(GetPid()); v8::Local<v8::Value> command_value = Nan::New(GetCommand()).ToLocalChecked(); v8::Local<v8::Value> command_name_value = Nan::New(GetCommandName()).ToLocalChecked(); v8::Local<v8::Value> icon_value = Nan::New(GetBase64Icon()).ToLocalChecked(); v8::Local<v8::Value> percent_cpu_value = Nan::New(GetPercentCPU()); Nan::Set(result, pid_prop, pid_value); Nan::Set(result, command_prop, command_value); Nan::Set(result, command_name_prop, command_name_value); Nan::Set(result, icon_prop, icon_value); Nan::Set(result, percent_cpu_prop, percent_cpu_value); return result; } } // namespace CPUMeter } // namespace StatsGenius
29.414894
80
0.653647
[ "object", "vector" ]
08c29eddd1fe2c9df7c51f6115af6e14ae0c118b
39,538
cpp
C++
admin/snapin/certmgr/saferentry.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/certmgr/saferentry.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/certmgr/saferentry.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- ///////////////////////////////////////////////////////////////////////////////// // // Microsoft Windows // Copyright (C) Microsoft Corporation, 2000-2002. // // File: SaferEntry.cpp // // Contents: Implementation of CSaferEntry // //---------------------------------------------------------------------------- #include "stdafx.h" #include <gpedit.h> #include "SaferEntry.h" #include "PolicyKey.h" #include "SaferLevel.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern HKEY g_hkeyLastSaferRegistryScope; const DWORD AUTHZ_UNKNOWN_LEVEL = 0xFFFFFFFF; extern GUID g_guidExtension; extern GUID g_guidRegExt; extern GUID g_guidSnapin; extern PCWSTR pcszNEWLINE; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CSaferEntry::CSaferEntry ( SAFER_ENTRY_TYPE saferEntryType, bool bIsMachine, PCWSTR pszMachineName, PCWSTR pszObjectName, PSAFER_IDENTIFICATION_HEADER pAuthzInfo, DWORD dwLevelID, IGPEInformation* pGPEInformation, CCertificate* pCertificate, CSaferEntries* pSaferEntries, CRSOPObjectArray& rRSOPArray, PCWSTR pszRSOPRegistryKey) : CCertMgrCookie (bIsMachine ? CERTMGR_SAFER_COMPUTER_ENTRY : CERTMGR_SAFER_USER_ENTRY, pszMachineName, pszObjectName), m_pAuthzInfo (pAuthzInfo), m_dwLevelID (dwLevelID), m_dwOriginalLevelID (dwLevelID), m_pCertificate (pCertificate), m_pSaferEntries (pSaferEntries), m_pGPEInformation (pGPEInformation), m_saferEntryType (saferEntryType), m_dwFlags (0), m_bDeleted (false), m_cbFileHash (0), m_UrlZoneId (0), m_szRSOPRegistryKey (pszRSOPRegistryKey), m_hashAlgid (0), m_bIsComputer (bIsMachine) { // security review 2/22/2002 BryanWal ok ::ZeroMemory (&m_nHashFileSize, sizeof (m_nHashFileSize)); ::SecureZeroMemory (m_rgbFileHash, sizeof (m_rgbFileHash)); m_szDisplayName = pszObjectName; if ( m_pCertificate ) m_pCertificate->AddRef (); if ( m_pSaferEntries ) m_pSaferEntries->AddRef (); if ( m_pGPEInformation ) { m_pGPEInformation->AddRef (); CPolicyKey policyKey (m_pGPEInformation, SAFER_HKLM_REGBASE, bIsMachine); if ( AUTHZ_UNKNOWN_LEVEL == m_dwLevelID ) { // Bug 264556 Set better Security level defaults for new Safer rules m_dwLevelID = CSaferLevel::ReturnDefaultLevel ( m_pGPEInformation, m_bIsComputer, rRSOPArray); if ( SAFER_LEVELID_FULLYTRUSTED == m_dwLevelID ) m_dwLevelID = SAFER_LEVELID_DISALLOWED; else m_dwLevelID = SAFER_LEVELID_FULLYTRUSTED; } m_szLevelFriendlyName = SaferGetLevelFriendlyName (m_dwLevelID, policyKey.GetKey (), m_bIsComputer); } else { m_szLevelFriendlyName = SaferGetLevelFriendlyName (m_dwLevelID, 0, m_bIsComputer); } if ( SAFER_ENTRY_TYPE_URLZONE == m_saferEntryType ) { if ( m_pAuthzInfo ) { ASSERT (SaferIdentityTypeUrlZone == m_pAuthzInfo->dwIdentificationType); PSAFER_URLZONE_IDENTIFICATION pURLEntry = reinterpret_cast <PSAFER_URLZONE_IDENTIFICATION> (m_pAuthzInfo); ASSERT (pURLEntry->header.cbStructSize == sizeof (SAFER_URLZONE_IDENTIFICATION)); m_UrlZoneId = pURLEntry->UrlZoneId; } else { // This is a new entry m_UrlZoneId = URLZONE_TRUSTED; } } } CSaferEntry::~CSaferEntry() { if ( m_pAuthzInfo ) LocalFree (m_pAuthzInfo); if ( m_pCertificate ) m_pCertificate->Release (); if ( m_pSaferEntries ) m_pSaferEntries->Release (); if ( m_pGPEInformation ) m_pGPEInformation->Release (); } CString CSaferEntry::GetDescription() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CString szDescription; if ( SAFER_ENTRY_TYPE_URLZONE == m_saferEntryType ) { switch (m_UrlZoneId) { case URLZONE_LOCAL_MACHINE: VERIFY (szDescription.LoadString (IDS_URLZONE_LOCAL_MACHINE_DESCRIPTION)); break; case URLZONE_INTRANET: VERIFY (szDescription.LoadString (IDS_URLZONE_INTRANET_DESCRIPTION)); break; case URLZONE_TRUSTED: VERIFY (szDescription.LoadString (IDS_URLZONE_TRUSTED_DESCRIPTION)); break; case URLZONE_INTERNET: VERIFY (szDescription.LoadString (IDS_URLZONE_INTERNET_DESCRIPTION)); break; case URLZONE_UNTRUSTED: VERIFY (szDescription.LoadString (IDS_URLZONE_UNTRUSTED_DESCRIPTION)); break; default: ASSERT (0); break; } } else if ( m_pAuthzInfo ) { switch (m_pAuthzInfo->dwIdentificationType) { case SaferIdentityTypeImageName: { PSAFER_PATHNAME_IDENTIFICATION pNameEntry = (PSAFER_PATHNAME_IDENTIFICATION) m_pAuthzInfo; ASSERT (pNameEntry->header.cbStructSize >= sizeof (SAFER_PATHNAME_IDENTIFICATION)); szDescription = pNameEntry->Description; } break; case SaferIdentityTypeImageHash: { PSAFER_HASH_IDENTIFICATION pHashEntry = (PSAFER_HASH_IDENTIFICATION) m_pAuthzInfo; ASSERT (pHashEntry->header.cbStructSize == sizeof (SAFER_HASH_IDENTIFICATION)); szDescription = pHashEntry->Description; } break; case SaferIdentityTypeUrlZone: ASSERT (0); break; default: ASSERT (0); break; } } else if ( m_pCertificate ) { // Is certificate szDescription = m_pCertificate->GetDescription (); } m_szDescription = szDescription; return szDescription; } SAFER_ENTRY_TYPE CSaferEntry::GetType () const { return m_saferEntryType; } CString CSaferEntry::GetTypeString() const { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CString szType; switch (m_saferEntryType) { case SAFER_ENTRY_TYPE_PATH: VERIFY (szType.LoadString (IDS_CodeIdentityType_ImageName)); break; case SAFER_ENTRY_TYPE_HASH: VERIFY (szType.LoadString (IDS_CodeIdentityType_ImageHash)); break; case SAFER_ENTRY_TYPE_URLZONE: VERIFY (szType.LoadString (IDS_CodeIdentityType_UrlZone)); break; case SAFER_ENTRY_TYPE_CERT: VERIFY (szType.LoadString (IDS_CodeIdentityType_Certificate)); break; default: ASSERT (0); break; } return szType; } CString CSaferEntry::GetLevelFriendlyName() const { return m_szLevelFriendlyName; } CString CSaferEntry::GetShortLastModified() const { CString szDate; if ( m_pAuthzInfo ) { VERIFY (SUCCEEDED (FormatDate (m_pAuthzInfo->lastModified, szDate, DATE_SHORTDATE, true)) ); } else if ( m_pCertificate ) { szDate = m_pCertificate->GetShortLastModified (); } return szDate; } CString CSaferEntry::GetLongLastModified() const { CString szDate; if ( m_pAuthzInfo ) { VERIFY (SUCCEEDED (FormatDate (m_pAuthzInfo->lastModified, szDate, DATE_LONGDATE, true)) ); } else if ( m_pCertificate ) { szDate = m_pCertificate->GetLongLastModified (); } return szDate; } HRESULT CSaferEntry::GetCertificate(CCertificate **ppCert) { ASSERT (ppCert); if ( !ppCert ) return E_POINTER; if ( !m_pCertificate ) return E_NOTIMPL; *ppCert = m_pCertificate; m_pCertificate->AddRef (); return S_OK; } HRESULT CSaferEntry::SetCertificate(CCertificate *pCert) { ASSERT (m_pSaferEntries); if ( !m_pSaferEntries ) return E_FAIL; HRESULT hr = S_OK; CCertStore* pStore = 0; switch (m_dwLevelID) { case SAFER_LEVELID_FULLYTRUSTED: hr = m_pSaferEntries->GetTrustedPublishersStore (&pStore); break; case SAFER_LEVELID_DISALLOWED: hr = m_pSaferEntries->GetDisallowedStore (&pStore); break; default: hr = E_FAIL; break; } if ( SUCCEEDED (hr) ) { if ( m_pCertificate ) { m_pCertificate->DeleteFromStore (false); m_pCertificate->Release (); m_pCertificate = 0; } if ( pCert ) { m_pCertificate = pCert; m_pCertificate->AddRef (); hr = pStore->AddCertificateContext (m_pCertificate->GetCertContext (), 0, false); if ( SUCCEEDED (hr) ) { m_pCertificate->GetNewCertContext (); } } } if ( pStore ) { pStore->Release (); pStore = 0; } return hr; } void CSaferEntry::SetDescription(const CString& szDescription) { m_szDescription = szDescription; } HRESULT CSaferEntry::GetSaferEntriesNode(CSaferEntries **ppSaferEntries) { if ( !ppSaferEntries ) return E_POINTER; if ( !m_pSaferEntries ) return E_NOTIMPL; m_pSaferEntries->AddRef (); *ppSaferEntries = m_pSaferEntries; return S_OK; } DWORD CSaferEntry::GetLevel() const { return m_dwLevelID; } HRESULT CSaferEntry::SetLevel(DWORD dwLevelID) { HRESULT hr = S_OK; if ( m_dwLevelID != dwLevelID ) { m_dwLevelID = dwLevelID; // Get the new "friendly name" if ( m_pGPEInformation ) { CPolicyKey policyKey (m_pGPEInformation, SAFER_HKLM_REGBASE, m_bIsComputer); m_szLevelFriendlyName = SaferGetLevelFriendlyName (dwLevelID, policyKey.GetKey (), m_bIsComputer); } else { m_szLevelFriendlyName = SaferGetLevelFriendlyName (dwLevelID, 0, m_bIsComputer); } } return hr; } CString CSaferEntry::GetPath() { _TRACE (1, L"Entering CSaferEntry::GetPath()\n"); CString szPath; #ifdef DBG PWSTR pszPath = 0; #endif if ( m_pAuthzInfo ) { if ( SaferIdentityTypeImageName == m_pAuthzInfo->dwIdentificationType ) { PSAFER_PATHNAME_IDENTIFICATION pNameEntry = (PSAFER_PATHNAME_IDENTIFICATION) m_pAuthzInfo; ASSERT (pNameEntry->header.cbStructSize >= sizeof (SAFER_PATHNAME_IDENTIFICATION)); ASSERT (SaferIdentityTypeImageName == m_pAuthzInfo->dwIdentificationType); szPath = pNameEntry->ImageName; #ifdef DBG pszPath = pNameEntry->ImageName; #endif } } m_szPath = szPath; #ifdef DBG _TRACE (-1, L"Leaving CSaferEntry::GetPath(): %s, %s\n", pszPath, (PCWSTR) szPath); #endif return szPath; } void CSaferEntry::SetPath(const CString &szPath) { m_szPath = szPath; } HRESULT CSaferEntry::Save() { _TRACE (1, L"Entering CSaferEntry::Save\n"); HRESULT hr = S_OK; ASSERT (!m_bDeleted); if ( m_bDeleted ) return E_FAIL; if ( m_pCertificate ) { // NTRAID# 461474 SAFER: last modified date is being updated // everytime the rules are refreshed. m_pCertificate->GetNewCertContext (); hr = m_pCertificate->SetDescription (m_szDescription); if ( SUCCEEDED (hr) ) { hr = m_pCertificate->SetLastModified (); if ( SUCCEEDED (hr) ) { // If the level has changed, then the cert must be removed // from the current level store added to the new one. if ( m_dwOriginalLevelID != m_dwLevelID ) { CCertStore* pStore = 0; switch (m_dwLevelID) { case SAFER_LEVELID_FULLYTRUSTED: hr = m_pSaferEntries->GetTrustedPublishersStore (&pStore); break; case SAFER_LEVELID_DISALLOWED: hr = m_pSaferEntries->GetDisallowedStore (&pStore); break; default: hr = E_FAIL; break; } if ( SUCCEEDED (hr) ) { m_pCertificate->DeleteFromStore (true); hr = pStore->AddCertificateContext (m_pCertificate->GetCertContext (), 0, false); if ( SUCCEEDED (hr) ) { m_pCertificate->SetStore (pStore); hr = PolicyChanged (); } } if ( pStore ) { pStore->Release (); pStore = 0; } } if ( SUCCEEDED (hr) ) m_szDisplayName = m_pCertificate->GetSubjectName (); } } } else if ( m_pGPEInformation ) { BOOL bRVal = TRUE; CPolicyKey policyKey (m_pGPEInformation, SAFER_HKLM_REGBASE, m_bIsComputer); hr = SetRegistryScope (policyKey.GetKey (), m_bIsComputer); if ( SUCCEEDED (hr) ) { DWORD dwInBufferSize = 0; switch (m_saferEntryType) { case SAFER_ENTRY_TYPE_PATH: dwInBufferSize = sizeof (SAFER_PATHNAME_IDENTIFICATION); break; case SAFER_ENTRY_TYPE_HASH: dwInBufferSize = sizeof (SAFER_HASH_IDENTIFICATION); break; case SAFER_ENTRY_TYPE_URLZONE: dwInBufferSize = sizeof (SAFER_URLZONE_IDENTIFICATION); break; default: ASSERT (0); break; } SAFER_LEVEL_HANDLE hLevel = 0; // If this entry is not being created for the first time // and the level has changed, delete this object from its original // level. if ( m_pAuthzInfo && AUTHZ_UNKNOWN_LEVEL != m_dwOriginalLevelID && m_dwOriginalLevelID != m_dwLevelID ) { bRVal = SaferCreateLevel(SAFER_SCOPEID_REGISTRY, m_dwOriginalLevelID, SAFER_LEVEL_OPEN, &hLevel, policyKey.GetKey ()); ASSERT (bRVal); if ( bRVal ) { SAFER_IDENTIFICATION_TYPES dwIdentificationType = m_pAuthzInfo->dwIdentificationType; m_pAuthzInfo->dwIdentificationType = (SAFER_IDENTIFICATION_TYPES) 0; // 0 will cause deletion bRVal = SaferSetLevelInformation(hLevel, SaferObjectSingleIdentification, m_pAuthzInfo, m_pAuthzInfo->cbStructSize); ASSERT (bRVal); if ( !bRVal ) { DWORD dwErr = GetLastError (); _TRACE (0, L"Attempt to delete entry using SaferSetLevelInformation(SaferObjectSingleIdentification) failed: %d\n", dwErr); hr = HRESULT_FROM_WIN32 (dwErr); } m_pAuthzInfo->dwIdentificationType = dwIdentificationType; // restore type VERIFY (SaferCloseLevel(hLevel)); } else { DWORD dwErr = GetLastError (); hr = HRESULT_FROM_WIN32 (dwErr); _TRACE (0, L"SaferCreateLevel(SAFER_SCOPEID_REGISTRY, 0x%x, SAFER_LEVEL_OPEN) failed: %d\n", m_dwOriginalLevelID, dwErr); } } if ( SUCCEEDED (hr) ) { // If this is new, create and initialize a new info structure if ( !m_pAuthzInfo ) { // generate guid GUID guid; hr = CoCreateGuid (&guid); if ( SUCCEEDED (hr) ) { m_pAuthzInfo = (PSAFER_IDENTIFICATION_HEADER) ::LocalAlloc (LPTR, dwInBufferSize); if ( m_pAuthzInfo ) { m_pAuthzInfo->cbStructSize = dwInBufferSize; // security review 2/22/2002 BryanWal ok memcpy (&m_pAuthzInfo->IdentificationGuid, &guid, sizeof (m_pAuthzInfo->IdentificationGuid)); } else hr = E_OUTOFMEMORY; } } if ( SUCCEEDED (hr) ) { switch (m_saferEntryType) { case SAFER_ENTRY_TYPE_PATH: { m_pAuthzInfo->dwIdentificationType = SaferIdentityTypeImageName; PSAFER_PATHNAME_IDENTIFICATION pNameEntry = reinterpret_cast<PSAFER_PATHNAME_IDENTIFICATION> (m_pAuthzInfo); ASSERT (pNameEntry->header.cbStructSize >= sizeof (SAFER_PATHNAME_IDENTIFICATION)); ASSERT (wcslen (m_szDescription) < SAFER_MAX_DESCRIPTION_SIZE); if ( wcslen (m_szDescription) < SAFER_MAX_DESCRIPTION_SIZE ) { // Security Review 3/21/2002 BryanWal - This is // okay because we're copying to 1 character less // than the length of the buffer wcsncpy (pNameEntry->Description, m_szDescription, SAFER_MAX_DESCRIPTION_SIZE); } pNameEntry->ImageName = const_cast <PWCHAR>((PCWSTR) m_szPath); pNameEntry->dwSaferFlags = m_dwFlags; } break; case SAFER_ENTRY_TYPE_HASH: { m_pAuthzInfo->dwIdentificationType = SaferIdentityTypeImageHash; PSAFER_HASH_IDENTIFICATION pHashEntry = reinterpret_cast<PSAFER_HASH_IDENTIFICATION>(m_pAuthzInfo); ASSERT (pHashEntry->header.cbStructSize == sizeof (SAFER_HASH_IDENTIFICATION)); ASSERT (wcslen (m_szHashFriendlyName) < SAFER_MAX_FRIENDLYNAME_SIZE); if ( wcslen (m_szHashFriendlyName) < SAFER_MAX_FRIENDLYNAME_SIZE ) { // Security Review 3/21/2002 BryanWal - This is // okay because we're copying to 1 character less // than the length of the buffer wcsncpy (pHashEntry->FriendlyName, m_szHashFriendlyName, SAFER_MAX_FRIENDLYNAME_SIZE); } ASSERT (wcslen (m_szDescription) < SAFER_MAX_DESCRIPTION_SIZE); if ( wcslen (m_szDescription) < SAFER_MAX_DESCRIPTION_SIZE ) { // Security Review 3/21/2002 BryanWal - This is // okay because we're copying to 1 character less // than the length of the buffer wcsncpy (pHashEntry->Description, m_szDescription, SAFER_MAX_DESCRIPTION_SIZE); } pHashEntry->dwSaferFlags = m_dwFlags; // Security Review 3/21/2002 BryanWal - This is // okay memcpy (pHashEntry->ImageHash, m_rgbFileHash, sizeof (pHashEntry->ImageHash)); pHashEntry->HashSize = m_cbFileHash; // Security Review 3/21/2002 BryanWal - This is // okay memcpy (&pHashEntry->ImageSize, &m_nHashFileSize, sizeof (pHashEntry->ImageSize)); pHashEntry->HashAlgorithm = m_hashAlgid; } break; case SAFER_ENTRY_TYPE_URLZONE: { m_pAuthzInfo->dwIdentificationType = SaferIdentityTypeUrlZone; PSAFER_URLZONE_IDENTIFICATION pURLEntry = reinterpret_cast <PSAFER_URLZONE_IDENTIFICATION> (m_pAuthzInfo); ASSERT (pURLEntry->header.cbStructSize == sizeof (SAFER_URLZONE_IDENTIFICATION)); pURLEntry->dwSaferFlags = m_dwFlags; pURLEntry->UrlZoneId = m_UrlZoneId; } break; } bRVal = SaferCreateLevel(SAFER_SCOPEID_REGISTRY, m_dwLevelID, SAFER_LEVEL_OPEN, &hLevel, policyKey.GetKey ()); ASSERT (bRVal); if ( bRVal ) { bRVal = SaferSetLevelInformation(hLevel, SaferObjectSingleIdentification, m_pAuthzInfo, m_pAuthzInfo->cbStructSize); if ( bRVal ) { switch ( m_saferEntryType ) { case SAFER_ENTRY_TYPE_HASH: m_szDisplayName = m_szHashFriendlyName; m_szDisplayName.Replace (pcszNEWLINE, L" "); break; case SAFER_ENTRY_TYPE_PATH: m_szDisplayName = m_szPath; break; case SAFER_ENTRY_TYPE_URLZONE: m_szDisplayName = GetURLZoneFriendlyName (m_UrlZoneId); break; default: ASSERT (0); break; } hr = PolicyChanged (); if ( SUCCEEDED (hr) ) { m_dwOriginalLevelID = m_dwLevelID; } } else { DWORD dwErr = GetLastError (); _TRACE (0, L"SaferSetLevelInformation(SaferObjectSingleIdentification) failed: %d\n", dwErr); hr = HRESULT_FROM_WIN32 (dwErr); } VERIFY (SaferCloseLevel(hLevel)); } else { DWORD dwErr = GetLastError (); hr = HRESULT_FROM_WIN32 (dwErr); _TRACE (0, L"SaferCreateLevel(AUTHZSCOPID_REGISTRY, 0x%x, SAFER_LEVEL_OPEN) failed: %d\n", m_dwLevelID, dwErr); } } } } } else hr = E_FAIL; _TRACE (-1, L"Leaving CSaferEntry::Save: 0x%x\n", hr); return hr; } HRESULT CSaferEntry::PolicyChanged() { _TRACE (1, L"Entering CSaferEntry::PolicyChanged\n"); HRESULT hr = E_FAIL; if ( m_pGPEInformation ) { hr = m_pGPEInformation->PolicyChanged ( m_bIsComputer ? TRUE : FALSE, TRUE, &g_guidExtension, &g_guidSnapin); hr = m_pGPEInformation->PolicyChanged ( m_bIsComputer ? TRUE : FALSE, TRUE, &g_guidRegExt, &g_guidSnapin); } _TRACE (-1, L"Leaving CSaferEntry::PolicyChanged\n"); return hr; } void CSaferEntry::SetFlags(DWORD dwFlags) { m_dwFlags = dwFlags; } HRESULT CSaferEntry::GetFlags(DWORD &dwFlags) { HRESULT hr = S_OK; if ( m_pAuthzInfo ) { switch (m_saferEntryType) { case SAFER_ENTRY_TYPE_PATH: { m_pAuthzInfo->dwIdentificationType = SaferIdentityTypeImageName; PSAFER_PATHNAME_IDENTIFICATION pNameEntry = reinterpret_cast<PSAFER_PATHNAME_IDENTIFICATION>(m_pAuthzInfo); ASSERT (pNameEntry->header.cbStructSize >= sizeof (SAFER_PATHNAME_IDENTIFICATION)); dwFlags = pNameEntry->dwSaferFlags; } break; case SAFER_ENTRY_TYPE_HASH: { m_pAuthzInfo->dwIdentificationType = SaferIdentityTypeImageHash; PSAFER_HASH_IDENTIFICATION pHashEntry = reinterpret_cast<PSAFER_HASH_IDENTIFICATION>(m_pAuthzInfo); ASSERT (pHashEntry->header.cbStructSize == sizeof (SAFER_HASH_IDENTIFICATION)); dwFlags = pHashEntry->dwSaferFlags; } break; case SAFER_ENTRY_TYPE_URLZONE: { m_pAuthzInfo->dwIdentificationType = SaferIdentityTypeUrlZone; PSAFER_URLZONE_IDENTIFICATION pURLEntry = reinterpret_cast<PSAFER_URLZONE_IDENTIFICATION>(m_pAuthzInfo); ASSERT (pURLEntry->header.cbStructSize == sizeof (SAFER_URLZONE_IDENTIFICATION)); dwFlags = pURLEntry->dwSaferFlags; } break; default: hr = E_FAIL; break; } } else if ( m_pCertificate ) { hr = E_NOTIMPL; } return hr; } HRESULT CSaferEntry::Delete(bool bCommit) { _TRACE (1, L"Entering CSaferEntry::Delete\n"); HRESULT hr = S_OK; ASSERT (!m_bDeleted); if ( m_bDeleted ) return E_FAIL; if ( m_pCertificate ) { BOOL bRVal = m_pCertificate->DeleteFromStore (bCommit); if ( bRVal ) { m_bDeleted = true; } else { DWORD dwErr = GetLastError (); hr = HRESULT_FROM_WIN32 (dwErr); } } else if ( m_pGPEInformation ) { BOOL bRVal = TRUE; CPolicyKey policyKey (m_pGPEInformation, SAFER_HKLM_REGBASE, m_bIsComputer); hr = SetRegistryScope (policyKey.GetKey (), m_bIsComputer); if ( SUCCEEDED (hr) ) { DWORD dwInBufferSize = 0; switch (m_saferEntryType) { case SAFER_ENTRY_TYPE_PATH: dwInBufferSize = sizeof (SAFER_PATHNAME_IDENTIFICATION); break; case SAFER_ENTRY_TYPE_HASH: dwInBufferSize = sizeof (SAFER_HASH_IDENTIFICATION); break; case SAFER_ENTRY_TYPE_URLZONE: dwInBufferSize = sizeof (SAFER_URLZONE_IDENTIFICATION); break; default: ASSERT (0); break; } SAFER_LEVEL_HANDLE hLevel = 0; if ( m_pAuthzInfo ) { bRVal = SaferCreateLevel(SAFER_SCOPEID_REGISTRY, m_dwOriginalLevelID, SAFER_LEVEL_OPEN, &hLevel, policyKey.GetKey ()); ASSERT (bRVal); if ( bRVal ) { SAFER_IDENTIFICATION_TYPES dwIdentificationType = m_pAuthzInfo->dwIdentificationType; m_pAuthzInfo->dwIdentificationType = (SAFER_IDENTIFICATION_TYPES) 0; // 0 will cause deletion bRVal = SaferSetLevelInformation(hLevel, SaferObjectSingleIdentification, m_pAuthzInfo, m_pAuthzInfo->cbStructSize); ASSERT (bRVal); if ( bRVal ) { m_bDeleted = true; if ( bCommit ) { hr = m_pGPEInformation->PolicyChanged ( m_bIsComputer ? TRUE : FALSE, TRUE, &g_guidExtension, &g_guidSnapin); hr = m_pGPEInformation->PolicyChanged ( m_bIsComputer ? TRUE : FALSE, TRUE, &g_guidRegExt, &g_guidSnapin); } } else { DWORD dwErr = GetLastError (); _TRACE (0, L"Attempt to delete entry using SaferSetLevelInformation(SaferObjectSingleIdentification) failed: %d\n", dwErr); hr = HRESULT_FROM_WIN32 (dwErr); } m_pAuthzInfo->dwIdentificationType = dwIdentificationType; VERIFY (SaferCloseLevel(hLevel)); // restore type } else { DWORD dwErr = GetLastError (); hr = HRESULT_FROM_WIN32 (dwErr); _TRACE (0, L"SaferCreateLevel(AUTHZSCOPID_REGISTRY, 0x%x, SAFER_LEVEL_OPEN) failed: %d\n", m_dwOriginalLevelID, dwErr); } } } } else hr = E_FAIL; _TRACE (-1, L"Leaving CSaferEntry::Delete: 0x%x\n", hr); return hr; } HRESULT CSaferEntry::GetHash(BYTE rgbFileHash[SAFER_MAX_HASH_SIZE], DWORD& cbFileHash, __int64& nFileSize, ALG_ID& algId) const { HRESULT hr = S_OK; if ( m_pAuthzInfo ) { if ( SAFER_ENTRY_TYPE_HASH == m_saferEntryType ) { PSAFER_HASH_IDENTIFICATION pHashEntry = reinterpret_cast<PSAFER_HASH_IDENTIFICATION>(m_pAuthzInfo); ASSERT (pHashEntry->header.cbStructSize == sizeof (SAFER_HASH_IDENTIFICATION)); // security review - 3/21/2002 BryanWal OK ::SecureZeroMemory (rgbFileHash, SAFER_MAX_HASH_SIZE); ASSERT (pHashEntry->HashSize <= SAFER_MAX_HASH_SIZE); if ( pHashEntry->HashSize <= SAFER_MAX_HASH_SIZE ) { memcpy (rgbFileHash, pHashEntry->ImageHash, pHashEntry->HashSize); cbFileHash = pHashEntry->HashSize; } else hr = E_FAIL; // security review - 3/21/2002 BryanWal OK memcpy (&nFileSize, &pHashEntry->ImageSize, sizeof (nFileSize)); algId = pHashEntry->HashAlgorithm; } else hr = E_NOTIMPL; } else hr = E_FAIL; return hr; } HRESULT CSaferEntry::SetHash ( BYTE rgbFileHash[SAFER_MAX_HASH_SIZE], DWORD cbFileHash, __int64 nFileSize, ALG_ID hashAlgid) { ASSERT (cbFileHash <= SAFER_MAX_HASH_SIZE); if ( cbFileHash > SAFER_MAX_HASH_SIZE ) return E_FAIL; ASSERT (rgbFileHash); if ( !rgbFileHash ) return E_POINTER; m_nHashFileSize = nFileSize; m_cbFileHash = cbFileHash; // Security review 2/25/2002 BryanWal ok ::SecureZeroMemory (m_rgbFileHash, sizeof (m_rgbFileHash)); ASSERT (cbFileHash <= SAFER_MAX_HASH_SIZE); if ( cbFileHash <= SAFER_MAX_HASH_SIZE ) memcpy (m_rgbFileHash, rgbFileHash, cbFileHash); else return E_FAIL; m_hashAlgid = hashAlgid; return S_OK; } DWORD CSaferEntry::GetURLZoneID() const { return m_UrlZoneId; } void CSaferEntry::SetURLZoneID(DWORD dwURLZoneID) { m_UrlZoneId = dwURLZoneID; } CString CSaferEntry::GetHashFriendlyName() { CString szFriendlyName; if ( m_szHashFriendlyName.IsEmpty () ) { if ( m_pAuthzInfo ) { if ( SaferIdentityTypeImageHash == m_pAuthzInfo->dwIdentificationType ) { PSAFER_HASH_IDENTIFICATION pHashEntry = (PSAFER_HASH_IDENTIFICATION) m_pAuthzInfo; ASSERT (pHashEntry->header.cbStructSize == sizeof (SAFER_HASH_IDENTIFICATION)); m_szHashFriendlyName = pHashEntry->FriendlyName; } } } return m_szHashFriendlyName; } void CSaferEntry::SetHashFriendlyName(const CString &szFriendlyName) { m_szHashFriendlyName = szFriendlyName; } int CSaferEntry::CompareLastModified (const CSaferEntry& saferEntry) const { int compVal = 0; FILETIME thisFt; FILETIME inFt; if ( m_pAuthzInfo ) thisFt = m_pAuthzInfo->lastModified; else if ( m_pCertificate ) { if ( FAILED (m_pCertificate->GetLastModifiedFileTime (thisFt)) ) return 0; } else { ASSERT (0); return 0; } if ( saferEntry.m_pAuthzInfo ) inFt = saferEntry.m_pAuthzInfo->lastModified; else if ( saferEntry.m_pCertificate ) { if ( FAILED (saferEntry.m_pCertificate->GetLastModifiedFileTime (inFt)) ) return 0; } else { ASSERT (0); return 0; } compVal = ::CompareFileTime (&thisFt, &inFt); return compVal; } CString CSaferEntry::GetRSOPRegistryKey () const { CString szRegistryKey; if ( m_pCertificate ) { if ( SAFER_LEVELID_FULLYTRUSTED == m_dwLevelID ) szRegistryKey = CERT_TRUST_PUB_SAFER_GROUP_POLICY_TRUSTED_PUBLISHER_STORE_REGPATH; else szRegistryKey = CERT_TRUST_PUB_SAFER_GROUP_POLICY_DISALLOWED_STORE_REGPATH; szRegistryKey += STR_REGKEY_CERTIFICATES; szRegistryKey += L"\\"; //szRegistryKey += m_pCertificate->GetMD5Hash (); szRegistryKey += m_pCertificate->GetSHAHash (); } else szRegistryKey = m_szRSOPRegistryKey; ASSERT (!szRegistryKey.IsEmpty ()); return szRegistryKey; } void CSaferEntry::Refresh() { _TRACE (1, L"Entering CSaferEntry::Refresh ()\n"); if ( m_pAuthzInfo ) { if ( m_pGPEInformation ) { SAFER_LEVEL_HANDLE hLevel = 0; CPolicyKey policyKey (m_pGPEInformation, SAFER_HKLM_REGBASE, m_bIsComputer); BOOL bRVal = SaferCreateLevel(SAFER_SCOPEID_REGISTRY, m_dwLevelID, SAFER_LEVEL_OPEN, &hLevel, policyKey.GetKey ()); if ( bRVal ) { DWORD dwBufferSize = sizeof (SAFER_IDENTIFICATION_HEADER); bRVal = SaferGetLevelInformation (hLevel, SaferObjectSingleIdentification, m_pAuthzInfo, dwBufferSize, &dwBufferSize); if ( !bRVal && ERROR_INSUFFICIENT_BUFFER == GetLastError () ) { PBYTE pBytes = (PBYTE) LocalAlloc (LPTR, dwBufferSize); if ( pBytes ) { PSAFER_IDENTIFICATION_HEADER pCommon = (PSAFER_IDENTIFICATION_HEADER) pBytes; pCommon->cbStructSize = dwBufferSize; // security review 2/25/2002 BryanWal ok memcpy (&pCommon->IdentificationGuid, &m_pAuthzInfo->IdentificationGuid, sizeof (pCommon->IdentificationGuid)); bRVal = SaferGetLevelInformation (hLevel, SaferObjectSingleIdentification, pBytes, dwBufferSize, &dwBufferSize); ASSERT (bRVal); if ( bRVal ) { LocalFree (m_pAuthzInfo); m_pAuthzInfo = (PSAFER_IDENTIFICATION_HEADER) pBytes; } else { _TRACE (0, L"SaferGetLevelInformation () failed: %d\n", GetLastError ()); } } } VERIFY (SaferCloseLevel(hLevel)); } else { _TRACE (0, L"SaferCreateLevel() failed: %d\n", GetLastError ()); } } else { // Is RSOP } } _TRACE (-1, L"Leaving CSaferEntry::Refresh ()\n"); }
33.678024
148
0.492387
[ "object" ]
08c4af0e1b1c61e125d4cdf8f49e83ce41a11795
32,592
cc
C++
tools/fidlcat/lib/syscall_decoder_dispatcher.cc
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
[ "BSD-3-Clause" ]
10
2020-12-28T17:04:44.000Z
2022-03-12T03:20:43.000Z
tools/fidlcat/lib/syscall_decoder_dispatcher.cc
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
[ "BSD-3-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
tools/fidlcat/lib/syscall_decoder_dispatcher.cc
dahliaOS/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
[ "BSD-3-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tools/fidlcat/lib/syscall_decoder_dispatcher.h" #include <zircon/system/public/zircon/errors.h> #include <zircon/system/public/zircon/types.h> #include <cstdint> #include <fstream> #include <memory> #include <sstream> #include "src/developer/debug/zxdb/client/process.h" #include "src/developer/debug/zxdb/client/thread.h" #include "src/lib/fidl_codec/semantic.h" #include "tools/fidlcat/lib/code_generator/test_generator.h" #include "tools/fidlcat/lib/inference.h" #include "tools/fidlcat/lib/syscall_decoder.h" #include "tools/fidlcat/lib/top.h" #include "tools/fidlcat/proto/session.pb.h" namespace fidlcat { std::unique_ptr<fidl_codec::Struct> uint128_struct_definition = nullptr; std::unique_ptr<fidl_codec::Type> SyscallTypeToFidlCodecType(fidlcat::SyscallType syscall_type) { switch (syscall_type) { case SyscallType::kBool: return std::make_unique<fidl_codec::BoolType>(); case SyscallType::kBtiPerm: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kBtiPerm); case SyscallType::kCachePolicy: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kCachePolicy); case SyscallType::kChar: return std::make_unique<fidl_codec::Int8Type>(fidl_codec::Int8Type::Kind::kChar); case SyscallType::kClock: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kClock); case SyscallType::kDuration: return std::make_unique<fidl_codec::Int64Type>(fidl_codec::Int64Type::Kind::kDuration); case SyscallType::kExceptionState: return std::make_unique<fidl_codec::Uint32Type>( fidl_codec::Uint32Type::Kind::kExceptionState); case SyscallType::kGpAddr: return std::make_unique<fidl_codec::Uint64Type>(fidl_codec::Uint64Type::Kind::kGpAddr); case SyscallType::kHandle: return std::make_unique<fidl_codec::HandleType>(); case SyscallType::kInt32: return std::make_unique<fidl_codec::Int32Type>(); case SyscallType::kInt64: return std::make_unique<fidl_codec::Int64Type>(); case SyscallType::kObjectInfoTopic: return std::make_unique<fidl_codec::Uint32Type>( fidl_codec::Uint32Type::Kind::kObjectInfoTopic); case SyscallType::kPacketGuestVcpuType: return std::make_unique<fidl_codec::Uint8Type>( fidl_codec::Uint8Type::Kind::kPacketGuestVcpuType); case SyscallType::kPacketPageRequestCommand: return std::make_unique<fidl_codec::Uint16Type>( fidl_codec::Uint16Type::Kind::kPacketPageRequestCommand); case SyscallType::kPaddr: return std::make_unique<fidl_codec::Uint64Type>(fidl_codec::Uint64Type::Kind::kPaddr); case SyscallType::kPciBarType: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kPciBarType); case SyscallType::kPortPacketType: return std::make_unique<fidl_codec::Uint32Type>( fidl_codec::Uint32Type::Kind::kPortPacketType); case SyscallType::kProfileInfoFlags: return std::make_unique<fidl_codec::Uint32Type>( fidl_codec::Uint32Type::Kind::kProfileInfoFlags); case SyscallType::kPropType: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kPropType); case SyscallType::kRights: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kRights); case SyscallType::kSignals: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kSignals); case SyscallType::kSize: return std::make_unique<fidl_codec::Uint64Type>(fidl_codec::Uint64Type::Kind::kSize); case SyscallType::kStatus: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kStatus); case SyscallType::kTime: return std::make_unique<fidl_codec::Int64Type>(fidl_codec::Int64Type::Kind::kTime); case SyscallType::kUint8: return std::make_unique<fidl_codec::Uint8Type>(); case SyscallType::kUint8Hexa: return std::make_unique<fidl_codec::Uint8Type>(fidl_codec::Uint8Type::Kind::kHexaDecimal); case SyscallType::kUint16: return std::make_unique<fidl_codec::Uint16Type>(); case SyscallType::kUint16Hexa: return std::make_unique<fidl_codec::Uint16Type>(fidl_codec::Uint16Type::Kind::kHexaDecimal); case SyscallType::kUint32: return std::make_unique<fidl_codec::Uint32Type>(); case SyscallType::kUint32Hexa: return std::make_unique<fidl_codec::Uint32Type>(fidl_codec::Uint32Type::Kind::kHexaDecimal); case SyscallType::kUint64: return std::make_unique<fidl_codec::Uint64Type>(); case SyscallType::kUint64Hexa: return std::make_unique<fidl_codec::Uint64Type>(fidl_codec::Uint64Type::Kind::kHexaDecimal); case SyscallType::kUint128Hexa: if (uint128_struct_definition == nullptr) { uint128_struct_definition = std::make_unique<fidl_codec::Struct>("zx.uint128"); uint128_struct_definition->AddMember("low", SyscallTypeToFidlCodecType(SyscallType::kUint64Hexa)); uint128_struct_definition->AddMember("high", SyscallTypeToFidlCodecType(SyscallType::kUint64Hexa)); } return std::make_unique<fidl_codec::StructType>(*uint128_struct_definition, false); case SyscallType::kUintptr: return std::make_unique<fidl_codec::Uint64Type>(fidl_codec::Uint64Type::Kind::kUintptr); case SyscallType::kVaddr: return std::make_unique<fidl_codec::Uint64Type>(fidl_codec::Uint64Type::Kind::kVaddr); default: return nullptr; } } std::unique_ptr<fidl_codec::Type> AccessBase::ComputeType() const { return SyscallTypeToFidlCodecType(GetSyscallType()); } std::unique_ptr<fidl_codec::Type> SyscallInputOutputBase::ComputeType() const { return nullptr; } std::unique_ptr<fidl_codec::Value> SyscallInputOutputBase::GenerateValue(SyscallDecoder* decoder, Stage stage) const { return std::make_unique<fidl_codec::InvalidValue>(); } void SyscallInputOutputStringBuffer::DisplayOutline(SyscallDecoder* decoder, Stage stage, fidl_codec::PrettyPrinter& printer) const { printer << name(); printer << ": " << fidl_codec::Green << "string" << fidl_codec::ResetColor << " = "; const char* const* buffer = buffer_->Content(decoder, stage); if (buffer == nullptr) { printer << fidl_codec::Red << "nullptr" << fidl_codec::ResetColor; } else { uint32_t count = count_->Value(decoder, stage); if (count == 0) { printer << "empty\n"; return; } const char* separator = ""; for (uint32_t i = 0; i < count; ++i) { if (buffer[i] != nullptr) { printer << separator; const char* string = reinterpret_cast<const char*>( decoder->BufferContent(stage, reinterpret_cast<uint64_t>(buffer[i]))); size_t string_size = (string == nullptr) ? 0 : strnlen(string, max_size_); printer.DisplayString(std::string_view(string, string_size)); separator = ", "; } } } printer << '\n'; } const char* SyscallInputOutputFixedSizeString::DisplayInline( SyscallDecoder* decoder, Stage stage, const char* separator, fidl_codec::PrettyPrinter& printer) const { printer << separator; printer << name() << ": " << fidl_codec::Green << "string" << fidl_codec::ResetColor << " = "; const char* string = string_->Content(decoder, stage); size_t string_size = (string == nullptr) ? 0 : strnlen(string, string_size_); printer.DisplayString(std::string_view(string, string_size)); return ", "; } std::unique_ptr<fidl_codec::Type> SyscallFidlMessageHandle::ComputeType() const { return std::make_unique<fidl_codec::FidlMessageType>(); } std::unique_ptr<fidl_codec::Value> SyscallFidlMessageHandle::GenerateValue(SyscallDecoder* decoder, Stage stage) const { zx_handle_t handle_value = handle()->Value(decoder, stage); const uint8_t* bytes_value = bytes()->Content(decoder, stage); uint32_t num_bytes_value = num_bytes()->Value(decoder, stage); const zx_handle_t* handles_value = handles()->Content(decoder, stage); uint32_t num_handles_value = num_handles()->Value(decoder, stage); zx_handle_info_t* handle_infos_value = nullptr; if (num_handles_value > 0) { handle_infos_value = new zx_handle_info_t[num_handles_value]; for (uint32_t i = 0; i < num_handles_value; ++i) { handle_infos_value[i].handle = handles_value[i]; handle_infos_value[i].type = ZX_OBJ_TYPE_NONE; handle_infos_value[i].rights = 0; } } fidl_codec::DecodedMessage message; std::stringstream error_stream; message.DecodeMessage(decoder->dispatcher()->MessageDecoderDispatcher(), decoder->fidlcat_thread()->process()->koid(), handle_value, bytes_value, num_bytes_value, handle_infos_value, num_handles_value, type(), error_stream); auto result = std::make_unique<fidl_codec::FidlMessageValue>( &message, error_stream.str(), bytes_value, num_bytes_value, handle_infos_value, num_handles_value); delete[] handle_infos_value; if (result->is_request()) { if (result->matched_request()) { decoder->set_semantic(result->method()->semantic()); decoder->set_decoded_request(result->decoded_request()); } if (result->matched_response()) { decoder->set_semantic(result->method()->semantic()); decoder->set_decoded_response(result->decoded_response()); } } return result; } std::unique_ptr<fidl_codec::Type> SyscallFidlMessageHandleInfo::ComputeType() const { return std::make_unique<fidl_codec::FidlMessageType>(); } std::unique_ptr<fidl_codec::Value> SyscallFidlMessageHandleInfo::GenerateValue( SyscallDecoder* decoder, Stage stage) const { zx_handle_t handle_value = handle()->Value(decoder, stage); const uint8_t* bytes_value = bytes()->Content(decoder, stage); uint32_t num_bytes_value = num_bytes()->Value(decoder, stage); const zx_handle_info_t* handle_infos_value = handles()->Content(decoder, stage); uint32_t num_handles_value = num_handles()->Value(decoder, stage); fidl_codec::DecodedMessage message; std::stringstream error_stream; message.DecodeMessage(decoder->dispatcher()->MessageDecoderDispatcher(), decoder->fidlcat_thread()->process()->koid(), handle_value, bytes_value, num_bytes_value, handle_infos_value, num_handles_value, type(), error_stream); auto result = std::make_unique<fidl_codec::FidlMessageValue>( &message, error_stream.str(), bytes_value, num_bytes_value, handle_infos_value, num_handles_value); if (result->is_request()) { if (result->matched_request()) { decoder->set_semantic(result->method()->semantic()); decoder->set_decoded_request(result->decoded_request()); } if (result->matched_response()) { decoder->set_semantic(result->method()->semantic()); decoder->set_decoded_response(result->decoded_response()); } } return result; } bool ComputeTypes(const std::vector<std::unique_ptr<SyscallInputOutputBase>>& fields, std::vector<std::unique_ptr<fidl_codec::StructMember>>* inline_members, std::vector<std::unique_ptr<fidl_codec::StructMember>>* outline_members) { for (const auto& field : fields) { std::unique_ptr<fidl_codec::Type> type = field->ComputeType(); if (type == nullptr) { return false; } if (field->InlineValue()) { inline_members->emplace_back( std::make_unique<fidl_codec::StructMember>(field->name(), std::move(type), field->id())); } else { outline_members->emplace_back( std::make_unique<fidl_codec::StructMember>(field->name(), std::move(type), field->id())); } } return true; } void Syscall::ComputeTypes() { fidl_codec_values_ready_ = true; if (!fidlcat::ComputeTypes(inputs_, &input_inline_members_, &input_outline_members_)) { fidl_codec_values_ready_ = false; return; } if (!fidlcat::ComputeTypes(outputs_, &output_inline_members_, &output_outline_members_)) { fidl_codec_values_ready_ = false; return; } } const fidl_codec::StructMember* Syscall::SearchInlineMember(const std::string& name, bool invoked) const { if (invoked) { for (const auto& member : input_inline_members_) { if (member->name() == name) { return member.get(); } } } else { for (const auto& member : output_inline_members_) { if (member->name() == name) { return member.get(); } } } return nullptr; } const fidl_codec::StructMember* Syscall::SearchInlineMember(uint32_t id, bool invoked) const { if (invoked) { for (const auto& member : input_inline_members_) { if (member->id() == id) { return member.get(); } } } else { for (const auto& member : output_inline_members_) { if (member->id() == id) { return member.get(); } } } return nullptr; } const fidl_codec::StructMember* Syscall::SearchOutlineMember(const std::string& name, bool invoked) const { if (invoked) { for (const auto& member : input_outline_members_) { if (member->name() == name) { return member.get(); } } } else { for (const auto& member : output_outline_members_) { if (member->name() == name) { return member.get(); } } } return nullptr; } const fidl_codec::StructMember* Syscall::SearchOutlineMember(uint32_t id, bool invoked) const { if (invoked) { for (const auto& member : input_outline_members_) { if (member->id() == id) { return member.get(); } } } else { for (const auto& member : output_outline_members_) { if (member->id() == id) { return member.get(); } } } return nullptr; } void Syscall::ComputeStatistics(const OutputEvent* event) const { if (compute_statistics_ != nullptr) { (*compute_statistics_)(event); } } SyscallDecoderDispatcher::SyscallDecoderDispatcher(const DecodeOptions& decode_options) : decode_options_(decode_options), startup_timestamp_(time(nullptr)), inference_(this) { Populate(); ComputeTypes(); if (!decode_options.trigger_filters.empty()) { // We have at least one trigger => wait for a message satisfying the trigger before displaying // any syscall. display_started_ = false; } if (!decode_options.message_filters.empty() || !decode_options.exclude_message_filters.empty()) { has_filter_ = true; } if ((decode_options.stack_level != kNoStack) || !decode_options_.save.empty()) { needs_stack_frame_ = true; } if (!decode_options_.save.empty()) { needs_to_save_events_ = true; } else { switch (decode_options_.output_mode) { case OutputMode::kNone: case OutputMode::kStandard: break; case OutputMode::kTextProtobuf: needs_to_save_events_ = true; break; } } } HandleInfo* SyscallDecoderDispatcher::CreateHandleInfo(Thread* thread, uint32_t handle, int64_t creation_time, bool startup) { auto old_value = thread->process()->SearchHandleInfo(handle); if (old_value != nullptr) { return old_value; } auto result = std::make_unique<HandleInfo>(thread, handle, creation_time, startup); auto returned_value = result.get(); thread->process()->handle_infos().emplace_back(result.get()); thread->process()->handle_info_map().emplace(std::make_pair(handle, result.get())); handle_infos_.emplace_back(std::move(result)); return returned_value; } void SyscallDecoderDispatcher::DecodeSyscall(InterceptingThreadObserver* thread_observer, zxdb::Thread* thread, Syscall* syscall) { uint64_t thread_id = thread->GetKoid(); auto current = syscall_decoders_.find(thread_id); if (current != syscall_decoders_.end()) { FX_LOGS(ERROR) << thread->GetProcess()->GetName() << ' ' << thread->GetProcess()->GetKoid() << ':' << thread_id << ": Internal error: already decoding the thread"; return; } auto decoder = CreateDecoder(thread_observer, thread, syscall); auto tmp = decoder.get(); syscall_decoders_[thread_id] = std::move(decoder); tmp->Decode(); } void SyscallDecoderDispatcher::DecodeException(InterceptionWorkflow* workflow, zxdb::Thread* thread) { uint64_t thread_id = thread->GetKoid(); auto current = exception_decoders_.find(thread_id); if (current != exception_decoders_.end()) { FX_LOGS(ERROR) << thread->GetProcess()->GetName() << ' ' << thread->GetProcess()->GetKoid() << ':' << thread_id << ": Internal error: already decoding an exception for the thread"; return; } auto decoder = CreateDecoder(workflow, thread); auto tmp = decoder.get(); exception_decoders_[thread_id] = std::move(decoder); tmp->Decode(); } void SyscallDecoderDispatcher::DeleteDecoder(SyscallDecoder* decoder) { if (!decoder->aborted()) { zxdb::Thread* thread = decoder->get_thread(); if (thread != nullptr) { thread->Continue(false); } } syscall_decoders_.erase(decoder->fidlcat_thread()->koid()); } void SyscallDecoderDispatcher::DeleteDecoder(ExceptionDecoder* decoder) { zxdb::Thread* thread = decoder->get_thread(); if (thread != nullptr) { thread->Continue(false); } exception_decoders_.erase(decoder->thread_id()); } void SyscallDecoderDispatcher::AddStopMonitoringEvent(std::shared_ptr<StopMonitoringEvent> event) { for (const auto& decoder : syscall_decoders_) { if (decoder.second->fidlcat_thread()->process() == event->process()) { decoder.second->set_aborted(); } } } void SyscallDecoderDispatcher::SaveEvent(std::shared_ptr<Event> event) { if (needs_to_save_events()) { decoded_events_.emplace_back(std::move(event)); } } void SyscallDecoderDispatcher::SessionEnded() { bool generate_proto_session = false; if (!decode_options_.save.empty()) { generate_proto_session = true; } else { switch (decode_options_.output_mode) { case OutputMode::kNone: case OutputMode::kStandard: break; case OutputMode::kTextProtobuf: generate_proto_session = true; break; } } if (generate_proto_session) { proto::Session session; GenerateProtoSession(&session); if (!decode_options_.save.empty()) { std::fstream output(decode_options_.save, std::ios::out | std::ios::trunc | std::ios::binary); if (output.fail()) { FX_LOGS(ERROR) << "Can't open <" << decode_options_.save << "> for writing."; } else if (!session.SerializeToOstream(&output)) { FX_LOGS(ERROR) << "Failed to write session to protobuf file <" << decode_options_.save << ">."; } } switch (decode_options_.output_mode) { case OutputMode::kNone: case OutputMode::kStandard: break; case OutputMode::kTextProtobuf: std::cout << session.DebugString(); break; } } } void SyscallDecoderDispatcher::GenerateProtoSession(proto::Session* session) { for (const auto& process : processes_) { proto::Process* proto_process = session->add_process(); proto_process->set_koid(process.second->koid()); proto_process->set_name(process.second->name()); auto process_semantic = inference().GetProcessSemantic(process.second->koid()); if (process_semantic != nullptr) { for (const auto& linked_handles : process_semantic->linked_handles) { if (linked_handles.first < linked_handles.second) { proto::LinkedHandles* proto_linked_handles = proto_process->add_linked_handles(); proto_linked_handles->set_handle_0(linked_handles.first); proto_linked_handles->set_handle_1(linked_handles.second); } } } } for (const auto& thread : threads_) { proto::Thread* proto_thread = session->add_thread(); proto_thread->set_koid(thread.second->koid()); proto_thread->set_process_koid(thread.second->process()->koid()); } for (const auto& handle_info : handle_infos_) { fidl_codec::semantic::InferredHandleInfo* inferred_handle_info = inference().GetInferredHandleInfo(handle_info->thread()->process()->koid(), handle_info->handle()); proto::HandleDescription* proto_handle_description = session->add_handle_description(); proto_handle_description->set_handle(handle_info->handle()); proto_handle_description->set_thread_koid(handle_info->thread()->koid()); proto_handle_description->set_creation_time(handle_info->creation_time()); proto_handle_description->set_startup(handle_info->startup()); if (inferred_handle_info != nullptr) { proto_handle_description->set_type(inferred_handle_info->type()); proto_handle_description->set_fd(inferred_handle_info->fd()); proto_handle_description->set_path(inferred_handle_info->path()); proto_handle_description->set_attributes(inferred_handle_info->attributes()); } proto_handle_description->set_koid(handle_info->koid()); proto_handle_description->set_object_type(handle_info->object_type()); } for (const auto& linked_koids : inference().linked_koids()) { if (linked_koids.first < linked_koids.second) { proto::LinkedKoids* proto_linked_koids = session->add_linked_koids(); proto_linked_koids->set_koid_0(linked_koids.first); proto_linked_koids->set_koid_1(linked_koids.second); } } for (const auto& event : decoded_events_) { event->Write(session->add_event()); } } void SyscallDecoderDispatcher::ComputeTypes() { for (const auto& syscall : syscalls_) { syscall.second->ComputeTypes(); } } std::unique_ptr<SyscallDecoder> SyscallDisplayDispatcher::CreateDecoder( InterceptingThreadObserver* thread_observer, zxdb::Thread* thread, const Syscall* syscall) { return std::make_unique<SyscallDecoder>(this, thread_observer, thread, syscall, std::make_unique<SyscallDisplay>(this, os_)); } std::unique_ptr<ExceptionDecoder> SyscallDisplayDispatcher::CreateDecoder( InterceptionWorkflow* workflow, zxdb::Thread* thread) { return std::make_unique<ExceptionDecoder>(workflow, this, thread, std::make_unique<ExceptionDisplay>(this, os_)); } void SyscallDisplayDispatcher::AddProcessLaunchedEvent( std::shared_ptr<ProcessLaunchedEvent> event) { if (decode_options().output_mode == OutputMode::kStandard) { last_displayed_syscall_ = nullptr; if (event->error_message().empty()) { os_ << colors().green << "\nLaunched " << colors().blue << event->command() << colors().reset << '\n'; } else { os_ << colors().red << "\nCan't launch " << colors().blue << event->command() << colors().reset << " : " << colors().red << event->error_message() << colors().reset << '\n'; } } SaveEvent(std::move(event)); } void SyscallDisplayDispatcher::AddProcessMonitoredEvent( std::shared_ptr<ProcessMonitoredEvent> event) { if (decode_options().output_mode == OutputMode::kStandard) { last_displayed_syscall_ = nullptr; if (event->error_message().empty()) { os_ << colors().green << "\nMonitoring "; } else { os_ << colors().red << "\nCan't monitor "; } if (event->process()->name().empty()) { os_ << colors().reset << "process with koid "; } else { os_ << colors().blue << event->process()->name() << colors().reset << " koid="; } os_ << colors().red << event->process()->koid() << colors().reset; if (!event->error_message().empty()) { os_ << " : " << colors().red << event->error_message() << colors().reset; } os_ << '\n'; } SaveEvent(std::move(event)); } void SyscallDisplayDispatcher::AddStopMonitoringEvent(std::shared_ptr<StopMonitoringEvent> event) { if (decode_options().output_mode == OutputMode::kStandard) { last_displayed_syscall_ = nullptr; os_ << colors().green; if (event->process()->name().empty()) { os_ << "\nStop monitoring process with koid "; } else { os_ << "\nStop monitoring " << colors().blue << event->process()->name() << colors().reset << " koid="; } os_ << colors().red << event->process()->koid() << colors().reset << '\n'; } SaveEvent(event); SyscallDecoderDispatcher::AddStopMonitoringEvent(std::move(event)); } void SyscallDisplayDispatcher::AddInvokedEvent(std::shared_ptr<InvokedEvent> invoked_event) { invoked_event->set_id(GetNextInvokedEventId()); if (!extra_generation().empty()) { invoked_event->ComputeHandleInfo(this); } if (!display_started()) { // The user specified a trigger. Check if this is a message which satisfies one of the triggers. const fidl_codec::FidlMessageValue* message = invoked_event->GetMessage(); if ((message == nullptr) || !decode_options().IsTrigger(message->method()->fully_qualified_name())) { return; } // We found a trigger => allow the display. set_display_started(); } if (has_filter() && invoked_event->syscall()->has_fidl_message()) { // We have filters and this is a syscalls with a FIDL message. // Only display the syscall if the message satifies the conditions. const fidl_codec::FidlMessageValue* message = invoked_event->GetMessage(); if ((message == nullptr) || !decode_options().SatisfiesMessageFilters(message->method()->fully_qualified_name())) { return; } } invoked_event->set_displayed(); DisplayInvokedEvent(invoked_event.get()); SaveEvent(std::move(invoked_event)); } void SyscallDisplayDispatcher::DisplayInvokedEvent(const InvokedEvent* invoked_event) { if (decode_options().output_mode != OutputMode::kStandard) { return; } std::string line_header = invoked_event->thread()->process()->name() + ' ' + colors().red + std::to_string(invoked_event->thread()->process()->koid()) + colors().reset + ':' + colors().red + std::to_string(invoked_event->thread()->koid()) + colors().reset + ' '; if (with_process_info()) { os_ << line_header; } os_ << '\n'; FidlcatPrinter printer(this, invoked_event->thread()->process(), os_, line_header); // We have been able to create values from the syscall => print them. invoked_event->PrettyPrint(printer); last_displayed_syscall_ = nullptr; last_displayed_event_ = invoked_event; } void SyscallDisplayDispatcher::AddOutputEvent(std::shared_ptr<OutputEvent> output_event) { if (!extra_generation().empty()) { if (output_event->invoked_event()->handle_info() != nullptr) { output_event->invoked_event()->handle_info()->AddEvent(output_event.get()); } output_event->syscall()->ComputeStatistics(output_event.get()); } if (!output_event->invoked_event()->displayed()) { // The display of the syscall wasn't allowed by the input arguments. Check if the output // arguments allows its display. if (!display_started()) { // The user specified a trigger. Check if this is a message which satisfies one of the // triggers. const fidl_codec::FidlMessageValue* message = output_event->GetMessage(); if ((message == nullptr) || !decode_options().IsTrigger(message->method()->fully_qualified_name())) { return; } set_display_started(); } if (has_filter() && output_event->syscall()->has_fidl_message()) { // We have filters and this is a syscalls with a FIDL message. // Only display the syscall if the message satifies the conditions. const fidl_codec::FidlMessageValue* message = output_event->GetMessage(); if ((message == nullptr) || !decode_options().SatisfiesMessageFilters(message->method()->fully_qualified_name())) { return; } } // We can display the syscall but the inputs have not been displayed => display the inputs // before displaying the outputs. DisplayInvokedEvent(output_event->invoked_event()); } if (decode_options().output_mode == OutputMode::kStandard) { if (output_event->syscall()->return_type() != SyscallReturnType::kNoReturn) { if (last_displayed_event_ != output_event->invoked_event()) { // Add a blank line to tell the user that this display is not linked to the // previous displayed lines. os_ << "\n"; } std::string line_header; if (with_process_info() || (last_displayed_event_ != output_event->invoked_event())) { line_header = output_event->thread()->process()->name() + ' ' + colors().red + std::to_string(output_event->thread()->process()->koid()) + colors().reset + ':' + colors().red + std::to_string(output_event->thread()->koid()) + colors().reset + ' '; } FidlcatPrinter printer(this, output_event->thread()->process(), os_, line_header); // We have been able to create values from the syscall => print them. output_event->PrettyPrint(printer); last_displayed_syscall_ = nullptr; last_displayed_event_ = output_event.get(); } } SaveEvent(std::move(output_event)); } void SyscallDisplayDispatcher::AddExceptionEvent(std::shared_ptr<ExceptionEvent> exception_event) { if (decode_options().output_mode == OutputMode::kStandard) { os_ << '\n'; std::string line_header = exception_event->thread()->process()->name() + ' ' + colors().red + std::to_string(exception_event->thread()->process()->koid()) + colors().reset + ':' + colors().red + std::to_string(exception_event->thread()->koid()) + colors().reset + ' '; FidlcatPrinter printer(this, exception_event->thread()->process(), os_, line_header); exception_event->PrettyPrint(printer); } SaveEvent(std::move(exception_event)); } void SyscallDisplayDispatcher::SessionEnded() { SyscallDecoderDispatcher::SessionEnded(); const char* separator = ""; for (const auto& extra_generation : extra_generation()) { if (extra_generation.path.empty()) { os_ << separator; switch (extra_generation.kind) { case ExtraGeneration::Kind::kSummary: DisplaySummary(os_); break; case ExtraGeneration::Kind::kTop: { Top top(this); top.Display(os_); break; } case ExtraGeneration::Kind::kCpp: GenerateTests("/tmp/fidlcat-generated-tests/" + std::to_string(std::time(0))); break; } separator = "\n"; } else { if (extra_generation.kind == ExtraGeneration::Kind::kCpp) { GenerateTests(extra_generation.path); } else { std::fstream output(extra_generation.path, std::ios::out | std::ios::trunc); if (output.fail()) { FX_LOGS(ERROR) << "Can't open <" << extra_generation.path << "> for writing."; } else { switch (extra_generation.kind) { case ExtraGeneration::Kind::kSummary: DisplaySummary(output); break; case ExtraGeneration::Kind::kTop: { Top top(this); top.Display(output); break; } case ExtraGeneration::Kind::kCpp: break; } } } } } } std::unique_ptr<SyscallDecoder> SyscallCompareDispatcher::CreateDecoder( InterceptingThreadObserver* thread_observer, zxdb::Thread* thread, const Syscall* syscall) { return std::make_unique<SyscallDecoder>(this, thread_observer, thread, syscall, std::make_unique<SyscallCompare>(this, comparator_, os_)); } void SyscallDisplayDispatcher::GenerateTests(const std::string& output_directory) { auto test_generator = TestGenerator(this, output_directory); test_generator.GenerateTests(); } } // namespace fidlcat
40.386617
100
0.666697
[ "vector" ]
08c61481c40b6e225cfbbd68304bb088366257aa
1,985
cpp
C++
Elven/src/Elven/Core/Application.cpp
kryvytskyidenys/ElvenEngine
a9505df0df0bb85e8885e0a92452ce56028ec4b7
[ "Apache-2.0" ]
1
2021-01-18T12:49:28.000Z
2021-01-18T12:49:28.000Z
Elven/src/Elven/Core/Application.cpp
kryvytskyidenys/ElvenEngine
a9505df0df0bb85e8885e0a92452ce56028ec4b7
[ "Apache-2.0" ]
12
2021-04-10T10:29:53.000Z
2022-03-23T16:29:10.000Z
Elven/src/Elven/Core/Application.cpp
kryvytskyidenys/ElvenEngine
a9505df0df0bb85e8885e0a92452ce56028ec4b7
[ "Apache-2.0" ]
null
null
null
#include "elpch.h" #include "Elven/Core/Application.h" #include "Elven/Core/Input.h" #include "Elven/Renderer/Renderer.h" namespace Elven { Ref<VertexArray> VA; Application* Application::s_Instance = nullptr; Application::Application() : m_Running(true) { EL_CORE_ASSERT(!s_Instance, "Application already exist!"); s_Instance = this; m_Window = Window::Create(); m_Window->SetEventCallback(EL_BIND_EVENT_FN(Application::OnEvent)); m_ImGuiLayer = new ImGuiLayer(); PushOverlay(m_ImGuiLayer); } Application::~Application() { } void Application::OnEvent(Event& e) { EventDispatcher dispatcher(e); dispatcher.Dispatch<WindowCloseEvent>(EL_BIND_EVENT_FN(Application::OnWindowClose)); for (auto it = m_LayerStack.rbegin(); it != m_LayerStack.rend(); ++it) { if (e.Handled) break; (*it)->OnEvent(e); } } void Application::PushLayer(Layer* layer) { m_LayerStack.PushLayer(layer); layer->OnAttach(); } void Application::PushOverlay(Layer* overlay) { m_LayerStack.PushOverlay(overlay); overlay->OnAttach(); } void Application::Run() { Timer timer; while (m_Running) { float elapsedTime = timer.elapsed(); timer.restart(); // Layers update for (Layer* layer : m_LayerStack) { layer->OnUpdate(elapsedTime); } // ImGui layers render m_ImGuiLayer->Begin(); for (Layer* layer : m_LayerStack) { layer->OnImGuiRender(); } m_ImGuiLayer->End(); // Window update m_Window->OnUpdate(); } } bool Application::OnWindowClose(WindowCloseEvent& e) { m_Running = false; return true; } }
22.303371
92
0.55063
[ "render" ]
c0a347c1502d1b85291cdc8e1a1f525bc9007796
2,324
hpp
C++
shared/socket_utils.hpp
raygoe/nsp-asio
eccf6bce80f21aaf3c2b9cff45f4b225bec180bc
[ "MIT" ]
null
null
null
shared/socket_utils.hpp
raygoe/nsp-asio
eccf6bce80f21aaf3c2b9cff45f4b225bec180bc
[ "MIT" ]
null
null
null
shared/socket_utils.hpp
raygoe/nsp-asio
eccf6bce80f21aaf3c2b9cff45f4b225bec180bc
[ "MIT" ]
null
null
null
#ifndef SHARED_SOCKET_UTILS_HPP #define SHARED_SOCKET_UTILS_HPP #include <socket_types.hpp> #include <algorithm> //! Static object for several different utilities. class SocketUtils { public: //! Checks if the given connection handshake demonstrates little endianness. /*! * \param connection_handshake& hs Handshake reference. * \return bool whether the handshake represents little endian. */ static bool NetCheckLittleEndian(const connection_handshake& hs); //! Flips the endian of the given data and returns it. /*! * \param T data Data to flip endian. * \param size_t length Length of the data (defaults to zero, use sizeof) * \return T Flipped endian version of data. */ template <typename T> static T FlipEndian(T data, size_t length = 0); //! Flips the endian of the given data in place. /*! * \param T* data Data to flip endian in place. * \param size_t length Length of the data (defaults to zero, use sizeof) */ template <typename T> static void FlipEndian(T* data, size_t length = 0); //! Checks whether the opcode is sane. /*! Checks sanity by returning the number of opcodes in a given * service tag. If the opcode or service_tag does not compute, the * connection can detect it and close the socket. * * \param uint8_t service_tag service_tag to return amount of opcodes. * \return uint8_t Returns the opcode amount given a service_tag. */ static uint8_t CheckOpcode(uint8_t service_tag); //! Whether the application indicates little endian or not. static bool isLittleEndian; }; template <typename T> T SocketUtils::FlipEndian(T data, size_t length) { if (length) { std::reverse(reinterpret_cast<char*>(&data), reinterpret_cast<char*>(&data) + length); } else { std::reverse(reinterpret_cast<char*>(&data), reinterpret_cast<char*>(&data) + sizeof(data)); } return data; } template <typename T> void SocketUtils::FlipEndian(T* data, size_t length) { if (length) { std::reverse(reinterpret_cast<char*>(data), reinterpret_cast<char*>(data) + length); } else { std::reverse(reinterpret_cast<char*>(data), reinterpret_cast<char*>(data) + sizeof(data)); } } #endif /* SHARED_SOCKET_UTILS_HPP */
30.578947
100
0.682874
[ "object" ]
c0a751efeedac5bef86cd8407f19eb1944951fc3
3,904
cpp
C++
build/android/jni/StarCatcherNative.cpp
JeremyCBrooks/StarGlider
90c12698dbdee754434aab8b1287d9f9b9baf904
[ "MIT" ]
1
2016-01-27T06:25:21.000Z
2016-01-27T06:25:21.000Z
build/android/jni/StarCatcherNative.cpp
JeremyCBrooks/StarGlider
90c12698dbdee754434aab8b1287d9f9b9baf904
[ "MIT" ]
null
null
null
build/android/jni/StarCatcherNative.cpp
JeremyCBrooks/StarGlider
90c12698dbdee754434aab8b1287d9f9b9baf904
[ "MIT" ]
null
null
null
#include <jni.h> #include <jniUtils.h> #include "StarCatcherApplication.h" #include "PlatformAndroid.h" extern "C" { jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; LOGD("Loading external library and passing jvm"); if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } GLOBAL_APPLICATION = new StarCatcherApplication(vm); // Get jclass with env->FindClass. // Register methods with env->RegisterNatives. return JNI_VERSION_1_6; } /* static void loadAPK (const char* apkPath) { LOGI("Loading APK %s", apkPath); GLOBAL_APPLICATION->SetAPKArchive(zip_open(apkPath, 0, NULL)); if (GLOBAL_APPLICATION->GetAPKArchive() == NULL) { LOGE("Error loading APK"); return; } LOGD("Successfully loaded apkPath"); //Just for debug, print APK contents #ifdef NDEBUG zip* APKArchive = GLOBAL_APPLICATION->GetAPKArchive(); int numFiles = zip_get_num_files(APKArchive); for (int i=0; i<numFiles; i++) { const char* name = zip_get_name(APKArchive, i, 0); if (name == NULL) { LOGE("Error reading zip file name at index %i : %s",i, zip_strerror(APKArchive)); return; } LOGI("File %i : %s\n", i, name); } #endif }*/ JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_createEngineJni( JNIEnv* env, jobject object, jstring apkPath, jobject platform, jint screenw,jint screenh) { const char* str; jboolean isCopy; str = env->GetStringUTFChars(apkPath, &isCopy); jobject gplatform = env->NewGlobalRef(platform); PlatformAndroid* nplatform = new PlatformAndroid(gplatform); GLOBAL_APPLICATION->InitGame(nplatform,(int)screenw,(int)screenh); (env)->ReleaseStringUTFChars(apkPath, str); } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_deleteEngineJni(JNIEnv * env, jobject object) { delete GLOBAL_APPLICATION; GLOBAL_APPLICATION = NULL; } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_updateJni(JNIEnv * env, jobject object) { if (GLOBAL_APPLICATION != NULL) { GLOBAL_APPLICATION->Update(); } else { LOGW("Trying co call update on disposed game"); } } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_mouseDownJni(JNIEnv * env, jobject object,jfloat x,jfloat y) { if (GLOBAL_APPLICATION != NULL) { GLOBAL_APPLICATION->MouseDown(x,y); } else { LOGW("Trying co call mousedown on disposed game"); } } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_mouseUpJni(JNIEnv * env, jobject object,jfloat x,jfloat y) { if (GLOBAL_APPLICATION != NULL) { GLOBAL_APPLICATION->MouseUp(x,y); } else { LOGW("Trying co call mouseUp on disposed game"); } } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_mouseMotionJni(JNIEnv * env, jobject object,jfloat x,jfloat y) { if (GLOBAL_APPLICATION != NULL) { GLOBAL_APPLICATION->MouseMotion(x,y); } else { LOGW("Trying co call MouseMotion on disposed game"); } } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_keyDownJni(JNIEnv * env, jobject object) { if (GLOBAL_APPLICATION != NULL) { GLOBAL_APPLICATION->KeyDown(); } else { LOGW("Trying co call keyDown on disposed game"); } } JNIEXPORT void JNICALL Java_com_brooks_jeremy_starglider_glglue_NativeGame_KeyUpJni(JNIEnv * env, jobject object) { if (GLOBAL_APPLICATION != NULL) { GLOBAL_APPLICATION->KeyUp(); } else { LOGW("Trying co call KeyUp on disposed game"); } } } //extern C
27.111111
139
0.668801
[ "object" ]
c0aad35cd105235e983c08e1e4ee387ca1c8265f
139,208
cpp
C++
generated/nirfsa/nirfsa_service.cpp
vvacharya/grpc-device
22326f69b83d774457c0f5409b71ce7fc66002f6
[ "MIT" ]
null
null
null
generated/nirfsa/nirfsa_service.cpp
vvacharya/grpc-device
22326f69b83d774457c0f5409b71ce7fc66002f6
[ "MIT" ]
null
null
null
generated/nirfsa/nirfsa_service.cpp
vvacharya/grpc-device
22326f69b83d774457c0f5409b71ce7fc66002f6
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------- // This file is automatically generated. All manual edits will be lost. //--------------------------------------------------------------------- // Service implementation for the NI-RFSA Metadata //--------------------------------------------------------------------- #include "nirfsa_service.h" #include <sstream> #include <fstream> #include <iostream> #include <atomic> #include <vector> #include "custom/nirfsa_aliases.h" #include "custom/ivi_errors.h" #include <server/converters.h> namespace nirfsa_grpc { using nidevice_grpc::converters::allocate_output_storage; using nidevice_grpc::converters::calculate_linked_array_size; using nidevice_grpc::converters::convert_from_grpc; using nidevice_grpc::converters::convert_to_grpc; using nidevice_grpc::converters::MatchState; const auto kErrorReadBufferTooSmall = -200229; const auto kWarningCAPIStringTruncatedToFitBuffer = 200026; NiRFSAService::NiRFSAService( NiRFSALibraryInterface* library, ResourceRepositorySharedPtr resource_repository, const NiRFSAFeatureToggles& feature_toggles) : library_(library), session_repository_(resource_repository), feature_toggles_(feature_toggles) { } NiRFSAService::~NiRFSAService() { } // Returns true if it's safe to use outputs of a method with the given status. inline bool status_ok(int32 status) { return status >= 0; } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Abort(::grpc::ServerContext* context, const AbortRequest* request, AbortResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->Abort(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::CheckAcquisitionStatus(::grpc::ServerContext* context, const CheckAcquisitionStatusRequest* request, CheckAcquisitionStatusResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViBoolean is_done {}; auto status = library_->CheckAcquisitionStatus(vi, &is_done); response->set_status(status); if (status_ok(status)) { response->set_is_done(is_done); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ClearError(::grpc::ServerContext* context, const ClearErrorRequest* request, ClearErrorResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->ClearError(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ClearSelfCalibrateRange(::grpc::ServerContext* context, const ClearSelfCalibrateRangeRequest* request, ClearSelfCalibrateRangeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->ClearSelfCalibrateRange(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Close(::grpc::ServerContext* context, const CloseRequest* request, CloseResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); session_repository_->remove_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->Close(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Commit(::grpc::ServerContext* context, const CommitRequest* request, CommitResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->Commit(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureAcquisitionType(::grpc::ServerContext* context, const ConfigureAcquisitionTypeRequest* request, ConfigureAcquisitionTypeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 acquisition_type; switch (request->acquisition_type_enum_case()) { case nirfsa_grpc::ConfigureAcquisitionTypeRequest::AcquisitionTypeEnumCase::kAcquisitionType: { acquisition_type = static_cast<ViInt32>(request->acquisition_type()); break; } case nirfsa_grpc::ConfigureAcquisitionTypeRequest::AcquisitionTypeEnumCase::kAcquisitionTypeRaw: { acquisition_type = static_cast<ViInt32>(request->acquisition_type_raw()); break; } case nirfsa_grpc::ConfigureAcquisitionTypeRequest::AcquisitionTypeEnumCase::ACQUISITION_TYPE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for acquisition_type was not specified or out of range"); break; } } auto status = library_->ConfigureAcquisitionType(vi, acquisition_type); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureDeembeddingTableInterpolationLinear(::grpc::ServerContext* context, const ConfigureDeembeddingTableInterpolationLinearRequest* request, ConfigureDeembeddingTableInterpolationLinearResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto port = request->port().c_str(); auto table_name = request->table_name().c_str(); ViInt32 format; switch (request->format_enum_case()) { case nirfsa_grpc::ConfigureDeembeddingTableInterpolationLinearRequest::FormatEnumCase::kFormat: { format = static_cast<ViInt32>(request->format()); break; } case nirfsa_grpc::ConfigureDeembeddingTableInterpolationLinearRequest::FormatEnumCase::kFormatRaw: { format = static_cast<ViInt32>(request->format_raw()); break; } case nirfsa_grpc::ConfigureDeembeddingTableInterpolationLinearRequest::FormatEnumCase::FORMAT_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for format was not specified or out of range"); break; } } auto status = library_->ConfigureDeembeddingTableInterpolationLinear(vi, port, table_name, format); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureDeembeddingTableInterpolationNearest(::grpc::ServerContext* context, const ConfigureDeembeddingTableInterpolationNearestRequest* request, ConfigureDeembeddingTableInterpolationNearestResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto port = request->port().c_str(); auto table_name = request->table_name().c_str(); auto status = library_->ConfigureDeembeddingTableInterpolationNearest(vi, port, table_name); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureDeembeddingTableInterpolationSpline(::grpc::ServerContext* context, const ConfigureDeembeddingTableInterpolationSplineRequest* request, ConfigureDeembeddingTableInterpolationSplineResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto port = request->port().c_str(); auto table_name = request->table_name().c_str(); auto status = library_->ConfigureDeembeddingTableInterpolationSpline(vi, port, table_name); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureDigitalEdgeAdvanceTrigger(::grpc::ServerContext* context, const ConfigureDigitalEdgeAdvanceTriggerRequest* request, ConfigureDigitalEdgeAdvanceTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViConstString source; switch (request->source_enum_case()) { case nirfsa_grpc::ConfigureDigitalEdgeAdvanceTriggerRequest::SourceEnumCase::kSourceMapped: { auto source_imap_it = digitaledgetriggersource_input_map_.find(request->source_mapped()); if (source_imap_it == digitaledgetriggersource_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for source_mapped was not specified or out of range."); } source = const_cast<ViConstString>((source_imap_it->second).c_str()); break; } case nirfsa_grpc::ConfigureDigitalEdgeAdvanceTriggerRequest::SourceEnumCase::kSourceRaw: { source = const_cast<ViConstString>(request->source_raw().c_str()); break; } case nirfsa_grpc::ConfigureDigitalEdgeAdvanceTriggerRequest::SourceEnumCase::SOURCE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for source was not specified or out of range"); break; } } ViInt32 edge; switch (request->edge_enum_case()) { case nirfsa_grpc::ConfigureDigitalEdgeAdvanceTriggerRequest::EdgeEnumCase::kEdge: { edge = static_cast<ViInt32>(request->edge()); break; } case nirfsa_grpc::ConfigureDigitalEdgeAdvanceTriggerRequest::EdgeEnumCase::kEdgeRaw: { edge = static_cast<ViInt32>(request->edge_raw()); break; } case nirfsa_grpc::ConfigureDigitalEdgeAdvanceTriggerRequest::EdgeEnumCase::EDGE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for edge was not specified or out of range"); break; } } auto status = library_->ConfigureDigitalEdgeAdvanceTrigger(vi, source, edge); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureDigitalEdgeRefTrigger(::grpc::ServerContext* context, const ConfigureDigitalEdgeRefTriggerRequest* request, ConfigureDigitalEdgeRefTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViConstString source; switch (request->source_enum_case()) { case nirfsa_grpc::ConfigureDigitalEdgeRefTriggerRequest::SourceEnumCase::kSourceMapped: { auto source_imap_it = digitaledgetriggersource_input_map_.find(request->source_mapped()); if (source_imap_it == digitaledgetriggersource_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for source_mapped was not specified or out of range."); } source = const_cast<ViConstString>((source_imap_it->second).c_str()); break; } case nirfsa_grpc::ConfigureDigitalEdgeRefTriggerRequest::SourceEnumCase::kSourceRaw: { source = const_cast<ViConstString>(request->source_raw().c_str()); break; } case nirfsa_grpc::ConfigureDigitalEdgeRefTriggerRequest::SourceEnumCase::SOURCE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for source was not specified or out of range"); break; } } ViInt32 edge; switch (request->edge_enum_case()) { case nirfsa_grpc::ConfigureDigitalEdgeRefTriggerRequest::EdgeEnumCase::kEdge: { edge = static_cast<ViInt32>(request->edge()); break; } case nirfsa_grpc::ConfigureDigitalEdgeRefTriggerRequest::EdgeEnumCase::kEdgeRaw: { edge = static_cast<ViInt32>(request->edge_raw()); break; } case nirfsa_grpc::ConfigureDigitalEdgeRefTriggerRequest::EdgeEnumCase::EDGE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for edge was not specified or out of range"); break; } } ViInt64 pretrigger_samples = request->pretrigger_samples(); auto status = library_->ConfigureDigitalEdgeRefTrigger(vi, source, edge, pretrigger_samples); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureDigitalEdgeStartTrigger(::grpc::ServerContext* context, const ConfigureDigitalEdgeStartTriggerRequest* request, ConfigureDigitalEdgeStartTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViConstString source; switch (request->source_enum_case()) { case nirfsa_grpc::ConfigureDigitalEdgeStartTriggerRequest::SourceEnumCase::kSourceMapped: { auto source_imap_it = digitaledgetriggersource_input_map_.find(request->source_mapped()); if (source_imap_it == digitaledgetriggersource_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for source_mapped was not specified or out of range."); } source = const_cast<ViConstString>((source_imap_it->second).c_str()); break; } case nirfsa_grpc::ConfigureDigitalEdgeStartTriggerRequest::SourceEnumCase::kSourceRaw: { source = const_cast<ViConstString>(request->source_raw().c_str()); break; } case nirfsa_grpc::ConfigureDigitalEdgeStartTriggerRequest::SourceEnumCase::SOURCE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for source was not specified or out of range"); break; } } ViInt32 edge; switch (request->edge_enum_case()) { case nirfsa_grpc::ConfigureDigitalEdgeStartTriggerRequest::EdgeEnumCase::kEdge: { edge = static_cast<ViInt32>(request->edge()); break; } case nirfsa_grpc::ConfigureDigitalEdgeStartTriggerRequest::EdgeEnumCase::kEdgeRaw: { edge = static_cast<ViInt32>(request->edge_raw()); break; } case nirfsa_grpc::ConfigureDigitalEdgeStartTriggerRequest::EdgeEnumCase::EDGE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for edge was not specified or out of range"); break; } } auto status = library_->ConfigureDigitalEdgeStartTrigger(vi, source, edge); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureIQCarrierFrequency(::grpc::ServerContext* context, const ConfigureIQCarrierFrequencyRequest* request, ConfigureIQCarrierFrequencyResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 carrier_frequency = request->carrier_frequency(); auto status = library_->ConfigureIQCarrierFrequency(vi, channel_list, carrier_frequency); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureIQPowerEdgeRefTrigger(::grpc::ServerContext* context, const ConfigureIQPowerEdgeRefTriggerRequest* request, ConfigureIQPowerEdgeRefTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto source = "0"; ViReal64 level = request->level(); ViInt32 slope; switch (request->slope_enum_case()) { case nirfsa_grpc::ConfigureIQPowerEdgeRefTriggerRequest::SlopeEnumCase::kSlope: { slope = static_cast<ViInt32>(request->slope()); break; } case nirfsa_grpc::ConfigureIQPowerEdgeRefTriggerRequest::SlopeEnumCase::kSlopeRaw: { slope = static_cast<ViInt32>(request->slope_raw()); break; } case nirfsa_grpc::ConfigureIQPowerEdgeRefTriggerRequest::SlopeEnumCase::SLOPE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for slope was not specified or out of range"); break; } } ViInt64 pretrigger_samples = request->pretrigger_samples(); auto status = library_->ConfigureIQPowerEdgeRefTrigger(vi, source, level, slope, pretrigger_samples); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureIQRate(::grpc::ServerContext* context, const ConfigureIQRateRequest* request, ConfigureIQRateResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 iq_rate = request->iq_rate(); auto status = library_->ConfigureIQRate(vi, channel_list, iq_rate); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureNumberOfRecords(::grpc::ServerContext* context, const ConfigureNumberOfRecordsRequest* request, ConfigureNumberOfRecordsResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViBoolean number_of_records_is_finite = request->number_of_records_is_finite(); ViInt64 number_of_records = request->number_of_records(); auto status = library_->ConfigureNumberOfRecords(vi, channel_list, number_of_records_is_finite, number_of_records); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureNumberOfSamples(::grpc::ServerContext* context, const ConfigureNumberOfSamplesRequest* request, ConfigureNumberOfSamplesResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViBoolean number_of_samples_is_finite = request->number_of_samples_is_finite(); ViInt64 samples_per_record = request->samples_per_record(); auto status = library_->ConfigureNumberOfSamples(vi, channel_list, number_of_samples_is_finite, samples_per_record); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigurePXIChassisClk10(::grpc::ServerContext* context, const ConfigurePXIChassisClk10Request* request, ConfigurePXIChassisClk10Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViConstString pxi_clk10_source; switch (request->pxi_clk10_source_enum_case()) { case nirfsa_grpc::ConfigurePXIChassisClk10Request::PxiClk10SourceEnumCase::kPxiClk10SourceMapped: { auto pxi_clk10_source_imap_it = pxichassisclk10source_input_map_.find(request->pxi_clk10_source_mapped()); if (pxi_clk10_source_imap_it == pxichassisclk10source_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for pxi_clk10_source_mapped was not specified or out of range."); } pxi_clk10_source = const_cast<ViConstString>((pxi_clk10_source_imap_it->second).c_str()); break; } case nirfsa_grpc::ConfigurePXIChassisClk10Request::PxiClk10SourceEnumCase::kPxiClk10SourceRaw: { pxi_clk10_source = const_cast<ViConstString>(request->pxi_clk10_source_raw().c_str()); break; } case nirfsa_grpc::ConfigurePXIChassisClk10Request::PxiClk10SourceEnumCase::PXI_CLK10_SOURCE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for pxi_clk10_source was not specified or out of range"); break; } } auto status = library_->ConfigurePXIChassisClk10(vi, pxi_clk10_source); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureRefClock(::grpc::ServerContext* context, const ConfigureRefClockRequest* request, ConfigureRefClockResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViConstString clock_source; switch (request->clock_source_enum_case()) { case nirfsa_grpc::ConfigureRefClockRequest::ClockSourceEnumCase::kClockSourceMapped: { auto clock_source_imap_it = refclocksource_input_map_.find(request->clock_source_mapped()); if (clock_source_imap_it == refclocksource_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for clock_source_mapped was not specified or out of range."); } clock_source = const_cast<ViConstString>((clock_source_imap_it->second).c_str()); break; } case nirfsa_grpc::ConfigureRefClockRequest::ClockSourceEnumCase::kClockSourceRaw: { clock_source = const_cast<ViConstString>(request->clock_source_raw().c_str()); break; } case nirfsa_grpc::ConfigureRefClockRequest::ClockSourceEnumCase::CLOCK_SOURCE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for clock_source was not specified or out of range"); break; } } ViReal64 ref_clock_rate = request->ref_clock_rate(); auto status = library_->ConfigureRefClock(vi, clock_source, ref_clock_rate); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureReferenceLevel(::grpc::ServerContext* context, const ConfigureReferenceLevelRequest* request, ConfigureReferenceLevelResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 reference_level = request->reference_level(); auto status = library_->ConfigureReferenceLevel(vi, channel_list, reference_level); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureResolutionBandwidth(::grpc::ServerContext* context, const ConfigureResolutionBandwidthRequest* request, ConfigureResolutionBandwidthResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 resolution_bandwidth = request->resolution_bandwidth(); auto status = library_->ConfigureResolutionBandwidth(vi, channel_list, resolution_bandwidth); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureSoftwareEdgeAdvanceTrigger(::grpc::ServerContext* context, const ConfigureSoftwareEdgeAdvanceTriggerRequest* request, ConfigureSoftwareEdgeAdvanceTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->ConfigureSoftwareEdgeAdvanceTrigger(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureSoftwareEdgeRefTrigger(::grpc::ServerContext* context, const ConfigureSoftwareEdgeRefTriggerRequest* request, ConfigureSoftwareEdgeRefTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt64 pretrigger_samples = request->pretrigger_samples(); auto status = library_->ConfigureSoftwareEdgeRefTrigger(vi, pretrigger_samples); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureSoftwareEdgeStartTrigger(::grpc::ServerContext* context, const ConfigureSoftwareEdgeStartTriggerRequest* request, ConfigureSoftwareEdgeStartTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->ConfigureSoftwareEdgeStartTrigger(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureSpectrumFrequencyCenterSpan(::grpc::ServerContext* context, const ConfigureSpectrumFrequencyCenterSpanRequest* request, ConfigureSpectrumFrequencyCenterSpanResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 center_frequency = request->center_frequency(); ViReal64 span = request->span(); auto status = library_->ConfigureSpectrumFrequencyCenterSpan(vi, channel_list, center_frequency, span); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ConfigureSpectrumFrequencyStartStop(::grpc::ServerContext* context, const ConfigureSpectrumFrequencyStartStopRequest* request, ConfigureSpectrumFrequencyStartStopResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 start_frequency = request->start_frequency(); ViReal64 stop_frequency = request->stop_frequency(); auto status = library_->ConfigureSpectrumFrequencyStartStop(vi, channel_list, start_frequency, stop_frequency); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::CreateConfigurationList(::grpc::ServerContext* context, const CreateConfigurationListRequest* request, CreateConfigurationListResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto list_name = request->list_name().c_str(); ViInt32 number_of_list_attributes = static_cast<ViInt32>(request->list_attribute_ids().size()); auto list_attribute_ids = const_cast<ViAttr*>(reinterpret_cast<const ViAttr*>(request->list_attribute_ids().data())); ViBoolean set_as_active_list = request->set_as_active_list(); auto status = library_->CreateConfigurationList(vi, list_name, number_of_list_attributes, list_attribute_ids, set_as_active_list); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::CreateConfigurationListStep(::grpc::ServerContext* context, const CreateConfigurationListStepRequest* request, CreateConfigurationListStepResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViBoolean set_as_active_step = request->set_as_active_step(); auto status = library_->CreateConfigurationListStep(vi, set_as_active_step); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::CreateDeembeddingSparameterTableArray(::grpc::ServerContext* context, const CreateDeembeddingSparameterTableArrayRequest* request, CreateDeembeddingSparameterTableArrayResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto port = request->port().c_str(); auto table_name = request->table_name().c_str(); auto frequencies = const_cast<ViReal64*>(request->frequencies().data()); ViInt32 frequencies_size = static_cast<ViInt32>(request->frequencies().size()); auto sparameter_table = convert_from_grpc<NIComplexNumber_struct>(request->sparameter_table()); ViInt32 sparameter_table_size = static_cast<ViInt32>(request->sparameter_table().size()); ViInt32 number_of_ports = request->number_of_ports(); ViInt32 sparameter_orientation; switch (request->sparameter_orientation_enum_case()) { case nirfsa_grpc::CreateDeembeddingSparameterTableArrayRequest::SparameterOrientationEnumCase::kSparameterOrientation: { sparameter_orientation = static_cast<ViInt32>(request->sparameter_orientation()); break; } case nirfsa_grpc::CreateDeembeddingSparameterTableArrayRequest::SparameterOrientationEnumCase::kSparameterOrientationRaw: { sparameter_orientation = static_cast<ViInt32>(request->sparameter_orientation_raw()); break; } case nirfsa_grpc::CreateDeembeddingSparameterTableArrayRequest::SparameterOrientationEnumCase::SPARAMETER_ORIENTATION_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for sparameter_orientation was not specified or out of range"); break; } } auto status = library_->CreateDeembeddingSparameterTableArray(vi, port, table_name, frequencies, frequencies_size, sparameter_table.data(), sparameter_table_size, number_of_ports, sparameter_orientation); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::CreateDeembeddingSparameterTableS2PFile(::grpc::ServerContext* context, const CreateDeembeddingSparameterTableS2PFileRequest* request, CreateDeembeddingSparameterTableS2PFileResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto port = request->port().c_str(); auto table_name = request->table_name().c_str(); auto s2p_file_path = request->s2p_file_path().c_str(); ViInt32 sparameter_orientation; switch (request->sparameter_orientation_enum_case()) { case nirfsa_grpc::CreateDeembeddingSparameterTableS2PFileRequest::SparameterOrientationEnumCase::kSparameterOrientation: { sparameter_orientation = static_cast<ViInt32>(request->sparameter_orientation()); break; } case nirfsa_grpc::CreateDeembeddingSparameterTableS2PFileRequest::SparameterOrientationEnumCase::kSparameterOrientationRaw: { sparameter_orientation = static_cast<ViInt32>(request->sparameter_orientation_raw()); break; } case nirfsa_grpc::CreateDeembeddingSparameterTableS2PFileRequest::SparameterOrientationEnumCase::SPARAMETER_ORIENTATION_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for sparameter_orientation was not specified or out of range"); break; } } auto status = library_->CreateDeembeddingSparameterTableS2PFile(vi, port, table_name, s2p_file_path, sparameter_orientation); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::DeleteAllDeembeddingTables(::grpc::ServerContext* context, const DeleteAllDeembeddingTablesRequest* request, DeleteAllDeembeddingTablesResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->DeleteAllDeembeddingTables(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::DeleteConfigurationList(::grpc::ServerContext* context, const DeleteConfigurationListRequest* request, DeleteConfigurationListResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto list_name = request->list_name().c_str(); auto status = library_->DeleteConfigurationList(vi, list_name); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::DeleteDeembeddingTable(::grpc::ServerContext* context, const DeleteDeembeddingTableRequest* request, DeleteDeembeddingTableResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto port = request->port().c_str(); auto table_name = request->table_name().c_str(); auto status = library_->DeleteDeembeddingTable(vi, port, table_name); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Disable(::grpc::ServerContext* context, const DisableRequest* request, DisableResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->Disable(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::DisableAdvanceTrigger(::grpc::ServerContext* context, const DisableAdvanceTriggerRequest* request, DisableAdvanceTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->DisableAdvanceTrigger(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::DisableRefTrigger(::grpc::ServerContext* context, const DisableRefTriggerRequest* request, DisableRefTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->DisableRefTrigger(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::DisableStartTrigger(::grpc::ServerContext* context, const DisableStartTriggerRequest* request, DisableStartTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->DisableStartTrigger(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::EnableSessionAccess(::grpc::ServerContext* context, const EnableSessionAccessRequest* request, EnableSessionAccessResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViBoolean enable = request->enable(); auto status = library_->EnableSessionAccess(vi, enable); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ErrorMessage(::grpc::ServerContext* context, const ErrorMessageRequest* request, ErrorMessageResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViStatus status_code = request->status_code(); std::string error_message(1024 - 1, '\0'); auto status = library_->ErrorMessage(vi, status_code, (ViChar*)error_message.data()); response->set_status(status); if (status_ok(status)) { response->set_error_message(error_message); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_error_message())); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ErrorQuery(::grpc::ServerContext* context, const ErrorQueryRequest* request, ErrorQueryResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 error_code {}; std::string error_message(1024 - 1, '\0'); auto status = library_->ErrorQuery(vi, &error_code, (ViChar*)error_message.data()); response->set_status(status); if (status_ok(status)) { response->set_error_code(error_code); response->set_error_message(error_message); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_error_message())); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ExportSignal(::grpc::ServerContext* context, const ExportSignalRequest* request, ExportSignalResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 signal; switch (request->signal_enum_case()) { case nirfsa_grpc::ExportSignalRequest::SignalEnumCase::kSignal: { signal = static_cast<ViInt32>(request->signal()); break; } case nirfsa_grpc::ExportSignalRequest::SignalEnumCase::kSignalRaw: { signal = static_cast<ViInt32>(request->signal_raw()); break; } case nirfsa_grpc::ExportSignalRequest::SignalEnumCase::SIGNAL_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for signal was not specified or out of range"); break; } } auto signal_identifier = request->signal_identifier().c_str(); ViConstString output_terminal; switch (request->output_terminal_enum_case()) { case nirfsa_grpc::ExportSignalRequest::OutputTerminalEnumCase::kOutputTerminalMapped: { auto output_terminal_imap_it = exportterminal_input_map_.find(request->output_terminal_mapped()); if (output_terminal_imap_it == exportterminal_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for output_terminal_mapped was not specified or out of range."); } output_terminal = const_cast<ViConstString>((output_terminal_imap_it->second).c_str()); break; } case nirfsa_grpc::ExportSignalRequest::OutputTerminalEnumCase::kOutputTerminalRaw: { output_terminal = const_cast<ViConstString>(request->output_terminal_raw().c_str()); break; } case nirfsa_grpc::ExportSignalRequest::OutputTerminalEnumCase::OUTPUT_TERMINAL_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for output_terminal was not specified or out of range"); break; } } auto status = library_->ExportSignal(vi, signal, signal_identifier, output_terminal); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::FetchIQMultiRecordComplexF32(::grpc::ServerContext* context, const FetchIQMultiRecordComplexF32Request* request, FetchIQMultiRecordComplexF32Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 starting_record = request->starting_record(); ViInt64 number_of_records = request->number_of_records(); ViInt64 number_of_samples = request->number_of_samples(); ViReal64 timeout = request->timeout(); std::vector<NIComplexNumberF32_struct> data(number_of_samples * number_of_records, NIComplexNumberF32_struct()); std::vector<niRFSA_wfmInfo_struct> wfm_info(number_of_records, niRFSA_wfmInfo_struct()); auto status = library_->FetchIQMultiRecordComplexF32(vi, channel_list, starting_record, number_of_records, number_of_samples, timeout, data.data(), wfm_info.data()); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::FetchIQMultiRecordComplexF64(::grpc::ServerContext* context, const FetchIQMultiRecordComplexF64Request* request, FetchIQMultiRecordComplexF64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 starting_record = request->starting_record(); ViInt64 number_of_records = request->number_of_records(); ViInt64 number_of_samples = request->number_of_samples(); ViReal64 timeout = request->timeout(); std::vector<NIComplexNumber_struct> data(number_of_samples * number_of_records, NIComplexNumber_struct()); std::vector<niRFSA_wfmInfo_struct> wfm_info(number_of_records, niRFSA_wfmInfo_struct()); auto status = library_->FetchIQMultiRecordComplexF64(vi, channel_list, starting_record, number_of_records, number_of_samples, timeout, data.data(), wfm_info.data()); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::FetchIQMultiRecordComplexI16(::grpc::ServerContext* context, const FetchIQMultiRecordComplexI16Request* request, FetchIQMultiRecordComplexI16Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 starting_record = request->starting_record(); ViInt64 number_of_records = request->number_of_records(); ViInt64 number_of_samples = request->number_of_samples(); ViReal64 timeout = request->timeout(); std::vector<NIComplexI16_struct> data(number_of_samples * number_of_records, NIComplexI16_struct()); std::vector<niRFSA_wfmInfo_struct> wfm_info(number_of_records, niRFSA_wfmInfo_struct()); auto status = library_->FetchIQMultiRecordComplexI16(vi, channel_list, starting_record, number_of_records, number_of_samples, timeout, data.data(), wfm_info.data()); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::FetchIQSingleRecordComplexF32(::grpc::ServerContext* context, const FetchIQSingleRecordComplexF32Request* request, FetchIQSingleRecordComplexF32Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 record_number = request->record_number(); ViInt64 number_of_samples = request->number_of_samples(); ViReal64 timeout = request->timeout(); std::vector<NIComplexNumberF32_struct> data(number_of_samples, NIComplexNumberF32_struct()); niRFSA_wfmInfo_struct wfm_info {}; auto status = library_->FetchIQSingleRecordComplexF32(vi, channel_list, record_number, number_of_samples, timeout, data.data(), &wfm_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::FetchIQSingleRecordComplexF64(::grpc::ServerContext* context, const FetchIQSingleRecordComplexF64Request* request, FetchIQSingleRecordComplexF64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 record_number = request->record_number(); ViInt64 number_of_samples = request->number_of_samples(); ViReal64 timeout = request->timeout(); std::vector<NIComplexNumber_struct> data(number_of_samples, NIComplexNumber_struct()); niRFSA_wfmInfo_struct wfm_info {}; auto status = library_->FetchIQSingleRecordComplexF64(vi, channel_list, record_number, number_of_samples, timeout, data.data(), &wfm_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::FetchIQSingleRecordComplexI16(::grpc::ServerContext* context, const FetchIQSingleRecordComplexI16Request* request, FetchIQSingleRecordComplexI16Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 record_number = request->record_number(); ViInt64 number_of_samples = request->number_of_samples(); ViReal64 timeout = request->timeout(); std::vector<NIComplexI16_struct> data(number_of_samples, NIComplexI16_struct()); niRFSA_wfmInfo_struct wfm_info {}; auto status = library_->FetchIQSingleRecordComplexI16(vi, channel_list, record_number, number_of_samples, timeout, data.data(), &wfm_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetAttributeViBoolean(::grpc::ServerContext* context, const GetAttributeViBooleanRequest* request, GetAttributeViBooleanResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViBoolean value {}; auto status = library_->GetAttributeViBoolean(vi, channel_name, attribute_id, &value); response->set_status(status); if (status_ok(status)) { response->set_value(value); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetAttributeViInt32(::grpc::ServerContext* context, const GetAttributeViInt32Request* request, GetAttributeViInt32Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViInt32 value {}; auto status = library_->GetAttributeViInt32(vi, channel_name, attribute_id, &value); response->set_status(status); if (status_ok(status)) { response->set_value(value); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetAttributeViInt64(::grpc::ServerContext* context, const GetAttributeViInt64Request* request, GetAttributeViInt64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViInt64 value {}; auto status = library_->GetAttributeViInt64(vi, channel_name, attribute_id, &value); response->set_status(status); if (status_ok(status)) { response->set_value(value); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetAttributeViReal64(::grpc::ServerContext* context, const GetAttributeViReal64Request* request, GetAttributeViReal64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViReal64 value {}; auto status = library_->GetAttributeViReal64(vi, channel_name, attribute_id, &value); response->set_status(status); if (status_ok(status)) { response->set_value(value); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetAttributeViSession(::grpc::ServerContext* context, const GetAttributeViSessionRequest* request, GetAttributeViSessionResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViSession value {}; auto status = library_->GetAttributeViSession(vi, channel_name, attribute_id, &value); response->set_status(status); if (status_ok(status)) { auto session_id = session_repository_->resolve_session_id(value); response->mutable_value()->set_id(session_id); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetAttributeViString(::grpc::ServerContext* context, const GetAttributeViStringRequest* request, GetAttributeViStringResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); while (true) { auto status = library_->GetAttributeViString(vi, channel_name, attribute_id, 0, nullptr); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } ViInt32 buf_size = status; std::string value; if (buf_size > 0) { value.resize(buf_size - 1); } status = library_->GetAttributeViString(vi, channel_name, attribute_id, buf_size, (ViChar*)value.data()); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer || status > static_cast<decltype(status)>(buf_size)) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->set_value(value); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_value())); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetCalUserDefinedInfo(::grpc::ServerContext* context, const GetCalUserDefinedInfoRequest* request, GetCalUserDefinedInfoResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); std::string info(2048 - 1, '\0'); auto status = library_->GetCalUserDefinedInfo(vi, (ViChar*)info.data()); response->set_status(status); if (status_ok(status)) { response->set_info(info); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_info())); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetCalUserDefinedInfoMaxSize(::grpc::ServerContext* context, const GetCalUserDefinedInfoMaxSizeRequest* request, GetCalUserDefinedInfoMaxSizeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 info_size {}; auto status = library_->GetCalUserDefinedInfoMaxSize(vi, &info_size); response->set_status(status); if (status_ok(status)) { response->set_info_size(info_size); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetDeembeddingSparameters(::grpc::ServerContext* context, const GetDeembeddingSparametersRequest* request, GetDeembeddingSparametersResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 number_of_sparameters {}; ViInt32 number_of_ports {}; while (true) { auto status = library_->GetDeembeddingSparameters(vi, nullptr, 0, &number_of_sparameters, &number_of_ports); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } std::vector<NIComplexNumber_struct> sparameters(number_of_sparameters, NIComplexNumber_struct()); auto sparameters_array_size = number_of_sparameters; status = library_->GetDeembeddingSparameters(vi, sparameters.data(), sparameters_array_size, &number_of_sparameters, &number_of_ports); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { convert_to_grpc(sparameters, response->mutable_sparameters()); { auto shrunk_size = number_of_sparameters; auto current_size = response->mutable_sparameters()->size(); if (shrunk_size != current_size) { response->mutable_sparameters()->DeleteSubrange(shrunk_size, current_size - shrunk_size); } } response->set_number_of_sparameters(number_of_sparameters); response->set_number_of_ports(number_of_ports); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetDeviceResponse(::grpc::ServerContext* context, const GetDeviceResponseRequest* request, GetDeviceResponseResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 response_type; switch (request->response_type_enum_case()) { case nirfsa_grpc::GetDeviceResponseRequest::ResponseTypeEnumCase::kResponseType: { response_type = static_cast<ViInt32>(request->response_type()); break; } case nirfsa_grpc::GetDeviceResponseRequest::ResponseTypeEnumCase::kResponseTypeRaw: { response_type = static_cast<ViInt32>(request->response_type_raw()); break; } case nirfsa_grpc::GetDeviceResponseRequest::ResponseTypeEnumCase::RESPONSE_TYPE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for response_type was not specified or out of range"); break; } } ViInt32 number_of_frequencies {}; while (true) { auto status = library_->GetDeviceResponse(vi, channel_list, response_type, 0, nullptr, nullptr, nullptr, &number_of_frequencies); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } response->mutable_frequencies()->Resize(number_of_frequencies, 0); ViReal64* frequencies = response->mutable_frequencies()->mutable_data(); response->mutable_magnitude_response()->Resize(number_of_frequencies, 0); ViReal64* magnitude_response = response->mutable_magnitude_response()->mutable_data(); response->mutable_phase_response()->Resize(number_of_frequencies, 0); ViReal64* phase_response = response->mutable_phase_response()->mutable_data(); auto buffer_size = number_of_frequencies; status = library_->GetDeviceResponse(vi, channel_list, response_type, buffer_size, frequencies, magnitude_response, phase_response, &number_of_frequencies); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->mutable_frequencies()->Resize(number_of_frequencies, 0); response->mutable_magnitude_response()->Resize(number_of_frequencies, 0); response->mutable_phase_response()->Resize(number_of_frequencies, 0); response->set_number_of_frequencies(number_of_frequencies); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetError(::grpc::ServerContext* context, const GetErrorRequest* request, GetErrorResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); while (true) { auto status = library_->GetError(vi, nullptr, 0, nullptr); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } ViInt32 error_description_buffer_size = status; ViStatus error_code {}; std::string error_description; if (error_description_buffer_size > 0) { error_description.resize(error_description_buffer_size - 1); } status = library_->GetError(vi, &error_code, error_description_buffer_size, (ViChar*)error_description.data()); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer || status > static_cast<decltype(status)>(error_description_buffer_size)) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->set_error_code(error_code); response->set_error_description(error_description); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_error_description())); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetExtCalLastDateAndTime(::grpc::ServerContext* context, const GetExtCalLastDateAndTimeRequest* request, GetExtCalLastDateAndTimeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 year {}; ViInt32 month {}; ViInt32 day {}; ViInt32 hour {}; ViInt32 minute {}; auto status = library_->GetExtCalLastDateAndTime(vi, &year, &month, &day, &hour, &minute); response->set_status(status); if (status_ok(status)) { response->set_year(year); response->set_month(month); response->set_day(day); response->set_hour(hour); response->set_minute(minute); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetExtCalLastTemp(::grpc::ServerContext* context, const GetExtCalLastTempRequest* request, GetExtCalLastTempResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViReal64 temperature {}; auto status = library_->GetExtCalLastTemp(vi, &temperature); response->set_status(status); if (status_ok(status)) { response->set_temperature(temperature); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetExtCalRecommendedInterval(::grpc::ServerContext* context, const GetExtCalRecommendedIntervalRequest* request, GetExtCalRecommendedIntervalResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 months {}; auto status = library_->GetExtCalRecommendedInterval(vi, &months); response->set_status(status); if (status_ok(status)) { response->set_months(months); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetFetchBacklog(::grpc::ServerContext* context, const GetFetchBacklogRequest* request, GetFetchBacklogResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt64 record_number = request->record_number(); ViInt64 backlog {}; auto status = library_->GetFetchBacklog(vi, channel_list, record_number, &backlog); response->set_status(status); if (status_ok(status)) { response->set_backlog(backlog); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetFrequencyResponse(::grpc::ServerContext* context, const GetFrequencyResponseRequest* request, GetFrequencyResponseResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 number_of_frequencies {}; while (true) { auto status = library_->GetFrequencyResponse(vi, channel_list, 0, nullptr, nullptr, nullptr, &number_of_frequencies); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } response->mutable_frequencies()->Resize(number_of_frequencies, 0); ViReal64* frequencies = response->mutable_frequencies()->mutable_data(); response->mutable_magnitude_response()->Resize(number_of_frequencies, 0); ViReal64* magnitude_response = response->mutable_magnitude_response()->mutable_data(); response->mutable_phase_response()->Resize(number_of_frequencies, 0); ViReal64* phase_response = response->mutable_phase_response()->mutable_data(); auto buffer_size = number_of_frequencies; status = library_->GetFrequencyResponse(vi, channel_list, buffer_size, frequencies, magnitude_response, phase_response, &number_of_frequencies); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->mutable_frequencies()->Resize(number_of_frequencies, 0); response->mutable_magnitude_response()->Resize(number_of_frequencies, 0); response->mutable_phase_response()->Resize(number_of_frequencies, 0); response->set_number_of_frequencies(number_of_frequencies); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetNormalizationCoefficients(::grpc::ServerContext* context, const GetNormalizationCoefficientsRequest* request, GetNormalizationCoefficientsResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 number_of_coefficient_sets {}; while (true) { auto status = library_->GetNormalizationCoefficients(vi, channel_list, 0, nullptr, &number_of_coefficient_sets); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } std::vector<niRFSA_coefficientInfo_struct> coefficient_info(number_of_coefficient_sets, niRFSA_coefficientInfo_struct()); auto array_size = number_of_coefficient_sets; status = library_->GetNormalizationCoefficients(vi, channel_list, array_size, coefficient_info.data(), &number_of_coefficient_sets); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { convert_to_grpc(coefficient_info, response->mutable_coefficient_info()); { auto shrunk_size = number_of_coefficient_sets; auto current_size = response->mutable_coefficient_info()->size(); if (shrunk_size != current_size) { response->mutable_coefficient_info()->DeleteSubrange(shrunk_size, current_size - shrunk_size); } } response->set_number_of_coefficient_sets(number_of_coefficient_sets); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetNumberOfSpectralLines(::grpc::ServerContext* context, const GetNumberOfSpectralLinesRequest* request, GetNumberOfSpectralLinesResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 number_of_spectral_lines {}; auto status = library_->GetNumberOfSpectralLines(vi, channel_list, &number_of_spectral_lines); response->set_status(status); if (status_ok(status)) { response->set_number_of_spectral_lines(number_of_spectral_lines); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetRelayName(::grpc::ServerContext* context, const GetRelayNameRequest* request, GetRelayNameResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 index = request->index(); ViInt32 buffer_size {}; while (true) { auto status = library_->GetRelayName(vi, channel_list, index, nullptr, &buffer_size); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } std::string name; if (buffer_size > 0) { name.resize(buffer_size /* Workaround: strlen-bug */); } status = library_->GetRelayName(vi, channel_list, index, (ViChar*)name.data(), &buffer_size); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->set_name(name); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_name())); response->set_buffer_size(buffer_size); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetRelayOperationsCount(::grpc::ServerContext* context, const GetRelayOperationsCountRequest* request, GetRelayOperationsCountResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 buffer_size {}; while (true) { auto status = library_->GetRelayOperationsCount(vi, channel_list, nullptr, &buffer_size); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } response->mutable_operations_count()->Resize(buffer_size, 0); ViInt32* operations_count = reinterpret_cast<ViInt32*>(response->mutable_operations_count()->mutable_data()); status = library_->GetRelayOperationsCount(vi, channel_list, operations_count, &buffer_size); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->mutable_operations_count()->Resize(buffer_size, 0); response->set_buffer_size(buffer_size); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetScalingCoefficients(::grpc::ServerContext* context, const GetScalingCoefficientsRequest* request, GetScalingCoefficientsResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViInt32 number_of_coefficient_sets {}; while (true) { auto status = library_->GetScalingCoefficients(vi, channel_list, 0, nullptr, &number_of_coefficient_sets); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } std::vector<niRFSA_coefficientInfo_struct> coefficient_info(number_of_coefficient_sets, niRFSA_coefficientInfo_struct()); auto array_size = number_of_coefficient_sets; status = library_->GetScalingCoefficients(vi, channel_list, array_size, coefficient_info.data(), &number_of_coefficient_sets); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { convert_to_grpc(coefficient_info, response->mutable_coefficient_info()); { auto shrunk_size = number_of_coefficient_sets; auto current_size = response->mutable_coefficient_info()->size(); if (shrunk_size != current_size) { response->mutable_coefficient_info()->DeleteSubrange(shrunk_size, current_size - shrunk_size); } } response->set_number_of_coefficient_sets(number_of_coefficient_sets); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetSelfCalLastDateAndTime(::grpc::ServerContext* context, const GetSelfCalLastDateAndTimeRequest* request, GetSelfCalLastDateAndTimeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt64 self_calibration_step = request->self_calibration_step(); ViInt32 year {}; ViInt32 month {}; ViInt32 day {}; ViInt32 hour {}; ViInt32 minute {}; auto status = library_->GetSelfCalLastDateAndTime(vi, self_calibration_step, &year, &month, &day, &hour, &minute); response->set_status(status); if (status_ok(status)) { response->set_year(year); response->set_month(month); response->set_day(day); response->set_hour(hour); response->set_minute(minute); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetSelfCalLastTemp(::grpc::ServerContext* context, const GetSelfCalLastTempRequest* request, GetSelfCalLastTempResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt64 self_calibration_step = request->self_calibration_step(); ViReal64 temp {}; auto status = library_->GetSelfCalLastTemp(vi, self_calibration_step, &temp); response->set_status(status); if (status_ok(status)) { response->set_temp(temp); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetSpectralInfoForSMT(::grpc::ServerContext* context, const GetSpectralInfoForSMTRequest* request, GetSpectralInfoForSMTResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); SmtSpectrumInfo_struct spectrum_info {}; auto status = library_->GetSpectralInfoForSMT(vi, &spectrum_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(spectrum_info, response->mutable_spectrum_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetStreamEndpointHandle(::grpc::ServerContext* context, const GetStreamEndpointHandleRequest* request, GetStreamEndpointHandleResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto stream_endpoint = request->stream_endpoint().c_str(); ViUInt32 writer_handle {}; auto status = library_->GetStreamEndpointHandle(vi, stream_endpoint, &writer_handle); response->set_status(status); if (status_ok(status)) { response->set_writer_handle(writer_handle); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetTerminalName(::grpc::ServerContext* context, const GetTerminalNameRequest* request, GetTerminalNameResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 signal; switch (request->signal_enum_case()) { case nirfsa_grpc::GetTerminalNameRequest::SignalEnumCase::kSignal: { signal = static_cast<ViInt32>(request->signal()); break; } case nirfsa_grpc::GetTerminalNameRequest::SignalEnumCase::kSignalRaw: { signal = static_cast<ViInt32>(request->signal_raw()); break; } case nirfsa_grpc::GetTerminalNameRequest::SignalEnumCase::SIGNAL_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for signal was not specified or out of range"); break; } } auto signal_identifier = request->signal_identifier().c_str(); ViInt32 buffer_size = request->buffer_size(); std::string terminal_name; if (buffer_size > 0) { terminal_name.resize(buffer_size - 1); } auto status = library_->GetTerminalName(vi, signal, signal_identifier, buffer_size, (ViChar*)terminal_name.data()); response->set_status(status); if (status_ok(status)) { response->set_terminal_name(terminal_name); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_terminal_name())); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::GetUserData(::grpc::ServerContext* context, const GetUserDataRequest* request, GetUserDataResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto identifier = request->identifier().c_str(); ViInt32 actual_data_size {}; while (true) { auto status = library_->GetUserData(vi, identifier, 0, nullptr, &actual_data_size); if (status < 0) { response->set_status(status); return ::grpc::Status::OK; } std::string data(actual_data_size, '\0'); auto buffer_size = actual_data_size; status = library_->GetUserData(vi, identifier, buffer_size, (ViInt8*)data.data(), &actual_data_size); if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) { // buffer is now too small, try again continue; } response->set_status(status); if (status_ok(status)) { response->set_data(data); response->mutable_data()->resize(actual_data_size); response->set_actual_data_size(actual_data_size); } return ::grpc::Status::OK; } } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Init(::grpc::ServerContext* context, const InitRequest* request, InitResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { ViRsrc resource_name = (ViRsrc)request->resource_name().c_str(); ViBoolean id_query = request->id_query(); ViBoolean reset = request->reset(); auto init_lambda = [&] () { ViSession vi; auto status = library_->Init(resource_name, id_query, reset, &vi); return std::make_tuple(status, vi); }; uint32_t session_id = 0; const std::string& grpc_device_session_name = request->session_name(); auto cleanup_lambda = [&] (ViSession id) { library_->Close(id); }; int status = session_repository_->add_session(grpc_device_session_name, init_lambda, cleanup_lambda, session_id); response->set_status(status); if (status_ok(status)) { response->mutable_vi()->set_id(session_id); } else { const auto error_message = get_last_error_message(library_); response->set_error_message(error_message); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::InitWithOptions(::grpc::ServerContext* context, const InitWithOptionsRequest* request, InitWithOptionsResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { ViRsrc resource_name = (ViRsrc)request->resource_name().c_str(); ViBoolean id_query = request->id_query(); ViBoolean reset = request->reset(); auto option_string = request->option_string().c_str(); auto init_lambda = [&] () { ViSession vi; auto status = library_->InitWithOptions(resource_name, id_query, reset, option_string, &vi); return std::make_tuple(status, vi); }; uint32_t session_id = 0; const std::string& grpc_device_session_name = request->session_name(); auto cleanup_lambda = [&] (ViSession id) { library_->Close(id); }; int status = session_repository_->add_session(grpc_device_session_name, init_lambda, cleanup_lambda, session_id); response->set_status(status); if (status_ok(status)) { response->mutable_vi()->set_id(session_id); } else { const auto error_message = get_last_error_message(library_); response->set_error_message(error_message); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Initiate(::grpc::ServerContext* context, const InitiateRequest* request, InitiateResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->Initiate(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::InvalidateAllAttributes(::grpc::ServerContext* context, const InvalidateAllAttributesRequest* request, InvalidateAllAttributesResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->InvalidateAllAttributes(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::IsSelfCalValid(::grpc::ServerContext* context, const IsSelfCalValidRequest* request, IsSelfCalValidResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViBoolean self_cal_valid {}; ViInt64 valid_steps {}; auto status = library_->IsSelfCalValid(vi, &self_cal_valid, &valid_steps); response->set_status(status); if (status_ok(status)) { response->set_self_cal_valid(self_cal_valid); if (valid_steps & 0x1) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_ALIGNMENT); if (valid_steps & 0x2) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_GAIN_REFERENCE); if (valid_steps & 0x4) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_IF_FLATNESS); if (valid_steps & 0x8) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_DIGITIZER_SELF_CAL); if (valid_steps & 0x10) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_LO_SELF_CAL); if (valid_steps & 0x20) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_AMPLITUDE_ACCURACY); if (valid_steps & 0x40) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_RESIDUAL_LO_POWER); if (valid_steps & 0x80) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_IMAGE_SUPPRESSION); if (valid_steps & 0x100) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_SYNTHESIZER_ALIGNMENT); if (valid_steps & 0x200) response->add_valid_steps_array(SelfCalibrateSteps::SELF_CALIBRATE_STEPS_DC_OFFSET); response->set_valid_steps_raw(valid_steps); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::PerformThermalCorrection(::grpc::ServerContext* context, const PerformThermalCorrectionRequest* request, PerformThermalCorrectionResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->PerformThermalCorrection(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ReadIQSingleRecordComplexF64(::grpc::ServerContext* context, const ReadIQSingleRecordComplexF64Request* request, ReadIQSingleRecordComplexF64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 timeout = request->timeout(); ViInt64 data_array_size = request->data_array_size(); std::vector<NIComplexNumber_struct> data(data_array_size, NIComplexNumber_struct()); niRFSA_wfmInfo_struct wfm_info {}; auto status = library_->ReadIQSingleRecordComplexF64(vi, channel_list, timeout, data.data(), data_array_size, &wfm_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(data, response->mutable_data()); convert_to_grpc(wfm_info, response->mutable_wfm_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ReadPowerSpectrumF32(::grpc::ServerContext* context, const ReadPowerSpectrumF32Request* request, ReadPowerSpectrumF32Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 timeout = request->timeout(); ViInt32 data_array_size = request->data_array_size(); response->mutable_power_spectrum_data()->Resize(data_array_size, 0); ViReal32* power_spectrum_data = response->mutable_power_spectrum_data()->mutable_data(); niRFSA_spectrumInfo_struct spectrum_info {}; auto status = library_->ReadPowerSpectrumF32(vi, channel_list, timeout, power_spectrum_data, data_array_size, &spectrum_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(spectrum_info, response->mutable_spectrum_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ReadPowerSpectrumF64(::grpc::ServerContext* context, const ReadPowerSpectrumF64Request* request, ReadPowerSpectrumF64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_list = request->channel_list().c_str(); ViReal64 timeout = request->timeout(); ViInt32 data_array_size = request->data_array_size(); response->mutable_power_spectrum_data()->Resize(data_array_size, 0); ViReal64* power_spectrum_data = response->mutable_power_spectrum_data()->mutable_data(); niRFSA_spectrumInfo_struct spectrum_info {}; auto status = library_->ReadPowerSpectrumF64(vi, channel_list, timeout, power_spectrum_data, data_array_size, &spectrum_info); response->set_status(status); if (status_ok(status)) { convert_to_grpc(spectrum_info, response->mutable_spectrum_info()); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::Reset(::grpc::ServerContext* context, const ResetRequest* request, ResetResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->Reset(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ResetAttribute(::grpc::ServerContext* context, const ResetAttributeRequest* request, ResetAttributeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); auto status = library_->ResetAttribute(vi, channel_name, attribute_id); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ResetDevice(::grpc::ServerContext* context, const ResetDeviceRequest* request, ResetDeviceResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->ResetDevice(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ResetWithDefaults(::grpc::ServerContext* context, const ResetWithDefaultsRequest* request, ResetWithDefaultsResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->ResetWithDefaults(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::ResetWithOptions(::grpc::ServerContext* context, const ResetWithOptionsRequest* request, ResetWithOptionsResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViUInt64 steps_to_omit; switch (request->steps_to_omit_enum_case()) { case nirfsa_grpc::ResetWithOptionsRequest::StepsToOmitEnumCase::kStepsToOmit: { steps_to_omit = static_cast<ViUInt64>(request->steps_to_omit()); break; } case nirfsa_grpc::ResetWithOptionsRequest::StepsToOmitEnumCase::kStepsToOmitRaw: { steps_to_omit = static_cast<ViUInt64>(request->steps_to_omit_raw()); break; } case nirfsa_grpc::ResetWithOptionsRequest::StepsToOmitEnumCase::STEPS_TO_OMIT_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for steps_to_omit was not specified or out of range"); break; } } auto status = library_->ResetWithOptions(vi, steps_to_omit); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::RevisionQuery(::grpc::ServerContext* context, const RevisionQueryRequest* request, RevisionQueryResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); std::string driver_rev(256 - 1, '\0'); std::string instr_rev(256 - 1, '\0'); auto status = library_->RevisionQuery(vi, (ViChar*)driver_rev.data(), (ViChar*)instr_rev.data()); response->set_status(status); if (status_ok(status)) { response->set_driver_rev(driver_rev); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_driver_rev())); response->set_instr_rev(instr_rev); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_instr_rev())); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SelfCal(::grpc::ServerContext* context, const SelfCalRequest* request, SelfCalResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto status = library_->SelfCal(vi); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SelfCalibrate(::grpc::ServerContext* context, const SelfCalibrateRequest* request, SelfCalibrateResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt64 steps_to_omit; switch (request->steps_to_omit_enum_case()) { case nirfsa_grpc::SelfCalibrateRequest::StepsToOmitEnumCase::kStepsToOmit: { steps_to_omit = static_cast<ViInt64>(request->steps_to_omit()); break; } case nirfsa_grpc::SelfCalibrateRequest::StepsToOmitEnumCase::kStepsToOmitRaw: { steps_to_omit = static_cast<ViInt64>(request->steps_to_omit_raw()); break; } case nirfsa_grpc::SelfCalibrateRequest::StepsToOmitEnumCase::STEPS_TO_OMIT_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for steps_to_omit was not specified or out of range"); break; } } auto status = library_->SelfCalibrate(vi, steps_to_omit); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SelfCalibrateRange(::grpc::ServerContext* context, const SelfCalibrateRangeRequest* request, SelfCalibrateRangeResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt64 steps_to_omit; switch (request->steps_to_omit_enum_case()) { case nirfsa_grpc::SelfCalibrateRangeRequest::StepsToOmitEnumCase::kStepsToOmit: { steps_to_omit = static_cast<ViInt64>(request->steps_to_omit()); break; } case nirfsa_grpc::SelfCalibrateRangeRequest::StepsToOmitEnumCase::kStepsToOmitRaw: { steps_to_omit = static_cast<ViInt64>(request->steps_to_omit_raw()); break; } case nirfsa_grpc::SelfCalibrateRangeRequest::StepsToOmitEnumCase::STEPS_TO_OMIT_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for steps_to_omit was not specified or out of range"); break; } } ViReal64 min_frequency = request->min_frequency(); ViReal64 max_frequency = request->max_frequency(); ViReal64 min_reference_level = request->min_reference_level(); ViReal64 max_reference_level = request->max_reference_level(); auto status = library_->SelfCalibrateRange(vi, steps_to_omit, min_frequency, max_frequency, min_reference_level, max_reference_level); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SelfTest(::grpc::ServerContext* context, const SelfTestRequest* request, SelfTestResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt16 test_result {}; std::string test_message(2048 - 1, '\0'); auto status = library_->SelfTest(vi, &test_result, (ViChar*)test_message.data()); response->set_status(status); if (status_ok(status)) { response->set_test_result(test_result); response->set_test_message(test_message); nidevice_grpc::converters::trim_trailing_nulls(*(response->mutable_test_message())); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SendSoftwareEdgeTrigger(::grpc::ServerContext* context, const SendSoftwareEdgeTriggerRequest* request, SendSoftwareEdgeTriggerResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); ViInt32 trigger; switch (request->trigger_enum_case()) { case nirfsa_grpc::SendSoftwareEdgeTriggerRequest::TriggerEnumCase::kTrigger: { trigger = static_cast<ViInt32>(request->trigger()); break; } case nirfsa_grpc::SendSoftwareEdgeTriggerRequest::TriggerEnumCase::kTriggerRaw: { trigger = static_cast<ViInt32>(request->trigger_raw()); break; } case nirfsa_grpc::SendSoftwareEdgeTriggerRequest::TriggerEnumCase::TRIGGER_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for trigger was not specified or out of range"); break; } } auto trigger_identifier = request->trigger_identifier().c_str(); auto status = library_->SendSoftwareEdgeTrigger(vi, trigger, trigger_identifier); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetAttributeViBoolean(::grpc::ServerContext* context, const SetAttributeViBooleanRequest* request, SetAttributeViBooleanResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViBoolean value = request->value(); auto status = library_->SetAttributeViBoolean(vi, channel_name, attribute_id, value); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetAttributeViInt32(::grpc::ServerContext* context, const SetAttributeViInt32Request* request, SetAttributeViInt32Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViInt32 value; switch (request->value_enum_case()) { case nirfsa_grpc::SetAttributeViInt32Request::ValueEnumCase::kValue: { value = static_cast<ViInt32>(request->value()); break; } case nirfsa_grpc::SetAttributeViInt32Request::ValueEnumCase::kValueRaw: { value = static_cast<ViInt32>(request->value_raw()); break; } case nirfsa_grpc::SetAttributeViInt32Request::ValueEnumCase::VALUE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for value was not specified or out of range"); break; } } auto status = library_->SetAttributeViInt32(vi, channel_name, attribute_id, value); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetAttributeViInt64(::grpc::ServerContext* context, const SetAttributeViInt64Request* request, SetAttributeViInt64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViInt64 value = request->value_raw(); auto status = library_->SetAttributeViInt64(vi, channel_name, attribute_id, value); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetAttributeViReal64(::grpc::ServerContext* context, const SetAttributeViReal64Request* request, SetAttributeViReal64Response* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViReal64 value = request->value_raw(); auto status = library_->SetAttributeViReal64(vi, channel_name, attribute_id, value); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetAttributeViSession(::grpc::ServerContext* context, const SetAttributeViSessionRequest* request, SetAttributeViSessionResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); auto value_grpc_session = request->value(); ViSession value = session_repository_->access_session(value_grpc_session.id(), value_grpc_session.name()); auto status = library_->SetAttributeViSession(vi, channel_name, attribute_id, value); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetAttributeViString(::grpc::ServerContext* context, const SetAttributeViStringRequest* request, SetAttributeViStringResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto channel_name = request->channel_name().c_str(); ViAttr attribute_id = request->attribute_id(); ViConstString value; switch (request->value_enum_case()) { case nirfsa_grpc::SetAttributeViStringRequest::ValueEnumCase::kValueMapped: { auto value_imap_it = nirfsastringattributevaluesmapped_input_map_.find(request->value_mapped()); if (value_imap_it == nirfsastringattributevaluesmapped_input_map_.end()) { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for value_mapped was not specified or out of range."); } value = const_cast<ViConstString>((value_imap_it->second).c_str()); break; } case nirfsa_grpc::SetAttributeViStringRequest::ValueEnumCase::kValueRaw: { value = const_cast<ViConstString>(request->value_raw().c_str()); break; } case nirfsa_grpc::SetAttributeViStringRequest::ValueEnumCase::VALUE_ENUM_NOT_SET: { return ::grpc::Status(::grpc::INVALID_ARGUMENT, "The value for value was not specified or out of range"); break; } } auto status = library_->SetAttributeViString(vi, channel_name, attribute_id, value); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetCalUserDefinedInfo(::grpc::ServerContext* context, const SetCalUserDefinedInfoRequest* request, SetCalUserDefinedInfoResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto info = request->info().c_str(); auto status = library_->SetCalUserDefinedInfo(vi, info); response->set_status(status); return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- ::grpc::Status NiRFSAService::SetUserData(::grpc::ServerContext* context, const SetUserDataRequest* request, SetUserDataResponse* response) { if (context->IsCancelled()) { return ::grpc::Status::CANCELLED; } try { auto vi_grpc_session = request->vi(); ViSession vi = session_repository_->access_session(vi_grpc_session.id(), vi_grpc_session.name()); auto identifier = request->identifier().c_str(); ViInt32 buffer_size = request->buffer_size(); std::string data(buffer_size, '\0'); auto status = library_->SetUserData(vi, identifier, buffer_size, (ViInt8*)data.data()); response->set_status(status); if (status_ok(status)) { response->set_data(data); } return ::grpc::Status::OK; } catch (nidevice_grpc::LibraryLoadException& ex) { return ::grpc::Status(::grpc::NOT_FOUND, ex.what()); } } NiRFSAFeatureToggles::NiRFSAFeatureToggles( const nidevice_grpc::FeatureToggles& feature_toggles) : is_enabled( feature_toggles.is_feature_enabled("nirfsa", CodeReadiness::kRelease)) { } } // namespace nirfsa_grpc namespace nidevice_grpc { namespace converters { template <> void convert_to_grpc(const niRFSA_wfmInfo_struct& input, nirfsa_grpc::WaveformInfo* output) { output->set_absolute_initial_x(input.absoluteInitialX); output->set_relative_initial_x(input.relativeInitialX); output->set_x_increment(input.xIncrement); output->set_actual_samples(input.actualSamples); output->set_offset(input.offset); output->set_gain(input.gain); } template <> void convert_to_grpc(const niRFSA_coefficientInfo_struct& input, nirfsa_grpc::CoefficientInfo* output) { output->set_offset(input.offset); output->set_gain(input.gain); } template <> void convert_to_grpc(const niRFSA_spectrumInfo_struct& input, nirfsa_grpc::SpectrumInfo* output) { output->set_initial_frequency(input.initialFrequency); output->set_frequency_increment(input.frequencyIncrement); output->set_number_of_spectral_lines(input.numberOfSpectralLines); } } // converters } // nidevice_grpc
45.522564
243
0.608435
[ "vector" ]
c0abecf6df4b27182c916cf7b066dab1cd64b132
1,154
cpp
C++
#1126 Eulerian Path.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
1
2021-12-26T08:34:47.000Z
2021-12-26T08:34:47.000Z
#1126 Eulerian Path.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#1126 Eulerian Path.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; size_t DFSTrav(const vector<vector<size_t>> &graph, const size_t &src){ vector<bool> visit(graph.size(), false); auto DFS = [&graph, &visit](const size_t &src, const auto &DFS_ref) -> size_t { if(visit[src]) return 0; size_t cnt = 1; visit[src] = true; for(const size_t &nbr : graph[src]) cnt += DFS_ref(nbr, DFS_ref); return cnt; }; return DFS(1, DFS); } int main() { size_t n, m, cnt, oddDegreeCnt = 0; if(scanf("%zu%zu", &n, &m) != 2) return 0; vector<size_t> degree(n+1); vector<vector<size_t>> graph(n+1); for(size_t i = 0, u, v; i < m && scanf("%zu%zu", &u, &v); ++i) { graph[u].emplace_back(v); graph[v].emplace_back(u); ++degree[u]; ++degree[v]; } cnt = DFSTrav(graph, 1); for(size_t i = 1; i <= n; ++i) { printf("%zu%c", degree[i], " \n"[i==n]); if(degree[i] % 2 == 1) ++oddDegreeCnt; } if(oddDegreeCnt == 0 && cnt == n) printf("Eulerian\n"); else if(oddDegreeCnt == 2 && cnt == n) printf("Semi-Eulerian\n"); else printf("Non-Eulerian\n"); return 0; }
32.971429
83
0.555459
[ "vector" ]
c0b0dca6fe9ba4e8594797da9cf2939658c7d1b2
8,630
cpp
C++
src/jit/impl/mlir/compiler.cpp
Olalaye/MegEngine
695d24f24517536e6544b07936d189dbc031bbce
[ "Apache-2.0" ]
5,168
2020-03-19T06:10:04.000Z
2022-03-31T11:11:54.000Z
src/jit/impl/mlir/compiler.cpp
Olalaye/MegEngine
695d24f24517536e6544b07936d189dbc031bbce
[ "Apache-2.0" ]
286
2020-03-25T01:36:23.000Z
2022-03-31T10:26:33.000Z
src/jit/impl/mlir/compiler.cpp
Olalaye/MegEngine
695d24f24517536e6544b07936d189dbc031bbce
[ "Apache-2.0" ]
515
2020-03-19T06:10:05.000Z
2022-03-30T09:15:59.000Z
/** * \file src/jit/impl/mlir/compiler.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "megbrain_build_config.h" #if MGB_JIT && MGB_JIT_MLIR #include "./compiler.h" #include "./executable_cpu.h" #include "./executable_cuda.h" #include "./mlir_gen.h" #include "megbrain/common.h" #include "megbrain/comp_node_env.h" #include "megbrain/jit/mlir/ir/dialect.h" #include "megbrain/jit/mlir/ir/passes.h" #include "megbrain/utils/timer.h" #include <mlir/Conversion/GPUCommon/GPUCommonPass.h> #include <mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h> #include <mlir/Conversion/SCFToStandard/SCFToStandard.h> #include <mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h> #include <mlir/Dialect/GPU/Passes.h> #include <mlir/IR/Dialect.h> #include <mlir/IR/MLIRContext.h> #include <mlir/IR/Module.h> #include <mlir/InitAllDialects.h> #include <mlir/Pass/PassManager.h> #include <mlir/Support/LogicalResult.h> #include <mlir/Target/NVVMIR.h> #include <mlir/Transforms/Passes.h> #include <llvm/IRReader/IRReader.h> #include <llvm/Linker/Linker.h> #include <llvm/Pass.h> #include <llvm/Support/TargetSelect.h> #include <dirent.h> #include <dlfcn.h> using namespace mgb; using namespace jit; namespace { struct LLVMInitializer { LLVMInitializer() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); } }; static LLVMInitializer initializer; #if MGB_CUDA mlir::OwnedBlob compile_ptx_to_cubin( const std::string ptx, mlir::Location, llvm::StringRef) { OwnedBlob result = std::make_unique<std::vector<char>>(ptx.data(), ptx.data() + ptx.size()); return result; } std::unique_ptr<llvm::Module> translate_module_to_nvvm_ir_and_link_device( Operation* m, llvm::LLVMContext& llvmContext, llvm::StringRef name) { std::unique_ptr<llvm::Module> module = mlir::translateModuleToNVVMIR(m, llvmContext); auto get_device_path = []() -> std::string { auto cuda_path = getenv("CUDA_BIN_PATH"); std::string device_dir; if (!cuda_path) { char cuda_lib_path[PATH_MAX]; auto handle = dlopen("libcudart.so", RTLD_GLOBAL | RTLD_LAZY); mgb_assert(handle != nullptr, "%s", dlerror()); mgb_assert( dlinfo(handle, RTLD_DI_ORIGIN, &cuda_lib_path) != -1, "%s", dlerror()); device_dir = std::string(cuda_lib_path) + "/../../../nvvm/libdevice/"; mgb_assert(!dlclose(handle), "fail to dlclose handle"); } else { device_dir = std::string(cuda_path) + "/nvvm/libdevice/"; } DIR* dirp; struct dirent* directory; dirp = opendir(device_dir.c_str()); if (dirp) { while ((directory = readdir(dirp)) != nullptr) { if (!strncmp(directory->d_name, "libdevice", 9)) { closedir(dirp); return device_dir + std::string(directory->d_name); } } closedir(dirp); } return {}; }; //! load libdevice.bc llvm::SMDiagnostic err; auto libdevice_path = get_device_path(); std::unique_ptr<llvm::Module> mlib = llvm::parseIRFile(libdevice_path.c_str(), err, module->getContext()); if (mlib.get()) { mlib->setTargetTriple(module->getTargetTriple()); mlib->setDataLayout(module->getDataLayout()); RealTimer timer; mgb_assert( !llvm::Linker::linkModules( *module, std::move(mlib), llvm::Linker::Flags::LinkOnlyNeeded), "failed to parse ir file libdevice.bc"); mgb_log("MLIR JIT: link libdevice.bc, used: %.3fms", timer.get_msecs()); } else { mgb_log_warn("Fail to load bitcode file %s", libdevice_path.c_str()); } return module; } #endif void add_cpu_lowering_pass(mlir::PassManager& manager) { { mlir::OpPassManager& opt_pm = manager.nest<mlir::FuncOp>(); opt_pm.addPass(mlir::createCanonicalizerPass()); opt_pm.addPass(mlir::createCSEPass()); } { mlir::OpPassManager& opt_pm = manager.nest<mlir::FuncOp>(); opt_pm.addPass(create_lower_to_affine_pass()); opt_pm.addPass(mlir::createCanonicalizerPass()); opt_pm.addPass(mlir::createCSEPass()); opt_pm.addPass(mlir::createLoopFusionPass()); opt_pm.addPass(mlir::createMemRefDataFlowOptPass()); } manager.addPass(create_lower_to_llvm_pass()); } #if MGB_CUDA void add_cuda_lowering_pass( mlir::PassManager& manager, const std::string& target_chip) { { mlir::OpPassManager& opt_pm = manager.nest<mlir::FuncOp>(); opt_pm.addPass(mlir::createCanonicalizerPass()); opt_pm.addPass(mlir::createCSEPass()); opt_pm.addPass(mlir::createLoopFusionPass()); opt_pm.addPass(mlir::createMemRefDataFlowOptPass()); } manager.addPass(create_lower_to_gpu_pass()); { mlir::OpPassManager& opt_pm = manager.nest<gpu::GPUModuleOp>(); opt_pm.addPass(mlir::createLowerToCFGPass()); opt_pm.addPass(mlir::createCanonicalizerPass()); opt_pm.addPass(mlir::createCSEPass()); opt_pm.addPass(mlir::createLowerGpuOpsToNVVMOpsPass()); opt_pm.addPass(mlir::createConvertGPUKernelToBlobPass( translate_module_to_nvvm_ir_and_link_device, compile_ptx_to_cubin, "nvptx64-nvidia-cuda", target_chip, "+ptx60", MLIRCUDAExecutable::sm_blob_annotation)); } } #endif } // namespace /* ==================== MLIRCompiler ===================== */ thread_local mlir::MLIRContext MLIRCompiler::sm_ctx; MLIRCompiler::MLIRCompiler(CompNode::DeviceType device_type) : m_device_type{device_type} { #if MGB_CUDA if (m_device_type == CompNode::DeviceType::CUDA) { LLVMInitializeNVPTXTarget(); LLVMInitializeNVPTXTargetInfo(); LLVMInitializeNVPTXTargetMC(); LLVMInitializeNVPTXAsmPrinter(); } #endif } void MLIRCompiler::run_lowering_pass(mlir::OwningModuleRef& module, CompNode cn) { mgb_assert(cn.device_type() == m_device_type); mlir::PassManager manager(module->getContext()); std::string target_chip; switch (m_device_type) { case CompNode::DeviceType::CPU: add_cpu_lowering_pass(manager); break; #if MGB_CUDA case CompNode::DeviceType::CUDA: { auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop; std::string target_chip = ssprintf("sm_%d%d", prop.major, prop.minor); add_cuda_lowering_pass(manager, target_chip); break; } #endif default: mgb_throw( InternalError, "Unsupport device type: %d", static_cast<int>(m_device_type)); break; } RealTimer timer; mgb_assert(mlir::succeeded(manager.run(*module))); mgb_log("MLIR JIT: run lowering pass used: %.3f ms", timer.get_msecs()); } std::unique_ptr<Executable> MLIRCompiler::do_compile( const InternalGraph& graph, const JITExecutor::Args& args) { mlir::MLIRContext ctx; ctx.getOrLoadDialect<MgbDialect>(); ctx.printStackTraceOnDiagnostic(true); ctx.printOpOnDiagnostic(true); auto&& res = mlir_gen(ctx, graph, args); mgb_assert(res.second, "failed to generate module"); CompNode cn = args.owner->comp_node(); run_lowering_pass(res.second, cn); switch (cn.device_type()) { case CompNode::DeviceType::CPU: return std::make_unique<MLIRCPUExecutable>(res.second, res.first.str()); #if MGB_CUDA case CompNode::DeviceType::CUDA: return std::make_unique<MLIRCUDAExecutable>(res.second, res.first.str()); #endif default: mgb_throw( InternalError, "Unsupport device type: %d", static_cast<int>(cn.device_type())); return nullptr; } } size_t MLIRCompiler::get_nr_workspace_outputs(JITExecutor* opr) const { MGB_MARK_USED_VAR(opr); return 0; } void MLIRCompiler::init_workspace_size_infer(JITExecutor* opr) { MGB_MARK_USED_VAR(opr); } #endif // MGB_JIT && MGB_JIT_MLIR // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
33.843137
87
0.649247
[ "vector" ]
c0b2beeb856f7c30676ed1b35e25db31d176576a
6,365
cpp
C++
isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCamera.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCamera.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCamera.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "NewHorizonsMvicFrameCamera.h" #include <QDebug> #include <QString> #include "Camera.h" #include "CameraDetectorMap.h" #include "CameraDistortionMap.h" #include "CameraFocalPlaneMap.h" #include "CameraGroundMap.h" #include "CameraSkyMap.h" #include "IString.h" #include "iTime.h" #include "NewHorizonsMvicFrameCameraDistortionMap.h" #include "NaifStatus.h" using namespace std; namespace Isis { /** * Constructs a New Horizons MVIC Framing Camera object. The MVIC push-frame camera operates * in "staring" mode, so it has been implemented as a framing camera rather than a push-frame. * The test images show the same part of the planet in each framelet, so the push-frame * implementation will not work since the same lat/lon values are located in possibly every * framelet. * * @param lab Pvl label from a New Horizons MVIC Framing Camera image. * * @author Tracie Sucharski * @internal */ NewHorizonsMvicFrameCamera::NewHorizonsMvicFrameCamera(Cube &cube) : FramingCamera(cube) { m_instrumentNameLong = "Multispectral Visible Imaging Framing Camera"; m_instrumentNameShort = "MVIC FRAMING"; m_spacecraftNameLong = "New Horizons"; m_spacecraftNameShort = "NewHorizons"; NaifStatus::CheckErrors(); SetFocalLength(); SetPixelPitch(); // Get the start time from labels Pvl &lab = *cube.label(); PvlGroup &inst = lab.findGroup("Instrument", Pvl::Traverse); m_exposure = inst["ExposureDuration"]; QString stime = inst["SpacecraftClockStartCount"]; // ** TODO ** Need an offset time added to labels at ingestion?? The 0.125 value is // the value in DELTAT00. double offset = 0.125; m_etStart = getClockTime(stime).Et() + offset; SpiceChar utc[30]; et2utc_c(m_etStart, "ISOC", 3, 30, utc); // qDebug()<<"\n\nspacecraftClockStartCount + "<<offset<<" (offset) = "<<utc; // If bands have been extracted from the original image then we // need to read the band bin group so we can map from the cube band // number to the instrument band number. Also save times of each framelet which are stored // in the BandBin group. PvlGroup &bandBin = lab.findGroup("BandBin", Pvl::Traverse); PvlKeyword &origBand = bandBin["OriginalBand"]; PvlKeyword &utcTime = bandBin["UtcTime"]; for(int i = 0; i < origBand.size(); i++) { m_originalBand.push_back(toInt(origBand[i])); m_utcTime.push_back(utcTime[i]); } CameraDetectorMap *detectorMap = new CameraDetectorMap(this); detectorMap->SetDetectorSampleSumming(1); detectorMap->SetDetectorLineSumming(1); // Setup focal plane map. The class will read data from the instrument addendum kernel to pull // out the affine transforms from detector samp,line to focal plane x,y. CameraFocalPlaneMap *focalMap = new CameraFocalPlaneMap(this, naifIkCode()); focalMap->SetDetectorOrigin(2500.5, 64.5); // Read distortion coefficients and boresight offsets from the instrument kernels. Then // construct the distortion map. //read the distortion coefs from the NAIF Kernels QString naifXKey = "INS-98900_DISTORTION_COEF_X"; QString naifYKey = "INS-98900_DISTORTION_COEF_Y"; QString naifppKey = "INS-98900_PP_OFFSET"; vector<double> distCoefX; vector<double> distCoefY; for (int i=0; i < 20; i++) { distCoefX.push_back(getDouble(naifXKey,i)); distCoefY.push_back(getDouble(naifYKey,i)); } new NewHorizonsMvicFrameCameraDistortionMap(this, distCoefX, distCoefY); // Setup the ground and sky map new CameraGroundMap(this); new CameraSkyMap(this); // Internalize all the NAIF SPICE information into memory. LoadCache(); NaifStatus::CheckErrors(); } /** * Sets the band in the camera model * * @param band The band number to set */ void NewHorizonsMvicFrameCamera::SetBand(const int vband) { if(vband > (int) m_originalBand.size()) { QString msg = QObject::tr("Band number out of array bounds in NewHorizonsMvicFrameCamera::SetBand legal " "bands are [1-%1], input was [%2]"). arg(m_originalBand.size()).arg(vband); throw IException(IException::Programmer, msg, _FILEINFO_); } iTime time(m_utcTime[vband-1]); double et = time.Et(); SpiceChar utc[30]; et2utc_c(et, "ISOC", 3, 30, utc); Camera::setTime(et); pair<iTime, iTime> shuttertimes = ShutterOpenCloseTimes(et, m_exposure); // Set up valid band access Camera::SetBand(vband); } /** * Returns the shutter open and close times. The user should pass in the * ExposureDuration keyword value and the StartTime keyword value, converted * to ephemeris time. The StartTime keyword value from the labels represents * the shutter center time of the observation. To find the shutter open and * close times, half of the exposure duration is subtracted from and added to * the input time parameter, respectively. This method overrides the * FramingCamera class method. * * @param exposureDuration ExposureDuration keyword value from the labels, in * seconds. * @param time The StartTime keyword value from the labels, converted to * ephemeris time. * * @return @b pair < @b iTime, @b iTime > The first value is the shutter * open time and the second is the shutter close time. * * @author 2014-01-01 Tracie Sucharski */ pair<iTime, iTime> NewHorizonsMvicFrameCamera::ShutterOpenCloseTimes(double time, double exposureDuration) { return FramingCamera::ShutterOpenCloseTimes(time, exposureDuration); } } /** * This is the function that is called in order to instantiate a NewHorizonsMvicFrameCamera * object. * * @param lab Cube labels * * @return Isis::Camera* NewHorizonsMvicFrameCamera * @internal */ extern "C" Isis::Camera *NewHorizonsMvicFrameCameraPlugin(Isis::Cube &cube) { return new Isis::NewHorizonsMvicFrameCamera(cube); }
35.758427
111
0.701021
[ "object", "vector", "model" ]
c0b79c03a94b511260303e955c5603bbd019327b
875
cpp
C++
ACM-ICPC Official/Qualification/NEERC, Southern Subregional/B.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2017-10-25T13:33:27.000Z
2017-10-25T13:33:27.000Z
ACM-ICPC Official/Qualification/NEERC, Southern Subregional/B.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
null
null
null
ACM-ICPC Official/Qualification/NEERC, Southern Subregional/B.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2021-05-05T01:16:28.000Z
2021-05-05T01:16:28.000Z
#include <iostream> #include <vector> using namespace std; const int SIZE = 2e5 + 10; vector<int> res[SIZE]; int big[SIZE] = {0}; int bs(int len, int k) { if (len <= 0 || big[len - 1] > k) return -1; int res = 0, l = 0, r = len - 1; int m; while (l <= r) { m = l + (r - l) / 2; if (big[m] < k) { res = m; r = m - 1; } else l = m + 1; } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); int num = 0, T, t; bool flag; cin >> T; while (T--) { flag = false; cin >> t; int s = bs(num, t); // cout << "Search pos: " << s << endl; if (s == -1) { res[num].emplace_back(t); big[num++] = t; } else { res[s].emplace_back(t); big[s] = t; } } for (int i = 0; i < num; i++) { for (auto i : res[i]) cout << i << " "; cout << endl; } return 0; }
17.156863
46
0.446857
[ "vector" ]
c0b86fbb7b4ebbd08688492c751c2635bc90ba23
4,011
cpp
C++
BATS/code/BTHAIModule/Source/MedicAgent.cpp
Senth/bats
51d4ec39f3a118ed0eb90ec27a1864c0ceef3898
[ "Apache-2.0" ]
null
null
null
BATS/code/BTHAIModule/Source/MedicAgent.cpp
Senth/bats
51d4ec39f3a118ed0eb90ec27a1864c0ceef3898
[ "Apache-2.0" ]
null
null
null
BATS/code/BTHAIModule/Source/MedicAgent.cpp
Senth/bats
51d4ec39f3a118ed0eb90ec27a1864c0ceef3898
[ "Apache-2.0" ]
null
null
null
#include "MedicAgent.h" #include "PFManager.h" #include "AgentManager.h" #include "Utilities/Logger.h" #include "BATSModule/include/Config.h" #include "BATSModule/include/SquadManager.h" #include "BATSModule/include/Helper.h" #include "BATSModule/include/Squad.h" #include "BatsModule/include/UnitManager.h" using namespace BWAPI; using namespace std; bats::UnitManager* MedicAgent::msUnitManager = NULL; MedicAgent::MedicAgent(Unit* mUnit) : UnitAgent(mUnit) { agentType = "MedicAgent"; if (msUnitManager == NULL) { msUnitManager = bats::UnitManager::getInstance(); } } void MedicAgent::computeActions() { checkUnitsToHeal(); computeMoveAction(true); } void MedicAgent::checkUnitsToHeal() { try { int bestDist = INT_MAX; const Unit* toHeal = NULL; TilePosition closeSearchFrom = getUnit()->getTilePosition(); /// @todo If assigned to squad, only heal units in the squad, or close units. /// Also heal close allied units if possible // Search for squad units if (getSquadId().isValid()) { bats::SquadCstPtr squad = msSquadManager->getSquad(getSquadId()); closeSearchFrom = squad->getCenter(); const vector<const UnitAgent*>& units = squad->getUnits(); for (size_t i = 0; i < units.size(); ++i) { if (isMedicTarget(units[i]->getUnit())) { int distSquared = bats::getSquaredDistance(units[i]->getUnit()->getTilePosition(), getUnit()->getTilePosition()); if (distSquared < bestDist) { bestDist = distSquared; toHeal = units[i]->getUnit(); } } } } // Else - Search all our units else { const vector<UnitAgent*>& units = msUnitManager->getUnitsByFilter(); for (size_t i = 0; i < units.size(); i++) { if (isMedicTarget(units[i]->getUnit())) { int distSquared = bats::getSquaredDistance(units[i]->getUnit()->getTilePosition(), getUnit()->getTilePosition()); if (distSquared < bestDist && distSquared <= bats::config::unit::medic::HEAL_SEARCH_DISTANCE_SQUARED) { bestDist = distSquared; toHeal = units[i]->getUnit(); } } } } // Check allied units too, if in squad it will search from the squad's center when checking // If the unit is close enough to the squad, otherwise it will use the unit's position const set<Player*>& players = Broodwar->allies(); set<Player*>::const_iterator playerIt; for (playerIt = players.begin(); playerIt != players.end(); ++playerIt) { const set<Unit*>& units = (*playerIt)->getUnits(); set<Unit*>::const_iterator unitIt; for (unitIt = units.begin(); unitIt != units.end(); ++unitIt) { if (isMedicTarget(*unitIt)) { int distSquared = bats::getSquaredDistance((*unitIt)->getTilePosition(), getUnit()->getTilePosition()); if (distSquared < bestDist && bats::isWithinRange(closeSearchFrom, (*unitIt)->getTilePosition(), bats::config::unit::medic::HEAL_SEARCH_DISTANCE)) { bestDist = distSquared; toHeal = (*unitIt); } } } } if (toHeal != NULL) { /// @todo remove const cast when fixed in BWAPI unit->useTech(TechTypes::Healing, const_cast<Unit*>(toHeal)); } } catch(exception) { ERROR_MESSAGE(false, "[" << unit->getID() << "] checkUnitToHeal() error"); } } bool MedicAgent::isMedicTarget(const Unit* unit) const { // Can only heal organic units if (!unit->getType().isOrganic()) { return false; } // We can heal workers, but no point in following them if (unit->getType().isWorker()) { return false; } // Don't heal loaded units, as in bunker or transport if (unit->isLoaded()) { return false; } // Only heal damaged units if (unit->getHitPoints() == unit->getType().maxHitPoints()) { return false; } // Only heal alive units if (unit->getHitPoints() == 0) { return false; } // Only heal completed units if (!unit->isCompleted()) { return false; } // Unit shall exist if (!unit->exists()) { return false; } // Don't heal ourselves if (unit->getID() == getUnitID()) { return false; } return true; }
26.215686
122
0.662678
[ "vector" ]
c0c94c62614b4c1f4f400d1ff1da99bdd3e990dc
5,692
cc
C++
components/viz/service/display/delegated_ink_point_renderer_skia.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/viz/service/display/delegated_ink_point_renderer_skia.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/viz/service/display/delegated_ink_point_renderer_skia.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/service/display/delegated_ink_point_renderer_skia.h" #include "base/metrics/histogram_macros.h" #include "base/trace_event/trace_event.h" #include "components/viz/common/delegated_ink_metadata.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/skia_util.h" namespace viz { void DelegatedInkPointRendererSkia::DrawDelegatedInkTrail(SkCanvas* canvas) { TRACE_EVENT1("viz", "DelegatedInkPointRendererSkia::DrawDelegatedInkTrail", "points", path_.countPoints()); if (!metadata_) return; if (!path_.isEmpty() && canvas) { canvas->save(); SkRect bounds = gfx::RectFToSkRect(metadata_->presentation_area()); canvas->clipRect(bounds); SkPaint paint; paint.setAntiAlias(true); paint.setBlendMode(SkBlendMode::kSrcOver); paint.setColor(metadata_->color()); paint.setFilterQuality(kNone_SkFilterQuality); paint.setStrokeCap(SkPaint::kRound_Cap); paint.setStrokeJoin(SkPaint::kRound_Join); paint.setStrokeWidth(SkScalar(metadata_->diameter())); paint.setStyle(SkPaint::kStroke_Style); canvas->drawPath(path_, paint); canvas->restore(); path_.rewind(); } // Always reset |metadata_| regardless of if the draw occurred or not so that // the trail is never incorrectly drawn if the aggregated frame did not // contain delegated ink metadata. metadata_.reset(); } gfx::Rect DelegatedInkPointRendererSkia::GetDamageRect() { if (old_trail_damage_rect_.IsEmpty() && new_trail_damage_rect_.IsEmpty()) return gfx::Rect(); gfx::RectF damage_rect_f = old_trail_damage_rect_; damage_rect_f.Union(new_trail_damage_rect_); return gfx::ToEnclosingRect(damage_rect_f); } base::TimeDelta GetImprovement( const std::vector<DelegatedInkPoint>* points_to_draw, const DelegatedInkMetadata* metadata) { if (points_to_draw->size() == 0) return base::TimeDelta::FromMilliseconds(0); return points_to_draw->back().timestamp() - metadata->timestamp(); } std::vector<SkPoint> DelegatedInkPointRendererSkia::GetPointsToDraw() { std::vector<DelegatedInkPoint> ink_points_to_draw = FilterPoints(); UMA_HISTOGRAM_TIMES( "Renderer.DelegatedInkTrail.LatencyImprovement.Skia.WithoutPrediction", GetImprovement(&ink_points_to_draw, metadata_.get())); PredictPoints(&ink_points_to_draw); std::vector<SkPoint> sk_points; for (DelegatedInkPoint ink_point : ink_points_to_draw) sk_points.push_back(gfx::PointFToSkPoint(ink_point.point())); return sk_points; } void DelegatedInkPointRendererSkia::FinalizePathForDraw() { // Always rewind the path first so that a path isn't drawn twice. path_.rewind(); // Setting the damage rect to empty ensures that the damage rect is cleared // when trails are not being drawn so that extra drawing doesn't occur. If // there isn't metadata, that also indicates that the previous trail has // finished so the predictor should be reset as well. if (!metadata_) { SetDamageRect(gfx::RectF()); ResetPrediction(); return; } std::vector<SkPoint> sk_points = GetPointsToDraw(); TRACE_EVENT_INSTANT1("viz", "Filtered and predicted points for delegated ink trail", TRACE_EVENT_SCOPE_THREAD, "points", sk_points.size()); // If there is only one point total after filtering and predicting, then it // will match the metadata point and therefore doesn't need to be drawn in // this way, as it will be rendered normally. if (sk_points.size() <= 1) { SetDamageRect(gfx::RectF()); return; } path_.moveTo(sk_points[0]); switch (sk_points.size()) { case 2: path_.lineTo(sk_points[1]); break; case 3: path_.quadTo(sk_points[1], sk_points[2]); break; case 4: path_.cubicTo(sk_points[1], sk_points[2], sk_points[3]); break; default: // The connection between two cubic bezier curves will be smooth only if // the second control point of the first curve, the end point of the first // curve/first control point of the second curve, and the second control // point of the second curve are colinear. Since this is unlikely to be // the case, connecting all four points via lines should be acceptable. for (uint64_t i = 1; i < sk_points.size(); ++i) path_.lineTo(sk_points[i]); break; } // path_.computeTightBounds() returns a rect that contains the points and // curves, but it isn't guaranteed to contain the drawn stroke, resulting in // the stroke sometimes existing outside of the damage_rect. Therefore, expand // it here to ensure that the stroke is included, then intersect with the // presentation area so that is can't extend beyond the drawable area. gfx::RectF damage_rect = gfx::SkRectToRectF(path_.computeTightBounds()); const float kRadius = metadata_->diameter() / 2.f; damage_rect.Inset(-kRadius, -kRadius); damage_rect.Intersect(metadata_->presentation_area()); TRACE_EVENT_INSTANT1( "viz", "DelegatedInkPointRendererSkia::FinalizePathForDraw", TRACE_EVENT_SCOPE_THREAD, "damage_rect", damage_rect.ToString()); SetDamageRect(damage_rect); } void DelegatedInkPointRendererSkia::SetDamageRect(gfx::RectF damage_rect) { old_trail_damage_rect_ = new_trail_damage_rect_; new_trail_damage_rect_ = damage_rect; } int DelegatedInkPointRendererSkia::GetPathPointCountForTest() const { return path_.countPoints(); } } // namespace viz
34.707317
80
0.727161
[ "geometry", "vector" ]
c0cbea86732cad44c1e75e631fa63e216d79e97d
1,339
cpp
C++
Modules/Core/src/DataManagement/mitkGeometry3D.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/Core/src/DataManagement/mitkGeometry3D.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/Core/src/DataManagement/mitkGeometry3D.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <iomanip> #include <sstream> #include "mitkGeometry3D.h" #include "mitkApplyTransformMatrixOperation.h" #include "mitkInteractionConst.h" #include "mitkMatrixConvert.h" #include "mitkPointOperation.h" #include "mitkRestorePlanePositionOperation.h" #include "mitkRotationOperation.h" #include <vtkMatrix4x4.h> #include <vtkMatrixToLinearTransform.h> // Standard constructor for the New() macro. Sets the geometry to 3 dimensions mitk::Geometry3D::Geometry3D() : BaseGeometry() { } mitk::Geometry3D::Geometry3D(const Geometry3D &other) : BaseGeometry(other) { } mitk::Geometry3D::~Geometry3D() { } itk::LightObject::Pointer mitk::Geometry3D::InternalClone() const { Self::Pointer newGeometry = new Self(*this); newGeometry->UnRegister(); return newGeometry.GetPointer(); }
27.326531
79
0.67289
[ "geometry" ]
c0d4b15b94ef8c609088b2f06b499e03b0f4edd2
1,303
cpp
C++
Cpp/Codes/Practice/LeetCode/413 Arithmetic Slices.cpp
QuincyWork/AllCodes
59fe045608dda924cb993dde957da4daff769438
[ "MIT" ]
null
null
null
Cpp/Codes/Practice/LeetCode/413 Arithmetic Slices.cpp
QuincyWork/AllCodes
59fe045608dda924cb993dde957da4daff769438
[ "MIT" ]
null
null
null
Cpp/Codes/Practice/LeetCode/413 Arithmetic Slices.cpp
QuincyWork/AllCodes
59fe045608dda924cb993dde957da4daff769438
[ "MIT" ]
1
2019-04-01T10:30:03.000Z
2019-04-01T10:30:03.000Z
#include <gtest\gtest.h> using namespace std; bool isArithmeticSlice(vector<int>& A, int begin, int end) { if (end - begin < 2) return false; int delta = A[begin] - A[begin + 1]; for (int i = begin + 1; i < end; ++i) { if ((A[begin] - A[begin + 1]) != delta) { return false; } } return true; } int numberOfArithmeticSlices1(vector<int>& A) { int count = 0; for (int i = 0; i < A.size() - 2; ++i) { for (int m = i + 2; m < A.size(); ++m) { if (isArithmeticSlice(A, i, m)) { ++count; } } } return count; } int numberOfArithmeticSlices(vector<int>& A) { if (A.size() < 3) { return 0; } vector<int> dp(A.size(), 0); int count = 0; for (int i = 2; i < A.size(); ++i) { if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { dp[i] = dp[i - 1] + 1; } count += dp[i]; } return count; } int numberOfArithmeticSlices2(vector<int>& A) { if (A.size() < 3) { return 0; } int current = 0; int count = 0; for (int i = 2; i < A.size(); ++i) { if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { current++; } else { current = 0; } count += current; } return count; } TEST(LeetCode, tNumberOfArithmeticSlices) { int d1[] = { 1, 2, 3, 4 }; vector<int> v1(d1, d1 + _countof(d1)); ASSERT_EQ(numberOfArithmeticSlices(v1), 3); }
14.010753
58
0.523408
[ "vector" ]
c0d8382f85d5d3c397ff7e43663f8cdb98affb26
6,758
hh
C++
include/sdf/Noise.hh
FirefoxMetzger/sdformat
b25ecbc75f6d54b0f35ceafb0222c8dd544fdbbc
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/sdf/Noise.hh
FirefoxMetzger/sdformat
b25ecbc75f6d54b0f35ceafb0222c8dd544fdbbc
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/sdf/Noise.hh
FirefoxMetzger/sdformat
b25ecbc75f6d54b0f35ceafb0222c8dd544fdbbc
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Open Source Robotics 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. * */ #ifndef SDF_NOISE_HH_ #define SDF_NOISE_HH_ #include <ignition/utils/ImplPtr.hh> #include <sdf/Error.hh> #include <sdf/Element.hh> #include <sdf/sdf_config.h> namespace sdf { // Inline bracke to help doxygen filtering. inline namespace SDF_VERSION_NAMESPACE { /// \enum NoiseType /// \brief The set of noise types. enum class NoiseType { /// \brief No noise model. NONE = 0, /// \brief Draw noise values independently for each measurement from a /// Gaussian distribution GAUSSIAN = 1, /// \brief Gaussian noise plus quantization of outputs (ie. rounding). GAUSSIAN_QUANTIZED = 2, }; /// \brief The Noise class contains information about a noise /// model, such as a Gaussian distribution. A Noise DOM object is /// typically available from a Sensor. class SDFORMAT_VISIBLE Noise { /// \brief Default constructor public: Noise(); /// \brief Return true if both Noise objects contain the same values. /// \param[_in] _noise Noise value to compare. /// \return True if 'this' == _noise. public: bool operator==(const Noise &_noise) const; /// \brief Return true the Noise objects do not contain the same values. /// \param[_in] _noise Noise value to compare. /// \returen True if 'this' != _noise. public: bool operator!=(const Noise &_noise) const; /// \brief Load the noise based on a element pointer. This is *not* /// the usual entry point. Typical usage of the SDF DOM is through the Root /// object. /// \param[in] _sdf The SDF Element pointer /// \return Errors, which is a vector of Error objects. Each Error includes /// an error code and message. An empty vector indicates no error. public: Errors Load(ElementPtr _sdf); /// \brief Get the type of noise. /// \return The noise type. public: NoiseType Type() const; /// \brief Set the type of noise. /// \param[in] _type The noise type. public: void SetType(NoiseType _type); /// \brief Get the mean of the Gaussian distribution /// from which noise values are drawn. This is applicable to "gaussian*" /// noise types. /// \return The mean of the Guassian distribution. public: double Mean() const; /// \brief Set the mean of the Gaussian distribution /// from which noise values are drawn. This is applicable to "gaussian*" /// noise types. /// \param[in] _mean The mean of the Guassian distribution. public: void SetMean(double _mean); /// \brief Get the standard deviation of the Gaussian distribution /// from which noise values are drawn. This is applicable to "gaussian*" /// noise types. /// \return The standard deviation of the Guassian distribution. public: double StdDev() const; /// \brief Set the standard deviation of the Gaussian distribution /// from which noise values are drawn. This is applicable to "gaussian*" /// noise types. /// \param[in] _stddev The standard deviation of the Guassian distribution. public: void SetStdDev(double _stddev); /// \brief Get the mean of the Gaussian distribution /// from which bias values are drawn. This is applicable to "gaussian*" /// noise types. /// \return The mean of the bias Guassian distribution. public: double BiasMean() const; /// \brief Set the mean of the Gaussian distribution /// from which bias values are drawn. This is applicable to "gaussian*" /// noise types. /// \param[in] _bias The mean of the bias Guassian distribution. public: void SetBiasMean(double _bias); /// \brief Get the standard deviation of the Gaussian distribution /// from which bias values are drawn. This is applicable to "gaussian*" /// noise types. /// \return The standard deviation of the bias Guassian distribution. public: double BiasStdDev() const; /// \brief Set the standard deviation of the Gaussian distribution /// from which bias values are drawn. This is applicable to "gaussian*" /// noise types. /// \param[in] _bias The standard deviation of the bias Guassian /// distribution. public: void SetBiasStdDev(double _bias); /// \brief For type "gaussian_quantized", get the precision of output /// signals. A value of zero implies infinite precision / no quantization. /// \return Precision of output signals. public: double Precision() const; /// \brief For type "gaussian_quantized", set the precision of output /// signals. A value of zero implies infinite precision / no quantization. /// \param[in] _precision Precision of output signals. public: void SetPrecision(double _precision); /// \brief For type "gaussian*", get the standard deviation of the noise /// used to drive a process to model slow variations in a sensor bias. /// \return The dynamic bias standard deviation. public: double DynamicBiasStdDev() const; /// \brief For type "gaussian*", set the standard deviation of the noise /// used to drive a process to model slow variations in a sensor bias. /// \param[in] _stddev The dynamic bias standard deviation. public: void SetDynamicBiasStdDev(double _stddev); /// \brief For type "gaussian*", get the correlation time of the noise /// used to drive a process to model slow variations in a sensor bias. /// \return The dynamic bias correlation time. public: double DynamicBiasCorrelationTime() const; /// \brief For type "gaussian*", set the correlation time in seconds of /// the noise used to drive a process to model slow variations in a sensor /// bias.A typical value, when used, would be on the order of /// 3600 seconds (1 hour). /// \param[in] _time The dynamic bias correlation time. public: void SetDynamicBiasCorrelationTime(double _time); /// \brief Get a pointer to the SDF element that was used during /// load. /// \return SDF element pointer. The value will be nullptr if Load has /// not been called. public: sdf::ElementPtr Element() const; /// \brief Private data pointer. IGN_UTILS_IMPL_PTR(dataPtr) }; } } #endif
39.520468
79
0.690885
[ "object", "vector", "model" ]
c0e08704c79bcdde0cbed6c7d771d2ccdf665699
46,037
cpp
C++
Implementation/iOSIlluminati/lib/SRC/KPM/kpmUtil.cpp
samssonart/gmtThesisAR
14813a2efb2e7fcf0aaf753ca68ab3ed7edcbd2e
[ "MIT" ]
null
null
null
Implementation/iOSIlluminati/lib/SRC/KPM/kpmUtil.cpp
samssonart/gmtThesisAR
14813a2efb2e7fcf0aaf753ca68ab3ed7edcbd2e
[ "MIT" ]
null
null
null
Implementation/iOSIlluminati/lib/SRC/KPM/kpmUtil.cpp
samssonart/gmtThesisAR
14813a2efb2e7fcf0aaf753ca68ab3ed7edcbd2e
[ "MIT" ]
null
null
null
/* * kpmUtil.cpp * ARToolKit5 * * This file is part of ARToolKit. * * ARToolKit 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. * * ARToolKit 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 ARToolKit. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, and to * copy and distribute the resulting executable under terms of your choice, * provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module * which is neither derived from nor based on this library. If you modify this * library, you may extend this exception to your version of the library, but you * are not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. * * Copyright 2015 Daqri, LLC. All rights reserved. * Copyright 2006-2015 ARToolworks, Inc. All rights reserved. * Author(s): Hirokazu Kato, Philip Lamb * */ #include <stdio.h> #include <stdlib.h> #include <AR/ar.h> #include <AR/icp.h> #include <KPM/kpm.h> #include <KPM/kpmType.h> #if BINARY_FEATURE #include <facade/visual_database_facade.h> #else #include <KPM/surfSub.h> #endif static ARUint8 *genBWImageFull ( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ); static ARUint8 *genBWImageHalf ( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ); static ARUint8 *genBWImageOneThird ( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ); static ARUint8 *genBWImageTwoThird ( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ); static ARUint8 *genBWImageQuart ( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ); #if !BINARY_FEATURE static int kpmUtilGetInitPoseHomography( float *sCoord, float *wCoord, int num, float initPose[3][4] ); #endif int kpmUtilGetCorner( ARUint8 *inImage, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int procMode, int maxPointNum, CornerPoints *cornerPoints ) { ARUint8 *inImageBW; int xsize2, ysize2; int cornerNum; int i; inImageBW = kpmUtilGenBWImage( inImage, pixFormat, xsize, ysize, procMode, &xsize2, &ysize2 ); //Eventually returns a //malloc()'ed buffer if( inImageBW == NULL ) return -1; #if BINARY_FEATURE vision::VisualDatabaseFacade *freakMatcher = new vision::VisualDatabaseFacade; freakMatcher->addImage(inImageBW, xsize, ysize, 1); const std::vector<vision::FeaturePoint>& points = freakMatcher->getQueryFeaturePoints(); cornerNum = (int)freakMatcher->getQueryFeaturePoints().size(); #else SurfSubHandleT *surfHandle; surfHandle = surfSubCreateHandle(xsize2, ysize2, AR_PIXEL_FORMAT_MONO); if (!surfHandle) { ARLOGe("Error: unable to initialise KPM feature matching.\n"); free( inImageBW ); //COVHI10283 return -1; } surfSubSetMaxPointNum( surfHandle, maxPointNum ); surfSubExtractFeaturePoint( surfHandle, inImageBW, NULL, 0 ); cornerNum = surfSubGetFeaturePointNum( surfHandle ); #endif if( procMode == KpmProcFullSize ) { for( i = 0; i < cornerNum; i++ ) { float x, y; #if BINARY_FEATURE x = points[i].x, y = points[i].y; #else surfSubGetFeaturePosition( surfHandle, i, &x, &y ); #endif cornerPoints->pt[i].x = (int)x; cornerPoints->pt[i].y = (int)y; } } else if( procMode == KpmProcTwoThirdSize ) { for( i = 0; i < cornerNum; i++ ) { float x, y; #if BINARY_FEATURE x = points[i].x, y = points[i].y; #else surfSubGetFeaturePosition( surfHandle, i, &x, &y ); #endif cornerPoints->pt[i].x = (int)(x * 1.5f); cornerPoints->pt[i].y = (int)(y * 1.5f); } } else if( procMode == KpmProcHalfSize ) { for( i = 0; i < cornerNum; i++ ) { float x, y; #if BINARY_FEATURE x = points[i].x, y = points[i].y; #else surfSubGetFeaturePosition( surfHandle, i, &x, &y ); #endif cornerPoints->pt[i].x = (int)(x * 2.0f); cornerPoints->pt[i].y = (int)(y * 2.0f); } } else if( procMode == KpmProcOneThirdSize ) { for( i = 0; i < cornerNum; i++ ) { float x, y; #if BINARY_FEATURE x = points[i].x, y = points[i].y; #else surfSubGetFeaturePosition( surfHandle, i, &x, &y ); #endif cornerPoints->pt[i].x = (int)(x * 3.0f); cornerPoints->pt[i].y = (int)(y * 3.0f); } } else { for( i = 0; i < cornerNum; i++ ) { float x, y; #if BINARY_FEATURE x = points[i].x, y = points[i].y; #else surfSubGetFeaturePosition( surfHandle, i, &x, &y ); #endif cornerPoints->pt[i].x = (int)(x * 4.0f); cornerPoints->pt[i].y = (int)(y * 4.0f); } } cornerPoints->num = cornerNum; free( inImageBW ); #if BINARY_FEATURE delete freakMatcher; #else surfSubDeleteHandle( &surfHandle ); #endif return 0; } ARUint8 *kpmUtilGenBWImage( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int procMode, int *newXsize, int *newYsize ) { if( procMode == KpmProcFullSize ) { return genBWImageFull( image, pixFormat, xsize, ysize, newXsize, newYsize ); } else if( procMode == KpmProcTwoThirdSize ) { return genBWImageTwoThird( image, pixFormat, xsize, ysize, newXsize, newYsize ); } else if( procMode == KpmProcHalfSize ) { return genBWImageHalf( image, pixFormat, xsize, ysize, newXsize, newYsize ); } else if( procMode == KpmProcOneThirdSize ) { return genBWImageOneThird( image, pixFormat, xsize, ysize, newXsize, newYsize ); } else { return genBWImageQuart( image, pixFormat, xsize, ysize, newXsize, newYsize ); } } #if !BINARY_FEATURE int kpmUtilGetPose( ARParamLT *cparamLT, KpmMatchResult *matchData, KpmRefDataSet *refDataSet, KpmInputDataSet *inputDataSet, float camPose[3][4], float *error ) { ICPHandleT *icpHandle; ICPDataT icpData; ICP2DCoordT *sCoord; ICP3DCoordT *wCoord; ARdouble initMatXw2Xc[3][4]; ARdouble err; int i; if( matchData->num < 4 ) return -1; arMalloc( sCoord, ICP2DCoordT, matchData->num ); arMalloc( wCoord, ICP3DCoordT, matchData->num ); for( i = 0; i < matchData->num; i++ ) { sCoord[i].x = inputDataSet->coord[matchData->match[i].inIndex].x; sCoord[i].y = inputDataSet->coord[matchData->match[i].inIndex].y; wCoord[i].x = refDataSet->refPoint[matchData->match[i].refIndex].coord3D.x; wCoord[i].y = refDataSet->refPoint[matchData->match[i].refIndex].coord3D.y; wCoord[i].z = 0.0; //printf("%3d: (%f %f) - (%f %f)\n", i, sCoord[i].x, sCoord[i].y, wCoord[i].x, wCoord[i].y); } icpData.num = i; icpData.screenCoord = &sCoord[0]; icpData.worldCoord = &wCoord[0]; if( icpGetInitXw2Xc_from_PlanarData( cparamLT->param.mat, sCoord, wCoord, matchData->num, initMatXw2Xc ) < 0 ) { //printf("Error!! at icpGetInitXw2Xc_from_PlanarData.\n"); free( sCoord ); free( wCoord ); return -1; } /* printf("--- Init pose ---\n"); for( int j = 0; j < 3; j++ ) { for( i = 0; i < 4; i++ ) printf(" %8.3f", initMatXw2Xc[j][i]); printf("\n"); } */ if( (icpHandle = icpCreateHandle( cparamLT->param.mat )) == NULL ) { free( sCoord ); free( wCoord ); return -1; } #if 0 if( icpData.num > 10 ) { icpSetInlierProbability( icpHandle, 0.7 ); if( icpPointRobust( icpHandle, &icpData, initMatXw2Xc, camPose, &err ) < 0 ) { ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } } else { if( icpPoint( icpHandle, &icpData, initMatXw2Xc, camPose, &err ) < 0 ) { ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } } #else # ifdef ARDOUBLE_IS_FLOAT if( icpPoint( icpHandle, &icpData, initMatXw2Xc, camPose, &err ) < 0 ) { //ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } # else ARdouble camPosed[3][4]; if( icpPoint( icpHandle, &icpData, initMatXw2Xc, camPosed, &err ) < 0 ) { //ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } for (int r = 0; r < 3; r++) for (int c = 0; c < 4; c++) camPose[r][c] = (float)camPosed[r][c]; # endif #endif icpDeleteHandle( &icpHandle ); /* printf("error = %f\n", err); for( int j = 0; j < 3; j++ ) { for( i = 0; i < 4; i++ ) printf(" %8.3f", camPose[j][i]); printf("\n"); } if( err > 10.0f ) { for( i = 0; i < matchData->num; i++ ) { printf("%d\t%f\t%f\t%f\t%f\n", i+1, sCoord[i].x, sCoord[i].y, wCoord[i].x, wCoord[i].y); } } */ free( sCoord ); free( wCoord ); *error = (float)err; if( *error > 10.0f ) return -1; return 0; } int kpmUtilGetPose2( ARParamLT *cparamLT, KpmMatchResult *matchData, KpmRefDataSet *refDataSet, int *redDataIndex, KpmInputDataSet *inputDataSet, float camPose[3][4], float *error ) { ICPHandleT *icpHandle; ICPDataT icpData; ICP2DCoordT *sCoord; ICP3DCoordT *wCoord; ARdouble initMatXw2Xc[3][4]; ARdouble err; int i; if( matchData->num < 4 ) return -1; arMalloc( sCoord, ICP2DCoordT, matchData->num ); arMalloc( wCoord, ICP3DCoordT, matchData->num ); for( i = 0; i < matchData->num; i++ ) { sCoord[i].x = inputDataSet->coord[matchData->match[i].inIndex].x; sCoord[i].y = inputDataSet->coord[matchData->match[i].inIndex].y; wCoord[i].x = refDataSet->refPoint[redDataIndex[matchData->match[i].refIndex]].coord3D.x; wCoord[i].y = refDataSet->refPoint[redDataIndex[matchData->match[i].refIndex]].coord3D.y; wCoord[i].z = 0.0; } icpData.num = i; icpData.screenCoord = &sCoord[0]; icpData.worldCoord = &wCoord[0]; if( icpGetInitXw2Xc_from_PlanarData( cparamLT->param.mat, sCoord, wCoord, matchData->num, initMatXw2Xc ) < 0 ) { //ARLOGe("Error!! at icpGetInitXw2Xc_from_PlanarData.\n"); free( sCoord ); free( wCoord ); return -1; } /* ARLOG("--- Init pose ---\n"); for( int j = 0; j < 3; j++ ) { for( i = 0; i < 4; i++ ) ARLOG(" %8.3f", initMatXw2Xc[j][i]); ARLOG("\n"); } */ if( (icpHandle = icpCreateHandle( cparamLT->param.mat )) == NULL ) { free( sCoord ); free( wCoord ); return -1; } #if 0 if( icpData.num > 10 ) { icpSetInlierProbability( icpHandle, 0.7 ); if( icpPointRobust( icpHandle, &icpData, initMatXw2Xc, camPose, &err ) < 0 ) { ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } } else { if( icpPoint( icpHandle, &icpData, initMatXw2Xc, camPose, &err ) < 0 ) { ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } } #else # ifdef ARDOUBLE_IS_FLOAT if( icpPoint( icpHandle, &icpData, initMatXw2Xc, camPose, &err ) < 0 ) { //ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } # else ARdouble camPosed[3][4]; if( icpPoint( icpHandle, &icpData, initMatXw2Xc, camPosed, &err ) < 0 ) { //ARLOGe("Error!! at icpPoint.\n"); free( sCoord ); free( wCoord ); icpDeleteHandle( &icpHandle ); return -1; } for (int r = 0; r < 3; r++) for (int c = 0; c < 4; c++) camPose[r][c] = (float)camPosed[r][c]; # endif #endif icpDeleteHandle( &icpHandle ); /* ARLOG("error = %f\n", err); for( int j = 0; j < 3; j++ ) { for( i = 0; i < 4; i++ ) ARLOG(" %8.3f", camPose[j][i]); ARLOG("\n"); } if( err > 10.0 ) { for( i = 0; i < matchData->num; i++ ) { ARLOG("%d\t%f\t%f\t%f\t%f\n", i+1, sCoord[i].x, sCoord[i].y, wCoord[i].x, wCoord[i].y); } } */ free( sCoord ); free( wCoord ); *error = (float)err; if( *error > 10.0f ) return -1; return 0; } int kpmUtilGetPoseHomography( KpmMatchResult *matchData, KpmRefDataSet *refDataSet, KpmInputDataSet *inputDataSet, float camPose[3][4], float *error ) { float *sCoord; float *wCoord; float initPose[3][4]; int num; int i; if( matchData->num < 4 ) return -1; num = matchData->num; arMalloc( sCoord, float, num*2 ); arMalloc( wCoord, float, num*2 ); for( i = 0; i < num; i++ ) { sCoord[i*2+0] = inputDataSet->coord[matchData->match[i].inIndex].x; sCoord[i*2+1] = inputDataSet->coord[matchData->match[i].inIndex].y; wCoord[i*2+0] = refDataSet->refPoint[matchData->match[i].refIndex].coord3D.x; wCoord[i*2+1] = refDataSet->refPoint[matchData->match[i].refIndex].coord3D.y; } if( kpmUtilGetInitPoseHomography( sCoord, wCoord, num, initPose ) < 0 ) { free( sCoord ); free( wCoord ); return -1; } for( int j = 0; j < 3; j++ ) { for( i = 0; i < 4; i++ ) camPose[j][i] = initPose[j][i]; } *error = 0.0; float *p1 = sCoord; float *p2 = wCoord; for( i = 0; i < num; i++ ) { float x, y, w; x = camPose[0][0] * *p2 + camPose[0][1] * *(p2+1) + camPose[0][3]; y = camPose[1][0] * *p2 + camPose[1][1] * *(p2+1) + camPose[1][3]; w = camPose[2][0] * *p2 + camPose[2][1] * *(p2+1) + camPose[2][3]; if( w == 0.0 ) { free( sCoord ); free( wCoord ); return -1; } x /= w; y /= w; *error += (*p1 - x)*(*p1 - x) + (*(p1+1) - y)*(*(p1+1) - y); } *error /= num; free( sCoord ); free( wCoord ); if( *error > 10.0 ) return -1; return 0; } #endif static ARUint8 *genBWImageFull( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ) { ARUint8 *newImage, *p; int xsize2, ysize2; int i, j; *newXsize = xsize2 = xsize; *newYsize = ysize2 = ysize; arMalloc( newImage, ARUint8, xsize*ysize ); if( pixFormat == AR_PIXEL_FORMAT_RGB || pixFormat == AR_PIXEL_FORMAT_BGR ) { p = newImage; for( j = 0; j < ysize2; j++ ) { for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*image + (int)*(image+1) + (int)*(image+2) ) / 3; image+=3; } } } else if( pixFormat == AR_PIXEL_FORMAT_RGBA || pixFormat == AR_PIXEL_FORMAT_BGRA ) { p = newImage; for( j = 0; j < ysize2; j++ ) { for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*image + (int)*(image+1) + (int)*(image+2) ) / 3; image+=4; } } } else if( pixFormat == AR_PIXEL_FORMAT_ABGR || pixFormat == AR_PIXEL_FORMAT_ARGB) { p = newImage; for( j = 0; j < ysize2; j++ ) { for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(image+1) + (int)*(image+2) + (int)*(image+3) ) / 3; image+=4; } } } else if( pixFormat == AR_PIXEL_FORMAT_MONO || pixFormat == AR_PIXEL_FORMAT_420f || pixFormat == AR_PIXEL_FORMAT_420v || pixFormat == AR_PIXEL_FORMAT_NV21 ) { p = newImage; for( j = 0; j < ysize2; j++ ) { for( i = 0; i < xsize2; i++ ) { *(p++) = *(image++); } } } else if( pixFormat == AR_PIXEL_FORMAT_2vuy ) { p = newImage; for( j = 0; j < ysize2; j++ ) { for( i = 0; i < xsize2; i++ ) { *(p++) = *(image+1); image+=2; } } } else if( pixFormat == AR_PIXEL_FORMAT_yuvs ) { p = newImage; for( j = 0; j < ysize2; j++ ) { for( i = 0; i < xsize2; i++ ) { *(p++) = *image; image+=2; } } } return newImage; } static ARUint8 *genBWImageHalf( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ) { ARUint8 *newImage; ARUint8 *p, *p1, *p2; int xsize2, ysize2; int i, j; *newXsize = xsize2 = xsize/2; *newYsize = ysize2 = ysize/2; arMalloc( newImage, ARUint8, xsize2*ysize2 ); if( pixFormat == AR_PIXEL_FORMAT_RGB || pixFormat == AR_PIXEL_FORMAT_BGR ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*3*(j*2+0); p2 = image + xsize*3*(j*2+1); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p1+4) + (int)*(p1+5) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5) ) / 12; p1+=6; p2+=6; } } } else if( pixFormat == AR_PIXEL_FORMAT_RGBA || pixFormat == AR_PIXEL_FORMAT_BGRA ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*4*(j*2+0); p2 = image + xsize*4*(j*2+1); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+4) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6) ) / 12; p1+=8; p2+=8; } } } else if( pixFormat == AR_PIXEL_FORMAT_ABGR || pixFormat == AR_PIXEL_FORMAT_ARGB) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*4*(j*2+0); p2 = image + xsize*4*(j*2+1); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7) ) / 12; p1+=8; p2+=8; } } } else if( pixFormat == AR_PIXEL_FORMAT_MONO || pixFormat == AR_PIXEL_FORMAT_420f || pixFormat == AR_PIXEL_FORMAT_420v || pixFormat == AR_PIXEL_FORMAT_NV21) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*(j*2+0); p2 = image + xsize*(j*2+1); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p2+0) + (int)*(p2+1) ) / 4; p1+=2; p2+=2; } } } else if( pixFormat == AR_PIXEL_FORMAT_2vuy) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*2*(j*2+0); p2 = image + xsize*2*(j*2+1); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+1) + (int)*(p1+3) + (int)*(p2+1) + (int)*(p2+3) ) / 4; p1+=4; p2+=4; } } } else if( pixFormat == AR_PIXEL_FORMAT_yuvs) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*2*(j*2+0); p2 = image + xsize*2*(j*2+1); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+2) + (int)*(p2+0) + (int)*(p2+2) ) / 4; p1+=4; p2+=4; } } } return newImage; } static ARUint8 *genBWImageQuart( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ) { ARUint8 *newImage; ARUint8 *p, *p1, *p2, *p3, *p4; int xsize2, ysize2; int i, j; *newXsize = xsize2 = xsize/4; *newYsize = ysize2 = ysize/4; arMalloc( newImage, ARUint8, xsize2*ysize2 ); if( pixFormat == AR_PIXEL_FORMAT_RGB || pixFormat == AR_PIXEL_FORMAT_BGR ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*3*(j*4+0); p2 = image + xsize*3*(j*4+1); p3 = image + xsize*3*(j*4+2); p4 = image + xsize*3*(j*4+3); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p1+4) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7) + (int)*(p1+8) + (int)*(p1+9) + (int)*(p1+10) + (int)*(p1+11) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7) + (int)*(p2+8) + (int)*(p2+9) + (int)*(p2+10) + (int)*(p2+11) + (int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3) + (int)*(p3+4) + (int)*(p3+5) + (int)*(p3+6) + (int)*(p3+7) + (int)*(p3+8) + (int)*(p3+9) + (int)*(p3+10) + (int)*(p3+11) + (int)*(p4+0) + (int)*(p4+1) + (int)*(p4+2) + (int)*(p4+3) + (int)*(p4+4) + (int)*(p4+5) + (int)*(p4+6) + (int)*(p4+7) + (int)*(p4+8) + (int)*(p4+9) + (int)*(p4+10) + (int)*(p4+11)) / 48; p1+=12; p2+=12; p3+=12; p4+=12; } } } else if( pixFormat == AR_PIXEL_FORMAT_RGBA || pixFormat == AR_PIXEL_FORMAT_BGRA ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*4*(j*4+0); p2 = image + xsize*4*(j*4+1); p3 = image + xsize*4*(j*4+2); p4 = image + xsize*4*(j*4+3); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+4) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+8) + (int)*(p1+9) + (int)*(p1+10) + (int)*(p1+12) + (int)*(p1+13) + (int)*(p1+14) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+8) + (int)*(p2+9) + (int)*(p2+10) + (int)*(p2+12) + (int)*(p2+13) + (int)*(p2+14) + (int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+4) + (int)*(p3+5) + (int)*(p3+6) + (int)*(p3+8) + (int)*(p3+9) + (int)*(p3+10) + (int)*(p3+12) + (int)*(p3+13) + (int)*(p3+14) + (int)*(p4+0) + (int)*(p4+1) + (int)*(p4+2) + (int)*(p4+4) + (int)*(p4+5) + (int)*(p4+6) + (int)*(p4+8) + (int)*(p4+9) + (int)*(p4+10) + (int)*(p4+12) + (int)*(p4+13) + (int)*(p4+14)) / 48; p1+=16; p2+=16; p3+=16; p4+=16; } } } else if( pixFormat == AR_PIXEL_FORMAT_ABGR || pixFormat == AR_PIXEL_FORMAT_ARGB) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*4*(j*4+0); p2 = image + xsize*4*(j*4+1); p3 = image + xsize*4*(j*4+2); p4 = image + xsize*4*(j*4+3); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7) + (int)*(p1+9) + (int)*(p1+10) + (int)*(p1+11) + (int)*(p1+13) + (int)*(p1+14) + (int)*(p1+15) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7) + (int)*(p2+9) + (int)*(p2+10) + (int)*(p2+11) + (int)*(p2+13) + (int)*(p2+14) + (int)*(p2+15) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3) + (int)*(p3+5) + (int)*(p3+6) + (int)*(p3+7) + (int)*(p3+9) + (int)*(p3+10) + (int)*(p3+11) + (int)*(p3+13) + (int)*(p3+14) + (int)*(p3+15) + (int)*(p4+1) + (int)*(p4+2) + (int)*(p4+3) + (int)*(p4+5) + (int)*(p4+6) + (int)*(p4+7) + (int)*(p4+9) + (int)*(p4+10) + (int)*(p4+11) + (int)*(p4+13) + (int)*(p4+14) + (int)*(p4+15)) / 48; p1+=16; p2+=16; p3+=16; p4+=16; } } } else if( pixFormat == AR_PIXEL_FORMAT_MONO || pixFormat == AR_PIXEL_FORMAT_420f || pixFormat == AR_PIXEL_FORMAT_420v || pixFormat == AR_PIXEL_FORMAT_NV21 ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*(j*4+0); p2 = image + xsize*(j*4+1); p3 = image + xsize*(j*4+2); p4 = image + xsize*(j*4+3); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3) + (int)*(p4+0) + (int)*(p4+1) + (int)*(p4+2) + (int)*(p4+3)) / 16; p1+=4; p2+=4; p3+=4; p4+=4; } } } else if( pixFormat == AR_PIXEL_FORMAT_2vuy ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*2*(j*4+0); p2 = image + xsize*2*(j*4+1); p3 = image + xsize*2*(j*4+2); p4 = image + xsize*2*(j*4+3); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+1) + (int)*(p1+3) + (int)*(p1+5) + (int)*(p1+7) + (int)*(p2+1) + (int)*(p2+3) + (int)*(p2+5) + (int)*(p2+7) + (int)*(p3+1) + (int)*(p3+3) + (int)*(p3+5) + (int)*(p3+7) + (int)*(p4+1) + (int)*(p4+3) + (int)*(p4+5) + (int)*(p4+7)) / 16; p1+=8; p2+=8; p3+=8; p4+=8; } } } else if( pixFormat == AR_PIXEL_FORMAT_yuvs ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*2*(j*4+0); p2 = image + xsize*2*(j*4+1); p3 = image + xsize*2*(j*4+2); p4 = image + xsize*2*(j*4+3); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+2) + (int)*(p1+4) + (int)*(p1+6) + (int)*(p2+0) + (int)*(p2+2) + (int)*(p2+4) + (int)*(p2+6) + (int)*(p3+0) + (int)*(p3+2) + (int)*(p3+4) + (int)*(p3+6) + (int)*(p4+0) + (int)*(p4+2) + (int)*(p4+4) + (int)*(p4+6)) / 16; p1+=8; p2+=8; p3+=8; p4+=8; } } } return newImage; } static ARUint8 *genBWImageOneThird( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ) { ARUint8 *newImage; ARUint8 *p, *p1, *p2, *p3; int xsize2, ysize2; int i, j; *newXsize = xsize2 = xsize/3; *newYsize = ysize2 = ysize/3; arMalloc( newImage, ARUint8, xsize2*ysize2 ); if( pixFormat == AR_PIXEL_FORMAT_RGB || pixFormat == AR_PIXEL_FORMAT_BGR ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*3*(j*3+0); p2 = image + xsize*3*(j*3+1); p3 = image + xsize*3*(j*3+2); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p1+4) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7) + (int)*(p1+8) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7) + (int)*(p2+8) + (int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3) + (int)*(p3+4) + (int)*(p3+5) + (int)*(p3+6) + (int)*(p3+7) + (int)*(p3+8) ) / 27; p1+=9; p2+=9; p3+=9; } } } else if( pixFormat == AR_PIXEL_FORMAT_RGBA || pixFormat == AR_PIXEL_FORMAT_BGRA ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*4*(j*3+0); p2 = image + xsize*4*(j*3+1); p3 = image + xsize*4*(j*3+2); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+4) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+8) + (int)*(p1+9) + (int)*(p1+10) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+8) + (int)*(p2+9) + (int)*(p2+10) + (int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+4) + (int)*(p3+5) + (int)*(p3+6) + (int)*(p3+8) + (int)*(p3+9) + (int)*(p3+10) ) / 27; p1+=12; p2+=12; p3+=12; } } } else if( pixFormat == AR_PIXEL_FORMAT_ABGR || pixFormat == AR_PIXEL_FORMAT_ARGB) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*4*(j*3+0); p2 = image + xsize*4*(j*3+1); p3 = image + xsize*4*(j*3+2); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3) + (int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7) + (int)*(p1+9) + (int)*(p1+10) + (int)*(p1+11) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3) + (int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7) + (int)*(p2+9) + (int)*(p2+10) + (int)*(p2+11) + (int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3) + (int)*(p3+5) + (int)*(p3+6) + (int)*(p3+7) + (int)*(p3+9) + (int)*(p3+10) + (int)*(p3+11) ) / 27; p1+=12; p2+=12; p3+=12; } } } else if( pixFormat == AR_PIXEL_FORMAT_MONO || pixFormat == AR_PIXEL_FORMAT_420f || pixFormat == AR_PIXEL_FORMAT_420v || pixFormat == AR_PIXEL_FORMAT_NV21 ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*(j*3+0); p2 = image + xsize*(j*3+1); p3 = image + xsize*(j*3+2); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2) + (int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2) + (int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2) ) / 9; p1+=3; p2+=3; p3+=3; } } } else if( pixFormat == AR_PIXEL_FORMAT_2vuy ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*2*(j*3+0); p2 = image + xsize*2*(j*3+1); p3 = image + xsize*2*(j*3+2); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+1) + (int)*(p1+3) + (int)*(p1+5) + (int)*(p2+1) + (int)*(p2+3) + (int)*(p2+5) + (int)*(p3+1) + (int)*(p3+3) + (int)*(p3+5) ) / 9; p1+=6; p2+=6; p3+=6; } } } else if( pixFormat == AR_PIXEL_FORMAT_yuvs ) { p = newImage; for( j = 0; j < ysize2; j++ ) { p1 = image + xsize*2*(j*3+0); p2 = image + xsize*2*(j*3+1); p3 = image + xsize*2*(j*3+2); for( i = 0; i < xsize2; i++ ) { *(p++) = ( (int)*(p1+0) + (int)*(p1+2) + (int)*(p1+4) + (int)*(p2+0) + (int)*(p2+2) + (int)*(p2+4) + (int)*(p3+0) + (int)*(p3+2) + (int)*(p3+4) ) / 9; p1+=6; p2+=6; p3+=6; } } } return newImage; } static ARUint8 *genBWImageTwoThird ( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int *newXsize, int *newYsize ) { ARUint8 *newImage; ARUint8 *q1, *q2, *p1, *p2, *p3; int xsize2, ysize2; int i, j; *newXsize = xsize2 = xsize/3*2; *newYsize = ysize2 = ysize/3*2; arMalloc( newImage, ARUint8, xsize2*ysize2 ); if( pixFormat == AR_PIXEL_FORMAT_RGB || pixFormat == AR_PIXEL_FORMAT_BGR ) { q1 = newImage; q2 = newImage + xsize2; for( j = 0; j < ysize2/2; j++ ) { p1 = image + xsize*3*(j*3+0); p2 = image + xsize*3*(j*3+1); p3 = image + xsize*3*(j*3+2); for( i = 0; i < xsize2/2; i++ ) { *(q1++) = ( ((int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2)) + ((int)*(p1+3) + (int)*(p1+4) + (int)*(p1+5))/2 + ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/2 + ((int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5))/4 ) * 4/27; *(q2++) = ( ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/2 + ((int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5))/4 + ((int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2)) + ((int)*(p3+3) + (int)*(p3+4) + (int)*(p3+5))/2 ) * 4/27; p1+=3; p2+=3; p3+=3; *(q1++) = ( ((int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2))/2 + ((int)*(p1+3) + (int)*(p1+4) + (int)*(p1+5)) + ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/4 + ((int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5))/2 ) * 4/27; *(q2++) = ( ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/4 + ((int)*(p2+3) + (int)*(p2+4) + (int)*(p2+5))/2 + ((int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2))/2 + ((int)*(p3+3) + (int)*(p3+4) + (int)*(p3+5)) ) * 4/27; p1+=6; p2+=6; p3+=6; } q1 += xsize2; q2 += xsize2; } } else if( pixFormat == AR_PIXEL_FORMAT_RGBA || pixFormat == AR_PIXEL_FORMAT_BGRA ) { q1 = newImage; q2 = newImage + xsize2; for( j = 0; j < ysize2/2; j++ ) { p1 = image + xsize*4*(j*3+0); p2 = image + xsize*4*(j*3+1); p3 = image + xsize*4*(j*3+2); for( i = 0; i < xsize2/2; i++ ) { *(q1++) = ( ((int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2)) + ((int)*(p1+4) + (int)*(p1+5) + (int)*(p1+6))/2 + ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/2 + ((int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6))/4 ) * 4/27; *(q2++) = ( ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/2 + ((int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6))/4 + ((int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2)) + ((int)*(p3+4) + (int)*(p3+5) + (int)*(p3+6))/2 ) * 4/27; p1+=4; p2+=4; p3+=4; *(q1++) = ( ((int)*(p1+0) + (int)*(p1+1) + (int)*(p1+2))/2 + ((int)*(p1+4) + (int)*(p1+4) + (int)*(p1+4)) + ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/4 + ((int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6))/2 ) * 4/27; *(q2++) = ( ((int)*(p2+0) + (int)*(p2+1) + (int)*(p2+2))/4 + ((int)*(p2+4) + (int)*(p2+5) + (int)*(p2+6))/2 + ((int)*(p3+0) + (int)*(p3+1) + (int)*(p3+2))/2 + ((int)*(p3+4) + (int)*(p3+5) + (int)*(p3+6)) ) * 4/27; p1+=8; p2+=8; p3+=8; } q1 += xsize2; q2 += xsize2; } } else if( pixFormat == AR_PIXEL_FORMAT_ABGR || pixFormat == AR_PIXEL_FORMAT_ARGB) { q1 = newImage; q2 = newImage + xsize2; for( j = 0; j < ysize2/2; j++ ) { p1 = image + xsize*4*(j*3+0); p2 = image + xsize*4*(j*3+1); p3 = image + xsize*4*(j*3+2); for( i = 0; i < xsize2/2; i++ ) { *(q1++) = ( ((int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3)) + ((int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7))/2 + ((int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3))/2 + ((int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7))/4 ) * 4/27; *(q2++) = ( ((int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3))/2 + ((int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7))/4 + ((int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3)) + ((int)*(p3+5) + (int)*(p3+6) + (int)*(p3+7))/2 ) * 4/27; p1+=4; p2+=4; p3+=4; *(q1++) = ( ((int)*(p1+1) + (int)*(p1+2) + (int)*(p1+3))/2 + ((int)*(p1+5) + (int)*(p1+6) + (int)*(p1+7)) + ((int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3))/4 + ((int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7))/2 ) * 4/27; *(q2++) = ( ((int)*(p2+1) + (int)*(p2+2) + (int)*(p2+3))/4 + ((int)*(p2+5) + (int)*(p2+6) + (int)*(p2+7))/2 + ((int)*(p3+1) + (int)*(p3+2) + (int)*(p3+3))/2 + ((int)*(p3+5) + (int)*(p3+6) + (int)*(p3+7)) ) * 4/27; p1+=8; p2+=8; p3+=8; } q1 += xsize2; q2 += xsize2; } } else if( pixFormat == AR_PIXEL_FORMAT_MONO || pixFormat == AR_PIXEL_FORMAT_420f || pixFormat == AR_PIXEL_FORMAT_420v || pixFormat == AR_PIXEL_FORMAT_NV21 ) { q1 = newImage; q2 = newImage + xsize2; for( j = 0; j < ysize2/2; j++ ) { p1 = image + xsize*(j*3+0); p2 = image + xsize*(j*3+1); p3 = image + xsize*(j*3+2); for( i = 0; i < xsize2/2; i++ ) { *(q1++) = ( (int)*(p1+0) + (int)*(p1+1)/2 + (int)*(p2+0)/2 + (int)*(p2+1)/4 ) *4/9; *(q2++) = ( (int)*(p2+0)/2 + (int)*(p2+1)/4 + (int)*(p3+0) + (int)*(p3+1)/2 ) *4/9; p1++; p2++; p3++; *(q1++) = ( (int)*(p1+0)/2 + (int)*(p1+1) + (int)*(p2+0)/4 + (int)*(p2+1)/2 ) *4/9; *(q2++) = ( (int)*(p2+0)/4 + (int)*(p2+1)/2 + (int)*(p3+0)/2 + (int)*(p3+1) ) *4/9; p1+=2; p2+=2; p3+=2; } q1 += xsize2; q2 += xsize2; } } else if( pixFormat == AR_PIXEL_FORMAT_2vuy ) { q1 = newImage; q2 = newImage + xsize2; for( j = 0; j < ysize2/2; j++ ) { p1 = image + xsize*2*(j*3+0); p2 = image + xsize*2*(j*3+1); p3 = image + xsize*2*(j*3+2); for( i = 0; i < xsize2/2; i++ ) { *(q1++) = ( (int)*(p1+1) + (int)*(p1+3)/2 + (int)*(p2+1)/2 + (int)*(p2+3)/4 ) *4/9; *(q2++) = ( (int)*(p2+1)/2 + (int)*(p2+3)/4 + (int)*(p3+1) + (int)*(p3+3)/2 ) *4/9; p1+=2; p2+=2; p3+=2; *(q1++) = ( (int)*(p1+1)/2 + (int)*(p1+3) + (int)*(p2+1)/4 + (int)*(p2+3)/2 ) *4/9; *(q2++) = ( (int)*(p2+1)/4 + (int)*(p2+3)/2 + (int)*(p3+1)/2 + (int)*(p3+3) ) *4/9; p1+=4; p2+=4; p3+=4; } q1 += xsize2; q2 += xsize2; } } else if( pixFormat == AR_PIXEL_FORMAT_yuvs ) { q1 = newImage; q2 = newImage + xsize2; for( j = 0; j < ysize2/2; j++ ) { p1 = image + xsize*2*(j*3+0); p2 = image + xsize*2*(j*3+1); p3 = image + xsize*2*(j*3+2); for( i = 0; i < xsize2/2; i++ ) { *(q1++) = ( (int)*(p1+0) + (int)*(p1+2)/2 + (int)*(p2+0)/2 + (int)*(p2+2)/4 ) *4/9; *(q2++) = ( (int)*(p2+0)/2 + (int)*(p2+2)/4 + (int)*(p3+0) + (int)*(p3+2)/2 ) *4/9; p1+=2; p2+=2; p3+=2; *(q1++) = ( (int)*(p1+0)/2 + (int)*(p1+2) + (int)*(p2+0)/4 + (int)*(p2+2)/2 ) *4/9; *(q2++) = ( (int)*(p2+0)/4 + (int)*(p2+2)/2 + (int)*(p3+0)/2 + (int)*(p3+2) ) *4/9; p1+=4; p2+=4; p3+=4; } q1 += xsize2; q2 += xsize2; } } return newImage; } #if !BINARY_FEATURE static int kpmUtilGetInitPoseHomography( float *sCoord, float *wCoord, int num, float initPose[3][4] ) { float *A, *B; ARMatf matA, matB; ARMatf *matAt, *matAtA, *matAtB, *matH; int i; int ret = 0; arMalloc( A, float, num*8*2 ); arMalloc( B, float, num*2 ); for( i = 0; i < num; i++ ) { A[i*16+ 0] = wCoord[i*2+0]; A[i*16+ 1] = wCoord[i*2+1]; A[i*16+ 2] = 1.0; A[i*16+ 3] = 0.0; A[i*16+ 4] = 0.0; A[i*16+ 5] = 0.0; A[i*16+ 6] = -sCoord[i*2+0]*wCoord[i*2+0]; A[i*16+ 7] = -sCoord[i*2+0]*wCoord[i*2+1]; A[i*16+ 8] = 0.0; A[i*16+ 9] = 0.0; A[i*16+10] = 0.0; A[i*16+11] = wCoord[i*2+0]; A[i*16+12] = wCoord[i*2+1]; A[i*16+13] = 1.0; A[i*16+14] = -sCoord[i*2+1]*wCoord[i*2+0]; A[i*16+15] = -sCoord[i*2+1]*wCoord[i*2+1]; B[i*2+0] = sCoord[i*2+0]; B[i*2+1] = sCoord[i*2+1]; } matA.row = num*2; matA.clm = 8; matA.m = A; matB.row = num*2; matB.clm = 1; matB.m = B; matAt = arMatrixAllocTransf( &matA ); if( matAt == NULL ) { ret = -1; goto bail; } matAtA = arMatrixAllocMulf( matAt, &matA ); if( matAtA == NULL ) { ret = -1; goto bail1; } matAtB = arMatrixAllocMulf( matAt, &matB ); if( matAtB == NULL ) { ret = -1; goto bail2; } if( arMatrixSelfInvf(matAtA) < 0 ) { ret = -1; goto bail3; } matH = arMatrixAllocMulf( matAtA, matAtB ); if( matH == NULL ) { ret = -1; goto bail3; } initPose[0][0] = matH->m[0]; initPose[0][1] = matH->m[1]; initPose[0][2] = 0.0; initPose[0][3] = matH->m[2]; initPose[1][0] = matH->m[3]; initPose[1][1] = matH->m[4]; initPose[1][2] = 0.0; initPose[1][3] = matH->m[5]; initPose[2][0] = matH->m[6]; initPose[2][1] = matH->m[7]; initPose[2][2] = 0.0; initPose[2][3] = 1.0; arMatrixFreef( matH ); bail3: arMatrixFreef( matAtB ); bail2: arMatrixFreef( matAtA ); bail1: arMatrixFreef( matAt ); bail: free(B); free(A); return (ret); } #endif
37.581224
183
0.421704
[ "vector", "3d" ]
c0ef13b6ccd67c042387afde8e40b5d16e0bc734
5,584
cpp
C++
third_party/WebKit/Source/modules/background_sync/SyncManager.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/background_sync/SyncManager.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/background_sync/SyncManager.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/background_sync/SyncManager.h" #include "bindings/core/v8/CallbackPromiseAdapter.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/DOMException.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "modules/serviceworkers/ServiceWorkerRegistration.h" #include "platform/bindings/ScriptState.h" #include "platform/heap/Persistent.h" #include "platform/wtf/Functional.h" #include "platform/wtf/PtrUtil.h" #include "public/platform/InterfaceProvider.h" #include "public/platform/Platform.h" namespace blink { SyncManager::SyncManager(ServiceWorkerRegistration* registration) : registration_(registration) { DCHECK(registration); } ScriptPromise SyncManager::registerFunction(ScriptState* script_state, const String& tag) { // TODO(jkarlin): Wait for the registration to become active instead of // rejecting. See crbug.com/542437. if (!registration_->active()) return ScriptPromise::RejectWithDOMException( script_state, DOMException::Create(kAbortError, "Registration failed - no active Service Worker")); ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); mojom::blink::SyncRegistrationPtr sync_registration = mojom::blink::SyncRegistration::New(); sync_registration->id = SyncManager::kUnregisteredSyncID; sync_registration->tag = tag; sync_registration->network_state = blink::mojom::BackgroundSyncNetworkState::ONLINE; GetBackgroundSyncServicePtr()->Register( std::move(sync_registration), registration_->WebRegistration()->RegistrationId(), ConvertToBaseCallback( WTF::Bind(SyncManager::RegisterCallback, WrapPersistent(resolver)))); return promise; } ScriptPromise SyncManager::getTags(ScriptState* script_state) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); GetBackgroundSyncServicePtr()->GetRegistrations( registration_->WebRegistration()->RegistrationId(), ConvertToBaseCallback(WTF::Bind(&SyncManager::GetRegistrationsCallback, WrapPersistent(resolver)))); return promise; } const mojom::blink::BackgroundSyncServicePtr& SyncManager::GetBackgroundSyncServicePtr() { if (!background_sync_service_.get()) { Platform::Current()->GetInterfaceProvider()->GetInterface( mojo::MakeRequest(&background_sync_service_)); } return background_sync_service_; } // static void SyncManager::RegisterCallback(ScriptPromiseResolver* resolver, mojom::blink::BackgroundSyncError error, mojom::blink::SyncRegistrationPtr options) { // TODO(iclelland): Determine the correct error message to return in each case switch (error) { case mojom::blink::BackgroundSyncError::NONE: if (!options) { resolver->Resolve(v8::Null(resolver->GetScriptState()->GetIsolate())); return; } resolver->Resolve(); break; case mojom::blink::BackgroundSyncError::NOT_FOUND: NOTREACHED(); break; case mojom::blink::BackgroundSyncError::STORAGE: resolver->Reject( DOMException::Create(kUnknownError, "Background Sync is disabled.")); break; case mojom::blink::BackgroundSyncError::NOT_ALLOWED: resolver->Reject( DOMException::Create(kInvalidAccessError, "Attempted to register a sync event without a " "window or registration tag too long.")); break; case mojom::blink::BackgroundSyncError::PERMISSION_DENIED: resolver->Reject( DOMException::Create(kPermissionDeniedError, "Permission denied.")); break; case mojom::blink::BackgroundSyncError::NO_SERVICE_WORKER: resolver->Reject( DOMException::Create(kUnknownError, "No service worker is active.")); break; } } // static void SyncManager::GetRegistrationsCallback( ScriptPromiseResolver* resolver, mojom::blink::BackgroundSyncError error, WTF::Vector<mojom::blink::SyncRegistrationPtr> registrations) { // TODO(iclelland): Determine the correct error message to return in each case switch (error) { case mojom::blink::BackgroundSyncError::NONE: { Vector<String> tags; for (const auto& r : registrations) { tags.push_back(r->tag); } resolver->Resolve(tags); break; } case mojom::blink::BackgroundSyncError::NOT_FOUND: case mojom::blink::BackgroundSyncError::NOT_ALLOWED: case mojom::blink::BackgroundSyncError::PERMISSION_DENIED: // These errors should never be returned from // BackgroundSyncManager::GetRegistrations NOTREACHED(); break; case mojom::blink::BackgroundSyncError::STORAGE: resolver->Reject( DOMException::Create(kUnknownError, "Background Sync is disabled.")); break; case mojom::blink::BackgroundSyncError::NO_SERVICE_WORKER: resolver->Reject( DOMException::Create(kUnknownError, "No service worker is active.")); break; } } DEFINE_TRACE(SyncManager) { visitor->Trace(registration_); } } // namespace blink
36.496732
80
0.69914
[ "vector" ]
c0f1e32ff30fe239a33bfc320017e544662ef6de
1,654
cpp
C++
Adhoc Problems/equalise_prices.cpp
moinak878/Data-Structures-and-Algorithms-
75692d39c50e57121f12eb8175aa2de13c13196d
[ "MIT" ]
2
2019-10-20T03:13:35.000Z
2020-06-23T16:23:35.000Z
Adhoc Problems/equalise_prices.cpp
moinak878/Data-Structures-and-Algorithms-
75692d39c50e57121f12eb8175aa2de13c13196d
[ "MIT" ]
2
2019-10-01T16:02:25.000Z
2020-01-30T18:28:38.000Z
Adhoc Problems/equalise_prices.cpp
moinak878/Data-Structures-and-Algorithms-
75692d39c50e57121f12eb8175aa2de13c13196d
[ "MIT" ]
5
2020-01-30T17:08:21.000Z
2020-10-01T13:48:22.000Z
#include<iostream> #include<vector> //#include<bits/stdc++.h> /* using namespace std; long check(vector<long> a,long n,long k,long b){ if(abs(a[0]-b)>k||abs(a[n-1]-b)>k){ return 0; } return 1; } int main(){ long q; long n,k; cin>>q; vector <long> answer; for(long x=1;x<=q;x++){ cin>>n>>k; cout<<"\n"; vector<long> a(n); for(long i=0;i<n;i++){ cin>>a[i]; } sort(a.begin(),a.end()); long b=a[0]-k; //min long good=-1; long bad=-1; for(;(b<=a[n-1]+k);b++){ if(b<0)continue; if(check(a,n,k,b)==1) { if(b>good) good=b; } else { bad=-1; } } if(good==bad) answer.push_back(-1); else { answer.push_back(good); } } for(long i=0;i<q;i++) cout<<answer[i]<<"\n"; return 0; } */ #include<iostream> //#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ int q; cin>>q; while(q--){ int n,k; cin>>n>>k; vector<ll> a(n);int tot=0; for(int i=0;i<n;i++){ //o(N) cin>>a[i]; tot+=a[i]; } /*Let the first price be zero ; We equalise the prices to k; if the last price was 2k ; it would be decreased by k at most but if the difference was more; no number could be possible.. At max, we can equalise prices till a[min]+k.... */ sort(a.begin(),a.end()); //O(log N) if((a[n-1]-a[0])>2*k) cout<<-1<<endl; else cout<<a[0]+k<<endl; } }
18.175824
69
0.452237
[ "vector" ]
c0f511f1fd4c8e1bc94cb405c32c424b24c7f62f
6,495
cc
C++
chrome/browser/webshare/chromeos/sharesheet_client_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/webshare/chromeos/sharesheet_client_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/webshare/chromeos/sharesheet_client_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/webshare/chromeos/sharesheet_client.h" #include <string> #include <vector> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/task_environment.h" #include "chrome/browser/ash/file_manager/path_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sharesheet/sharesheet_types.h" #include "chrome/browser/webshare/prepare_directory_task.h" #include "chrome/browser/webshare/store_file_task.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "content/public/browser/site_instance.h" #include "content/public/test/web_contents_tester.h" #include "third_party/blink/public/mojom/webshare/webshare.mojom.h" #include "url/gurl.h" namespace webshare { class SharesheetClientUnitTest : public ChromeRenderViewHostTestHarness { public: SharesheetClientUnitTest() : ChromeRenderViewHostTestHarness( base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); StoreFileTask::SkipCopyingForTesting(); SharesheetClient::SetSharesheetCallbackForTesting( base::BindRepeating(&SharesheetClientUnitTest::AcceptShareRequest)); } void SetGuest() { Profile* const otr_profile = profile()->GetOffTheRecordProfile( Profile::OTRProfileID::CreateUniqueForTesting(), /*create_if_needed=*/true); EXPECT_TRUE(otr_profile->IsOffTheRecord()); EXPECT_FALSE(otr_profile->IsIncognitoProfile()); scoped_refptr<content::SiteInstance> instance = content::SiteInstance::Create(otr_profile); SetContents(content::WebContentsTester::CreateTestWebContents( otr_profile, std::move(instance))); } void SetIncognito() { Profile* const otr_profile = profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true); EXPECT_TRUE(otr_profile->IsOffTheRecord()); EXPECT_TRUE(otr_profile->IsIncognitoProfile()); scoped_refptr<content::SiteInstance> instance = content::SiteInstance::Create(otr_profile); SetContents(content::WebContentsTester::CreateTestWebContents( otr_profile, std::move(instance))); } static void AcceptShareRequest( content::WebContents* web_contents, const std::vector<base::FilePath>& file_paths, const std::vector<std::string>& content_types, const std::vector<uint64_t>& file_sizes, const std::string& text, const std::string& title, sharesheet::DeliveredCallback delivered_callback) { std::move(delivered_callback).Run(sharesheet::SharesheetResult::kSuccess); } }; TEST_F(SharesheetClientUnitTest, TestDenyInIncognitoAfterDelay) { SetIncognito(); SharesheetClient sharesheet_client(web_contents()); const std::string title = "Subject"; const std::string text = "Message"; const GURL share_url("https://example.com/"); std::vector<blink::mojom::SharedFilePtr> files; files.push_back(blink::mojom::SharedFilePtr()); blink::mojom::ShareError error = blink::mojom::ShareError::INTERNAL_ERROR; sharesheet_client.Share( title, text, share_url, std::move(files), base::BindLambdaForTesting( [&error](blink::mojom::ShareError in_error) { error = in_error; })); // Should be cancelled after 1-2 seconds. So 500ms is not enough. task_environment()->FastForwardBy(base::Milliseconds(500)); EXPECT_EQ(error, blink::mojom::ShareError::INTERNAL_ERROR); // But 5*500ms > 2 seconds, so it should now be cancelled. for (int n = 0; n < 4; n++) task_environment()->FastForwardBy(base::Milliseconds(500)); EXPECT_EQ(error, blink::mojom::ShareError::CANCELED); } TEST_F(SharesheetClientUnitTest, TestWithoutFilesInIncognito) { SetIncognito(); SharesheetClient sharesheet_client(web_contents()); const std::string title = "Subject"; const std::string text = "Message"; const GURL share_url("https://example.com/"); std::vector<blink::mojom::SharedFilePtr> files; base::RunLoop run_loop; blink::mojom::ShareError error = blink::mojom::ShareError::INTERNAL_ERROR; sharesheet_client.Share( title, text, share_url, std::move(files), base::BindLambdaForTesting( [&run_loop, &error](blink::mojom::ShareError in_error) { error = in_error; run_loop.Quit(); })); run_loop.Run(); EXPECT_EQ(error, blink::mojom::ShareError::OK); } TEST_F(SharesheetClientUnitTest, DeleteAfterShare) { SetGuest(); SharesheetClient sharesheet_client(web_contents()); const base::FilePath share_cache_dir = file_manager::util::GetShareCacheFilePath(profile()); const base::FilePath first_file = share_cache_dir.AppendASCII(".WebShare/share1/first.txt"); const base::FilePath second_file = share_cache_dir.AppendASCII(".WebShare/share2/second.txt"); const std::string title = "Subject"; const std::string text = "Message"; const GURL share_url("https://example.com/"); std::vector<blink::mojom::SharedFilePtr> files; files.push_back( blink::mojom::SharedFile::New(first_file.BaseName().AsUTF8Unsafe(), blink::mojom::SerializedBlob::New())); files.push_back( blink::mojom::SharedFile::New(second_file.BaseName().AsUTF8Unsafe(), blink::mojom::SerializedBlob::New())); base::RunLoop run_loop; blink::mojom::ShareError error = blink::mojom::ShareError::INTERNAL_ERROR; sharesheet_client.Share( title, text, share_url, std::move(files), base::BindLambdaForTesting( [&run_loop, &error](blink::mojom::ShareError in_error) { error = in_error; run_loop.Quit(); })); run_loop.Run(); EXPECT_EQ(error, blink::mojom::ShareError::OK); task_environment()->FastForwardBy(PrepareDirectoryTask::kSharedFileLifetime / 2); EXPECT_TRUE(base::PathExists(first_file)); EXPECT_TRUE(base::PathExists(second_file)); task_environment()->FastForwardBy(PrepareDirectoryTask::kSharedFileLifetime * 2); EXPECT_FALSE(base::PathExists(first_file)); EXPECT_FALSE(base::PathExists(second_file)); } } // namespace webshare
37.543353
79
0.712086
[ "vector" ]
c0f717891a7bca6b118af2dbd758eab19cd37560
31,742
cpp
C++
src/libclang/function_parser.cpp
stevencpp/cppast
ab7a9b6627cc9ccc34ed30473957741ed0be00d7
[ "MIT" ]
null
null
null
src/libclang/function_parser.cpp
stevencpp/cppast
ab7a9b6627cc9ccc34ed30473957741ed0be00d7
[ "MIT" ]
null
null
null
src/libclang/function_parser.cpp
stevencpp/cppast
ab7a9b6627cc9ccc34ed30473957741ed0be00d7
[ "MIT" ]
null
null
null
// Copyright (C) 2017-2018 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #include <cppast/cpp_function.hpp> #include <cppast/cpp_member_function.hpp> #include "libclang_visitor.hpp" #include "parse_functions.hpp" using namespace cppast; namespace { std::unique_ptr<cpp_function_parameter> parse_parameter(const detail::parse_context& context, const CXCursor& cur) { auto name = detail::get_cursor_name(cur); auto type = detail::parse_type(context, cur, clang_getCursorType(cur)); cpp_attribute_list attributes; auto default_value = detail::parse_default_value(attributes, context, cur, name.c_str()); std::unique_ptr<cpp_function_parameter> result; if (name.empty()) result = cpp_function_parameter::build(std::move(type), std::move(default_value)); else result = cpp_function_parameter::build(*context.idx, detail::get_entity_id(cur), name.c_str(), std::move(type), std::move(default_value)); result->add_attribute(attributes); return result; } template <class Builder> void add_parameters(const detail::parse_context& context, Builder& builder, const CXCursor& cur) { if (clang_getCursorKind(cur) == CXCursor_FunctionTemplate) { // clang_Cursor_getNumArguments() doesn't work here // (of course it doesn't...) detail::visit_children(cur, [&](const CXCursor& child) { if (clang_getCursorKind(child) != CXCursor_ParmDecl) return; try { auto parameter = parse_parameter(context, child); builder.add_parameter(std::move(parameter)); } catch (detail::parse_error& ex) { context.error = true; context.logger->log("libclang parser", ex.get_diagnostic(context.file)); } catch (std::logic_error& ex) { context.error = true; context.logger->log("libclang parser", diagnostic{ex.what(), detail::make_location(context.file, child), severity::error}); } }); } else { auto no = clang_Cursor_getNumArguments(cur); DEBUG_ASSERT(no != -1, detail::parse_error_handler{}, cur, "unexpected number of arguments"); for (auto i = 0; i != no; ++i) try { auto parameter = parse_parameter(context, clang_Cursor_getArgument(cur, unsigned(i))); builder.add_parameter(std::move(parameter)); } catch (detail::parse_error& ex) { context.error = true; context.logger->log("libclang parser", ex.get_diagnostic(context.file)); } catch (std::logic_error& ex) { context.error = true; context.logger ->log("libclang parser", diagnostic{ex.what(), detail::make_location(context.file, clang_Cursor_getArgument(cur, unsigned(i))), severity::error}); } } } bool is_templated_cursor(const CXCursor& cur) { return clang_getTemplateCursorKind(cur) != CXCursor_NoDeclFound || !clang_Cursor_isNull(clang_getSpecializedCursorTemplate(cur)); } // precondition: after the name void skip_parameters(detail::cxtoken_stream& stream) { if (stream.peek() == "<") // specialization arguments detail::skip_brackets(stream); detail::skip_brackets(stream); } std::vector<CXCursor> get_semantic_parents(CXCursor cur) { std::vector<CXCursor> result; for (; !clang_isTranslationUnit(clang_getCursorKind(cur)); cur = clang_getCursorSemanticParent(cur)) result.push_back(cur); return result; } bool is_class(const CXCursor& parent) { auto kind = clang_getCursorKind(parent); return kind == CXCursor_ClassDecl || kind == CXCursor_StructDecl || kind == CXCursor_UnionDecl || kind == CXCursor_ClassTemplate || kind == CXCursor_ClassTemplatePartialSpecialization; } // returns the scope where the function is contained in // for regular functions that is the lexcial parent // for friend functions it is the enclosing scope of the class CXCursor get_definition_scope(const CXCursor& cur, bool is_friend) { auto parent = clang_getCursorLexicalParent(cur); if (is_friend) { // find the lexical parent that isn't a class // as the definition scope is a namespace while (is_class(parent)) parent = clang_getCursorSemanticParent(parent); DEBUG_ASSERT(clang_getCursorKind(parent) == CXCursor_Namespace || clang_getCursorKind(parent) == CXCursor_TranslationUnit, detail::parse_error_handler{}, cur, "unable to find definition scope of friend"); } return parent; } bool equivalent_cursor(const CXCursor& a, const CXCursor& b) { if (clang_getCursorKind(a) == clang_getCursorKind(b) && clang_getCursorKind(a) == CXCursor_Namespace) return detail::cxstring(clang_getCursorUSR(a)) == detail::cxstring(clang_getCursorUSR(b)); else return clang_equalCursors(a, b) == 1; } type_safe::optional<cpp_entity_ref> parse_scope(const CXCursor& cur, bool is_friend) { std::string scope_name; auto friended = clang_getCursorReferenced(cur); if (is_friend && !clang_Cursor_isNull(friended)) { // it refers to another function // find the common parent between the two cursors // scope is the scope from the common parent down to the function auto friended_parents = get_semantic_parents(friended); auto cur_parents = get_semantic_parents(get_definition_scope(cur, true)); // remove common parents while (!friended_parents.empty() && !cur_parents.empty() && equivalent_cursor(friended_parents.back(), cur_parents.back())) { friended_parents.pop_back(); cur_parents.pop_back(); } DEBUG_ASSERT(!clang_isTranslationUnit(clang_getCursorKind(friended_parents.back())) && !friended_parents.empty(), detail::parse_error_handler{}, cur, "invalid common parent of friend and friended"); // scope consists of all remaining parents of friended // (last one is cursor itself) for (auto iter = friended_parents.rbegin(); iter != std::prev(friended_parents.rend()); ++iter) { auto parent_name = detail::cxstring(clang_getCursorDisplayName(*iter)); scope_name += parent_name.std_str() + "::"; } } else { // find the difference between the definition scope parent and semantic parent // all semantic parents in between form the scope // the definition scope is the lexical parent for regular functions, // and the scope outside of the class for friend functions for (auto definition = get_definition_scope(cur, is_friend), parent = clang_getCursorSemanticParent(cur); !equivalent_cursor(definition, parent); parent = clang_getCursorSemanticParent(parent)) { DEBUG_ASSERT(!clang_isTranslationUnit(clang_getCursorKind(parent)), detail::parse_error_handler{}, cur, "infinite loop while calculating scope"); auto parent_name = detail::cxstring(clang_getCursorDisplayName(parent)); scope_name = parent_name.std_str() + "::" + std::move(scope_name); } } if (scope_name.empty()) return type_safe::nullopt; else return cpp_entity_ref(detail::get_entity_id(clang_getCursorSemanticParent(cur)), std::move(scope_name)); } // just the tokens occurring in the prefix struct prefix_info { cpp_attribute_list attributes; bool is_constexpr = false; bool is_virtual = false; bool is_explicit = false; bool is_friend = false; }; bool prefix_end(detail::cxtoken_stream& stream, const char* name, bool is_ctor_dtor) { auto cur = stream.cur(); // name can have multiple tokens if it is an operator if (!detail::skip_if(stream, name, true)) return false; else if (stream.peek() == "," || stream.peek() == ">" || stream.peek() == ">>") { // argument to template parameters stream.set_cur(cur); return false; } else if (is_ctor_dtor) { // need to make sure it is not actually a class name if (stream.peek() == "::") { // after name came "::", it is a class name stream.set_cur(cur); return false; } else if (stream.peek() == "<") { // after name came "<", it might be arguments for a class template, // or just a specialization // check if ( comes after the arguments detail::skip_brackets(stream); if (stream.peek() == "(") { // it was just a specialization, we're at the end stream.set_cur(cur); return true; } else { // class arguments stream.set_cur(cur); return false; } } else return true; } else if (std::strcmp(name, "operator") != 0 && stream.peek().kind() == CXToken_Identifier) { // can't be function name stream.set_cur(cur); return false; } else return true; } prefix_info parse_prefix_info(detail::cxtoken_stream& stream, const char* name, bool is_ctor_dtor) { prefix_info result; while (!stream.done() && !prefix_end(stream, name, is_ctor_dtor)) { if (detail::skip_if(stream, "constexpr")) result.is_constexpr = true; else if (detail::skip_if(stream, "virtual")) result.is_virtual = true; else if (detail::skip_if(stream, "explicit")) result.is_explicit = true; else { auto attributes = detail::parse_attributes(stream, true); result.attributes.insert(result.attributes.end(), attributes.begin(), attributes.end()); } } DEBUG_ASSERT(!stream.done(), detail::parse_error_handler{}, stream.cursor(), "unable to find end of function prefix"); while (detail::skip_if(stream, ")")) { // function name can be enclosed in parentheses } auto attributes = detail::parse_attributes(stream); result.attributes.insert(result.attributes.end(), attributes.begin(), attributes.end()); return result; } // just the tokens occurring in the suffix struct suffix_info { cpp_attribute_list attributes; std::unique_ptr<cpp_expression> noexcept_condition; cpp_function_body_kind body_kind; cpp_cv cv_qualifier = cpp_cv_none; cpp_reference ref_qualifier = cpp_ref_none; cpp_virtual virtual_keywords; suffix_info(const CXCursor& cur) : body_kind(clang_isCursorDefinition(cur) ? cpp_function_definition : cpp_function_declaration) {} }; cpp_cv parse_cv(detail::cxtoken_stream& stream) { if (detail::skip_if(stream, "const")) { if (detail::skip_if(stream, "volatile")) return cpp_cv_const_volatile; else return cpp_cv_const; } else if (detail::skip_if(stream, "volatile")) { if (detail::skip_if(stream, "const")) return cpp_cv_const_volatile; else return cpp_cv_volatile; } else return cpp_cv_none; } cpp_reference parse_ref(detail::cxtoken_stream& stream) { if (detail::skip_if(stream, "&")) return cpp_ref_lvalue; else if (detail::skip_if(stream, "&&")) return cpp_ref_rvalue; else return cpp_ref_none; } std::unique_ptr<cpp_expression> parse_noexcept(detail::cxtoken_stream& stream, const detail::parse_context& context) { if (!detail::skip_if(stream, "noexcept")) return nullptr; auto type = cpp_builtin_type::build(cpp_bool); if (stream.peek().value() != "(") return cpp_literal_expression::build(std::move(type), "true"); auto closing = detail::find_closing_bracket(stream); detail::skip(stream, "("); auto expr = detail::parse_raw_expression(context, stream, closing, std::move(type)); detail::skip(stream, ")"); return expr; } cpp_function_body_kind parse_body_kind(detail::cxtoken_stream& stream, bool& pure_virtual) { pure_virtual = false; if (detail::skip_if(stream, "default")) return cpp_function_defaulted; else if (detail::skip_if(stream, "delete")) return cpp_function_deleted; else if (detail::skip_if(stream, "0")) { pure_virtual = true; return cpp_function_declaration; } DEBUG_UNREACHABLE(detail::parse_error_handler{}, stream.cursor(), "unexpected token for function body kind"); return cpp_function_declaration; } void parse_body(detail::cxtoken_stream& stream, suffix_info& result, bool allow_virtual) { auto pure_virtual = false; result.body_kind = parse_body_kind(stream, pure_virtual); if (pure_virtual) { DEBUG_ASSERT(allow_virtual, detail::parse_error_handler{}, stream.cursor(), "unexpected token"); if (result.virtual_keywords) result.virtual_keywords.value() |= cpp_virtual_flags::pure; else result.virtual_keywords = cpp_virtual_flags::pure; } } // precondition: we've skipped the function parameters suffix_info parse_suffix_info(detail::cxtoken_stream& stream, const detail::parse_context& context, bool allow_qualifier, bool allow_virtual) { suffix_info result(stream.cursor()); // syntax: <attribute> <cv> <ref> <exception> result.attributes = detail::parse_attributes(stream); if (allow_qualifier) { result.cv_qualifier = parse_cv(stream); result.ref_qualifier = parse_ref(stream); } if (detail::skip_if(stream, "throw")) // just because I can detail::skip_brackets(stream); result.noexcept_condition = parse_noexcept(stream, context); // check if we have leftovers of the return type // i.e.: `void (*foo(int a, int b) const)(int)`; // ^^^^^^- attributes // ^^^^^^- leftovers // if we have a closing parenthesis, skip brackets if (detail::skip_if(stream, ")")) detail::skip_brackets(stream); // check for trailing return type if (detail::skip_if(stream, "->")) { // this is rather tricky to skip // so loop over all tokens and see if matching keytokens occur // note that this isn't quite correct // use a heuristic to skip brackets, which should be good enough while (!stream.done()) { auto attributes = detail::parse_attributes(stream); if (!attributes.empty()) result.attributes.insert(result.attributes.end(), attributes.begin(), attributes.end()); else if (stream.peek() == "(" || stream.peek() == "[" || stream.peek() == "<") detail::skip_brackets(stream); else if (stream.peek() == "{") // begin of definition break; else if (detail::skip_if(stream, "override")) { DEBUG_ASSERT(allow_virtual, detail::parse_error_handler{}, stream.cursor(), "unexpected token"); if (result.virtual_keywords) result.virtual_keywords.value() |= cpp_virtual_flags::override; else result.virtual_keywords = cpp_virtual_flags::override; } else if (detail::skip_if(stream, "final")) { DEBUG_ASSERT(allow_virtual, detail::parse_error_handler{}, stream.cursor(), "unexpected token"); if (result.virtual_keywords) result.virtual_keywords.value() |= cpp_virtual_flags::final; else result.virtual_keywords = cpp_virtual_flags::final; } else if (detail::skip_if(stream, "=")) parse_body(stream, result, allow_virtual); else stream.bump(); } if (stream.peek() == "{" || stream.peek() == ":" || stream.peek() == "try") result.body_kind = cpp_function_definition; } else { // syntax: <virtuals> <body> if (detail::skip_if(stream, "override")) { DEBUG_ASSERT(allow_virtual, detail::parse_error_handler{}, stream.cursor(), "unexpected token"); result.virtual_keywords = cpp_virtual_flags::override; if (detail::skip_if(stream, "final")) result.virtual_keywords.value() |= cpp_virtual_flags::final; } else if (detail::skip_if(stream, "final")) { DEBUG_ASSERT(allow_virtual, detail::parse_error_handler{}, stream.cursor(), "unexpected token"); result.virtual_keywords = cpp_virtual_flags::final; if (detail::skip_if(stream, "override")) result.virtual_keywords.value() |= cpp_virtual_flags::override; } auto attributes = detail::parse_attributes(stream); if (!attributes.empty()) result.attributes.insert(result.attributes.end(), attributes.begin(), attributes.end()); if (detail::skip_if(stream, "=")) parse_body(stream, result, allow_virtual); else if (detail::skip_if(stream, "{") || detail::skip_if(stream, ":") || detail::skip_if(stream, "try")) result.body_kind = cpp_function_definition; } return result; } std::unique_ptr<cpp_entity> parse_cpp_function_impl(const detail::parse_context& context, const CXCursor& cur, bool is_static, bool is_friend) { auto name = detail::get_cursor_name(cur); detail::cxtokenizer tokenizer(context.tu, context.file, cur); detail::cxtoken_stream stream(tokenizer, cur); auto prefix = parse_prefix_info(stream, name.c_str(), false); DEBUG_ASSERT(!prefix.is_virtual && !prefix.is_explicit, detail::parse_error_handler{}, cur, "free function cannot be virtual or explicit"); cpp_function::builder builder(name.c_str(), detail::parse_type(context, cur, clang_getCursorResultType(cur))); context.comments.match(builder.get(), cur); builder.get().add_attribute(prefix.attributes); add_parameters(context, builder, cur); if (clang_Cursor_isVariadic(cur)) builder.is_variadic(); builder.storage_class(cpp_storage_class_specifiers( detail::get_storage_class(cur) | (is_static ? cpp_storage_class_static : cpp_storage_class_none))); if (prefix.is_constexpr) builder.is_constexpr(); skip_parameters(stream); auto suffix = parse_suffix_info(stream, context, false, false); builder.get().add_attribute(suffix.attributes); if (suffix.noexcept_condition) builder.noexcept_condition(std::move(suffix.noexcept_condition)); if (is_templated_cursor(cur)) return builder.finish(detail::get_entity_id(cur), suffix.body_kind, parse_scope(cur, is_friend)); else return builder.finish(*context.idx, detail::get_entity_id(cur), suffix.body_kind, parse_scope(cur, is_friend)); } } // namespace std::unique_ptr<cpp_entity> detail::parse_cpp_function(const detail::parse_context& context, const CXCursor& cur, bool is_friend) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_FunctionDecl || clang_getTemplateCursorKind(cur) == CXCursor_FunctionDecl, detail::assert_handler{}); type_safe::optional<cpp_entity_ref> semantic_parent; return parse_cpp_function_impl(context, cur, false, is_friend); } std::unique_ptr<cpp_entity> detail::try_parse_static_cpp_function( const detail::parse_context& context, const CXCursor& cur) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_CXXMethod || clang_getTemplateCursorKind(cur) == CXCursor_CXXMethod, detail::assert_handler{}); if (clang_CXXMethod_isStatic(cur)) return parse_cpp_function_impl(context, cur, true, false); return nullptr; } namespace { bool overrides_function(const CXCursor& cur) { CXCursor* overrides = nullptr; auto num = 0u; clang_getOverriddenCursors(cur, &overrides, &num); clang_disposeOverriddenCursors(overrides); return num != 0u; } cpp_virtual calculate_virtual(const CXCursor& cur, bool virtual_keyword, const cpp_virtual& virtual_suffix) { if (!clang_CXXMethod_isVirtual(cur) && !virtual_keyword && !virtual_suffix) return {}; else if (clang_CXXMethod_isPureVirtual(cur)) { // pure virtual function - all information in the suffix DEBUG_ASSERT(virtual_suffix.has_value() && virtual_suffix.value() & cpp_virtual_flags::pure, detail::parse_error_handler{}, cur, "pure virtual not detected"); return virtual_suffix; } else { // non-pure virtual function DEBUG_ASSERT(!virtual_suffix.has_value() || !(virtual_suffix.value() & cpp_virtual_flags::pure), detail::parse_error_handler{}, cur, "pure virtual function detected, even though it isn't"); // calculate whether it overrides auto overrides = !virtual_keyword || (virtual_suffix.has_value() && virtual_suffix.value() & cpp_virtual_flags::override) || overrides_function(cur); // result are all the flags in the suffix auto result = virtual_suffix; if (!result) // make sure it isn't empty result.emplace(); if (overrides) // make sure it contains the override flag result.value() |= cpp_virtual_flags::override; return result; } } template <class Builder> auto set_qualifier(int, Builder& b, cpp_cv cv, cpp_reference ref) -> decltype(b.cv_ref_qualifier(cv, ref), true) { b.cv_ref_qualifier(cv, ref); return true; } template <class Builder> bool set_qualifier(short, Builder&, cpp_cv, cpp_reference) { return false; } template <class Builder> std::unique_ptr<cpp_entity> handle_suffix(const detail::parse_context& context, const CXCursor& cur, Builder& builder, detail::cxtoken_stream& stream, bool is_virtual, type_safe::optional<cpp_entity_ref> semantic_parent) { auto allow_qualifiers = set_qualifier(0, builder, cpp_cv_none, cpp_ref_none); auto suffix = parse_suffix_info(stream, context, allow_qualifiers, true); builder.get().add_attribute(suffix.attributes); set_qualifier(0, builder, suffix.cv_qualifier, suffix.ref_qualifier); if (suffix.noexcept_condition) builder.noexcept_condition(move(suffix.noexcept_condition)); if (auto virt = calculate_virtual(cur, is_virtual, suffix.virtual_keywords)) builder.virtual_info(virt.value()); if (is_templated_cursor(cur)) return builder.finish(detail::get_entity_id(cur), suffix.body_kind, std::move(semantic_parent)); else return builder.finish(*context.idx, detail::get_entity_id(cur), suffix.body_kind, std::move(semantic_parent)); } } // namespace std::unique_ptr<cpp_entity> detail::parse_cpp_member_function(const detail::parse_context& context, const CXCursor& cur, bool is_friend) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_CXXMethod || clang_getTemplateCursorKind(cur) == CXCursor_CXXMethod, detail::assert_handler{}); auto name = detail::get_cursor_name(cur); detail::cxtokenizer tokenizer(context.tu, context.file, cur); detail::cxtoken_stream stream(tokenizer, cur); auto prefix = parse_prefix_info(stream, name.c_str(), false); DEBUG_ASSERT(!prefix.is_explicit, detail::parse_error_handler{}, cur, "member function cannot be explicit"); cpp_member_function::builder builder(name.c_str(), detail::parse_type(context, cur, clang_getCursorResultType(cur))); context.comments.match(builder.get(), cur); builder.get().add_attribute(prefix.attributes); add_parameters(context, builder, cur); if (clang_Cursor_isVariadic(cur)) builder.is_variadic(); if (prefix.is_constexpr) builder.is_constexpr(); skip_parameters(stream); return handle_suffix(context, cur, builder, stream, prefix.is_virtual, parse_scope(cur, is_friend)); } std::unique_ptr<cpp_entity> detail::parse_cpp_conversion_op(const detail::parse_context& context, const CXCursor& cur, bool is_friend) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_ConversionFunction || clang_getTemplateCursorKind(cur) == CXCursor_ConversionFunction, detail::assert_handler{}); detail::cxtokenizer tokenizer(context.tu, context.file, cur); detail::cxtoken_stream stream(tokenizer, cur); auto prefix = parse_prefix_info(stream, "operator", false); // heuristic to find arguments tokens // skip forward, skipping inside brackets auto type_start = stream.cur(); auto finished = false; while (!stream.done() && !finished) { if (stream.peek() == "(") { if (detail::skip_if(stream, "(") && detail::skip_if(stream, ")")) finished = true; else detail::skip_brackets(stream); } else if (stream.peek() == "[") detail::skip_brackets(stream); else if (stream.peek() == "{") detail::skip_brackets(stream); else if (stream.peek() == "<") detail::skip_brackets(stream); else stream.bump(); } DEBUG_ASSERT(finished, detail::parse_error_handler{}, cur, "unable to find end of conversion op type"); // bump arguments back stream.bump_back(); stream.bump_back(); auto type_end = stream.cur(); // read the type stream.set_cur(type_start); auto type_spelling = detail::to_string(stream, type_end).as_string(); // parse arguments again detail::skip(stream, "("); detail::skip(stream, ")"); auto type = clang_getCursorResultType(cur); cpp_conversion_op::builder builder("operator " + type_spelling, detail::parse_type(context, cur, type)); context.comments.match(builder.get(), cur); builder.get().add_attribute(prefix.attributes); if (prefix.is_explicit) builder.is_explicit(); else if (prefix.is_constexpr) builder.is_constexpr(); return handle_suffix(context, cur, builder, stream, prefix.is_virtual, parse_scope(cur, is_friend)); } std::unique_ptr<cpp_entity> detail::parse_cpp_constructor(const detail::parse_context& context, const CXCursor& cur, bool is_friend) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_Constructor || clang_getTemplateCursorKind(cur) == CXCursor_Constructor, detail::assert_handler{}); std::string name = detail::get_cursor_name(cur).c_str(); auto pos = name.find('<'); if (pos != std::string::npos) name.erase(pos); detail::cxtokenizer tokenizer(context.tu, context.file, cur); detail::cxtoken_stream stream(tokenizer, cur); auto prefix = parse_prefix_info(stream, name.c_str(), true); DEBUG_ASSERT(!prefix.is_virtual, detail::parse_error_handler{}, cur, "constructor cannot be virtual"); cpp_constructor::builder builder(name.c_str()); context.comments.match(builder.get(), cur); add_parameters(context, builder, cur); builder.get().add_attribute(prefix.attributes); if (clang_Cursor_isVariadic(cur)) builder.is_variadic(); if (prefix.is_constexpr) builder.is_constexpr(); else if (prefix.is_explicit) builder.is_explicit(); skip_parameters(stream); auto suffix = parse_suffix_info(stream, context, false, false); builder.get().add_attribute(suffix.attributes); if (suffix.noexcept_condition) builder.noexcept_condition(std::move(suffix.noexcept_condition)); if (is_templated_cursor(cur)) return builder.finish(detail::get_entity_id(cur), suffix.body_kind, parse_scope(cur, is_friend)); else return builder.finish(*context.idx, detail::get_entity_id(cur), suffix.body_kind, parse_scope(cur, is_friend)); } std::unique_ptr<cpp_entity> detail::parse_cpp_destructor(const detail::parse_context& context, const CXCursor& cur, bool is_friend) { DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_Destructor, detail::assert_handler{}); detail::cxtokenizer tokenizer(context.tu, context.file, cur); detail::cxtoken_stream stream(tokenizer, cur); auto prefix_info = parse_prefix_info(stream, "~", true); DEBUG_ASSERT(!prefix_info.is_constexpr && !prefix_info.is_explicit, detail::assert_handler{}); auto name = std::string("~") + stream.get().c_str(); cpp_destructor::builder builder(std::move(name)); context.comments.match(builder.get(), cur); builder.get().add_attribute(prefix_info.attributes); detail::skip(stream, "("); detail::skip(stream, ")"); return handle_suffix(context, cur, builder, stream, prefix_info.is_virtual, parse_scope(cur, is_friend)); }
38.475152
100
0.602293
[ "vector" ]
c0f9193c7aa1880bde78499b57e168f7326d4168
4,526
cpp
C++
src/utils/viewer/ObjectPickingHelper.cpp
qureshinomaan/habitat-sim
df2540b658d0444e84bbc7a0c3fb995f8d523b52
[ "MIT" ]
null
null
null
src/utils/viewer/ObjectPickingHelper.cpp
qureshinomaan/habitat-sim
df2540b658d0444e84bbc7a0c3fb995f8d523b52
[ "MIT" ]
null
null
null
src/utils/viewer/ObjectPickingHelper.cpp
qureshinomaan/habitat-sim
df2540b658d0444e84bbc7a0c3fb995f8d523b52
[ "MIT" ]
null
null
null
#include "ObjectPickingHelper.h" #include <Corrade/Containers/StridedArrayView.h> #include <Corrade/Utility/Assert.h> #include <Magnum/GL/Framebuffer.h> #include <Magnum/GL/Renderbuffer.h> #include <Magnum/GL/RenderbufferFormat.h> #include <Magnum/Image.h> #include <Magnum/Magnum.h> #include <Magnum/PixelFormat.h> #include <Magnum/Shaders/Generic.h> #include <Magnum/Shaders/MeshVisualizer.h> namespace Cr = Corrade; namespace Mn = Magnum; using Mn::Math::Literals::operator""_rgbf; using Mn::Math::Literals::operator""_rgbaf; ObjectPickingHelper::ObjectPickingHelper(Mn::Vector2i viewportSize) { // create the framebuffer and set the color attachment recreateFramebuffer(viewportSize); mapForDraw(); CORRADE_INTERNAL_ASSERT( selectionFramebuffer_.checkStatus(Mn::GL::FramebufferTarget::Draw) == Mn::GL::Framebuffer::Status::Complete); shader_.setViewportSize(Mn::Vector2{viewportSize}); shader_.setColor(0x2f83cc7f_rgbaf) .setWireframeColor(0xdcdcdc_rgbf) .setWireframeWidth(2.0); } void ObjectPickingHelper::recreateFramebuffer(Mn::Vector2i viewportSize) { // setup an offscreen frame buffer for object selection selectionDepth_.setStorage(Mn::GL::RenderbufferFormat::DepthComponent24, viewportSize); selectionDrawableId_.setStorage(Mn::GL::RenderbufferFormat::R32UI, viewportSize); selectionFramebuffer_ = Mn::GL::Framebuffer{{{}, viewportSize}}; selectionFramebuffer_ .attachRenderbuffer(Mn::GL::Framebuffer::BufferAttachment::Depth, selectionDepth_) .attachRenderbuffer(Mn::GL::Framebuffer::ColorAttachment{1}, selectionDrawableId_); } ObjectPickingHelper& ObjectPickingHelper::prepareToDraw() { selectionFramebuffer_.bind(); mapForDraw(); selectionFramebuffer_.clearDepth(1.0f).clearColor(1, Mn::Vector4ui{0xffff}); CORRADE_INTERNAL_ASSERT( selectionFramebuffer_.checkStatus(Mn::GL::FramebufferTarget::Draw) == Mn::GL::Framebuffer::Status::Complete); // remove any visualized object that is picked before if (meshVisualizerDrawable_) { delete meshVisualizerDrawable_; meshVisualizerDrawable_ = nullptr; } return *this; } ObjectPickingHelper& ObjectPickingHelper::mapForDraw() { selectionFramebuffer_.mapForDraw({{Mn::Shaders::Generic3D::ColorOutput, Mn::GL::Framebuffer::DrawAttachment::None}, {Mn::Shaders::Generic3D::ObjectIdOutput, Mn::GL::Framebuffer::ColorAttachment{1}}}); return *this; } ObjectPickingHelper& ObjectPickingHelper::handleViewportChange( Mn::Vector2i viewportSize) { recreateFramebuffer(viewportSize); selectionFramebuffer_.setViewport({{}, viewportSize}); shader_.setViewportSize(Mn::Vector2{viewportSize}); return *this; } unsigned int ObjectPickingHelper::getObjectId( const Mn::Vector2i& mouseEventPosition, const Mn::Vector2i& windowSize) { selectionFramebuffer_.mapForRead(Mn::GL::Framebuffer::ColorAttachment{1}); CORRADE_INTERNAL_ASSERT( selectionFramebuffer_.checkStatus(Mn::GL::FramebufferTarget::Read) == Mn::GL::Framebuffer::Status::Complete); // First scale the position from being relative to window size to being // relative to framebuffer size as those two can be different on HiDPI // systems const Mn::Vector2i position = mouseEventPosition * Mn::Vector2{selectionFramebuffer_.viewport().size()} / Mn::Vector2{windowSize}; const Mn::Vector2i fbPosition{ position.x(), selectionFramebuffer_.viewport().sizeY() - position.y() - 1}; const Mn::Range2Di area = Mn::Range2Di::fromSize(fbPosition, Mn::Vector2i{1}); const Mn::UnsignedInt pickedObject = selectionFramebuffer_.read(area, {Mn::PixelFormat::R32UI}) .pixels<Mn::UnsignedInt>()[0][0]; return pickedObject; } void ObjectPickingHelper::createPickedObjectVisualizer( esp::gfx::Drawable* pickedObject) { if (meshVisualizerDrawable_) { delete meshVisualizerDrawable_; meshVisualizerDrawable_ = nullptr; } if (!pickedObject) { return; } // magnum scene graph will handle the garbage collection even we did not // recycle it by the end of the simulation meshVisualizerDrawable_ = new esp::gfx::MeshVisualizerDrawable( static_cast<esp::scene::SceneNode&>(pickedObject->object()), shader_, pickedObject->getMesh(), &pickedObjectDrawbles_); return; }
35.637795
80
0.714317
[ "object" ]
c0ff3e993228c658a9375b5c73d1342dd211ed8c
498
cpp
C++
src/events.cpp
lkk7/two-bodies
490f6fdc1cb5dec8c369b459e3d68835431746cb
[ "MIT" ]
null
null
null
src/events.cpp
lkk7/two-bodies
490f6fdc1cb5dec8c369b459e3d68835431746cb
[ "MIT" ]
null
null
null
src/events.cpp
lkk7/two-bodies
490f6fdc1cb5dec8c369b459e3d68835431746cb
[ "MIT" ]
null
null
null
#include "events.hpp" namespace events { /* Object for storing SDL events */ SDL_Event ev; } bool handle_events() { /* Check clicked keys */ while (SDL_PollEvent(&events::ev)) { if (events::ev.type == SDL_QUIT) { return false; } else if (events::ev.type == SDL_KEYDOWN) { if (events::ev.key.keysym.sym == SDLK_ESCAPE) { return false; } } } return true; }
17.172414
57
0.485944
[ "object" ]
8d01da5fef07396422caace3a0ecee2c20779ed9
2,802
cxx
C++
MITK/Modules/MIDAS/Interactions/niftkFilteringStateMachine.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Modules/MIDAS/Interactions/niftkFilteringStateMachine.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Modules/MIDAS/Interactions/niftkFilteringStateMachine.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "niftkFilteringStateMachine.h" #include <itkCommand.h> #include <mitkGlobalInteraction.h> #include <mitkToolManager.h> // MicroServices #include <usGetModuleContext.h> #include <usModule.h> #include <usModuleRegistry.h> #include "niftkStateMachineEventFilter.h" namespace niftk { //----------------------------------------------------------------------------- FilteringStateMachine::FilteringStateMachine() { } //----------------------------------------------------------------------------- FilteringStateMachine::~FilteringStateMachine() { } //----------------------------------------------------------------------------- bool FilteringStateMachine::CanHandleEvent(mitk::InteractionEvent* event) { if (this->IsFiltered(event)) { return false; } return this->CanHandle(event); } //----------------------------------------------------------------------------- void FilteringStateMachine::InstallEventFilter(StateMachineEventFilter* eventFilter) { std::vector<StateMachineEventFilter*>::iterator it = std::find(m_EventFilters.begin(), m_EventFilters.end(), eventFilter); if (it == m_EventFilters.end()) { m_EventFilters.push_back(eventFilter); } } //----------------------------------------------------------------------------- void FilteringStateMachine::RemoveEventFilter(StateMachineEventFilter* eventFilter) { std::vector<StateMachineEventFilter*>::iterator it = std::find(m_EventFilters.begin(), m_EventFilters.end(), eventFilter); if (it != m_EventFilters.end()) { m_EventFilters.erase(it); } } //----------------------------------------------------------------------------- std::vector<StateMachineEventFilter*> FilteringStateMachine::GetEventFilters() const { return m_EventFilters; } //----------------------------------------------------------------------------- bool FilteringStateMachine::IsFiltered(mitk::InteractionEvent* event) { /// Sanity check. if (!event || !event->GetSender()) { return true; } std::vector<StateMachineEventFilter*>::const_iterator it = m_EventFilters.begin(); std::vector<StateMachineEventFilter*>::const_iterator itEnd = m_EventFilters.end(); for ( ; it != itEnd; ++it) { if ((*it)->EventFilter(event)) { return true; } } return false; } }
24.79646
85
0.544254
[ "vector" ]
8d02903f9a6edfb11d8984a1b5124b4b9c44f7de
11,119
cpp
C++
inetsrv/uddi/source/mmc/basesnap.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/uddi/source/mmc/basesnap.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/uddi/source/mmc/basesnap.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include <objbase.h> #include <olectl.h> #include <initguid.h> #include "guids.h" #include "basesnap.h" #include "comp.h" #include "compdata.h" #include "about.h" #include "uddi.h" #include <assert.h> LONG UnRegisterServer( const CLSID& clsid ); // // Globals Variables // HINSTANCE g_hinst; BOOL WINAPI DllMain( HINSTANCE hinst, DWORD fdwReason, void* lpvReserved ) { if( DLL_PROCESS_ATTACH == fdwReason ) { g_hinst = hinst; } return TRUE; } STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvObj) { if( ( rclsid != CLSID_CUDDIServices ) && ( rclsid != CLSID_CSnapinAbout ) ) return CLASS_E_CLASSNOTAVAILABLE; if( !ppvObj ) return E_FAIL; *ppvObj = NULL; // // We can only hand out IUnknown and IClassFactory pointers. Fail // if they ask for anything else. // if( !IsEqualIID(riid, IID_IUnknown) && !IsEqualIID( riid, IID_IClassFactory ) ) return E_NOINTERFACE; CClassFactory *pFactory = NULL; // // make the factory passing in the creation function for the type of object they want // if( CLSID_CUDDIServices == rclsid ) pFactory = new CClassFactory( CClassFactory::COMPONENT ); else if( CLSID_CSnapinAbout == rclsid ) pFactory = new CClassFactory( CClassFactory::ABOUT ); if( NULL == pFactory ) return E_OUTOFMEMORY; HRESULT hr = pFactory->QueryInterface( riid, ppvObj ); return hr; } STDAPI DllCanUnloadNow(void) { if( ( 0 == g_uObjects ) && ( 0 == g_uSrvLock ) ) return S_OK; else return S_FALSE; } CClassFactory::CClassFactory(FACTORY_TYPE factoryType) : m_cref(0) , m_factoryType(factoryType) { OBJECT_CREATED } CClassFactory::~CClassFactory() { OBJECT_DESTROYED } STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, LPVOID *ppv) { if( !ppv ) return E_FAIL; *ppv = NULL; if( IsEqualIID( riid, IID_IUnknown ) ) *ppv = static_cast<IClassFactory *>(this); else if( IsEqualIID(riid, IID_IClassFactory ) ) *ppv = static_cast<IClassFactory *>(this); if( *ppv ) { reinterpret_cast<IUnknown *>(*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) CClassFactory::AddRef() { return InterlockedIncrement( (LONG*)&m_cref ); } STDMETHODIMP_(ULONG) CClassFactory::Release() { if( 0 == InterlockedDecrement( (LONG *)&m_cref ) ) { delete this; return 0; } return m_cref; } STDMETHODIMP CClassFactory::CreateInstance( LPUNKNOWN pUnkOuter, REFIID riid, LPVOID * ppvObj ) { HRESULT hr; void* pObj; if( !ppvObj ) return E_FAIL; *ppvObj = NULL; // // Our object does does not support aggregation, so we need to // fail if they ask us to do aggregation. // if( pUnkOuter ) return CLASS_E_NOAGGREGATION; if( COMPONENT == m_factoryType ) { pObj = new CComponentData(); } else { pObj = new CSnapinAbout(); } if( !pObj ) return E_OUTOFMEMORY; // // QueryInterface will do the AddRef() for us, so we do not // do it in this function // hr = ( (LPUNKNOWN) pObj )->QueryInterface( riid, ppvObj ); if( FAILED(hr) ) delete pObj; return hr; } STDMETHODIMP CClassFactory::LockServer( BOOL fLock ) { if( fLock ) InterlockedIncrement( (LONG *) &g_uSrvLock ); else InterlockedDecrement( (LONG *) &g_uSrvLock); return S_OK; } // // Register the component in the registry. // HRESULT RegisterServer( HMODULE hModule, // DLL module handle const CLSID& clsid, // Class ID const _TCHAR* szFriendlyName ) // IDs { LPOLESTR wszCLSID = NULL; try { // // Get server location. // _TCHAR szModule[ MAX_PATH + 1]; DWORD dwResult = ::GetModuleFileName( hModule, szModule, sizeof(szModule)/sizeof(_TCHAR) ); szModule[ MAX_PATH ] = NULL; assert( 0 != dwResult ); // // Get CLSID // HRESULT hr = StringFromCLSID( clsid, &wszCLSID ); if( FAILED(hr) || ( NULL == wszCLSID ) ) { return hr; } // // Build the key CLSID\\{...} // tstring strKey( _T("CLSID\\") ); strKey += wszCLSID; CUDDIRegistryKey::Create( HKEY_CLASSES_ROOT, strKey ); CUDDIRegistryKey key( HKEY_CLASSES_ROOT, strKey ); key.SetValue( _T(""), szFriendlyName ); key.Close(); strKey += _T( "\\InprocServer32" ); CUDDIRegistryKey::Create( HKEY_CLASSES_ROOT, strKey ); CUDDIRegistryKey keyInprocServer32( HKEY_CLASSES_ROOT, strKey ); keyInprocServer32.SetValue( _T(""), szModule ); keyInprocServer32.SetValue( _T("ThreadingModel"), _T("Apartment") ); keyInprocServer32.Close(); // // Free memory. // CoTaskMemFree( wszCLSID ); return S_OK; } catch( ... ) { CoTaskMemFree( wszCLSID ); return E_OUTOFMEMORY; } } ////////////////////////////////////////////////////////// // // Exported functions // // // Server registration // STDAPI DllRegisterServer() { try { HRESULT hr = S_OK; _TCHAR szName[ 256 ]; _TCHAR szSnapInName[ 256 ]; _TCHAR szAboutName[ 256 ]; _TCHAR szProvider[ 256 ]; // // TODO: Fix the version thing here // //_TCHAR szVersion[ 100 ]; LoadString( g_hinst, IDS_UDDIMMC_NAME, szName, ARRAYLEN( szName ) ); LoadString( g_hinst, IDS_UDDIMMC_SNAPINNAME, szSnapInName, ARRAYLEN( szSnapInName ) ); LoadString( g_hinst, IDS_UDDIMMC_ABOUTNAME, szAboutName, ARRAYLEN( szAboutName ) ); LoadString( g_hinst, IDS_UDDIMMC_PROVIDER, szProvider, ARRAYLEN( szProvider ) ); // // TODO: Fix the version thing here // //LoadString( g_hinst, IDS_UDDIMMC_VERSION, szVersion, ARRAYLEN( szVersion ) ); // // Register our Components // hr = RegisterServer( g_hinst, CLSID_CUDDIServices, szName ); if( FAILED(hr) ) return hr; hr = RegisterServer( g_hinst, CLSID_CSnapinAbout, szAboutName ); if( FAILED(hr) ) return hr; // // Create the primary snapin nodes // LPOLESTR wszCLSID = NULL; hr = StringFromCLSID( CLSID_CUDDIServices, &wszCLSID ); if( FAILED(hr) ) { return hr; } LPOLESTR wszCLSIDAbout = NULL; hr = StringFromCLSID( CLSID_CSnapinAbout, &wszCLSIDAbout ); if( FAILED(hr) ) { CoTaskMemFree( wszCLSID ); return hr; } TCHAR szPath[ MAX_PATH + 1 ]; GetModuleFileName( g_hinst, szPath, MAX_PATH ); tstring strNameStringIndirect( _T("@") ); strNameStringIndirect += szPath; strNameStringIndirect += _T(",-"); _TCHAR szNameResourceIndex[ 10 ]; strNameStringIndirect += _itot( IDS_UDDIMMC_NAME, szNameResourceIndex, 10 ); tstring strMMCKey( g_szMMCBasePath ); strMMCKey += _T("\\SnapIns\\"); strMMCKey += wszCLSID; CUDDIRegistryKey::Create( HKEY_LOCAL_MACHINE, strMMCKey ); CUDDIRegistryKey keyMMC( strMMCKey ); keyMMC.SetValue( _T("About"), wszCLSIDAbout ); keyMMC.SetValue( _T("NameString"), szName ); keyMMC.SetValue( _T("NameStringIndirect"), strNameStringIndirect.c_str() ); keyMMC.SetValue( _T("Provider"), szProvider ); // // TODO: Fix the version thing here // keyMMC.SetValue( _T("Version" ), _T("1.0") ); keyMMC.Close(); tstring strStandAlone( strMMCKey ); strStandAlone += _T("\\StandAlone"); CUDDIRegistryKey::Create( HKEY_LOCAL_MACHINE, strStandAlone ); tstring strNodeTypes( strMMCKey ); strNodeTypes += _T("\\NodeTypes"); CUDDIRegistryKey::Create( HKEY_LOCAL_MACHINE, strNodeTypes ); // // No NodeTypes to register // We do not allow extensions of our nodes // // // Register as a dynamic extension to computer management // tstring strExtKey( g_szMMCBasePath ); strExtKey += _T("\\NodeTypes\\"); strExtKey += g_szServerAppsGuid; strExtKey += _T("\\Dynamic Extensions"); CUDDIRegistryKey dynamicExtensions( strExtKey ); dynamicExtensions.SetValue( wszCLSID, szSnapInName ); dynamicExtensions.Close(); // // Register as a namespace extension to computer management // tstring strNameSpaceExtensionKey( g_szMMCBasePath ); strNameSpaceExtensionKey += _T("\\NodeTypes\\"); strNameSpaceExtensionKey += g_szServerAppsGuid; strNameSpaceExtensionKey += _T("\\Extensions\\NameSpace"); CUDDIRegistryKey hkeyNameSpace( strNameSpaceExtensionKey ); hkeyNameSpace.SetValue( wszCLSID, szSnapInName ); hkeyNameSpace.Close(); CoTaskMemFree( wszCLSID ); CoTaskMemFree( wszCLSIDAbout ); return hr; } catch( ... ) { return E_FAIL; } } STDAPI DllUnregisterServer() { LPOLESTR wszCLSID = NULL; try { HRESULT hr = S_OK; UnRegisterServer( CLSID_CUDDIServices ); if( FAILED(hr) ) return hr; UnRegisterServer( CLSID_CSnapinAbout ); if( FAILED(hr) ) return hr; // // Remove \\SnapIns\\ entry // hr = StringFromCLSID( CLSID_CUDDIServices, &wszCLSID ); if( FAILED( hr) || ( NULL == wszCLSID ) ) { return hr; } tstring strMMCKey( g_szMMCBasePath ); strMMCKey += _T("\\SnapIns\\"); strMMCKey += wszCLSID; CUDDIRegistryKey::DeleteKey( HKEY_LOCAL_MACHINE, strMMCKey ); // // Remove \\Dynamic Extensions key // tstring strExtKey( g_szMMCBasePath ); strExtKey += _T("\\NodeTypes\\"); strExtKey += g_szServerAppsGuid; strExtKey += _T("\\Dynamic Extensions"); CUDDIRegistryKey dynamicExtensions( strExtKey ); dynamicExtensions.DeleteValue( wszCLSID ); dynamicExtensions.Close(); // // Delete \\NodeTypes\\...\\Extensions\\Namespace Value // tstring strNameSpaceExtensionKey( g_szMMCBasePath ); strNameSpaceExtensionKey += _T("\\NodeTypes\\"); strNameSpaceExtensionKey += g_szServerAppsGuid; strNameSpaceExtensionKey += _T("\\Extensions\\NameSpace"); CUDDIRegistryKey hkeyNameSpace( strNameSpaceExtensionKey ); hkeyNameSpace.DeleteValue( wszCLSID ); hkeyNameSpace.Close(); CoTaskMemFree( wszCLSID ); return S_OK; } catch(...) { CoTaskMemFree( wszCLSID ); return E_FAIL; } } // // Remove the component from the registry. // LONG UnRegisterServer( const CLSID& clsid ) { LPOLESTR wszCLSID = NULL; try { // // Get CLSID // HRESULT hr = StringFromCLSID( clsid, &wszCLSID ); if( FAILED(hr) || ( NULL == wszCLSID ) ) { return hr; } // // Build the key CLSID\\{...} // wstring wstrKey( L"CLSID\\" ); wstrKey += wszCLSID; // // Delete the CLSID Key - CLSID\{...} // CUDDIRegistryKey::DeleteKey( HKEY_CLASSES_ROOT, wstrKey ); } catch( ... ) { // // Free memory. // CoTaskMemFree( wszCLSID ); return E_OUTOFMEMORY; } // // Free memory. // CoTaskMemFree( wszCLSID ); return S_OK ; }
23.261506
96
0.620469
[ "object" ]
8d05d7fff4553b483e3656503bc976bcd7e55733
977
cpp
C++
problems/210.course-schedule-ii.cpp
bigfishi/leetcode
3e512f2822a742349384a0bdd7954696f5867683
[ "MIT" ]
null
null
null
problems/210.course-schedule-ii.cpp
bigfishi/leetcode
3e512f2822a742349384a0bdd7954696f5867683
[ "MIT" ]
null
null
null
problems/210.course-schedule-ii.cpp
bigfishi/leetcode
3e512f2822a742349384a0bdd7954696f5867683
[ "MIT" ]
null
null
null
// 在207的基础上修改,不要注意的是,如果无法完成拓扑遍历,返回空列表 class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> graph(numCourses); vector<int> in(numCourses, 0); for (size_t i = 0; i < graph.size(); i++) { for (size_t j = 0; j < numCourses; j++) { graph[i].push_back(0); } } for (size_t i = 0; i < prerequisites.size(); i++) { graph[prerequisites[i][0]][prerequisites[i][1]] = 1; in[prerequisites[i][1]]++; } queue<int> q; for (size_t i = 0; i < in.size(); i++) { if (in[i] == 0) q.push(i); } vector<int> list; while (q.size()) { int i = q.front(); q.pop(); list.push_back(i); for (size_t j = 0; j < graph.size(); j++) { if (graph[i][j]) { in[j]--; graph[i][j] = 0; if (in[j] == 0) q.push(j); } } } if (list.size() == numCourses) { reverse(list.begin(), list.end()); return list; } else { return {}; } } };
19.938776
76
0.525077
[ "vector" ]
8d078a1923b5f51b0040d8bab1bbe0d039a21e4e
18,467
cpp
C++
Ipopt-3.12.7/Ipopt/contrib/RInterface/src/IpoptRNLP.cpp
MikeBMW/CarND-MPC-Project
81e6e92de2768dce9fbfd1848de6f4465d468a0e
[ "MIT" ]
9
2020-07-09T06:40:31.000Z
2022-03-28T02:50:21.000Z
third-party/CoinIpopt/Ipopt/contrib/RInterface/src/IpoptRNLP.cpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
null
null
null
third-party/CoinIpopt/Ipopt/contrib/RInterface/src/IpoptRNLP.cpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
5
2020-12-01T01:41:12.000Z
2022-01-04T01:21:49.000Z
/* * Copyright (C) 2010 Jelmer Ypma. All Rights Reserved. * This code is published under the Eclipse Public License. * * file: IpoptRNLP.cpp * author: Jelmer Ypma * date: 18 April 2010 * * This file defines a C++ class that derives from Ipopt::TNLP. The class * takes care of interaction between Ipopt and user-defined functions in R. * * Financial support of the UK Economic and Social Research Council * through a grant (RES-589-28-0001) to the ESRC Centre for Microdata * Methods and Practice (CeMMAP) is gratefully acknowledged. * * Changelog: * 09/03/2012: added outputs in finalize_solution; z_L, z_U, constraints, lambda (thanks to Michael Schedl) */ #include "IpoptRNLP.hpp" /* Constructor. */ IpoptRNLP::IpoptRNLP() : d_hessian_approximation( false ), d_num_protected_members( 0 ) {} IpoptRNLP::~IpoptRNLP() { // UNPROTECT all SEXP members that we PROTECT UNPROTECT( d_num_protected_members ); } // // Functions to load R Objects into IpoptRProblem // void IpoptRNLP::set_R_environment( SEXP env ) { PROTECT(R_environment = env); d_num_protected_members++; } void IpoptRNLP::set_R_eval_f( SEXP f ) { PROTECT(R_eval_f = f); d_num_protected_members++; } void IpoptRNLP::set_R_eval_grad_f( SEXP f ) { PROTECT(R_eval_grad_f = f); d_num_protected_members++; } void IpoptRNLP::set_R_init_values( SEXP x0 ) { PROTECT(R_init_values = x0); d_num_protected_members++; } void IpoptRNLP::set_R_lower_bounds( SEXP lb ) { PROTECT(R_lower_bounds = lb); d_num_protected_members++; } void IpoptRNLP::set_R_upper_bounds( SEXP ub ) { PROTECT(R_upper_bounds = ub); d_num_protected_members++; } void IpoptRNLP::set_R_eval_g( SEXP g ) { PROTECT(R_eval_g = g); d_num_protected_members++; } void IpoptRNLP::set_R_eval_jac_g( SEXP g ) { PROTECT(R_eval_jac_g = g); d_num_protected_members++; } void IpoptRNLP::set_R_eval_jac_g_structure( SEXP s ) { PROTECT(R_eval_jac_g_structure = s); d_num_protected_members++; } void IpoptRNLP::set_R_constraint_lower_bounds( SEXP lb ) { PROTECT(R_constraint_lower_bounds = lb); d_num_protected_members++; } void IpoptRNLP::set_R_constraint_upper_bounds( SEXP ub ) { PROTECT(R_constraint_upper_bounds = ub); d_num_protected_members++; } void IpoptRNLP::set_R_eval_h( SEXP h ) { PROTECT(R_eval_h = h); d_num_protected_members++; } void IpoptRNLP::set_R_eval_h_structure( SEXP s ) { PROTECT(R_eval_h_structure = s); d_num_protected_members++; } void IpoptRNLP::set_hessian_approximation( bool b ) { d_hessian_approximation = b; } SEXP IpoptRNLP::get_R_result_list() { return R_result_list; } bool IpoptRNLP::get_nlp_info(Ipopt::Index& n, Ipopt::Index& m, Ipopt::Index& nnz_jac_g, Ipopt::Index& nnz_h_lag, IndexStyleEnum& index_style) { // Check for user interruption from R R_CheckUserInterrupt(); // number of control variables n = length( R_init_values ); // number of constraints m = length( R_constraint_lower_bounds ); // Loop over the elements in R_eval_jac_g_structure and count the number of non-zero indices // in the Jacobian. As far as I know unlist() does not exist in C, so we cannot call that directly. nnz_jac_g = 0; for (int list_cnt=0;list_cnt<length( R_eval_jac_g_structure );list_cnt++) { SEXP R_list_element; PROTECT(R_list_element = AS_INTEGER(VECTOR_ELT(R_eval_jac_g_structure, list_cnt))); nnz_jac_g += length( R_list_element ); UNPROTECT(1); } // Loop over the elements in R_eval_h_structure and count the number of non-zero indices // in the hessian of the lagrangian (combined hessian of the objective and hessian of the constraints). nnz_h_lag = 0; for (int list_cnt=0;list_cnt<length( R_eval_h_structure );list_cnt++) { SEXP R_list_element; PROTECT(R_list_element = AS_INTEGER(VECTOR_ELT(R_eval_h_structure, list_cnt))); nnz_h_lag+=length( R_list_element ); UNPROTECT(1); } // We use the standard Fortran Ipopt::Index style for row/col entries, // This is the same as R, start counting indices in the structure matrices at 1 index_style = FORTRAN_STYLE; return true; } bool IpoptRNLP::get_bounds_info(Ipopt::Index n, Ipopt::Number* x_l, Ipopt::Number* x_u, Ipopt::Index m, Ipopt::Number* g_l, Ipopt::Number* g_u) { // Check that the number of controls, n, and the number of constraints, m // are of the same length as the R variables that were passed. assert(n == length( R_init_values )); assert(n == length( R_lower_bounds )); assert(n == length( R_upper_bounds )); assert(m == length( R_constraint_lower_bounds )); assert(m == length( R_constraint_upper_bounds )); // Check for user interruption from R R_CheckUserInterrupt(); // set the upper and lower bounds of the control for (Ipopt::Index i=0;i<n;i++) { x_l[i] = REAL(R_lower_bounds)[i]; // lower bound x_u[i] = REAL(R_upper_bounds)[i]; // upper bound } // set the upper and lower bounds of the inequality constraints for (Ipopt::Index i=0;i<m;i++) { g_l[i] = REAL(R_constraint_lower_bounds)[i]; // lower bound g_u[i] = REAL(R_constraint_upper_bounds)[i]; // upper bound } return true; } bool IpoptRNLP::get_starting_point(Ipopt::Index n, bool init_x, Ipopt::Number* x, bool init_z, Ipopt::Number* z_L, Ipopt::Number* z_U, Ipopt::Index m, bool init_lambda, Ipopt::Number* lambda) { // We have starting values for the control, x, only. assert(init_x == true); assert(init_z == false); assert(init_lambda == false); // Check for user interruption from R R_CheckUserInterrupt(); // set initial values of the controls for (Ipopt::Index i=0;i<n;i++) { x[i] = REAL(R_init_values)[i]; } return true; } bool IpoptRNLP::eval_f(Ipopt::Index n, const Ipopt::Number* x, bool new_x, Ipopt::Number& obj_value) { // Calculate and return the value of the objective function // Check for user interruption from R R_CheckUserInterrupt(); SEXP rargs,Rcall,result; // Allocate memory for a vector of reals. // This vector will contain the elements of x, // x is the argument to the R function R_eval_f PROTECT(rargs = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(rargs)[i] = x[i]; } // evaluate R function R_eval_f with the control x as an argument PROTECT(Rcall = lang2(R_eval_f,rargs)); PROTECT(result = eval(Rcall,R_environment)); // recode the return value from SEXP to Number obj_value = REAL(result)[0]; UNPROTECT(3); return true; } bool IpoptRNLP::eval_grad_f(Ipopt::Index n, const Ipopt::Number* x, bool new_x, Ipopt::Number* grad_f) { // Calculate and return the gradient of the objective function grad_{x} f(x) // if we have two controls, x1 and x2: // grad_f[0] = grad_{x1} f(x) // grad_f[1] = grad_{x2} f(x) // Check for user interruption from R R_CheckUserInterrupt(); SEXP rargs,Rcall,result; // allocate memory for a vector of reals // this vector will contain the elements of x // x is the argument to the R function R_eval_grad_f PROTECT(rargs = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(rargs)[i] = x[i]; } // evaluate R function R_eval_grad_f with the control x as an argument PROTECT(Rcall = lang2(R_eval_grad_f,rargs)); PROTECT(result = eval(Rcall,R_environment)); // recode the return values from SEXP to Numbers for (Ipopt::Index i=0;i<n;i++) { grad_f[i] = REAL(result)[i]; } UNPROTECT(3); return true; } bool IpoptRNLP::eval_g(Ipopt::Index n, const Ipopt::Number* x, bool new_x, Ipopt::Index m, Ipopt::Number* g) { // Calculate and return the value of the constraints: g(x) // Check for user interruption from R R_CheckUserInterrupt(); SEXP rargs,Rcall,result; // Allocate memory for a vector of reals // this vector will contain the elements of x // x is the argument to the R function R_eval_g PROTECT(rargs = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(rargs)[i] = x[i]; } PROTECT(Rcall = lang2(R_eval_g,rargs)); PROTECT(result = eval(Rcall,R_environment)); for (Ipopt::Index i=0;i<m;i++) { g[i] = REAL(result)[i]; } UNPROTECT(3); return true; } bool IpoptRNLP::eval_jac_g(Ipopt::Index n, const Ipopt::Number* x, bool new_x, Ipopt::Index m, Ipopt::Index nele_jac, Ipopt::Index* iRow, Ipopt::Index *jCol, Ipopt::Number* values) { // These use Fortran indexing style and start counting at 1 // Check for user interruption from R R_CheckUserInterrupt(); if (values == NULL) { // return the structure of the jacobian of the constraints // element at 1,1: grad_{x1} g_{1}(x) //iRow[0] = 1; //jCol[0] = 1; // element at 1,2: grad_{x2} g_{1}(x) //iRow[1] = 1; //jCol[1] = 2; Ipopt::Index total_cnt = 0; for (int list_cnt=0;list_cnt<length( R_eval_jac_g_structure );list_cnt++) { SEXP R_list_element; PROTECT(R_list_element = AS_INTEGER(VECTOR_ELT(R_eval_jac_g_structure, list_cnt))); for (int vector_cnt=0;vector_cnt< length(R_list_element); vector_cnt++) { iRow[ total_cnt ] = list_cnt+1; // we have to add 1 to turn it into Fortran styl indexing jCol[ total_cnt ] = INTEGER(R_list_element)[vector_cnt]; total_cnt++; } UNPROTECT(1); } } else { // return the values of the jacobian of the constraints SEXP rargs,Rcall,result; // allocate memory for a vector of reals // this vector will contain the elements of x // x is the argument to the R function R_eval_g_jac PROTECT(rargs = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(rargs)[i] = x[i]; } PROTECT(Rcall = lang2(R_eval_jac_g,rargs)); PROTECT(result = eval(Rcall,R_environment)); for (Ipopt::Index i=0;i<nele_jac;i++) { values[i] = REAL(result)[i]; } UNPROTECT(3); } return true; } bool IpoptRNLP::eval_h(Ipopt::Index n, const Ipopt::Number* x, bool new_x, Ipopt::Number obj_factor, Ipopt::Index m, const Ipopt::Number* lambda, bool new_lambda, Ipopt::Index nele_hess, Ipopt::Index* iRow, Ipopt::Index* jCol, Ipopt::Number* values) { // Check for user interruption from R R_CheckUserInterrupt(); if ( d_hessian_approximation ) { return false; } else { if (values == NULL) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. // Note: off-diagonal elements are zero for this problem // element at 1,1: grad^2_{x1,x1} L(x,lambda) // iRow[0] = 1; // jCol[0] = 1; // element at 2,2: grad^2_{x2,x2} L(x,lambda) // iRow[1] = 2; // jCol[1] = 2; Ipopt::Index total_cnt = 0; for (int list_cnt=0;list_cnt<length( R_eval_h_structure );list_cnt++) { SEXP R_list_element; PROTECT(R_list_element = AS_INTEGER(VECTOR_ELT(R_eval_h_structure, list_cnt))); for (int vector_cnt=0;vector_cnt< length(R_list_element); vector_cnt++) { iRow[ total_cnt ] = list_cnt+1; // we have to add 1 to turn it into Fortran styl indexing jCol[ total_cnt ] = INTEGER(R_list_element)[vector_cnt]; total_cnt++; } UNPROTECT(1); } } else { // return the values // element at 1,1: grad^2_{x1,x1} L(x,lambda) // values[0] = -2.0 * lambda[0]; // element at 2,2: grad^2_{x2,x2} L(x,lambda) // values[1] = -2.0 * obj_factor; SEXP rargs_x; PROTECT(rargs_x = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(rargs_x)[i] = x[i]; } SEXP rargs_obj_factor; PROTECT(rargs_obj_factor = allocVector(REALSXP,1)); REAL(rargs_obj_factor)[0] = obj_factor; SEXP rargs_lambda; PROTECT(rargs_lambda = allocVector(REALSXP,m)); for (Ipopt::Index i=0;i<m;i++) { REAL(rargs_lambda)[i] = lambda[i]; } SEXP Rcall, result; PROTECT(Rcall = lang4(R_eval_h, rargs_x, rargs_obj_factor, rargs_lambda)); PROTECT(result = eval(Rcall, R_environment)); for (Ipopt::Index i=0;i<nele_hess;i++) { values[i] = REAL(result)[i]; } UNPROTECT(5); } return true; } } void IpoptRNLP::finalize_solution(Ipopt::SolverReturn status, Ipopt::Index n, const Ipopt::Number* x, const Ipopt::Number* z_L, const Ipopt::Number* z_U, Ipopt::Index m, const Ipopt::Number* g, const Ipopt::Number* lambda, Ipopt::Number obj_value, const Ipopt::IpoptData* ip_data, Ipopt::IpoptCalculatedQuantities* ip_cq) { // Here we convert the results from c++ to an SEXP list with elements // 0. status; integer with convergence status // 1. message; string with convergence status // 2. iterations; number of iterations // 3. objective; final value of the objective function // 4. solution; final values for the control variables // 5. z_L; final values for the lower bound multipliers // 6. z_U; final values for the upper bound multipliers // 7. constraints; final values for the constraints // 8. lambda; final values for the Lagrange mulipliers int num_return_elements = 9; // R_result_list is a member object, which has been protected in the constructor // and will be unprotected in the destructor. PROTECT(R_result_list = allocVector(VECSXP, num_return_elements)); d_num_protected_members++; // attach names to the return list SEXP names; PROTECT(names = allocVector(STRSXP, num_return_elements)); SET_STRING_ELT(names, 0, mkChar("status")); SET_STRING_ELT(names, 1, mkChar("message")); SET_STRING_ELT(names, 2, mkChar("iterations")); SET_STRING_ELT(names, 3, mkChar("objective")); SET_STRING_ELT(names, 4, mkChar("solution")); SET_STRING_ELT(names, 5, mkChar("z_L")); SET_STRING_ELT(names, 6, mkChar("z_U")); SET_STRING_ELT(names, 7, mkChar("constraints")); SET_STRING_ELT(names, 8, mkChar("lambda")); setAttrib(R_result_list, R_NamesSymbol, names); // convert status to an R object SEXP R_status; PROTECT(R_status = allocVector(INTSXP,1)); INTEGER(R_status)[0] = (int) status; SEXP R_status_message; PROTECT(R_status_message = allocVector(STRSXP, 1)); switch ( status ) { case Ipopt::SUCCESS: SET_STRING_ELT(R_status_message, 0, mkChar("SUCCESS: Algorithm terminated successfully at a locally optimal point, satisfying the convergence tolerances (can be specified by options).")); break; case Ipopt::MAXITER_EXCEEDED: SET_STRING_ELT(R_status_message, 0, mkChar("MAXITER_EXCEEDED: Maximum number of iterations exceeded (can be specified by an option).")); break; case Ipopt::STOP_AT_TINY_STEP: SET_STRING_ELT(R_status_message, 0, mkChar("STOP_AT_TINY_STEP: Algorithm proceeds with very little progress.")); break; case Ipopt::STOP_AT_ACCEPTABLE_POINT: SET_STRING_ELT(R_status_message, 0, mkChar("STOP_AT_ACCEPTABLE_POINT: Algorithm stopped at a point that was converged, not to ``desired'' tolerances, but to ``acceptable'' tolerances (see the acceptable-... options).")); break; case Ipopt::LOCAL_INFEASIBILITY: SET_STRING_ELT(R_status_message, 0, mkChar("LOCAL_INFEASIBILITY: Algorithm converged to a point of local infeasibility. Problem may be infeasible.")); break; case Ipopt::USER_REQUESTED_STOP: SET_STRING_ELT(R_status_message, 0, mkChar("USER_REQUESTED_STOP: The user call-back function intermediate_callback (see Section 3.3.4) returned false, i.e., the user code requested a premature termination of the optimization.")); break; case Ipopt::DIVERGING_ITERATES: SET_STRING_ELT(R_status_message, 0, mkChar("DIVERGING_ITERATES: It seems that the iterates diverge.")); break; case Ipopt::RESTORATION_FAILURE: SET_STRING_ELT(R_status_message, 0, mkChar("RESTORATION_FAILURE: Restoration phase failed, algorithm doesn't know how to proceed.")); break; case Ipopt::ERROR_IN_STEP_COMPUTATION: SET_STRING_ELT(R_status_message, 0, mkChar("ERROR_IN_STEP_COMPUTATION: An unrecoverable error occurred while IPOPT tried to compute the search direction.")); break; case Ipopt::INVALID_NUMBER_DETECTED: SET_STRING_ELT(R_status_message, 0, mkChar("INVALID_NUMBER_DETECTED: Algorithm received an invalid number (such as NaN or Inf) from the NLP; see also option check_derivatives_for_naninf.")); break; case Ipopt::INTERNAL_ERROR: SET_STRING_ELT(R_status_message, 0, mkChar("INTERNAL_ERROR: An unknown internal error occurred. Please contact the IPOPT authors through the mailing list.")); break; default: SET_STRING_ELT(R_status_message, 0, mkChar("Return status not recognized.")); } // !!! we add number of iterations in the main program // convert value of objective function to an R object SEXP R_objective; PROTECT(R_objective = allocVector(REALSXP,1)); REAL(R_objective)[0] = obj_value; // convert the value of the controls to an R object SEXP R_solution; PROTECT(R_solution = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(R_solution)[i] = x[i]; } SEXP R_z_L; PROTECT(R_z_L = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(R_z_L)[i] = z_L[i]; } SEXP R_z_U; PROTECT(R_z_U = allocVector(REALSXP,n)); for (Ipopt::Index i=0;i<n;i++) { REAL(R_z_U)[i] = z_U[i]; } SEXP R_constraints; PROTECT(R_constraints = allocVector(REALSXP,m)); for (Ipopt::Index i=0;i<m;i++) { REAL(R_constraints)[i] = g[i]; } SEXP R_lambda; PROTECT(R_lambda = allocVector(REALSXP,m)); for (Ipopt::Index i=0;i<m;i++) { REAL(R_lambda)[i] = lambda[i]; } // add elements to the list SET_VECTOR_ELT(R_result_list, 0, R_status); SET_VECTOR_ELT(R_result_list, 1, R_status_message); SET_VECTOR_ELT(R_result_list, 3, R_objective); SET_VECTOR_ELT(R_result_list, 4, R_solution); SET_VECTOR_ELT(R_result_list, 5, R_z_L); SET_VECTOR_ELT(R_result_list, 6, R_z_U); SET_VECTOR_ELT(R_result_list, 7, R_constraints); SET_VECTOR_ELT(R_result_list, 8, R_lambda); UNPROTECT(num_return_elements); }
31.247039
241
0.675692
[ "object", "vector" ]
8d0cc4836eff18a3c17c1400db9d12623cf87c02
1,197
cpp
C++
Algorithms/1505.Minimum_Possible_Integer_After_at_Most_K_Adjacent_Swaps_On_Digits.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1505.Minimum_Possible_Integer_After_at_Most_K_Adjacent_Swaps_On_Digits.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1505.Minimum_Possible_Integer_After_at_Most_K_Adjacent_Swaps_On_Digits.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: void update(int x , int n , int add , vector<int>& tree) { while(x <= n) { tree[x] += add; x += (x&(-x)); } } int query(int x , vector<int>& tree) { int res = 0; while(x) { res += tree[x]; x -= (x&(-x)); } return res; } string minInteger(string s, int k) { queue<int> Q[10]; int n = s.length(); s = "@" + s; vector<int> tree(n+1,0); for( int i = 1 ; i <= n ; i++ ) Q[s[i]-'0'].push(i); string ans = ""; for( int i = 1 ; i <= n ; i++ ) for( int j = 0 ; j < 10 ; j++ ) if(!Q[j].empty()) { char c = '0' + j; int ind = Q[j].front(); int move = query(ind,tree); int place = ind+move; if(place-1 <= k) { Q[j].pop(); k -= place-1; ans.push_back(c); update(ind,n,-1,tree); break; } } return ans; } };
28.5
62
0.314954
[ "vector" ]
8d0f34721fe5146c2ab45874f85b23a0bb13e09d
2,229
cpp
C++
CLRS/Sorting/MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/Sorting/MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/Sorting/MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
/* You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut. Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7. Example 1: Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3] Output: 4 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. Example 2: Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1] Output: 6 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. Example 3: Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3] Output: 9 Constraints: 2 <= h, w <= 109 1 <= horizontalCuts.length <= min(h - 1, 105) 1 <= verticalCuts.length <= min(w - 1, 105) 1 <= horizontalCuts[i] < h 1 <= verticalCuts[i] < w All the elements in horizontalCuts are distinct. All the elements in verticalCuts are distinct. */ // class Solution { public: int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) { sort(horizontalCuts.begin(),horizontalCuts.end()); sort(verticalCuts.begin(),verticalCuts.end()); long maxheight = max(horizontalCuts[0],h-horizontalCuts[horizontalCuts.size()-1]); long maxwidth = max(verticalCuts[0],w-verticalCuts[verticalCuts.size()-1]); for ( int i = 1; i < horizontalCuts.size(); i++ ) maxheight = max(maxheight,(long)(horizontalCuts[i]-horizontalCuts[i-1])); for ( int i = 1; i < verticalCuts.size(); i++ ) maxwidth = max(maxwidth,(long)(verticalCuts[i]-verticalCuts[i-1])); return (maxheight * maxwidth) % (1000000007); } };
41.277778
221
0.705249
[ "vector" ]
8d0f9ea41e4ecf3ef60b4d18de1e69bd9aa5b893
1,775
hpp
C++
lkRay/Scene/BVH.hpp
lookeypl/lkRay
c12d87add95f5958d77a8a8a683fc954837b6c60
[ "WTFPL" ]
null
null
null
lkRay/Scene/BVH.hpp
lookeypl/lkRay
c12d87add95f5958d77a8a8a683fc954837b6c60
[ "WTFPL" ]
null
null
null
lkRay/Scene/BVH.hpp
lookeypl/lkRay
c12d87add95f5958d77a8a8a683fc954837b6c60
[ "WTFPL" ]
null
null
null
#pragma once #include "Geometry/AABB.hpp" #include "Renderer/RayCollision.hpp" #include "Containers.hpp" #include <list> #include <functional> namespace lkRay { namespace Scene { struct BVHNode; struct BVHLeafData { uint32_t obj[2]; BVHLeafData() : obj{ UINT32_MAX, UINT32_MAX } { } }; struct BVHMidData { BVHNode* left; BVHNode* right; BVHMidData() : left(nullptr) , right(nullptr) { } }; struct BVHNode { Geometry::AABB bBox; BVHMidData midData; BVHLeafData leafData; }; using BVHObjIdCollection = std::vector<uint32_t>; template <typename T> class BVH { BVHNode* mRootNode; Containers::Container<T> mObjects; std::list<BVHNode> mNodes; size_t mNodeCount; BVHObjIdCollection::iterator FindSplitPoint(BVHObjIdCollection& ids, const BVHNode* currentNode); void BuildStep(BVHObjIdCollection& objIds, BVHNode* currentNode); void PrintStep(BVHNode* currentNode, uint32_t depth) const; public: BVH(); ~BVH(); void Build(); void Clean(); Renderer::RayCollision Traverse(const Geometry::Ray& ray) const; void Print() const; LKCOMMON_INLINE void PushObject(T& ptr) { mObjects.push_back(ptr); } template <typename... Ts> LKCOMMON_INLINE void EmplaceObject(Ts&&... args) { mObjects.emplace_back(std::forward<Ts>(args)...); } LKCOMMON_INLINE const Containers::Container<T>& GetPrimitives() const { return mObjects; } LKCOMMON_INLINE const T& GetObject(size_t i) const { return mObjects[i]; } LKCOMMON_INLINE size_t GetObjectCount() const { return mObjects.size(); } }; } // namespace Scene } // namespace lkRay #include "BVHImpl.hpp"
17.75
101
0.651831
[ "geometry", "vector" ]
8d11170b481fae4a913334635c924ffa94526e8e
4,712
cpp
C++
WebKit/Source/WebKit/gtk/webkit/webkitwebplugindatabase.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
1
2019-06-18T06:52:54.000Z
2019-06-18T06:52:54.000Z
WebKit/Source/WebKit/gtk/webkit/webkitwebplugindatabase.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
WebKit/Source/WebKit/gtk/webkit/webkitwebplugindatabase.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2010 Igalia S.L. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "webkitwebplugindatabase.h" #include "PluginDatabase.h" #include "webkitglobalsprivate.h" #include "webkitwebplugindatabaseprivate.h" #include "webkitwebpluginprivate.h" /** * SECTION:webkitwebplugindatabase * @short_description: Provides information about the plugins the engine knows about * @see_also: #WebKitWebPlugin * * This object allows you to query information about the plugins found * by the engine while scanning the usual directories. You can then * use the #WebKitWebPlugin objects to get more information or * enable/disable individual plugins. */ using namespace WebKit; using namespace WebCore; G_DEFINE_TYPE(WebKitWebPluginDatabase, webkit_web_plugin_database, G_TYPE_OBJECT) static void webkit_web_plugin_database_dispose(GObject* object) { G_OBJECT_CLASS(webkit_web_plugin_database_parent_class)->dispose(object); } static void webkit_web_plugin_database_class_init(WebKitWebPluginDatabaseClass* klass) { webkitInit(); GObjectClass* gobjectClass = reinterpret_cast<GObjectClass*>(klass); gobjectClass->dispose = webkit_web_plugin_database_dispose; g_type_class_add_private(klass, sizeof(WebKitWebPluginDatabasePrivate)); } static void webkit_web_plugin_database_init(WebKitWebPluginDatabase* database) { WebKitWebPluginDatabasePrivate* priv = G_TYPE_INSTANCE_GET_PRIVATE(database, WEBKIT_TYPE_WEB_PLUGIN_DATABASE, WebKitWebPluginDatabasePrivate); database->priv = priv; priv->coreDatabase = PluginDatabase::installedPlugins(); } /** * webkit_web_plugin_database_list_free: * @list: a #WebKitWebPluginDatabasePluginList * * Frees @list. * * Since: 1.3.8 */ void webkit_web_plugin_database_plugins_list_free(GSList* list) { if (!list) return; for (GSList* p = list; p; p = p->next) g_object_unref(p->data); g_slist_free(list); } /** * webkit_web_plugin_database_get_plugins: * @database: a #WebKitWebPluginDatabase * * Returns all #WebKitWebPlugin available in @database. * The returned list must be freed with webkit_web_plugin_database_plugins_list_free() * * Returns: (transfer full) (element-type WebKitWebPlugin): a #GSList of #WebKitWebPlugin * * Since: 1.3.8 */ GSList* webkit_web_plugin_database_get_plugins(WebKitWebPluginDatabase* database) { g_return_val_if_fail(WEBKIT_IS_WEB_PLUGIN_DATABASE(database), 0); GSList* gPlugins = 0; const Vector<PluginPackage*>& plugins = database->priv->coreDatabase->plugins(); for (unsigned int i = 0; i < plugins.size(); ++i) { PluginPackage* plugin = plugins[i]; gPlugins = g_slist_append(gPlugins, kitNew(plugin)); } return gPlugins; } /** * webkit_web_plugin_database_get_plugin_for_mimetype: * @database: a #WebKitWebPluginDatabase * @mime_type: a mime type * * Returns the #WebKitWebPlugin that is handling @mimeType in the * @database, or %NULL if there's none doing so. * * Returns: (transfer full): a #WebKitWebPlugin * * Since: 1.3.8 */ WebKitWebPlugin* webkit_web_plugin_database_get_plugin_for_mimetype(WebKitWebPluginDatabase* database, const char* mimeType) { g_return_val_if_fail(WEBKIT_IS_WEB_PLUGIN_DATABASE(database), 0); g_return_val_if_fail(mimeType, 0); return kitNew(database->priv->coreDatabase->pluginForMIMEType(mimeType)); } /** * webkit_web_plugin_database_refresh: * @database: a #WebKitWebPluginDatabase * * Refreshes @database adding new plugins that are now in use and * removing those that have been disabled or are otherwise no longer * available. * * Since: 1.3.8 */ void webkit_web_plugin_database_refresh(WebKitWebPluginDatabase* database) { g_return_if_fail(WEBKIT_IS_WEB_PLUGIN_DATABASE(database)); database->priv->coreDatabase->refresh(); } WebKitWebPluginDatabase* webkit_web_plugin_database_new(void) { return WEBKIT_WEB_PLUGIN_DATABASE(g_object_new(WEBKIT_TYPE_WEB_PLUGIN_DATABASE, 0)); }
30.797386
146
0.762946
[ "object", "vector" ]
8d1ab66bc0db89d637f4ab5de953d4bd2196996d
1,600
hpp
C++
src/common/utils.hpp
amiller/libsnark
d34b477ed9c0e36f74c78946012658bdecde0c00
[ "MIT" ]
null
null
null
src/common/utils.hpp
amiller/libsnark
d34b477ed9c0e36f74c78946012658bdecde0c00
[ "MIT" ]
null
null
null
src/common/utils.hpp
amiller/libsnark
d34b477ed9c0e36f74c78946012658bdecde0c00
[ "MIT" ]
null
null
null
/** @file ***************************************************************************** Declaration of misc math and serialization utility functions ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef UTILS_HPP_ #define UTILS_HPP_ #include <cassert> #include <iostream> #include <sstream> #include <string> #include <vector> namespace libsnark { typedef std::vector<bool> bit_vector; /// returns ceil(log2(n)), so 1<<log2(n) is the smallest power of 2, that is not less than n size_t log2(size_t n); size_t to_twos_complement(int i, size_t w); int from_twos_complement(size_t i, size_t w); size_t bitreverse(size_t n, const size_t l); bit_vector int_list_to_bits(const std::initializer_list<unsigned long> &l, const size_t wordsize); long long div_ceil(long long x, long long y); bool is_little_endian(); typedef std::vector<size_t> permutation; std::string FORMAT(const std::string &prefix, const char* format, ...); #ifdef DEBUG #define FMT FORMAT #else #define FMT(...) "" #endif void serialize_bit_vector(std::ostream &out, const bit_vector &v); void deserialize_bit_vector(std::istream &in, bit_vector &v); template<typename T> T reserialize(const T &obj) { std::stringstream ss; ss << obj; T tmp; ss >> tmp; assert(obj == tmp); return tmp; } } // libsnark #endif // UTILS_HPP_
26.229508
98
0.61
[ "vector" ]
8d1c7e23e3a9bf3eac086166007860739aa23fda
50,082
cpp
C++
tbb/tbb41_20120718oss/src/test/test_join_node.cpp
glycerine/shore-mt
39f1802ba9588bc9d32d34386ed0193477f7e8d1
[ "Spencer-94", "Spencer-86", "Xnet", "Linux-OpenIB", "Spencer-99", "X11", "CECILL-B" ]
3
2016-07-15T08:22:56.000Z
2019-10-10T02:26:08.000Z
tbb/tbb41_20120718oss/src/test/test_join_node.cpp
glycerine/shore-mt
39f1802ba9588bc9d32d34386ed0193477f7e8d1
[ "Spencer-94", "Spencer-86", "Xnet", "Linux-OpenIB", "Spencer-99", "X11", "CECILL-B" ]
null
null
null
tbb/tbb41_20120718oss/src/test/test_join_node.cpp
glycerine/shore-mt
39f1802ba9588bc9d32d34386ed0193477f7e8d1
[ "Spencer-94", "Spencer-86", "Xnet", "Linux-OpenIB", "Spencer-99", "X11", "CECILL-B" ]
2
2020-12-23T06:49:23.000Z
2021-03-05T07:00:28.000Z
/* Copyright 2005-2012 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #if _MSC_VER // Name length is limited to avoid "decorated name length exceeded, name was truncated" warning. #define _VARIADIC_MAX 8 #endif #include "harness.h" #if !__SUNPRO_CC #include "tbb/flow_graph.h" #include "tbb/task_scheduler_init.h" // the tuple-based tests with more inputs take a long time to compile. If changes // are made to the tuple implementation or any switch that controls it, the test // should be compiled with COMPREHENSIVE_TEST == 1 to ensure all tuple sizes are tested. #ifndef COMPREHENSIVE_TEST #define COMPREHENSIVE_TEST 0 #endif // // Tests // const int Count = 150; const int Recirc_count = 1000; // number of tuples to be generated const int MaxPorts = 10; const int MaxNSources = 5; // max # of source_nodes to register for each join_node input in parallel test bool outputCheck[MaxPorts][Count]; // for checking output using tbb::flow::NO_TAG; void check_outputCheck( int nUsed, int maxCnt) { for(int i=0; i < nUsed; ++i) { for( int j = 0; j < maxCnt; ++j) { ASSERT(outputCheck[i][j], NULL); } } } void reset_outputCheck( int nUsed, int maxCnt) { for(int i=0; i < nUsed; ++i) { for( int j = 0; j < maxCnt; ++j) { outputCheck[i][j] = false; } } } template<typename T> class name_of { public: static const char* name() { return "Unknown"; } }; template<> class name_of<int> { public: static const char* name() { return "int"; } }; template<> class name_of<float> { public: static const char* name() { return "float"; } }; template<> class name_of<double> { public: static const char* name() { return "double"; } }; template<> class name_of<long> { public: static const char* name() { return "long"; } }; template<> class name_of<short> { public: static const char* name() { return "short"; } }; // for recirculating tags, input is tuple<index,continue_msg> // output is index*my_mult cast to the right type template<typename TT> class recirc_func_body { TT my_mult; public: typedef std::tuple<int, tbb::flow::continue_msg> input_type; recirc_func_body(TT multiplier ) : my_mult(multiplier) {} recirc_func_body(const recirc_func_body &other) : my_mult(other.my_mult) { } void operator=( const recirc_func_body &other) { my_mult = other.my_mult; } TT operator()(const input_type &v) { return TT(std::get<0>(v)) * my_mult; } }; static int input_count; // source_nodes are serial static tbb::atomic<int> output_count; // emit input_count continue_msg class recirc_source_node_body { public: bool operator()(tbb::flow::continue_msg &v ) { --input_count; v = tbb::flow::continue_msg(); return 0 <= input_count; } }; // T must be arithmetic, and shouldn't wrap around for reasonable sizes of Count (which is now 150, and maxPorts is 10, // so the max number generated right now is 1500 or so.) Source will generate a series of TT with value // (init_val + (i-1)*addend) * my_mult, where i is the i-th invocation of the body. We are attaching addend // source nodes to a join_port, and each will generate part of the numerical series the port is expecting // to receive. If there is only one source node, the series order will be maintained; if more than one, // this is not guaranteed. template<typename TT> class source_body { const TT my_mult; int my_count; const int addend; source_body& operator=( const source_body& other); public: source_body(TT multiplier, int init_val, int addto) : my_mult(multiplier), my_count(init_val), addend(addto) { } bool operator()( TT &v) { int lc = my_count; v = my_mult * (TT)my_count; my_count += addend; return lc < Count; } }; template<typename TT> class tag_func { const TT my_mult; tag_func& operator=( const tag_func& other); public: tag_func(TT multiplier) : my_mult(multiplier) { } // operator() will return [0 .. Count) tbb::flow::tag_value operator()( TT v) { tbb::flow::tag_value t = tbb::flow::tag_value(v / my_mult); return t; } }; // allocator for join_node. This is specialized for tag_matching joins because they require a variable number // of tag_value methods passed to the constructor template<int N, typename JType, tbb::flow::graph_buffer_policy JP> class makeJoin { public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g); return temp; } static void destroy(JType *p) { delete p; } }; template<typename JType> class makeJoin<2,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)) ); return temp; } static void destroy(JType *p) { delete p; } }; template<typename JType> class makeJoin<3,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)) ); return temp; } static void destroy(JType *p) { delete p; } }; template<typename JType> class makeJoin<4,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)) ); return temp; } static void destroy(JType *p) { delete p; } }; template<typename JType> class makeJoin<5,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; typedef typename std::tuple_element<4, TType>::type T4; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)), tag_func<T4>(T4(6)) ); return temp; } static void destroy(JType *p) { delete p; } }; #if __TBB_VARIADIC_MAX >= 6 template<typename JType> class makeJoin<6,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; typedef typename std::tuple_element<4, TType>::type T4; typedef typename std::tuple_element<5, TType>::type T5; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)), tag_func<T4>(T4(6)), tag_func<T5>(T5(7)) ); return temp; } static void destroy(JType *p) { delete p; } }; #endif #if __TBB_VARIADIC_MAX >= 7 template<typename JType> class makeJoin<7,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; typedef typename std::tuple_element<4, TType>::type T4; typedef typename std::tuple_element<5, TType>::type T5; typedef typename std::tuple_element<6, TType>::type T6; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)), tag_func<T4>(T4(6)), tag_func<T5>(T5(7)), tag_func<T6>(T6(8)) ); return temp; } static void destroy(JType *p) { delete p; } }; #endif #if __TBB_VARIADIC_MAX >= 8 template<typename JType> class makeJoin<8,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; typedef typename std::tuple_element<4, TType>::type T4; typedef typename std::tuple_element<5, TType>::type T5; typedef typename std::tuple_element<6, TType>::type T6; typedef typename std::tuple_element<7, TType>::type T7; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)), tag_func<T4>(T4(6)), tag_func<T5>(T5(7)), tag_func<T6>(T6(8)), tag_func<T7>(T7(9)) ); return temp; } static void destroy(JType *p) { delete p; } }; #endif #if __TBB_VARIADIC_MAX >= 9 template<typename JType> class makeJoin<9,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; typedef typename std::tuple_element<4, TType>::type T4; typedef typename std::tuple_element<5, TType>::type T5; typedef typename std::tuple_element<6, TType>::type T6; typedef typename std::tuple_element<7, TType>::type T7; typedef typename std::tuple_element<8, TType>::type T8; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)), tag_func<T4>(T4(6)), tag_func<T5>(T5(7)), tag_func<T6>(T6(8)), tag_func<T7>(T7(9)), tag_func<T8>(T8(10)) ); return temp; } static void destroy(JType *p) { delete p; } }; #endif #if __TBB_VARIADIC_MAX >= 10 template<typename JType> class makeJoin<10,JType,tbb::flow::tag_matching> { typedef typename JType::output_type TType; typedef typename std::tuple_element<0, TType>::type T0; typedef typename std::tuple_element<1, TType>::type T1; typedef typename std::tuple_element<2, TType>::type T2; typedef typename std::tuple_element<3, TType>::type T3; typedef typename std::tuple_element<4, TType>::type T4; typedef typename std::tuple_element<5, TType>::type T5; typedef typename std::tuple_element<6, TType>::type T6; typedef typename std::tuple_element<7, TType>::type T7; typedef typename std::tuple_element<8, TType>::type T8; typedef typename std::tuple_element<9, TType>::type T9; public: static JType *create(tbb::flow::graph& g) { JType *temp = new JType(g, tag_func<T0>(T0(2)), tag_func<T1>(T1(3)), tag_func<T2>(T2(4)), tag_func<T3>(T3(5)), tag_func<T4>(T4(6)), tag_func<T5>(T5(7)), tag_func<T6>(T6(8)), tag_func<T7>(T7(9)), tag_func<T8>(T8(10)), tag_func<T9>(T9(11)) ); return temp; } static void destroy(JType *p) { delete p; } }; #endif // holder for source_node pointers for eventual deletion static void* all_source_nodes[MaxPorts][MaxNSources]; template<int ELEM, typename JNT> class source_node_helper { public: typedef JNT join_node_type; typedef tbb::flow::join_node<std::tuple<int, tbb::flow::continue_msg>, tbb::flow::reserving> input_join_type; typedef typename join_node_type::output_type TT; typedef typename std::tuple_element<ELEM-1,TT>::type IT; typedef typename tbb::flow::source_node<IT> my_source_node_type; typedef typename tbb::flow::function_node<std::tuple<int,tbb::flow::continue_msg>, IT> my_recirc_function_type; static void print_remark(const char * str) { source_node_helper<ELEM-1,JNT>::print_remark(str); REMARK(", %s", name_of<IT>::name()); } static void add_source_nodes(join_node_type &my_join, tbb::flow::graph &g, int nInputs) { for(int i=0; i < nInputs; ++i) { my_source_node_type *new_node = new my_source_node_type(g, source_body<IT>((IT)(ELEM+1), i, nInputs)); tbb::flow::make_edge( *new_node, tbb::flow::input_port<ELEM-1>(my_join) ); all_source_nodes[ELEM-1][i] = (void *)new_node; } // add the next source_node source_node_helper<ELEM-1, JNT>::add_source_nodes(my_join, g, nInputs); } static void add_recirc_func_nodes(join_node_type &my_join, input_join_type &my_input, tbb::flow::graph &g) { my_recirc_function_type *new_node = new my_recirc_function_type(g, tbb::flow::unlimited, recirc_func_body<IT>((IT)(ELEM+1))); tbb::flow::make_edge(*new_node, tbb::flow::input_port<ELEM-1>(my_join)); tbb::flow::make_edge(my_input, *new_node); all_source_nodes[ELEM-1][0] = (void *)new_node; source_node_helper<ELEM-1, JNT>::add_recirc_func_nodes(my_join, my_input, g); } static void only_check_value(const int i, const TT &v) { ASSERT( std::get<ELEM-1>(v) == (IT)(i*(ELEM+1)), NULL); source_node_helper<ELEM-1,JNT>::only_check_value(i, v); } static void check_value(int i, TT &v, bool is_serial) { // the fetched value will match only if there is only one source_node. ASSERT(!is_serial || std::get<ELEM-1>(v) == (IT)(i*(ELEM+1)), NULL); // tally the fetched value. int ival = (int)std::get<ELEM-1>(v); ASSERT(!(ival%(ELEM+1)), NULL); ival /= (ELEM+1); ASSERT(!outputCheck[ELEM-1][ival], NULL); outputCheck[ELEM-1][ival] = true; source_node_helper<ELEM-1,JNT>::check_value(i, v, is_serial); } static void remove_source_nodes(join_node_type& my_join, int nInputs) { for(int i=0; i< nInputs; ++i) { my_source_node_type *dp = reinterpret_cast<my_source_node_type *>(all_source_nodes[ELEM-1][i]); tbb::flow::remove_edge( *dp, tbb::flow::input_port<ELEM-1>(my_join) ); delete dp; } source_node_helper<ELEM-1, JNT>::remove_source_nodes(my_join, nInputs); } static void remove_recirc_func_nodes(join_node_type& my_join, input_join_type &my_input) { my_recirc_function_type *fn = reinterpret_cast<my_recirc_function_type *>(all_source_nodes[ELEM-1][0]); tbb::flow::remove_edge( *fn, tbb::flow::input_port<ELEM-1>(my_join) ); tbb::flow::remove_edge( my_input, *fn); delete fn; source_node_helper<ELEM-1, JNT>::remove_recirc_func_nodes(my_join,my_input); } }; template<typename JNT> class source_node_helper<1, JNT> { typedef JNT join_node_type; typedef tbb::flow::join_node<std::tuple<int, tbb::flow::continue_msg>, tbb::flow::reserving> input_join_type; typedef typename join_node_type::output_type TT; typedef typename std::tuple_element<0,TT>::type IT; typedef typename tbb::flow::source_node<IT> my_source_node_type; typedef typename tbb::flow::function_node<std::tuple<int,tbb::flow::continue_msg>, IT> my_recirc_function_type; public: static void print_remark(const char * str) { REMARK("%s< %s", str, name_of<IT>::name()); } static void add_source_nodes(join_node_type &my_join, tbb::flow::graph &g, int nInputs) { for(int i=0; i < nInputs; ++i) { my_source_node_type *new_node = new my_source_node_type(g, source_body<IT>((IT)2, i, nInputs)); tbb::flow::make_edge( *new_node, tbb::flow::input_port<0>(my_join) ); all_source_nodes[0][i] = (void *)new_node; } } static void add_recirc_func_nodes(join_node_type &my_join, input_join_type &my_input, tbb::flow::graph &g) { my_recirc_function_type *new_node = new my_recirc_function_type(g, tbb::flow::unlimited, recirc_func_body<IT>((IT)(2))); tbb::flow::make_edge(*new_node, tbb::flow::input_port<0>(my_join)); tbb::flow::make_edge(my_input, *new_node); all_source_nodes[0][0] = (void *)new_node; } static void only_check_value(const int i, const TT &v) { ASSERT( std::get<0>(v) == (IT)(i*2), NULL); } static void check_value(int i, TT &v, bool is_serial) { ASSERT(!is_serial || std::get<0>(v) == (IT)(i*(2)), NULL); int ival = (int)std::get<0>(v); ASSERT(!(ival%2), NULL); ival /= 2; ASSERT(!outputCheck[0][ival], NULL); outputCheck[0][ival] = true; } static void remove_source_nodes(join_node_type& my_join, int nInputs) { for(int i=0; i < nInputs; ++i) { my_source_node_type *dp = reinterpret_cast<my_source_node_type *>(all_source_nodes[0][i]); tbb::flow::remove_edge( *dp, tbb::flow::input_port<0>(my_join) ); delete dp; } } static void remove_recirc_func_nodes(join_node_type& my_join, input_join_type &my_input) { my_recirc_function_type *fn = reinterpret_cast<my_recirc_function_type *>(all_source_nodes[0][0]); tbb::flow::remove_edge( *fn, tbb::flow::input_port<0>(my_join) ); tbb::flow::remove_edge( my_input, *fn); delete fn; } }; // get the tag from the output tuple and emit it. // the first tuple component is tag * 2 cast to the type template<typename OutputTupleType> class recirc_output_func_body { public: // we only need this to use source_node_helper typedef typename tbb::flow::join_node<OutputTupleType, tbb::flow::tag_matching> join_node_type; static const int N = std::tuple_size<OutputTupleType>::value; int operator()(const OutputTupleType &v) { int out = int(std::get<0>(v)) / 2; source_node_helper<N,join_node_type>::only_check_value(out,v); ++output_count; return out; } }; template<typename JType> class tag_recirculation_test { public: typedef typename JType::output_type TType; typedef typename std::tuple<int, tbb::flow::continue_msg> input_tuple_type; typedef tbb::flow::join_node<input_tuple_type,tbb::flow::reserving> input_join_type; static const int N = std::tuple_size<TType>::value; static void test() { source_node_helper<N,JType>::print_remark("Recirculation test of tag-matching join"); REMARK(" >\n"); for(int maxTag = 1; maxTag <10; maxTag *= 3) { for(int i=0; i < N; ++i) all_source_nodes[i][0] = NULL; tbb::flow::graph g; // this is the tag-matching join we're testing JType * my_join = makeJoin<N,JType, tbb::flow::tag_matching>::create(g); // source_node for continue messages tbb::flow::source_node<tbb::flow::continue_msg> snode(g, recirc_source_node_body(), false); // reserving join that matches recirculating tags with continue messages. input_join_type * my_input_join = makeJoin<2,input_join_type,tbb::flow::reserving>::create(g); // tbb::flow::make_edge(snode, tbb::flow::input_port<1>(*my_input_join)); tbb::flow::make_edge(snode, std::get<1>(my_input_join->input_ports())); // queue to hold the tags tbb::flow::queue_node<int> tag_queue(g); tbb::flow::make_edge(tag_queue, tbb::flow::input_port<0>(*my_input_join)); // add all the function_nodes that are inputs to the tag-matching join source_node_helper<N,JType>::add_recirc_func_nodes(*my_join, *my_input_join, g); // add the function_node that accepts the output of the join and emits the int tag it was based on tbb::flow::function_node<TType, int> recreate_tag(g, tbb::flow::unlimited, recirc_output_func_body<TType>()); tbb::flow::make_edge(*my_join, recreate_tag); // now the recirculating part (output back to the queue) tbb::flow::make_edge(recreate_tag, tag_queue); // put the tags into the queue for(int t = 1; t <= maxTag; ++t) tag_queue.try_put(t); input_count = Recirc_count; output_count = 0; // start up the source node to get things going snode.activate(); // wait for everything to stop g.wait_for_all(); ASSERT(output_count == Recirc_count, "not all instances were received"); int j; // grab the tags from the queue, record them std::vector<bool> out_tally(maxTag, false); for(int i = 0; i < maxTag; ++i) { ASSERT(tag_queue.try_get(j), "not enough tags in queue"); ASSERT(!out_tally.at(j-1), "duplicate tag from queue"); out_tally[j-1] = true; } ASSERT(!tag_queue.try_get(j), "Extra tags in recirculation queue"); // deconstruct graph source_node_helper<N, JType>::remove_recirc_func_nodes(*my_join, *my_input_join); tbb::flow::remove_edge(*my_join, recreate_tag); makeJoin<N,JType,tbb::flow::tag_matching>::destroy(my_join); tbb::flow::remove_edge(tag_queue, tbb::flow::input_port<0>(*my_input_join)); tbb::flow::remove_edge(snode, tbb::flow::input_port<1>(*my_input_join)); makeJoin<2,input_join_type,tbb::flow::reserving>::destroy(my_input_join); } } }; template<typename JType, tbb::flow::graph_buffer_policy JP> class parallel_test { public: typedef typename JType::output_type TType; static const int SIZE = std::tuple_size<TType>::value; static const tbb::flow::graph_buffer_policy jp = JP; static void test() { TType v; source_node_helper<SIZE,JType>::print_remark("Parallel test of join_node"); REMARK(" >\n"); for(int i=0; i < MaxPorts; ++i) { for(int j=0; j < MaxNSources; ++j) { all_source_nodes[i][j] = NULL; } } for(int nInputs = 1; nInputs <= MaxNSources; ++nInputs) { tbb::flow::graph g; // JType my_join(g); bool not_out_of_order = (nInputs == 1) && (jp != tbb::flow::tag_matching); JType* my_join = makeJoin<SIZE,JType,JP>::create(g); tbb::flow::queue_node<TType> outq1(g); tbb::flow::queue_node<TType> outq2(g); tbb::flow::make_edge( *my_join, outq1 ); tbb::flow::make_edge( *my_join, outq2 ); source_node_helper<SIZE, JType>::add_source_nodes((*my_join), g, nInputs); g.wait_for_all(); reset_outputCheck(SIZE, Count); for(int i=0; i < Count; ++i) { ASSERT(outq1.try_get(v), NULL); source_node_helper<SIZE, JType>::check_value(i, v, not_out_of_order); } check_outputCheck(SIZE, Count); reset_outputCheck(SIZE, Count); for(int i=0; i < Count; i++) { ASSERT(outq2.try_get(v), NULL);; source_node_helper<SIZE, JType>::check_value(i, v, not_out_of_order); } check_outputCheck(SIZE, Count); ASSERT(!outq1.try_get(v), NULL); ASSERT(!outq2.try_get(v), NULL); source_node_helper<SIZE, JType>::remove_source_nodes((*my_join), nInputs); tbb::flow::remove_edge( *my_join, outq1 ); tbb::flow::remove_edge( *my_join, outq2 ); makeJoin<SIZE,JType,JP>::destroy(my_join); } } }; template<int ELEM, typename JType> class serial_queue_helper { public: typedef typename JType::output_type TT; typedef typename std::tuple_element<ELEM-1,TT>::type IT; typedef typename tbb::flow::queue_node<IT> my_queue_node_type; static void print_remark() { serial_queue_helper<ELEM-1,JType>::print_remark(); REMARK(", %s", name_of<IT>::name()); } static void add_queue_nodes(tbb::flow::graph &g, JType &my_join) { serial_queue_helper<ELEM-1,JType>::add_queue_nodes(g, my_join); my_queue_node_type *new_node = new my_queue_node_type(g); tbb::flow::make_edge( *new_node, std::get<ELEM-1>(my_join.input_ports()) ); all_source_nodes[ELEM-1][0] = (void *)new_node; } static void fill_one_queue(int maxVal) { // fill queue to "left" of me my_queue_node_type *qptr = reinterpret_cast<my_queue_node_type *>(all_source_nodes[ELEM-1][0]); serial_queue_helper<ELEM-1,JType>::fill_one_queue(maxVal); for(int i = 0; i < maxVal; ++i) { ASSERT(qptr->try_put((IT)(i*(ELEM+1))), NULL); } } static void put_one_queue_val(int myVal) { // put this val to my "left". serial_queue_helper<ELEM-1,JType>::put_one_queue_val(myVal); my_queue_node_type *qptr = reinterpret_cast<my_queue_node_type *>(all_source_nodes[ELEM-1][0]); ASSERT(qptr->try_put((IT)(myVal*(ELEM+1))), NULL); } static void check_queue_value(int i, TT &v) { serial_queue_helper<ELEM-1,JType>::check_queue_value(i, v); ASSERT( std::get<ELEM-1>(v) == (IT)(i * (ELEM+1)), NULL); } static void remove_queue_nodes(JType &my_join) { my_queue_node_type *vptr = reinterpret_cast<my_queue_node_type *>(all_source_nodes[ELEM-1][0]); tbb::flow::remove_edge( *vptr, std::get<ELEM-1>(my_join.input_ports()) ); serial_queue_helper<ELEM-1, JType>::remove_queue_nodes(my_join); delete vptr; } }; template<typename JType> class serial_queue_helper<1, JType> { public: typedef typename JType::output_type TT; typedef typename std::tuple_element<0,TT>::type IT; typedef typename tbb::flow::queue_node<IT> my_queue_node_type; static void print_remark() { REMARK("Serial test of join_node< %s", name_of<IT>::name()); } static void add_queue_nodes(tbb::flow::graph &g, JType &my_join) { my_queue_node_type *new_node = new my_queue_node_type(g); tbb::flow::make_edge( *new_node, tbb::flow::input_port<0>(my_join) ); all_source_nodes[0][0] = (void *)new_node; } static void fill_one_queue(int maxVal) { my_queue_node_type *qptr = reinterpret_cast<my_queue_node_type *>(all_source_nodes[0][0]); for(int i = 0; i < maxVal; ++i) { ASSERT(qptr->try_put((IT)(i*2)), NULL); } } static void put_one_queue_val(int myVal) { my_queue_node_type *qptr = reinterpret_cast<my_queue_node_type *>(all_source_nodes[0][0]); ASSERT(qptr->try_put((IT)(myVal*2)), NULL); } static void check_queue_value(int i, TT &v) { ASSERT( std::get<0>(v) == (IT)(i*2), NULL); } static void remove_queue_nodes(JType &my_join) { my_queue_node_type *vptr = reinterpret_cast<my_queue_node_type *>(all_source_nodes[0][0]); tbb::flow::remove_edge( *vptr, std::get<0>(my_join.input_ports()) ); delete vptr; } }; // // Single reservable predecessor at each port, single accepting successor // * put to buffer before port0, then put to buffer before port1, ... // * fill buffer before port0 then fill buffer before port1, ... template<typename JType, tbb::flow::graph_buffer_policy JP> void test_one_serial( JType &my_join, tbb::flow::graph &g) { typedef typename JType::output_type TType; static const int SIZE = std::tuple_size<TType>::value; std::vector<bool> flags; serial_queue_helper<SIZE, JType>::add_queue_nodes(g,my_join); typedef TType q3_input_type; tbb::flow::queue_node< q3_input_type > q3(g); tbb::flow::make_edge( my_join, q3 ); // fill each queue with its value one-at-a-time flags.clear(); for (int i = 0; i < Count; ++i ) { serial_queue_helper<SIZE,JType>::put_one_queue_val(i); flags.push_back(false); } g.wait_for_all(); tbb::flow::graph_buffer_policy jp = JP; for (int i = 0; i < Count; ++i ) { q3_input_type v; g.wait_for_all(); ASSERT(q3.try_get( v ), "Error in try_get()"); if(jp == tbb::flow::tag_matching) { // because we look up tags in the hash table, the output may be out of order. int j = int(std::get<0>(v)) / 2; // figure what the index should be serial_queue_helper<SIZE,JType>::check_queue_value(j, v); flags[j] = true; } else { serial_queue_helper<SIZE,JType>::check_queue_value(i, v); } } if(jp == tbb::flow::tag_matching) { for(int i = 0; i < Count; ++i) { ASSERT(flags[i], NULL); flags[i] = false; } } // fill each queue completely before filling the next. serial_queue_helper<SIZE, JType>::fill_one_queue(Count); g.wait_for_all(); for (int i = 0; i < Count; ++i ) { q3_input_type v; g.wait_for_all(); ASSERT(q3.try_get( v ), "Error in try_get()"); if(jp == tbb::flow::tag_matching) { int j = int(std::get<0>(v)) / 2; serial_queue_helper<SIZE,JType>::check_queue_value(j, v); flags[i] = true; } else { serial_queue_helper<SIZE,JType>::check_queue_value(i, v); } } if(jp == tbb::flow::tag_matching) { for(int i = 0; i < Count; ++i) { ASSERT(flags[i], NULL); } } serial_queue_helper<SIZE, JType>::remove_queue_nodes(my_join); } template<typename JType, tbb::flow::graph_buffer_policy JP> class serial_test { typedef typename JType::output_type TType; static const int SIZE = std::tuple_size<TType>::value; static const int ELEMS = 3; public: static void test() { tbb::flow::graph g; std::vector<bool> flags; flags.reserve(Count); JType* my_join = makeJoin<SIZE,JType,JP>::create(g); serial_queue_helper<SIZE, JType>::print_remark(); REMARK(" >\n"); test_one_serial<JType,JP>( *my_join, g); // build the vector with copy construction from the used join node. std::vector<JType>join_vector(ELEMS, *my_join); // destroy the tired old join_node in case we're accidentally reusing pieces of it. makeJoin<SIZE,JType,JP>::destroy(my_join); for(int e = 0; e < ELEMS; ++e) { // exercise each of the vector elements test_one_serial<JType,JP>( join_vector[e], g); } } }; // serial_test template< template<typename, tbb::flow::graph_buffer_policy> class TestType, // serial_test or parallel_test typename OutputTupleType, // type of the output of the join tbb::flow::graph_buffer_policy J> // graph_buffer_policy (reserving, queueing or tag_matching) class generate_test { public: typedef tbb::flow::join_node<OutputTupleType,J> join_node_type; static void do_test() { TestType<join_node_type,J>::test(); } }; template<typename JType> class generate_recirc_test { public: typedef tbb::flow::join_node<JType, tbb::flow::tag_matching> join_node_type; static void do_test() { tag_recirculation_test<join_node_type>::test(); } }; template<tbb::flow::graph_buffer_policy JP> void test_input_port_policies(); // join_node (reserving) does not consume inputs until an item is available at // every input. It tries to reserve each input, and if any fails it releases the // reservation. When it builds a tuple it broadcasts to all its successors and // consumes all the inputs. // // So our test will put an item at one input port, then attach another node to the // same node (a queue node in this case). The second successor should receive the // item in the queue, emptying it. // // We then place an item in the second input queue, and check the output queues; they // should still be empty. Then we place an item in the first queue; the output queues // should then receive a tuple. // // we then attach another function node to the second input. It should not receive // an item, verifying that the item in the queue is consumed. template<> void test_input_port_policies<tbb::flow::reserving>() { tbb::flow::graph g; typedef tbb::flow::join_node<std::tuple<int, int>, tbb::flow::reserving > JType; // two-phase is the default policy // create join_node<type0,type1> jn JType jn(g); // create output_queue oq0, oq1 typedef JType::output_type OQType; tbb::flow::queue_node<OQType> oq0(g); tbb::flow::queue_node<OQType> oq1(g); // create iq0, iq1 typedef tbb::flow::queue_node<int> IQType; IQType iq0(g); IQType iq1(g); // create qnp, qnq IQType qnp(g); IQType qnq(g); REMARK("Testing policies of join_node<reserving> input ports\n"); // attach jn to oq0, oq1 tbb::flow::make_edge( jn, oq0 ); tbb::flow::make_edge( jn, oq1 ); // attach iq0, iq1 to jn tbb::flow::make_edge( iq0, std::get<0>(jn.input_ports()) ); tbb::flow::make_edge( iq1, std::get<1>(jn.input_ports()) ); for(int loop = 0; loop < 3; ++loop) { // place one item in iq0 ASSERT(iq0.try_put(1), "Error putting to iq1"); // attach iq0 to qnp tbb::flow::make_edge( iq0, qnp ); // qnp should have an item in it. g.wait_for_all(); { int i; ASSERT(qnp.try_get(i) && i == 1, "Error in item fetched by qnp"); } // place item in iq1 ASSERT(iq1.try_put(2), "Error putting to iq1"); // oq0, oq1 should be empty g.wait_for_all(); { OQType t1; ASSERT(!oq0.try_get(t1) && !oq1.try_get(t1), "oq0 and oq1 not empty"); } // detach qnp from iq0 tbb::flow::remove_edge( iq0, qnp); // if we don't remove qnp it will gobble any values we put in iq0 // place item in iq0 ASSERT(iq0.try_put(3), "Error on second put to iq0"); // oq0, oq1 should have items in them g.wait_for_all(); { OQType t0; OQType t1; ASSERT(oq0.try_get(t0) && std::get<0>(t0) == 3 && std::get<1>(t0) == 2, "Error in oq0 output"); ASSERT(oq1.try_get(t1) && std::get<0>(t1) == 3 && std::get<1>(t1) == 2, "Error in oq1 output"); } // attach qnp to iq0, qnq to iq1 // qnp and qnq should be empty tbb::flow::make_edge( iq0, qnp ); tbb::flow::make_edge( iq1, qnq ); g.wait_for_all(); { int i; ASSERT(!qnp.try_get(i), "iq0 still had value in it"); ASSERT(!qnq.try_get(i), "iq1 still had value in it"); } tbb::flow::remove_edge( iq0, qnp ); tbb::flow::remove_edge( iq1, qnq ); } // for ( int loop ... } // join_node (queueing) consumes inputs as soon as they are available at // any input. When it builds a tuple it broadcasts to all its successors and // discards the broadcast values. // // So our test will put an item at one input port, then attach another node to the // same node (a queue node in this case). The second successor should not receive // an item (because the join consumed it). // // We then place an item in the second input queue, and check the output queues; they // should each have a tuple. // // we then attach another function node to the second input. It should not receive // an item, verifying that the item in the queue is consumed. template<> void test_input_port_policies<tbb::flow::queueing>() { tbb::flow::graph g; typedef tbb::flow::join_node<std::tuple<int, int>, tbb::flow::queueing > JType; // create join_node<type0,type1> jn JType jn(g); // create output_queue oq0, oq1 typedef JType::output_type OQType; tbb::flow::queue_node<OQType> oq0(g); tbb::flow::queue_node<OQType> oq1(g); // create iq0, iq1 typedef tbb::flow::queue_node<int> IQType; IQType iq0(g); IQType iq1(g); // create qnp, qnq IQType qnp(g); IQType qnq(g); REMARK("Testing policies of join_node<queueing> input ports\n"); // attach jn to oq0, oq1 tbb::flow::make_edge( jn, oq0 ); tbb::flow::make_edge( jn, oq1 ); // attach iq0, iq1 to jn tbb::flow::make_edge( iq0, std::get<0>(jn.input_ports()) ); tbb::flow::make_edge( iq1, std::get<1>(jn.input_ports()) ); for(int loop = 0; loop < 3; ++loop) { // place one item in iq0 ASSERT(iq0.try_put(1), "Error putting to iq1"); // attach iq0 to qnp tbb::flow::make_edge( iq0, qnp ); // qnp should have an item in it. g.wait_for_all(); { int i; ASSERT(!qnp.try_get(i), "Item was received by qnp"); } // place item in iq1 ASSERT(iq1.try_put(2), "Error putting to iq1"); // oq0, oq1 should have items g.wait_for_all(); { OQType t0; OQType t1; ASSERT(oq0.try_get(t0) && std::get<0>(t0) == 1 && std::get<1>(t0) == 2, "Error in oq0 output"); ASSERT(oq1.try_get(t1) && std::get<0>(t1) == 1 && std::get<1>(t1) == 2, "Error in oq1 output"); } // attach qnq to iq1 // qnp and qnq should be empty tbb::flow::make_edge( iq1, qnq ); g.wait_for_all(); { int i; ASSERT(!qnp.try_get(i), "iq0 still had value in it"); ASSERT(!qnq.try_get(i), "iq1 still had value in it"); } tbb::flow::remove_edge( iq0, qnp ); tbb::flow::remove_edge( iq1, qnq ); } // for ( int loop ... } tbb::flow::tag_value myTagValue(int i) { return tbb::flow::tag_value(i); } // join_node (tag_matching) consumes inputs as soon as they are available at // any input. When it builds a tuple it broadcasts to all its successors and // discards the broadcast values. // // It chooses the tuple it broadcasts by matching the tag values returned by the // methods given the constructor of the join, in this case the method just casts // the value in each port to tag_value. // // So our test will put an item at one input port, then attach another node to the // same node (a queue node in this case). The second successor should not receive // an item (because the join consumed it). // // We then place an item in the second input queue, and check the output queues; they // should each have a tuple. // // we then attach another queue node to the second input. It should not receive // an item, verifying that the item in the queue is consumed. // // We will then exercise the join with a bunch of values, and the output order should // be determined by the order we insert items into the second queue. (Each tuple set // corresponding to a tag will be complete when the second item is inserted.) template<> void test_input_port_policies<tbb::flow::tag_matching>() { tbb::flow::graph g; typedef tbb::flow::join_node<std::tuple<int, int>, tbb::flow::tag_matching > JType; JType jn(g, myTagValue, myTagValue); // create output_queue oq0, oq1 typedef JType::output_type OQType; tbb::flow::queue_node<OQType> oq0(g); tbb::flow::queue_node<OQType> oq1(g); // create iq0, iq1 typedef tbb::flow::queue_node<int> IQType; IQType iq0(g); IQType iq1(g); // create qnp, qnq IQType qnp(g); IQType qnq(g); REMARK("Testing policies of join_node<tag_matching> input ports\n"); // attach jn to oq0, oq1 tbb::flow::make_edge( jn, oq0 ); tbb::flow::make_edge( jn, oq1 ); // attach iq0, iq1 to jn tbb::flow::make_edge( iq0, tbb::flow::input_port<0>(jn) ); tbb::flow::make_edge( iq1, tbb::flow::input_port<1>(jn) ); // we'll put four discrete values in the inputs to the join_node. Each // set of inputs should result in one output. (NO_TAG is currently defined // to be tag_value(-1), so zero is an allowed tag_value.) for(int loop = 0; loop < 4; ++loop) { // place one item in iq0 ASSERT(iq0.try_put(loop), "Error putting to iq1"); // attach iq0 to qnp tbb::flow::make_edge( iq0, qnp ); // qnp should not have an item in it. (the join consumed it.) g.wait_for_all(); { int i; ASSERT(!qnp.try_get(i), "Item was received by qnp"); } // place item in iq1 ASSERT(iq1.try_put(loop), "Error putting to iq1"); // oq0, oq1 should have items g.wait_for_all(); { OQType t0; OQType t1; ASSERT(oq0.try_get(t0) && std::get<0>(t0) == loop && std::get<1>(t0) == loop, "Error in oq0 output"); ASSERT(oq1.try_get(t1) && std::get<0>(t1) == loop && std::get<1>(t1) == loop, "Error in oq1 output"); ASSERT(!oq0.try_get(t0), "extra object in output queue oq0"); ASSERT(!oq1.try_get(t0), "extra object in output queue oq1"); } // attach qnq to iq1 // qnp and qnq should be empty tbb::flow::make_edge( iq1, qnq ); g.wait_for_all(); { int i; ASSERT(!qnp.try_get(i), "iq0 still had value in it"); ASSERT(!qnq.try_get(i), "iq1 still had value in it"); } tbb::flow::remove_edge( iq0, qnp ); tbb::flow::remove_edge( iq1, qnq ); } // for ( int loop ... // Now we'll put [4 .. nValues - 1] in iq0, and then put [4 .. nValues - 1] in iq1 in // a different order. We should see tuples in the output queues in the order we inserted // the integers into iq1. const int nValues = 100; const int nIncr = 31; // relatively prime to nValues for(int loop = 4; loop < 4+nValues; ++loop) { // place one item in iq0 ASSERT(iq0.try_put(loop), "Error putting to iq1"); g.wait_for_all(); { OQType t3; ASSERT(!oq0.try_get(t3), "Object in output queue"); ASSERT(!oq1.try_get(t3), "Object in output queue"); } } // for ( int loop ... for(int loop = 1; loop <= nValues; ++loop) { int lp1 = 4 + (loop * nIncr)%nValues; // place item in iq1 ASSERT(iq1.try_put(lp1), "Error putting to iq1"); // oq0, oq1 should have items g.wait_for_all(); { OQType t0; OQType t1; ASSERT(oq0.try_get(t0) && std::get<0>(t0) == lp1 && std::get<1>(t0) == lp1, "Error in oq0 output"); ASSERT(oq1.try_get(t1) && std::get<0>(t1) == lp1 && std::get<1>(t1) == lp1, "Error in oq1 output"); ASSERT(!oq0.try_get(t0), "extra object in output queue oq0"); ASSERT(!oq1.try_get(t0), "extra object in output queue oq1"); } } // for ( int loop ... } int TestMain() { #if __TBB_USE_TBB_TUPLE REMARK(" Using TBB tuple\n"); #else REMARK(" Using platform tuple\n"); #endif test_input_port_policies<tbb::flow::reserving>(); test_input_port_policies<tbb::flow::queueing>(); test_input_port_policies<tbb::flow::tag_matching>(); for (int p = 0; p < 2; ++p) { REMARK("reserving\n"); generate_test<serial_test, std::tuple<float, double>, tbb::flow::reserving >::do_test(); generate_test<serial_test, std::tuple<float, double, int, long>, tbb::flow::reserving >::do_test(); #if __TBB_VARIADIC_MAX >= 6 generate_test<serial_test, std::tuple<double, double, int, long, int, short>, tbb::flow::reserving >::do_test(); #endif #if COMPREHENSIVE_TEST #if __TBB_VARIADIC_MAX >= 8 generate_test<serial_test, std::tuple<float, double, double, double, float, int, float, long>, tbb::flow::reserving >::do_test(); #endif #if __TBB_VARIADIC_MAX >= 10 generate_test<serial_test, std::tuple<float, double, int, double, double, float, long, int, float, long>, tbb::flow::reserving >::do_test(); #endif #endif generate_test<parallel_test, std::tuple<float, double>, tbb::flow::reserving >::do_test(); generate_test<parallel_test, std::tuple<float, int, long>, tbb::flow::reserving >::do_test(); generate_test<parallel_test, std::tuple<double, double, int, int, short>, tbb::flow::reserving >::do_test(); #if COMPREHENSIVE_TEST #if __TBB_VARIADIC_MAX >= 7 generate_test<parallel_test, std::tuple<float, int, double, float, long, float, long>, tbb::flow::reserving >::do_test(); #endif #if __TBB_VARIADIC_MAX >= 9 generate_test<parallel_test, std::tuple<float, double, int, double, double, long, int, float, long>, tbb::flow::reserving >::do_test(); #endif #endif REMARK("queueing\n"); generate_test<serial_test, std::tuple<float, double>, tbb::flow::queueing >::do_test(); generate_test<serial_test, std::tuple<float, double, int, long>, tbb::flow::queueing >::do_test(); #if __TBB_VARIADIC_MAX >= 6 generate_test<serial_test, std::tuple<double, double, int, long, int, short>, tbb::flow::queueing >::do_test(); #endif #if COMPREHENSIVE_TEST #if __TBB_VARIADIC_MAX >= 8 generate_test<serial_test, std::tuple<float, double, double, double, float, int, float, long>, tbb::flow::queueing >::do_test(); #endif #if __TBB_VARIADIC_MAX >= 10 generate_test<serial_test, std::tuple<float, double, int, double, double, float, long, int, float, long>, tbb::flow::queueing >::do_test(); #endif #endif generate_test<parallel_test, std::tuple<float, double>, tbb::flow::queueing >::do_test(); generate_test<parallel_test, std::tuple<float, int, long>, tbb::flow::queueing >::do_test(); generate_test<parallel_test, std::tuple<double, double, int, int, short>, tbb::flow::queueing >::do_test(); #if COMPREHENSIVE_TEST #if __TBB_VARIADIC_MAX >= 7 generate_test<parallel_test, std::tuple<float, int, double, float, long, float, long>, tbb::flow::queueing >::do_test(); #endif #if __TBB_VARIADIC_MAX >= 9 generate_test<parallel_test, std::tuple<float, double, int, double, double, long, int, float, long>, tbb::flow::queueing >::do_test(); #endif #endif REMARK("tag_matching\n"); generate_test<serial_test, std::tuple<float, double>, tbb::flow::tag_matching >::do_test(); generate_test<serial_test, std::tuple<float, double, int, long>, tbb::flow::tag_matching >::do_test(); #if __TBB_VARIADIC_MAX >= 6 generate_test<serial_test, std::tuple<double, double, int, long, int, short>, tbb::flow::tag_matching >::do_test(); #endif #if COMPREHENSIVE_TEST #if __TBB_VARIADIC_MAX >= 8 generate_test<serial_test, std::tuple<float, double, double, double, float, int, float, long>, tbb::flow::tag_matching >::do_test(); #endif #if __TBB_VARIADIC_MAX >= 10 generate_test<serial_test, std::tuple<float, double, int, double, double, float, long, int, float, long>, tbb::flow::tag_matching >::do_test(); #endif #endif generate_test<parallel_test, std::tuple<float, double>, tbb::flow::tag_matching >::do_test(); generate_test<parallel_test, std::tuple<float, int, long>, tbb::flow::tag_matching >::do_test(); generate_test<parallel_test, std::tuple<double, double, int, int, short>, tbb::flow::tag_matching >::do_test(); #if COMPREHENSIVE_TEST #if __TBB_VARIADIC_MAX >= 7 generate_test<parallel_test, std::tuple<float, int, double, float, long, float, long>, tbb::flow::tag_matching >::do_test(); #endif #if __TBB_VARIADIC_MAX >= 9 generate_test<parallel_test, std::tuple<float, double, int, double, double, long, int, float, long>, tbb::flow::tag_matching >::do_test(); #endif #endif generate_recirc_test<std::tuple<float,double> >::do_test(); generate_recirc_test<std::tuple<double, double, int, int, short> >::do_test(); } return Harness::Done; } #else // __SUNPRO_CC int TestMain() { return Harness::Skipped; } #endif // SUNPRO_CC
39.905976
150
0.635078
[ "object", "vector" ]
8d1ed745473455038fe2fafba69c51d41f286fea
955
cpp
C++
LeetCode/Algorithms/Easy/RemoveOneElementToMakeTheArrayStrictlyIncreasing.cpp
roshan11160/Competitive-Programming-Solutions
2d9cfe901c23a2b7344c410b7368eb02f7fa6e7e
[ "MIT" ]
40
2020-07-25T19:35:37.000Z
2022-01-28T02:57:02.000Z
LeetCode/Algorithms/Easy/RemoveOneElementToMakeTheArrayStrictlyIncreasing.cpp
afrozchakure/Hackerrank-Problem-Solutions
014155d841e08cb1f7609c23335576dc9b29cef3
[ "MIT" ]
160
2021-04-26T19:04:15.000Z
2022-03-26T20:18:37.000Z
LeetCode/Algorithms/Easy/RemoveOneElementToMakeTheArrayStrictlyIncreasing.cpp
afrozchakure/Hackerrank-Problem-Solutions
014155d841e08cb1f7609c23335576dc9b29cef3
[ "MIT" ]
24
2020-05-03T08:11:53.000Z
2021-10-04T03:23:20.000Z
class Solution { public: bool canBeIncreasing(vector<int>& nums) { int n = nums.size(); int count = 0; int index = -1; for(int i=1; i<n; i++) { if(nums[i-1] >= nums[i]) { count++; index = i; } } cout<<count<<"\n"; if(count > 1) return false; // if count = 0 if(count == 0) return true; // if last index is removed if(index == n-1 || index == 1) return true; // if a[index] is removed, check the next ones if(nums[index-1] < nums[index+1]) return true; // if a[index-1] is removed, if(nums[index-2] < nums[index]) return true; return false; } }; // Time complexity - O(N) // Space Complexity - O(1)
21.222222
55
0.391623
[ "vector" ]
8d232723d6882fb3f518643726e6986e6e3096f3
1,248
cpp
C++
src/pyper/binding/init_experience_replay.cpp
maichmueller/per
17eddea4d1aa1aac8fb9664f7437ecc1f119dcf5
[ "MIT" ]
null
null
null
src/pyper/binding/init_experience_replay.cpp
maichmueller/per
17eddea4d1aa1aac8fb9664f7437ecc1f119dcf5
[ "MIT" ]
2
2021-12-22T12:14:20.000Z
2021-12-23T21:39:14.000Z
src/pyper/binding/init_experience_replay.cpp
maichmueller/per
17eddea4d1aa1aac8fb9664f7437ecc1f119dcf5
[ "MIT" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "per/per.hpp" namespace py = pybind11; void init_experience_replay(py::module_& m) { using PyPrioritizedExperience = per::PrioritizedExperience< py::object >; py::class_< PyPrioritizedExperience > pe(m, "PrioritizedExperience"); pe.def( py::init< size_t, double, double, std::mt19937_64::result_type >(), py::arg("capacity"), py::arg("alpha") = 1., py::arg("beta") = 1., py::arg("seed") = std::random_device{}()); pe.def( "push", py::overload_cast< PyPrioritizedExperience::value_type >(&PyPrioritizedExperience::push), py::arg("value")); pe.def( "push", py::overload_cast< const PyPrioritizedExperience::ValueVec& >(&PyPrioritizedExperience::push), py::arg("value")); pe.def("update", &PyPrioritizedExperience::update, py::arg("indices"), py::arg("priorities")); pe.def("sample", &PyPrioritizedExperience::sample, py::arg("n")); pe.def_property( "alpha", py::overload_cast<>(&PyPrioritizedExperience::alpha, py::const_), py::overload_cast< double >(&PyPrioritizedExperience::alpha)); pe.def_property_readonly("capacity", &PyPrioritizedExperience::capacity); }
30.439024
100
0.661859
[ "object" ]
8d2614c1dfcb82c3065bf795d97cb49a6f04bf08
1,522
hpp
C++
nucleo_h7_gfx/src/ap/TouchGFX/gui/include/gui/model/Model.hpp
chcbaram/nucleo_h7_boy3
9cf524b04f9a6227fffe24de868c7ca6331317f5
[ "Apache-2.0" ]
6
2020-05-11T11:51:07.000Z
2022-03-17T08:33:59.000Z
nucleo_h7_gfx/src/ap/TouchGFX/gui/include/gui/model/Model.hpp
chcbaram/nucleo_h7_boy3
9cf524b04f9a6227fffe24de868c7ca6331317f5
[ "Apache-2.0" ]
1
2020-11-14T16:53:09.000Z
2020-11-14T16:53:09.000Z
nucleo_h7_gfx/src/ap/TouchGFX/gui/include/gui/model/Model.hpp
chcbaram/nucleo_h7_boy3
9cf524b04f9a6227fffe24de868c7ca6331317f5
[ "Apache-2.0" ]
3
2019-11-15T10:55:03.000Z
2020-07-04T13:39:30.000Z
#ifndef MODEL_HPP #define MODEL_HPP #include <touchgfx/Utils.hpp> class ModelListener; /** * The Model class defines the data model in the model-view-presenter paradigm. * The Model is a singular object used across all presenters. The currently active * presenter will have a pointer to the Model through deriving from ModelListener. * * The Model will typically contain UI state information that must be kept alive * through screen transitions. It also usually provides the interface to the rest * of the system (the backend). As such, the Model can receive events and data from * the backend and inform the current presenter of such events through the modelListener * pointer, which is automatically configured to point to the current presenter. * Conversely, the current presenter can trigger events in the backend through the Model. */ class Model { public: Model(); /** * Sets the modelListener to point to the currently active presenter. Called automatically * when switching screen. */ void bind(ModelListener* listener) { modelListener = listener; } /** * This function will be called automatically every frame. Can be used to e.g. sample hardware * peripherals or read events from the surrounding system and inject events to the GUI through * the ModelListener interface. */ void tick(); protected: /** * Pointer to the currently active presenter. */ ModelListener* modelListener; }; #endif /* MODEL_HPP */
31.708333
98
0.725361
[ "object", "model" ]
8d348233c181056f7e52d4c949752c0675f63f05
5,277
cpp
C++
Interactive-Visualization/Interactive-Visualization/cloth.cpp
tofhddl9/Interactive-visualization
3d09f344d44e492c024034ed2ad3ccd30da5fed8
[ "Apache-2.0" ]
null
null
null
Interactive-Visualization/Interactive-Visualization/cloth.cpp
tofhddl9/Interactive-visualization
3d09f344d44e492c024034ed2ad3ccd30da5fed8
[ "Apache-2.0" ]
null
null
null
Interactive-Visualization/Interactive-Visualization/cloth.cpp
tofhddl9/Interactive-visualization
3d09f344d44e492c024034ed2ad3ccd30da5fed8
[ "Apache-2.0" ]
null
null
null
#include "cloth.h" void Cloth::MakeCheckImage() { for (int i = 0; i < checkImageHeight; i++) { for (int j = 0; j < checkImageWidth; j++) { int c; if ((((i & 1) == 0) ^ ((j & 1)) == 0)) c = 255; else c = 0; checkImage[i][j][0] = (GLubyte)c; checkImage[i][j][1] = (GLubyte)c; checkImage[i][j][2] = (GLubyte)c; checkImage[i][j][3] = (GLubyte)255; } } } void Cloth::Init(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_DEPTH_TEST); MakeCheckImage(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); } Cloth::Cloth(int w, int h, float step, float len, float ks, float kd) { width_ = w, height_ = h, step_ = step; len_ = len, ks_ = ks, kd_ = kd; massSpring_ = new MassSpring(); grid_ = new PointMass**[h]; for (int i = 0; i < h; ++i) { grid_[i] = new PointMass * [w]; } //scene 1, 2 float z = 8.0f; for (int i = 0; i < height_; ++i) { float x = 5.0f; for (int j = 0; j < width_; ++j) { grid_[i][j] = massSpring_->AddMass(0.01, glm::vec3(x, 3.0f, z)); x += step_; if (j == 0 && (i % 3 == 0)) grid_[i][j]->SetIsFixed(true); } z += step_; } //scene 3 /* float z = 8.0f; for (int i = 0; i < height_; ++i) { float x = 5.0f; for (int j = 0; j < width_; ++j) { grid_[i][j] = massSpring_->AddMass(0.01, glm::vec3(x, 3.0f, z)); x += step_; } z += step_; } */ //scene4 /* float z = 8.0f; for (int i = 0; i < height_; ++i) { float x = 5.0f; for (int j = 0; j < width_; ++j) { grid_[i][j] = massSpring_->AddMass(0.03, glm::vec3(x, 3.0f, z)); x += step_; if (j % 5 == 0 || i % 5 == 0) grid_[i][j]->SetIsFixed(true); } z += step_; } */ //structural + shear for (int i = 0; i < height_ - 1; ++i) { for (int j = 0; j < width_ - 1; ++j) { Spring* s1 = massSpring_ ->AddSpring(len_, ks_, kd_, grid_[i][j], grid_[i][j + 1]); Spring* s2 = massSpring_ ->AddSpring(len_, ks_, kd_, grid_[i][j], grid_[i + 1][j]); if (i == height_ - 2) { Spring* s3 = massSpring_ ->AddSpring(len_, ks_, kd_, grid_[i + 1][j], grid_[i + 1][j + 1]); } if (j == width_ - 2) { Spring* s4 = massSpring_ ->AddSpring(len_, ks_, kd_, grid_[i][j + 1], grid_[i + 1][j + 1]); } Spring* s5 = massSpring_ ->AddSpring(len_ * 1.4142f, ks_, kd_, grid_[i][j], grid_[i + 1][j + 1]); Spring* s6 = massSpring_ ->AddSpring(len_ * 1.4142f, ks_, kd_, grid_[i + 1][j], grid_[i][j + 1]); } } //bending for (int i = 0; i < height_ - 2; ++i) { for (int j = 0; j < width_ - 2; ++j) { Spring* s1 = massSpring_ ->AddSpring(2 * len_, ks_, kd_, grid_[i][j], grid_[i][j + 2]); Spring* s2 = massSpring_ ->AddSpring(2 * len_, ks_, kd_, grid_[i][j], grid_[i + 2][j]); if (i == height_ - 3) { Spring* s3 = massSpring_ ->AddSpring(2 * len_, ks_, kd_, grid_[i + 2][j], grid_[i + 2][j + 2]); } if (j == width_ - 3) { Spring* s4 = massSpring_ ->AddSpring(2 * len_, ks_, kd_, grid_[i][j + 2], grid_[i + 2][j + 2]); } } } Init(); } void Cloth::Update(float dt) { massSpring_->Update(dt); } void Cloth::Render() { glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glBindTexture(GL_TEXTURE_2D, texName); glBegin(GL_QUADS); // p1 p2 // p4 p3 for (int i = 0; i < height_ - 1; i++) { for (int j = 0; j < width_ - 1; j++) { auto p1 = grid_[i][j]->GetPosition(); auto p2 = grid_[i][j + 1]->GetPosition(); auto p3 = grid_[i + 1][j + 1]->GetPosition(); auto p4 = grid_[i + 1][j]->GetPosition(); glTexCoord2f(0.0, 0.0); glVertex3f(p1.x, p1.y, p1.z); glTexCoord2f(0.0, 1.0); glVertex3f(p2.x, p2.y, p2.z); glTexCoord2f(1.0, 1.0); glVertex3f(p3.x, p3.y, p3.z); glTexCoord2f(1.0, 0.0); glVertex3f(p4.x, p4.y, p4.z); } } glEnd(); glDisable(GL_TEXTURE_2D); massSpring_->Render(); } void Cloth::CheckCollision(Floor *floor, Sphere *sphere) { CheckCollisionWithFloor(floor); CheckCollisionWithSphere(sphere); } void Cloth::CheckCollisionWithFloor(Floor *floor) { for (int i = 0; i < height_; ++i) { for (int j = 0; j < width_; ++j) { floor->ResolveCollision(grid_[i][j]); } } } void Cloth::CheckCollisionWithSphere(Sphere *sphere) { for (int i = 0; i < height_; ++i) { for (int j = 0; j < width_; ++j) { sphere->ResolveCollision(grid_[i][j]); } } } void Cloth::operator=(const Cloth& c) { width_ = c.width_; height_ = c.height_; step_ = c.step_; len_ = c.len_; ks_ = c.ks_; kd_ = c.kd_; for (int i = 0; i < checkImageHeight; ++i) { for (int j = 0; j < checkImageWidth; ++j) { for (int k = 0; k < 4; ++k) { checkImage[i][j][k] = c.checkImage[i][j][k]; } } } massSpring_ = c.massSpring_; grid_ = c.grid_; } void Cloth::SetAllUnFixed() { for (int i = 0; i < height_; ++i) { for (int j = 0; j < width_; ++j) { grid_[i][j]->SetIsFixed(false); } } }
23.246696
76
0.573053
[ "render" ]
8d38cb8d7ff445d8cab4e3deaa09752b37c1c7f7
659
cpp
C++
914.cpp
BYOUINZAKA/LeetCodeNotes
48e1b4522c1f769eeec4944cfbd57abf1281d09a
[ "MIT" ]
null
null
null
914.cpp
BYOUINZAKA/LeetCodeNotes
48e1b4522c1f769eeec4944cfbd57abf1281d09a
[ "MIT" ]
null
null
null
914.cpp
BYOUINZAKA/LeetCodeNotes
48e1b4522c1f769eeec4944cfbd57abf1281d09a
[ "MIT" ]
null
null
null
/* * @Author: Hata * @Date: 2020-08-03 21:14:55 * @LastEditors: Hata * @LastEditTime: 2020-08-03 21:29:12 * @FilePath: \LeetCode\914.cpp * @Description: https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/ */ #include <bits/stdc++.h> class Solution { int cnt[10000]; public: bool hasGroupsSizeX(std::vector<int>& deck) { for (auto&& x : deck) cnt[x]++; int g = -1; for (int i = 0; i < 10000; ++i) if (cnt[i]) { if (~g) g = std::gcd(g, cnt[i]); else g = cnt[i]; } return g >= 2 ? true : false; } };
23.535714
81
0.474962
[ "vector" ]
8d3a11a0b49c52fa748c8645d3897274e253db9b
10,595
hxx
C++
main/svtools/inc/svtools/unoevent.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svtools/inc/svtools/unoevent.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svtools/inc/svtools/unoevent.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #ifndef _SVTOOLS_UNOEVENT_HXX_ #define _SVTOOLS_UNOEVENT_HXX_ #include "svtools/svtdllapi.h" #include <com/sun/star/container/XNameReplace.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/XInterface.hpp> #include <cppuhelper/implbase2.hxx> class SvxMacroTableDtor; class SvxMacroItem; class SvxMacro; /** SvEventDescription: Description of a single event. mnEvent is the id used by SvxMacroItem mpEventName is the api name for this event the last event in an array is indicated by mnEvent && mpEventName == 0 */ struct SvEventDescription { sal_uInt16 mnEvent; const sal_Char* mpEventName; }; /** * SvBaseEventDescriptor: Abstract class that implements the basics * of an XNameReplace that is delivered by the * XEventsSupplier::getEvents() method. * * The functionality this class provides is: * 1) Which elements are in the XNameReplace? * 2) Mapping from Api names to item IDs. * 3) conversion from SvxMacroItem to Any and vice versa. * * All details of how to actually get and set SvxMacroItem(s) have to * be supplied by the base class. */ class SVT_DLLPUBLIC SvBaseEventDescriptor : public cppu::WeakImplHelper2 < ::com::sun::star::container::XNameReplace, ::com::sun::star::lang::XServiceInfo > { const ::rtl::OUString sEventType; const ::rtl::OUString sMacroName; const ::rtl::OUString sLibrary; const ::rtl::OUString sStarBasic; const ::rtl::OUString sJavaScript; const ::rtl::OUString sScript; const ::rtl::OUString sNone; /// name of own service const ::rtl::OUString sServiceName; protected: const ::rtl::OUString sEmpty; /// last element is 0, 0 const SvEventDescription* mpSupportedMacroItems; sal_Int16 mnMacroItems; public: SvBaseEventDescriptor(const SvEventDescription* pSupportedMacroItems); virtual ~SvBaseEventDescriptor(); // XNameReplace /// calls replaceByName(const sal_uInt16, const SvxMacro&) virtual void SAL_CALL replaceByName( const ::rtl::OUString& rName, /// API name of event const ::com::sun::star::uno::Any& rElement ) /// event (PropertyValues) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XNameAccess (via XNameReplace) /// calls getByName(sal_uInt16) virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& rName ) /// API name of event throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XNameAxcess (via XNameReplace) virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw(::com::sun::star::uno::RuntimeException); // XNameAccess (via XNameReplace) virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& rName ) throw(::com::sun::star::uno::RuntimeException); // XElementAccess (via XNameReplace) virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw(::com::sun::star::uno::RuntimeException); // XElementAccess (via XNameReplace) virtual sal_Bool SAL_CALL hasElements() throw(::com::sun::star::uno::RuntimeException); // XServiceInfo /// must be implemented in subclass virtual rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException ) = 0; // XServiceInfo virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException ); // XServiceInfo virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException ); protected: /// Must be implemented in subclass. virtual void replaceByName( const sal_uInt16 nEvent, /// item ID of event const SvxMacro& rMacro) /// event (will be copied) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0; /// Must be implemented in subclass. virtual void getByName( SvxMacro& rMacro, const sal_uInt16 nEvent ) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0; /// convert an API event name to the event ID as used by SvxMacroItem sal_uInt16 mapNameToEventID(const ::rtl::OUString& rName) const; /// convert an event ID to an API event name ::rtl::OUString mapEventIDToName(sal_uInt16 nPoolID) const; /// get the event ID for the name; return 0 if not supported sal_uInt16 getMacroID(const ::rtl::OUString& rName) const; /// create PropertyValues and Any from macro void getAnyFromMacro( ::com::sun::star::uno::Any& aAny, // Any to be filled by Macro values const SvxMacro& rMacro); /// create macro from PropertyValues (in an Any) void getMacroFromAny( SvxMacro& aMacro, // reference to be filled by Any const ::com::sun::star::uno::Any& rAny) throw ( ::com::sun::star::lang::IllegalArgumentException); }; /** * SvEventDescriptor: Implement the XNameReplace that is delivered by * the XEventsSupplier::getEvents() method. The SvEventDescriptor has * to be subclassed to implement the events for a specific * objects. The subclass has to * 1) supply the super class constructor with a list of known events (item IDs) * 2) supply the super class constructor with a reference of it's parent object * (to prevent destruction) * 3) implement getItem() and setItem(...) methods. * * If no object is available to which the SvEventDescriptor can attach itself, * the class SvDetachedEventDescriptor should be used. */ class SVT_DLLPUBLIC SvEventDescriptor : public SvBaseEventDescriptor { /// keep reference to parent to prevent it from being destroyed ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xParentRef; public: SvEventDescriptor(::com::sun::star::uno::XInterface& rParent, const SvEventDescription* pSupportedMacroItems); virtual ~SvEventDescriptor(); protected: using SvBaseEventDescriptor::replaceByName; virtual void replaceByName( const sal_uInt16 nEvent, /// item ID of event const SvxMacro& rMacro) /// event (will be copied) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); using SvBaseEventDescriptor::getByName; virtual void getByName( SvxMacro& rMacros, /// macro to be filled with values const sal_uInt16 nEvent ) /// item ID of event throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); /// Get the SvxMacroItem from the parent. /// must be implemented by subclass virtual const SvxMacroItem& getMacroItem() = 0; /// Set the SvxMacroItem at the parent. /// must be implemented by subclass virtual void setMacroItem(const SvxMacroItem& rItem) = 0; /// Get the SvxMacroItem Which Id needed for the current application /// must be implemented by subclass virtual sal_uInt16 getMacroItemWhich() const = 0; }; /** * SvDetachedEventDescriptor: */ class SVT_DLLPUBLIC SvDetachedEventDescriptor : public SvBaseEventDescriptor { // the macros; aMacros[i] is the value for aSupportedMacroItemIDs[i] SvxMacro** aMacros; const ::rtl::OUString sImplName; public: SvDetachedEventDescriptor(const SvEventDescription* pSupportedMacroItems); virtual ~SvDetachedEventDescriptor(); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException ); protected: sal_Int16 getIndex(const sal_uInt16 nID) const; using SvBaseEventDescriptor::replaceByName; virtual void replaceByName( const sal_uInt16 nEvent, /// item ID of event const SvxMacro& rMacro) /// event (will be copied) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); using SvBaseEventDescriptor::getByName; virtual void getByName( SvxMacro& rMacro, /// macro to be filled const sal_uInt16 nEvent ) /// item ID of event throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); /// do we have an event? /// return sal_True: we have a macro for the event /// return sal_False: no macro; getByName() will return an empty macro /// IllegalArgumentException: the event is not supported using SvBaseEventDescriptor::hasByName; virtual sal_Bool hasByName( const sal_uInt16 nEvent ) const /// item ID of event throw( ::com::sun::star::lang::IllegalArgumentException); }; class SVT_DLLPUBLIC SvMacroTableEventDescriptor : public SvDetachedEventDescriptor { public: SvMacroTableEventDescriptor(const SvEventDescription* pSupportedMacroItems); SvMacroTableEventDescriptor(const SvxMacroTableDtor& aFmt, const SvEventDescription* pSupportedMacroItems); virtual ~SvMacroTableEventDescriptor(); void copyMacrosFromTable(const SvxMacroTableDtor& aFmt); void copyMacrosIntoTable(SvxMacroTableDtor& aFmt); }; #endif
32.5
82
0.718075
[ "object" ]
8d3c404edda4adfcec8c877bbdb6f1f5d29e00fe
1,743
cc
C++
src/Board.cc
chrisboo/sudoku-solver
1053bfb54c8060f32998d4e11b45665837b04b5e
[ "MIT" ]
2
2018-07-08T11:30:52.000Z
2018-07-08T12:37:28.000Z
src/Board.cc
chrisboo/sudoku-solver
1053bfb54c8060f32998d4e11b45665837b04b5e
[ "MIT" ]
null
null
null
src/Board.cc
chrisboo/sudoku-solver
1053bfb54c8060f32998d4e11b45665837b04b5e
[ "MIT" ]
null
null
null
#include "Board.h" Board::Board() : rows_(9, std::vector<uint8_t>(9, 0)), cols_(9, std::vector<uint8_t>(9, 0)), subgrids_(9, std::vector<uint8_t>(9, 0)) {} Board::Board(std::vector<std::vector<uint8_t>> const& rows) : rows_(9, std::vector<uint8_t>(9, 0)), cols_(9, std::vector<uint8_t>(9, 0)), subgrids_(9, std::vector<uint8_t>(9, 0)) { for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; j++) { Update(i, j, rows[i][j]); } } } Board::~Board() {} void Board::Clear() { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { rows_[i][j] = cols_[i][j] = subgrids_[i][j] = 0; } } } uint8_t Board::Get(uint8_t i, uint8_t j) const { return rows_[i][j]; } void Board::Update(uint8_t i, uint8_t j, uint8_t val) { rows_[i][j] = cols_[j][i] = subgrids_[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] = val; } std::vector<std::vector<uint8_t>> const& Board::Rows() const { return rows_; } std::vector<std::vector<uint8_t>> const& Board::Cols() const { return cols_; } std::vector<std::vector<uint8_t>> const& Board::Subgrids() const { return subgrids_; } bool operator==(Board const& lhs, Board const& rhs) { return lhs.rows_ == rhs.rows_; } std::ostream& operator<<(std::ostream &os, Board const& board) { os << " 123 456 789 " << std::endl; for (uint8_t i = 0; i < 9; ++i) { if (i % 3 == 0) { os << "-------------" << std::endl; } for (uint8_t j = 0; j < 9; ++j) { if (j % 3 == 0) { os << '|'; } if (board.rows_[i][j] == 0) { os << " "; } else { os << unsigned(board.rows_[i][j]); } } os << "|" << char('1' + i) << std::endl; } os << "-------------" << std::endl; return os; }
24.9
86
0.502008
[ "vector" ]
8d3dd75b61063a7ddd28bce520c06555788d1ab9
1,591
cpp
C++
src/IceRay/render/2pierce/projector.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
2
2020-09-04T12:27:15.000Z
2022-01-17T14:49:40.000Z
src/IceRay/render/2pierce/projector.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
null
null
null
src/IceRay/render/2pierce/projector.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
1
2020-09-04T12:27:52.000Z
2020-09-04T12:27:52.000Z
#include "./projector.hpp" #include "../../camera/flat/perspective.hpp" #include "../3sheaf/all.hpp" using namespace GS_DDMRM::S_IceRay::S_render::S_pierce; GC_projector::GC_projector( void ) :M2_camera( nullptr ) ,M2_sheaf ( nullptr ) { Fv_camera( M2_camera ); Fv_sheaf( M2_sheaf ); } GC_projector::~GC_projector( void ) { } void GC_projector::Fv_camera( T_camera* P_camera ) { M2_camera = P_camera; if( nullptr == M2_camera ) { M2_camera = &Fs_camera(); } M2_beam.resize( F1_camera()->F_size() ); } GC_projector::T_camera & GC_projector::Fs_camera() { typedef GS_DDMRM::S_IceRay::S_camera::S_flat::GC_perspective T2_perspective; static T2_perspective Irs_camera; return Irs_camera; } void GC_projector::F1v_render( T_color & P_color, T_coord const& P_coord ) { static T_coord Is_one; ::math::linear::vector::fill( Is_one, 1 ); T_coord I_coord; ::math::linear::vector::scale( I_coord, 2, P_coord ); ::math::linear::vector::subtraction( I_coord , Is_one ); I_coord[1] = -I_coord[1]; F1_camera()->Fv_beam( M2_beam, I_coord ); T_color I_color( ::color::constant::black_t{} ); F_sheaf().Fv_do( I_color, M2_beam ); P_color = I_color; } void GC_projector::Fv_sheaf( T_sheaf * P_sheaf ) { M2_sheaf = P_sheaf; if( nullptr == M2_sheaf ) { M2_sheaf = &Fs_sheaf(); } } GC_projector::T_sheaf & GC_projector::Fs_sheaf() { typedef GS_DDMRM::S_IceRay::S_render::S_sheaf::GC_all Tf_all; static Tf_all Irs_all; return Irs_all; }
22.097222
80
0.648649
[ "vector" ]
8d3fa049d822487dc9223cd50d463f0f886fc822
702
hpp
C++
scenes/animation/ant/project.hpp
Marie-charlotteCalisto/epita_image_animation3d_vcl
ee56033839336c3149b410cfb038e0c28f412e61
[ "MIT" ]
null
null
null
scenes/animation/ant/project.hpp
Marie-charlotteCalisto/epita_image_animation3d_vcl
ee56033839336c3149b410cfb038e0c28f412e61
[ "MIT" ]
null
null
null
scenes/animation/ant/project.hpp
Marie-charlotteCalisto/epita_image_animation3d_vcl
ee56033839336c3149b410cfb038e0c28f412e61
[ "MIT" ]
null
null
null
#pragma once #include "main/scene_base/base.hpp" #include "ant.hpp" #include "utils.hpp" #ifdef SCENE_ANT struct scene_model : scene_base { void setup_data(std::map<std::string,GLuint>& shaders, scene_structure& scene, gui_structure& gui); void frame_draw(std::map<std::string,GLuint>& shaders, scene_structure& scene, gui_structure& gui); void mouse_click(scene_structure& scene, GLFWwindow* window, int button, int action, int mods); void set_gui(); void create_ants(std::map<std::string,GLuint>& shaders); std::vector<Ant> my_ants; size_t nb_ants = 20; vcl::mesh_drawable ground; gui_scene_structure gui_scene; vcl::timer_interval timer; }; #endif
22.645161
103
0.717949
[ "vector" ]
1d33b6a638422bfe3b1f6fb0b7d2ce8819a83af9
29,041
hpp
C++
src/math/eigen_algebra.hpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
src/math/eigen_algebra.hpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
src/math/eigen_algebra.hpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
#pragma once #if USE_STAN #include <stan/math.hpp> #include <stan/math/fwd.hpp> #endif // clang-format off #ifdef USE_CPPAD #include <cppad/cg.hpp> #include "math/cppad/eigen_mat_inv.hpp" #endif //USE_CPPAD // clang-format on #include <Eigen/Core> #include <Eigen/Geometry> #include <iostream> #include "math/conditionals.hpp" #include "math/tiny/neural_scalar.hpp" #include "spatial_vector.hpp" #undef max #undef min namespace tds { template <typename ScalarT = double> struct EigenAlgebraT { using Index = Eigen::Index; using Scalar = ScalarT; using EigenAlgebra = EigenAlgebraT<Scalar>; using Vector3 = Eigen::Matrix<Scalar, 3, 1>; using VectorX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>; using Matrix3 = Eigen::Matrix<Scalar, 3, 3>; using Matrix6 = Eigen::Matrix<Scalar, 6, 6>; using Matrix3X = Eigen::Matrix<Scalar, 3, Eigen::Dynamic>; using MatrixX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; using Quaternion = Eigen::Quaternion<Scalar>; using SpatialVector = tds::SpatialVector<EigenAlgebra>; using MotionVector = tds::MotionVector<EigenAlgebra>; using ForceVector = tds::ForceVector<EigenAlgebra>; template <typename T> EIGEN_ALWAYS_INLINE static auto transpose(const T &matrix) { return matrix.transpose(); } template <typename T> EIGEN_ALWAYS_INLINE static auto inverse(const T &matrix) { return matrix.inverse(); } template <typename T> EIGEN_ALWAYS_INLINE static auto inverse_transpose(const T &matrix) { return matrix.inverse().transpose(); } template <typename T1, typename T2> EIGEN_ALWAYS_INLINE static auto cross(const T1 &vector_a, const T2 &vector_b) { return vector_a.cross(vector_b); } /** * V1 = mv(w1, v1) * V2 = mv(w2, v2) * V1 x V2 = mv(w1 x w2, w1 x v2 + v1 x w2) */ static inline MotionVector cross(const MotionVector &a, const MotionVector &b) { return MotionVector(a.top.cross(b.top), a.top.cross(b.bottom) + a.bottom.cross(b.top)); } /** * V = mv(w, v) * F = fv(n, f) * V x* F = fv(w x n + v x f, w x f) */ static inline ForceVector cross(const MotionVector &a, const ForceVector &b) { return ForceVector(a.top.cross(b.top) + a.bottom.cross(b.bottom), a.top.cross(b.bottom)); } EIGEN_ALWAYS_INLINE static Index size(const VectorX &v) { return v.size(); } EIGEN_ALWAYS_INLINE static Matrix3X create_matrix_3x(int num_cols) { return Matrix3X(3, num_cols); } EIGEN_ALWAYS_INLINE static MatrixX create_matrix_x(int num_rows, int num_cols) { return MatrixX(num_rows, num_cols); } template <typename T> EIGEN_ALWAYS_INLINE static int num_rows(const T &matrix) { return matrix.rows(); } template <typename T> EIGEN_ALWAYS_INLINE static int num_cols(const T &matrix) { return matrix.cols(); } EIGEN_ALWAYS_INLINE static Scalar determinant(const Matrix3 &m) { return m.determinant(); } EIGEN_ALWAYS_INLINE static Scalar determinant(const MatrixX &m) { return m.determinant(); } /** * CppAD-friendly matrix inverse operation that assumes the input matrix is * positive-definite. */ static void plain_symmetric_inverse(const MatrixX &mat, MatrixX &mat_inv) { assert(mat.rows() == mat.cols()); VectorX diagonal = mat.diagonal(); mat_inv = mat; const int n = mat.rows(); int i, j, k; Scalar sum; for (i = 0; i < n; i++) { mat_inv(i, i) = one() / diagonal[i]; for (j = i + 1; j < n; j++) { sum = zero(); for (k = i; k < j; k++) { sum -= mat_inv(j, k) * mat_inv(k, i); } mat_inv(j, i) = sum / diagonal[j]; } } for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { mat_inv(i, j) = zero(); } } for (i = 0; i < n; i++) { mat_inv(i, i) = mat_inv(i, i) * mat_inv(i, i); for (k = i + 1; k < n; k++) { mat_inv(i, i) += mat_inv(k, i) * mat_inv(k, i); } for (j = i + 1; j < n; j++) { for (k = j; k < n; k++) { mat_inv(i, j) += mat_inv(k, i) * mat_inv(k, j); } } } for (i = 0; i < n; i++) { for (j = 0; j < i; j++) { mat_inv(i, j) = mat_inv(j, i); } } } /** * Returns true if the matrix `mat` is positive-definite, and assigns * `mat_inv` to the inverse of mat. * `mat` must be a symmetric matrix. */ static bool symmetric_inverse(const MatrixX &mat, MatrixX &mat_inv) { if constexpr (!is_cppad_scalar<Scalar>::value) { Eigen::LLT<MatrixX> llt(mat); if (llt.info() == Eigen::NumericalIssue) { return false; } mat_inv = mat.inverse(); } else { plain_symmetric_inverse(mat, mat_inv); // // FIXME the atomic op needs to remain in memory but it will fail when // the // // dimensions of the input matrix are not always the same // using InnerScalar = typename Scalar::value_type; // static atomic_eigen_mat_inv<InnerScalar> mat_inv_op; // mat_inv = mat_inv_op.op(mat); } return true; } /** * V = mv(w, v) * F = mv(n, f) * V.F = w.n + v.f */ EIGEN_ALWAYS_INLINE static Scalar dot(const MotionVector &a, const ForceVector &b) { return a.top.dot(b.top) + a.bottom.dot(b.bottom); } EIGEN_ALWAYS_INLINE static Scalar dot(const ForceVector &a, const MotionVector &b) { return dot(b, a); } template <typename T1, typename T2> EIGEN_ALWAYS_INLINE static auto dot(const T1 &vector_a, const T2 &vector_b) { return vector_a.dot(vector_b); } TINY_INLINE static Scalar norm(const MotionVector &v) { using std::sqrt; return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3] + v[4] * v[4] + v[5] * v[5]); } TINY_INLINE static Scalar norm(const ForceVector &v) { using std::sqrt; return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3] + v[4] * v[4] + v[5] * v[5]); } template <typename T> EIGEN_ALWAYS_INLINE static Scalar norm(const T &v) { return v.norm(); } template <typename T> EIGEN_ALWAYS_INLINE static Scalar sqnorm(const T &v) { return v.squaredNorm(); } template <typename T> EIGEN_ALWAYS_INLINE static auto normalize(T &v) { v.normalize(); return v; } EIGEN_ALWAYS_INLINE static Matrix3 cross_matrix(const Vector3 &v) { Matrix3 tmp; #ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS tmp << zero(), v[2], -v[1], -v[2], zero(), v[0], v[1], -v[0], zero(); #else tmp << zero(), -v[2], v[1], v[2], zero(), -v[0], -v[1], v[0], zero(); #endif return tmp; } EIGEN_ALWAYS_INLINE static Matrix3 zero33() { return Matrix3::Zero(); } EIGEN_ALWAYS_INLINE static VectorX zerox(Index size) { return VectorX::Zero(size); } EIGEN_ALWAYS_INLINE static Matrix3 diagonal3(const Vector3 &v) { Matrix3 tmp; tmp.setZero(); tmp(0, 0) = v[0]; tmp(1, 1) = v[1]; tmp(2, 2) = v[2]; return tmp; } EIGEN_ALWAYS_INLINE static Matrix3 diagonal3(const Scalar &v) { Matrix3 tmp; tmp.setZero(); tmp(0, 0) = v; tmp(1, 1) = v; tmp(2, 2) = v; return tmp; } EIGEN_ALWAYS_INLINE static Matrix3 eye3() { return Matrix3::Identity(); } EIGEN_ALWAYS_INLINE static void set_identity(Quaternion &quat) { quat = Quaternion(Scalar(1.), Scalar(0.), Scalar(0.), Scalar(0.)); } EIGEN_ALWAYS_INLINE static Scalar zero() { return Scalar(0); } EIGEN_ALWAYS_INLINE static Scalar one() { return Scalar(1); } EIGEN_ALWAYS_INLINE static Scalar two() { return Scalar(2); } EIGEN_ALWAYS_INLINE static Scalar half() { return Scalar(0.5); } EIGEN_ALWAYS_INLINE static Scalar pi() { return Scalar(M_PI); } EIGEN_ALWAYS_INLINE static Scalar fraction(int a, int b) { return (Scalar(a)) / b; } static Scalar scalar_from_string(const std::string &s) { return from_double(std::stod(s)); } EIGEN_ALWAYS_INLINE static Vector3 zero3() { return Vector3::Zero(); } EIGEN_ALWAYS_INLINE static Vector3 unit3_x() { return Vector3(one(), zero(), zero()); } EIGEN_ALWAYS_INLINE static Vector3 unit3_y() { return Vector3(zero(), one(), zero()); } EIGEN_ALWAYS_INLINE static Vector3 unit3_z() { return Vector3(zero(), zero(), one()); } EIGEN_ALWAYS_INLINE static VectorX segment(const VectorX &vec, int start_index, int length) { return vec.segment(start_index, length); } EIGEN_ALWAYS_INLINE static MatrixX block(const MatrixX &mat, int start_row_index, int start_col_index, int rows, int cols) { return mat.block(start_row_index, start_col_index, rows, cols); } EIGEN_ALWAYS_INLINE static void assign_block(Matrix3X &output, const Matrix3 &input, int i, int j, int m = -1, int n = -1, int input_i = 0, int input_j = 0) { if (m < 0) m = input.rows(); if (n < 0) n = input.cols(); assert(i + m <= output.rows() && j + n <= output.cols()); assert(input_i + m <= input.rows() && input_j + n <= input.cols()); for (int ii = 0; ii < m; ++ii) { for (int jj = 0; jj < n; ++jj) { output(ii + i, jj + j) = input(ii + input_i, jj + input_j); } } } EIGEN_ALWAYS_INLINE static void assign_block(Matrix6 &output, const Matrix3 &input, int i, int j, int m = -1, int n = -1, int input_i = 0, int input_j = 0) { if (m < 0) m = input.rows(); if (n < 0) n = input.cols(); assert(i + m <= output.rows() && j + n <= output.cols()); assert(input_i + m <= input.rows() && input_j + n <= input.cols()); for (int ii = 0; ii < m; ++ii) { for (int jj = 0; jj < n; ++jj) { output(ii + i, jj + j) = input(ii + input_i, jj + input_j); } } } EIGEN_ALWAYS_INLINE static void assign_block(Matrix3 &output, const Matrix6 &input, int i, int j, int m = -1, int n = -1, int input_i = 0, int input_j = 0) { if (m < 0) m = input.rows(); if (n < 0) n = input.cols(); assert(i + m <= output.rows() && j + n <= output.cols()); assert(input_i + m <= input.rows() && input_j + n <= input.cols()); for (int ii = 0; ii < m; ++ii) { for (int jj = 0; jj < n; ++jj) { output(ii + i, jj + j) = input(ii + input_i, jj + input_j); } } } EIGEN_ALWAYS_INLINE static void assign_block(MatrixX &output, const MatrixX &input, int i, int j, int m = -1, int n = -1, int input_i = 0, int input_j = 0) { if (m < 0) m = input.rows(); if (n < 0) n = input.cols(); assert(i + m <= output.rows() && j + n <= output.cols()); assert(input_i + m <= input.rows() && input_j + n <= input.cols()); for (int ii = 0; ii < m; ++ii) { for (int jj = 0; jj < n; ++jj) { output(ii + i, jj + j) = input(ii + input_i, jj + input_j); } } } template <int Rows1, int Cols1, int Rows2, int Cols2> EIGEN_ALWAYS_INLINE static void assign_block( Eigen::Matrix<Scalar, Rows1, Cols1> &output, const Eigen::Matrix<Scalar, Rows2, Cols2> &input, int i, int j, int m = -1, int n = -1, int input_i = 0, int input_j = 0) { if (m < 0) m = input.rows(); if (n < 0) n = input.cols(); assert(i + m <= output.rows() && j + n <= output.cols()); assert(input_i + m <= input.rows() && input_j + n <= input.cols()); for (int ii = 0; ii < m; ++ii) { for (int jj = 0; jj < n; ++jj) { output(ii + i, jj + j) = input(ii + input_i, jj + input_j); } } } EIGEN_ALWAYS_INLINE static void assign_column(Matrix3 &m, Index i, const Vector3 &v) { m.col(i) = v; } EIGEN_ALWAYS_INLINE static void assign_column(Matrix3 &m, Index i, const Matrix6 &v) { m.col(i) = v; } EIGEN_ALWAYS_INLINE static void assign_column(Matrix3X &m, Index i, const Vector3 &v) { m.col(i) = v; } EIGEN_ALWAYS_INLINE static void assign_column(MatrixX &m, Index i, const MatrixX &v) { m.col(i) = v; } EIGEN_ALWAYS_INLINE static void assign_column(MatrixX &m, Index i, const SpatialVector &v) { m.block(0, i, 3, 1) = v.top; m.block(3, i, 3, 1) = v.bottom; } template <int Rows, int Cols, typename Derived> EIGEN_ALWAYS_INLINE static void assign_column( Eigen::Matrix<Scalar, Rows, Cols> &m, Index i, const Eigen::DenseBase<Derived> &v) { assign_column(m, i, v.eval()); } EIGEN_ALWAYS_INLINE static void assign_row(MatrixX &m, Index i, const MatrixX &v) { m.row(i) = v; } EIGEN_ALWAYS_INLINE static void assign_row(MatrixX &m, Index i, const SpatialVector &v) { m.block(i, 0, 1, 3) = v.top; m.block(i, 3, 1, 3) = v.bottom; } EIGEN_ALWAYS_INLINE static void assign_horizontal(MatrixX &mat, const VectorX &vec, int start_row_index, int start_col_index) { mat.block(start_row_index, start_col_index, 1, vec.rows()) = vec.transpose(); } template <int Rows> EIGEN_ALWAYS_INLINE static void assign_vertical( MatrixX &mat, const Eigen::Matrix<Scalar, Rows, 1> &vec, int start_row_index, int start_col_index) { mat.block(start_row_index, start_col_index, vec.rows(), 1) = vec; } template <int Rows, int Cols> TINY_INLINE static VectorX mul_transpose( const Eigen::Matrix<Scalar, Rows, Cols> &mat, const Eigen::Matrix<Scalar, Cols, 1> &vec) { return mat.transpose() * vec; } TINY_INLINE static VectorX mul_transpose(const MatrixX &mat, const VectorX &vec) { return mat.transpose() * vec; } EIGEN_ALWAYS_INLINE static Matrix3 quat_to_matrix(const Quaternion &quat) { // NOTE: Eigen requires quat to be normalized return quat.toRotationMatrix(); } EIGEN_ALWAYS_INLINE static Matrix3 quat_to_matrix(const Scalar &x, const Scalar &y, const Scalar &z, const Scalar &w) { return Quaternion(w, x, y, z).toRotationMatrix(); } EIGEN_ALWAYS_INLINE static Quaternion matrix_to_quat(const Matrix3 &m) { if constexpr (is_cppad_scalar<Scalar>::value) { // add epsilon to denominator to prevent division by zero const Scalar eps = from_double(1e-6); Scalar tr = m(0, 0) + m(1, 1) + m(2, 2); Scalar q1[4], q2[4], q3[4], q4[4]; // if (tr > 0) { Scalar S = sqrt(abs(tr + 1.0)) * two() + eps; q1[0] = fraction(1, 4) * S; q1[1] = (m(2, 1) - m(1, 2)) / S; q1[2] = (m(0, 2) - m(2, 0)) / S; q1[3] = (m(1, 0) - m(0, 1)) / S; } // else if ((m(0,0) > m(1,1))&(m(0,0) > m(2,2))) { Scalar S = sqrt(abs(1.0 + m(0, 0) - m(1, 1) - m(2, 2))) * two() + eps; q2[0] = (m(2, 1) - m(1, 2)) / S; q2[1] = fraction(1, 4) * S; q2[2] = (m(0, 1) + m(1, 0)) / S; q2[3] = (m(0, 2) + m(2, 0)) / S; } // else if (m(1,1) > m(2,2)) { Scalar S = sqrt(abs(1.0 + m(1, 1) - m(0, 0) - m(2, 2))) * two() + eps; q3[0] = (m(0, 2) - m(2, 0)) / S; q3[1] = (m(0, 1) + m(1, 0)) / S; q3[2] = fraction(1, 4) * S; q3[3] = (m(1, 2) + m(2, 1)) / S; } // else { Scalar S = sqrt(abs(1.0 + m(2, 2) - m(0, 0) - m(1, 1))) * two() + eps; q4[0] = (m(1, 0) - m(0, 1)) / S; q4[1] = (m(0, 2) + m(2, 0)) / S; q4[2] = (m(1, 2) + m(2, 1)) / S; q4[3] = fraction(1, 4) * S; } Quaternion q; // (m(0,0) > m(1,1))&(m(0,0) > m(2,2)) Scalar m00_is_max = where_gt( m(0, 0), m(1, 1), where_gt(m(0, 0), m(2, 2), one(), zero()), zero()); Scalar m11_is_max = (one() - m00_is_max) * where_gt(m(1, 1), m(2, 2), one(), zero()); Scalar m22_is_max = (one() - m00_is_max) * (one() - m11_is_max); q.w() = where_gt( tr, zero(), q1[0], m00_is_max * q2[0] + m11_is_max * q3[0] + m22_is_max * q4[0]); q.x() = where_gt( tr, zero(), q1[1], m00_is_max * q2[1] + m11_is_max * q3[1] + m22_is_max * q4[1]); q.y() = where_gt( tr, zero(), q1[2], m00_is_max * q2[2] + m11_is_max * q3[2] + m22_is_max * q4[2]); q.z() = where_gt( tr, zero(), q1[3], m00_is_max * q2[3] + m11_is_max * q3[3] + m22_is_max * q4[3]); return q; } else { return Quaternion(m); } } EIGEN_ALWAYS_INLINE static Quaternion axis_angle_quaternion( const Vector3 &axis, const Scalar &angle) { return Quaternion(Eigen::AngleAxis(angle, axis)); } EIGEN_ALWAYS_INLINE static Matrix3 rotation_x_matrix(const Scalar &angle) { using std::cos, std::sin; Scalar c = cos(angle); Scalar s = sin(angle); Matrix3 temp; #ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS temp << one(), zero(), zero(), zero(), c, s, zero(), -s, c; #else temp << one(), zero(), zero(), zero(), c, -s, zero(), s, c; #endif //std::cout << "rot_x" << temp << std::endl; return temp; } EIGEN_ALWAYS_INLINE static Matrix3 rotation_y_matrix(const Scalar &angle) { using std::cos, std::sin; Scalar c = cos(angle); Scalar s = sin(angle); Matrix3 temp; #ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS temp << c, zero(), -s, zero(), one(), zero(), s, zero(), c; #else temp << c, zero(), s, zero(), one(), zero(), -s, zero(), c; #endif return temp; } EIGEN_ALWAYS_INLINE static Matrix3 rotation_z_matrix(const Scalar &angle) { using std::cos, std::sin; Scalar c = cos(angle); Scalar s = sin(angle); Matrix3 temp; #ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS temp << c, s, zero(), -s, c, zero(), zero(), zero(), one(); #else temp << c, -s, zero(), s, c, zero(), zero(), zero(), one(); #endif return temp; } static Matrix3 rotation_zyx_matrix(const Scalar &r, const Scalar &p, const Scalar &y) { using std::cos, std::sin; Scalar ci(cos(r)); Scalar cj(cos(p)); Scalar ch(cos(y)); Scalar si(sin(r)); Scalar sj(sin(p)); Scalar sh(sin(y)); Scalar cc = ci * ch; Scalar cs = ci * sh; Scalar sc = si * ch; Scalar ss = si * sh; Matrix3 temp; temp << cj * ch, sj * sc - cs, sj * cc + ss, cj * sh, sj * ss + cc, sj * cs - sc, -sj, cj * si, cj * ci; return temp; } EIGEN_ALWAYS_INLINE static Vector3 rotate(const Quaternion &q, const Vector3 &v) { return q * v; } /** * Computes the quaternion delta given current rotation q, angular velocity w, * time step dt. */ EIGEN_ALWAYS_INLINE static Quaternion quat_velocity(const Quaternion &q, const Vector3 &w, const Scalar &dt) { Quaternion delta((-q.x() * w[0] - q.y() * w[1] - q.z() * w[2]) * (0.5 * dt), (q.w() * w[0] + q.y() * w[2] - q.z() * w[1]) * (0.5 * dt), (q.w() * w[1] + q.z() * w[0] - q.x() * w[2]) * (0.5 * dt), (q.w() * w[2] + q.x() * w[1] - q.y() * w[0]) * (0.5 * dt)); return delta; } EIGEN_ALWAYS_INLINE static void quat_increment(Quaternion &a, const Quaternion &b) { a.x() += b.x(); a.y() += b.y(); a.z() += b.z(); a.w() += b.w(); } EIGEN_ALWAYS_INLINE static const Scalar &quat_x(const Quaternion &q) { return q.x(); } EIGEN_ALWAYS_INLINE static const Scalar &quat_y(const Quaternion &q) { return q.y(); } EIGEN_ALWAYS_INLINE static const Scalar &quat_z(const Quaternion &q) { return q.z(); } EIGEN_ALWAYS_INLINE static const Scalar &quat_w(const Quaternion &q) { return q.w(); } EIGEN_ALWAYS_INLINE static const Quaternion quat_from_xyzw(const Scalar &x, const Scalar &y, const Scalar &z, const Scalar &w) { // Eigen specific constructor coefficient order return Quaternion(w, x, y, z); } EIGEN_ALWAYS_INLINE static void set_zero(Matrix3X &m) { m.setZero(); } EIGEN_ALWAYS_INLINE static void set_zero(Vector3 &m) { m.setZero(); } EIGEN_ALWAYS_INLINE static void set_zero(VectorX &m) { m.setZero(); } EIGEN_ALWAYS_INLINE static void set_zero(MatrixX &m) { m.setZero(); } template <int Size1, int Size2 = 1> EIGEN_ALWAYS_INLINE static void set_zero( Eigen::Array<Scalar, Size1, Size2> &v) { v.setZero(); } EIGEN_ALWAYS_INLINE static void set_zero(MotionVector &v) { v.top.setZero(); v.bottom.setZero(); } EIGEN_ALWAYS_INLINE static void set_zero(ForceVector &v) { v.top.setZero(); v.bottom.setZero(); } /** * Non-differentiable comparison operator. */ TINY_INLINE static bool is_zero(const Scalar &a) { return a == zero(); } /** * Non-differentiable comparison operator. */ EIGEN_ALWAYS_INLINE static bool less_than(const Scalar &a, const Scalar &b) { return a < b; } /** * Non-differentiable comparison operator. */ EIGEN_ALWAYS_INLINE static bool less_than_zero(const Scalar &a) { return a < 0.; } /** * Non-differentiable comparison operator. */ EIGEN_ALWAYS_INLINE static bool greater_than_zero(const Scalar &a) { return a > 0.; } /** * Non-differentiable comparison operator. */ EIGEN_ALWAYS_INLINE static bool greater_than(const Scalar &a, const Scalar &b) { return a > b; } /** * Non-differentiable comparison operator. */ EIGEN_ALWAYS_INLINE static bool equals(const Scalar &a, const Scalar &b) { return a == b; } #ifdef USE_STAN template <typename InnerScalar> TINY_INLINE static std::enable_if_t< !std::is_same_v<Scalar, stan::math::fvar<InnerScalar>>, double> to_double(const stan::math::fvar<InnerScalar> &s) { return stan::math::value_of(s); } #endif TINY_INLINE static double to_double(const Scalar &s) { #ifdef USE_STAN if constexpr (std::is_same_v<Scalar, stan::math::var> || std::is_same_v<Scalar, stan::math::fvar<double>>) { return stan::math::value_of(s); } else #endif #ifdef USE_CPPAD if constexpr (std::is_same_v<std::remove_cv_t<Scalar>, CppAD::AD<CppAD::cg::CG<double>>>) { return CppAD::Value(CppAD::Var2Par(s)).getValue(); } else if constexpr (std::is_same_v<std::remove_cv_t<Scalar>, CppAD::AD<double>>) { return CppAD::Value(CppAD::Var2Par(s)); } else #endif //USE_CPPAD { return static_cast<double>(s); } } TINY_INLINE static Scalar from_double(double s) { return static_cast<Scalar>(s); } template <int Size1, int Size2> static void print(const std::string &title, Eigen::Matrix<Scalar, Size1, Size2> &m) { std::cout << title << "\n" << m << std::endl; } template <int Size1, int Size2 = 1> static void print(const std::string &title, Eigen::Array<Scalar, Size1, Size2> &v) { std::cout << title << "\n" << v << std::endl; } static void print(const std::string &title, const Scalar &v) { std::cout << title << "\n" << to_double(v) << std::endl; } template <typename T> static void print(const std::string &title, const T &abi) { abi.print(title.c_str()); } template <typename T> TINY_INLINE static auto sin(const T &s) { using std::sin; return sin(s); } template <typename T> TINY_INLINE static auto cos(const T &s) { using std::cos; return cos(s); } template <typename T> TINY_INLINE static auto tan(const T &s) { using std::tan; return tan(s); } template <typename T> TINY_INLINE static auto atan2(const T &dy, const T &dx) { using std::atan2; return atan2(dy, dx); } template <typename T> TINY_INLINE static auto abs(const T &s) { using std::abs; return abs(s); } template <typename T> TINY_INLINE static auto sqrt(const T &s) { using std::sqrt; return sqrt(s); } template <typename T> TINY_INLINE static auto tanh(const T &s) { using std::tanh; return tanh(s); } template <typename T> TINY_INLINE static auto pow(const T &s, const T &e) { using std::pow; return pow(s, e); } template <typename T> TINY_INLINE static auto exp(const T &s) { using std::exp; return exp(s); } template <typename T> TINY_INLINE static auto log(const T &s) { using std::log; return log(s); } template <typename T> TINY_INLINE static auto max(const T &x, const T &y) { return tds::where_gt(x, y, x, y); } template <typename T> TINY_INLINE static auto min(const T &x, const T &y) { return tds::where_lt(x, y, x, y); } EigenAlgebraT<Scalar>() = delete; }; typedef EigenAlgebraT<double> EigenAlgebra; // Helpers for NeuralAlgebra #ifdef USE_CPPAD template <typename Scalar> struct is_cppad_scalar<NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>> { static constexpr bool value = true; }; template <typename Scalar> static TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_gt( const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) { return CppAD::CondExpGt(x.evaluate(), y.evaluate(), if_true.evaluate(), if_false.evaluate()); } template <typename Scalar> static TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_ge( const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) { return CppAD::CondExpGe(x.evaluate(), y.evaluate(), if_true.evaluate(), if_false.evaluate()); } template <typename Scalar> static TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_lt( const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) { return CppAD::CondExpLt(x.evaluate(), y.evaluate(), if_true.evaluate(), if_false.evaluate()); } template <typename Scalar> static TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_le( const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) { return CppAD::CondExpLe(x.evaluate(), y.evaluate(), if_true.evaluate(), if_false.evaluate()); } template <typename Scalar> static TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_eq( const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true, const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) { return CppAD::CondExpEq(x.evaluate(), y.evaluate(), if_true.evaluate(), if_false.evaluate()); } #endif //USE_CPPAD } // end namespace tds
32.85181
80
0.560105
[ "geometry" ]
1d3bc5700f31eac184e4b24f1837f5701268c603
12,882
cpp
C++
src/libSBML/src/sbml/packages/render/sbml/LocalStyle.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
5
2015-04-16T14:27:38.000Z
2021-11-30T14:54:39.000Z
src/libSBML/src/sbml/packages/render/sbml/LocalStyle.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
8
2017-05-30T16:58:39.000Z
2022-02-22T16:51:34.000Z
src/libSBML/src/sbml/packages/render/sbml/LocalStyle.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
7
2016-05-29T08:12:59.000Z
2019-05-02T13:39:25.000Z
/** * @file LocalStyle.cpp * @brief class for representing a local style * @author Ralph Gauges * @author Frank T. Bergmann * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2020 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * 3. University College London, London, UK * * Copyright (C) 2019 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2013-2018 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2011-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright 2010 Ralph Gauges * Group for the modeling of biological processes * University of Heidelberg * Im Neuenheimer Feld 267 * 69120 Heidelberg * Germany * * 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. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ---------------------------------------------------------------------- -->*/ #include <sbml/packages/render/sbml/LocalStyle.h> #include <sbml/packages/render/sbml/ListOfLocalStyles.h> #include <sbml/packages/render/validator/RenderSBMLError.h> #include <sbml/packages/layout/util/LayoutUtilities.h> #include <sbml/xml/XMLInputStream.h> #include <algorithm> #include <assert.h> #ifndef OMIT_DEPRECATED #ifdef DEPRECATION_WARNINGS #include <iostream> #endif // DEPRECATION_WARNINGS #endif // OMIT_DEPRECATED #include <sbml/packages/render/extension/RenderExtension.h> #include <sbml/packages/layout/util/LayoutAnnotation.h> using namespace std; LIBSBML_CPP_NAMESPACE_BEGIN #ifdef __cplusplus /* * Creates a new LocalStyle using the given SBML Level, Version and * &ldquo;render&rdquo; package version. */ LocalStyle::LocalStyle(unsigned int level, unsigned int version, unsigned int pkgVersion) : Style(level,version, pkgVersion) { setSBMLNamespacesAndOwn(new RenderPkgNamespaces(level, version, pkgVersion)); } /* * Creates a new LocalStyle using the given RenderPkgNamespaces object. */ LocalStyle::LocalStyle(RenderPkgNamespaces *renderns) : Style(renderns) { setElementNamespace(renderns->getURI()); loadPlugins(renderns); } /** @cond doxygenLibsbmlInternal */ /* * Creates a new LocalStyle object from the given XMLNode object. * The XMLNode object has to contain a valid XML representation of a * LocalStyle object as defined in the render extension specification. * This method is normally called when render information is read from a file and * should normally not have to be called explicitly. * * @param node the XMLNode object reference that describes the LocalStyle * object to be instantiated. */ LocalStyle::LocalStyle(const XMLNode& node, unsigned int l2version):Style(node, l2version) { ExpectedAttributes ea; addExpectedAttributes(ea); this->readAttributes(node.getAttributes(), ea); setSBMLNamespacesAndOwn(new RenderPkgNamespaces(2,l2version)); connectToChild(); } /** @endcond */ #ifndef OMIT_DEPRECATED /** @cond doxygenLibsbmlInternal */ /* * Constructor which creates a LocalStyle with an empty group * and empty id, role and type list. * The group has to be filled before the * object is valid. * * This constructor is deprecated. The new libsbml API only has * constructors which take the SBML level and version or one that takes * an SBMLNamespaces object. */ LocalStyle::LocalStyle(RenderPkgNamespaces* renderns, const std::string& id):Style(renderns,id) { #ifdef DEPRECATION_WARNINGS std::cerr << "Warning. LocalStyle::LocalStyle(const std::string& id) is deprecated." << std::endl; #endif // DEPRECATION_WARNINGS // set the element namespace of this object setElementNamespace(renderns->getURI()); // connect child elements to this element. connectToChild(); // load package extensions bound with this object (if any) loadPlugins(renderns); } /** @endcond */ #endif // OMIT_DEPRECATED /* * Copy constructor for LocalStyle. */ LocalStyle::LocalStyle(const LocalStyle& orig) : Style( orig ) , mIdList ( orig.mIdList ) { } /* * Assignment operator for LocalStyle. */ LocalStyle& LocalStyle::operator=(const LocalStyle& rhs) { if (&rhs != this) { Style::operator=(rhs); mIdList = rhs.mIdList; } return *this; } /* * Creates and returns a deep copy of this LocalStyle object. */ LocalStyle* LocalStyle::clone() const { return new LocalStyle(*this); } /* * Destructor for LocalStyle. */ LocalStyle::~LocalStyle() { } /* * Returns the id list. */ const std::set<std::string>& LocalStyle::getIdList() const { return this->mIdList; } /* * Returns the id list. */ std::set<std::string>& LocalStyle::getIdList() { return this->mIdList; } /* * Returns the number of ids in the id set. */ unsigned int LocalStyle::getNumIds() const { return (unsigned int)this->mIdList.size(); } /* * Checks whether a given @p id is in the id list. */ bool LocalStyle::isInIdList(const std::string& id) const { return (this->mIdList.find(id)!=this->mIdList.end()); } /* * Adds another id to the set. * * @param id the id string to be added to the id list. */ int LocalStyle::addId(const std::string& id) { this->mIdList.insert(id); return LIBSBML_OPERATION_SUCCESS; } std::string LocalStyle::createIdString() const { return createStringFromSet(mIdList); } /* * Removes an id from the set. */ int LocalStyle::removeId(const std::string& id) { this->mIdList.erase(id); return LIBSBML_OPERATION_SUCCESS; } /* * Sets the id list. */ int LocalStyle::setIdList(const std::set<std::string>& idList) { this->mIdList=idList; return LIBSBML_OPERATION_SUCCESS; } /* * Returns the XML element name of this LocalStyle object. */ const std::string& LocalStyle::getElementName() const { static const string name = "style"; return name; } /* * Returns the libSBML type code for this LocalStyle object. */ int LocalStyle::getTypeCode() const { return SBML_RENDER_LOCALSTYLE; } /* * Creates an XMLNode object from this LocalStyle object. */ XMLNode LocalStyle::toXML() const { return getXmlNodeForSBase(this); } /** @cond doxygenLibsbmlInternal */ /* * Adds the expected attributes for this element */ void LocalStyle::addExpectedAttributes(ExpectedAttributes& attributes) { Style::addExpectedAttributes(attributes); attributes.add("idList"); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Reads the expected attributes into the member data variables */ void LocalStyle::readAttributes(const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes) { unsigned int level = getLevel(); unsigned int version = getVersion(); unsigned int pkgVersion = getPackageVersion(); unsigned int numErrs; SBMLErrorLog* log = getErrorLog(); if (log && getParentSBMLObject() && static_cast<ListOfLocalStyles*>(getParentSBMLObject())->size() < 2) { numErrs = log->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (log->getError(n)->getErrorId() == UnknownPackageAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownPackageAttribute); log->logPackageError("render", RenderLocalStyleAllowedAttributes, pkgVersion, level, version, details, getLine(), getColumn()); } else if (log->getError(n)->getErrorId() == UnknownCoreAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownCoreAttribute); log->logPackageError("render", RenderLocalRenderInformationLOLocalStylesAllowedCoreAttributes, pkgVersion, level, version, details, getLine(), getColumn()); } } } Style::readAttributes(attributes, expectedAttributes); if (log) { numErrs = log->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (log->getError(n)->getErrorId() == UnknownPackageAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownPackageAttribute); log->logPackageError("render", RenderLocalStyleAllowedAttributes, pkgVersion, level, version, details, getLine(), getColumn()); } else if (log->getError(n)->getErrorId() == UnknownCoreAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownCoreAttribute); log->logPackageError("render", RenderLocalStyleAllowedCoreAttributes, pkgVersion, level, version, details, getLine(), getColumn()); } } } // // idList string (use = "optional" ) // std::string s; attributes.readInto("idList", s, getErrorLog(), false, getLine(), getColumn()); // split the idList if(!s.empty()) { readIntoSet(s,this->mIdList); } } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Writes the attributes to the stream */ void LocalStyle::writeAttributes(XMLOutputStream& stream) const { Style::writeAttributes(stream); this->writeIdList(stream); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * This method adds the attribute for the list of ids to * the given XMLnode. * * @param node the node where the attribute needs to be added */ void LocalStyle::addListOfIds(XMLToken& node) const { std::string s=createStringFromSet(this->mIdList); if(!s.empty()) { node.addAttr("idList",s); } } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Writes the id list to an XML stream. */ void LocalStyle::writeIdList(XMLOutputStream& stream) const { std::string s=createStringFromSet(this->mIdList); if(!s.empty()) { stream.writeAttribute("idList", getPrefix(), s); } } /** @endcond */ #endif /* __cplusplus */ /* * Creates a new LocalStyle_t using the given SBML Level, Version and * &ldquo;render&rdquo; package version. */ LIBSBML_EXTERN LocalStyle_t * LocalStyle_create(unsigned int level, unsigned int version, unsigned int pkgVersion) { return new LocalStyle(level, version, pkgVersion); } /* * Creates and returns a deep copy of this LocalStyle_t object. */ LIBSBML_EXTERN LocalStyle_t* LocalStyle_clone(const LocalStyle_t* ls) { if (ls != NULL) { return static_cast<LocalStyle_t*>(ls->clone()); } else { return NULL; } } /* * Frees this LocalStyle_t object. */ LIBSBML_EXTERN void LocalStyle_free(LocalStyle_t* ls) { if (ls != NULL) { delete ls; } } ///* // * Returns the value of the "idList" attribute of this LocalStyle_t. // */ //LIBSBML_EXTERN //char * //LocalStyle_getIdList(const LocalStyle_t * ls) //{ // if (ls == NULL) // { // return NULL; // } // // return ls->getIdList().empty() ? NULL : safe_strdup(ls->getIdList().c_str()); //} /* * Predicate returning @c 1 (true) if this LocalStyle_t's "idList" attribute is * set. */ LIBSBML_EXTERN int LocalStyle_isSetIdList(const LocalStyle_t * ls) { return (ls != NULL) ? static_cast<int>(ls->getNumIds()) : 0; } /* * Sets the value of the "idList" attribute of this LocalStyle_t. */ LIBSBML_EXTERN int LocalStyle_setIdList(LocalStyle_t * ls, const char * idList) { return (ls != NULL) ? ls->addId(idList) : LIBSBML_INVALID_OBJECT; } ///* // * Unsets the value of the "idList" attribute of this LocalStyle_t. // */ //LIBSBML_EXTERN //int //LocalStyle_unsetIdList(LocalStyle_t * ls) //{ // return (ls != NULL) ? ls->unsetIdList() : LIBSBML_INVALID_OBJECT; //} // /* * Predicate returning @c 1 (true) if all the required attributes for this * LocalStyle_t object have been set. */ LIBSBML_EXTERN int LocalStyle_hasRequiredAttributes(const LocalStyle_t * ls) { return (ls != NULL) ? static_cast<int>(ls->hasRequiredAttributes()) : 0; } LIBSBML_CPP_NAMESPACE_END
22.921708
102
0.68064
[ "render", "object" ]
1d3e09a71a11fa8c5aa0c03371150bc6daad266f
13,818
hpp
C++
include/AnnEvents.hpp
Ybalrid/Annwvyn
30d63c722524c35a9054d51dcdd9f39af0599a3d
[ "MIT" ]
39
2015-04-02T15:32:19.000Z
2022-03-26T12:48:28.000Z
include/AnnEvents.hpp
Ybalrid/Annwvyn
30d63c722524c35a9054d51dcdd9f39af0599a3d
[ "MIT" ]
136
2015-02-24T19:45:59.000Z
2019-02-21T15:01:12.000Z
include/AnnEvents.hpp
Ybalrid/Annwvyn
30d63c722524c35a9054d51dcdd9f39af0599a3d
[ "MIT" ]
12
2015-02-24T19:37:38.000Z
2019-05-13T12:07:26.000Z
#pragma once #include "systemMacro.h" #include "AnnUserSpaceEvent.hpp" #include "AnnKeyCode.h" #include "AnnHandController.hpp" namespace Annwvyn { class AnnTimer; class AnnTriggerObject; class AnnPlayerBody; enum AnnEventType { NO_TYPE, USER_INPUT, TIMER_TIMEOUT, TRIGGER_CONTACT, HAND_CONTROLLER, COLLISION, PLAYER_COLLISION }; ///An input event class AnnDllExport AnnEvent { public: ///Event constructor AnnEvent(); AnnEventType getType() const; protected: AnnEventType type; friend class AnnEventManager; }; ///A keyboard event class AnnDllExport AnnKeyEvent : public AnnEvent { ///Keyboard event constructor AnnKeyEvent(); public: ///Get the key involved in that event KeyCode::code getKey() const; ///Return true if it's a key press. Key event are debounced. bool isPressed() const; ///Return true if it's a key release. Key event are debounced. bool isReleased() const; ///If this is true, it probably means that the keyboard is used for something else and that you should ignore this event. bool shouldIgnore() const; private: friend class AnnEventManager; ///Code of the key this event relate to KeyCode::code key; ///Pressed state bool pressed; ///Keyboard event that should be ignored has this flag as "true" bool ignored; ///Set the event as a key release event void setPressed(); ///Set the event as a key press event void setReleased(); ///Set the keycode of the key /// \param c Keycode void setCode(KeyCode::code c); }; ///Name and number of axes enum MouseAxisID { X, Y, Z, AxisCount, InvalidAxis }; ///Name and number of mouse button enum MouseButtonId { Left, Right, Middle, Button3, Button4, Button5, Button6, Button7, ButtonCount, InvalidButton }; ///A mouse axis information object class AnnDllExport AnnMouseAxis { public: ///Construct a mouse axis information object AnnMouseAxis(); ///Return the id of the axis that object represent MouseAxisID getMouseAxisId() const; ///Relative value in arbitrary unit int getRelValue() const; ///Absolute value in arbitrary unit int getAbsValue() const; private: ///Give access to private fields to the EventManager friend class AnnEventManager; ///Give access to private fields to the MouseEvent class friend class AnnMouseEvent; ///ID of the axis MouseAxisID id; ///Relative value int rel; ///Absolute value (if applicable) int abs; ///Set the id of the axis void setAxis(MouseAxisID ax); ///Set the relative value of the axis void setRelValue(int rel); ///Set the absolute value of the axis void setAbsValue(int abs); ///Private magic one line constructor !!!! ;-) AnnMouseAxis(MouseAxisID ax, int rel, int abs); }; ///A mouse event information object class AnnDllExport AnnMouseEvent : public AnnEvent { public: AnnMouseEvent(); ///Returns true if given button is pressed /// \param id Id of the button bool getButtonState(MouseButtonId id); ///Get given axis data /// \param id Id of the axis AnnMouseAxis getAxis(MouseAxisID id); private: AnnMouseAxis axes[AxisCount]; bool buttonsStatus[ButtonCount]; friend class AnnEventManager; ///Set the status of a button /// \param id Id of a specific button /// \param value Current pressed/released state of that button void setButtonStatus(MouseButtonId id, bool value); ///Set the information about an axis /// \param id Id of a specific axis /// \param information The information object of the given axis void setAxisInformation(MouseAxisID id, AnnMouseAxis information); }; ///A joystick event using ButtonId = int; using ControllerAxisID = int; using PovId = int; using ControllerID = int; static constexpr ControllerAxisID InvalidStickAxisId = -1; static constexpr float INVALID = 42.0f; ///A joystick axis class AnnDllExport AnnControllerAxis { public: ///This constructor will produce an invalid stick axis object AnnControllerAxis(); ///Get the ID if this axis ControllerAxisID getAxisId() const; ///Compute a float number between -1 and 1. if relative value isn't supported by the input, will return INVALID (42) float getRelValue() const; ///Compute a float number between -1 and 1 float getAbsValue() const; private: friend class AnnEventManager; friend class AnnControllerEvent; ///Raw values int a, r; ControllerAxisID id; ///Set the ID of the axis void setAxis(ControllerAxisID ax); ///Set a relative value void setRelValue(int rel); ///Set an absolute value void setAbsValue(int abs); ///Real constructor AnnControllerAxis(ControllerAxisID ax, int rel, int abs); ///True if the there's no "relative" value bool noRel; }; ///Represent a pad's POV controller class AnnDllExport AnnControllerPov { public: ///Construct a Pov with no direction pressed AnnControllerPov(); ///Get the up (north) state bool getNorth() const; ///Get the down (south) state bool getSouth() const; ///Get the right (east) state bool getEast() const; ///Get the left (west) state bool getWest() const; ///Get the north && east state bool getNorthEast() const; ///Get the south && east state bool getSouthEast() const; ///Get the north && west state bool getNorthWest() const; ///Get the south && west state bool getSouthWest() const; ///Return true if nothing is pressed on the POV controller bool isCentred() const; private: ///up bool north; ///down bool south; ///right bool east; ///left bool west; friend class AnnEventManager; friend class AnnControllerEvent; ///Private constructor used by the event manager. Need a direction integer from OIS AnnControllerPov(unsigned int binaryDirection); }; ///A joystick event class AnnDllExport AnnControllerEvent : public AnnEvent { public: ///Construct a stick event object AnnControllerEvent(); ///Destroy a stick event object ~AnnControllerEvent(); ///Number of buttons this controller has size_t getNbButtons() const; ///Get the list of pressed buttons std::vector<unsigned short> getPressed() const; ///Get the list of released buttons std::vector<unsigned short> getReleased() const; ///Return true if this button just have been pressed bool isPressed(ButtonId id); ///Return true if this button just have been released bool isReleased(ButtonId id); ///Return true if this button is currently pressed bool isDown(ButtonId id); ///Get the axis object for this ID AnnControllerAxis getAxis(ControllerAxisID ax); ///Get the number of axes the controller has size_t getAxisCount() const; ///Get the unique ID given by Annwvyn for this stick ControllerID getControllerID() const; ///Get the "vendor string" of this joystick (could be its name) std::string getVendor() const; ///Get the number of PoV controller on this one size_t getPovCount() const; ///Get the PoV corresponding to this ID AnnControllerPov getPov(PovId pov); ///Return true if this event is from an Xbox controller bool isXboxController() const; private: ///set to true if this is an Xbox controller (We're not using Xinput tho) bool xbox; friend class AnnEventManager; ///Button array std::vector<byte> buttons; ///Axis array std::vector<AnnControllerAxis> axes; ///Pov Array std::vector<AnnControllerPov> povs; ///Pressed event "queue" std::vector<unsigned short> pressed; ///Released event "queue" std::vector<unsigned short> released; ///Joystick "vendor" name (generally the brand and model) std::string vendor; ///Joystick ID for the engine int stickID; }; class AnnHandController; ///A hand controller event class AnnDllExport AnnHandControllerEvent : public AnnEvent { public: AnnHandControllerEvent(); AnnHandControllerEvent(AnnHandController* controller); ///Get the world position of the tracked controller AnnVect3 getPosition() const; ///Get the world orientaiton of the tracked controller AnnQuaternion getOrientation() const; ///Get a vector that is pointing forward according to the orientation of the controller AnnVect3 getPointingDirection() const; ///Get the current linear speed of the controller AnnVect3 getLinearSpeed() const; ///Get the current angular speed of the controller AnnVect3 getAngularSpeed() const; ///Get a reference to the axis object at specified ID AnnHandControllerAxis& getAxis(uint8_t id) const; ///Get the number of axes size_t getAxisCount() const; ///Get the number of buttons size_t getButtonCount() const; ///Has the asked button just been pressed? bool buttonPressed(uint8_t id) const; ///Has the asked button just been released bool buttonReleased(uint8_t id) const; ///Get the current state of the button bool buttonState(uint8_t id) const; ///Get the handside of the controller AnnHandController::AnnHandControllerSide getSide() const; ///Get the type of the controller AnnHandController::AnnHandControllerTypeHash getType() const; ///advanced : get access to the hand controller this event is related to AnnHandController* _getController() const; private: friend class AnnEventManager; AnnHandController* controller; }; using AnnTimerID = int; ///A timer timeout event class AnnDllExport AnnTimeEvent : public AnnEvent { public: ///Create a timer timeout event AnnTimeEvent(); AnnTimeEvent(const AnnTimer& timer); ///Get the ID of this timer AnnTimerID getID() const; private: friend class AnnEventManager; ///Set the ID of the timer void setTimerID(AnnTimerID id); ///Timer ID AnnTimerID tID; }; class AnnGameObject; ///Collision event between 2 game objects class AnnDllExport AnnCollisionEvent : public AnnEvent { public: ///Event constructor AnnCollisionEvent(AnnGameObject* first, AnnGameObject* second, AnnVect3 position, AnnVect3 normal); ///Check if this event is about that object bool hasObject(AnnGameObject* obj) const; ///Get first object AnnGameObject* getA() const; ///Get second object AnnGameObject* getB() const; ///Get the position of the "contact point" from that collision AnnVect3 getPosition() const; ///Get the normal on the "B" body at the "contact point" AnnVect3 getNormal() const; ///Return true if the collision occurred with a vertical plane. Computed with testing the dot product of +Y and the normal. ///\param scalarApprox Approximation threshold to consider when testing the equality of the dotProuct and 0.0f bool isWallCollision(float scalarApprox = 0.0125) const; ///Return true if the collision occurred with an horizontal plane below the object. This is computed by taking !isWallCollision(approx) && normal.y > 0 ///\param scalarApprox Approximation threshold to consider when testing the equality of the dotProuct and 0.0f bool isGroundCollision(float scalarApprox = 0.125) const; ///Return true if the collision occured with an horizontal plane above the object. See isGroundCollision, it's the same thing, but testing for a negative y on the normal ///\param scalarApprox Approximation threshold to consider when testing the equality of the dotProuct and 0.0f bool isCeilingCollision(float scalarApprox = 0.125) const; private: ///Some naked pointers AnnGameObject *a, *b; const AnnVect3 position, normal; }; ///Collision between the player and another object class AnnDllExport AnnPlayerCollisionEvent : public AnnEvent { public: ///Constructor AnnPlayerCollisionEvent(AnnGameObject* collided); ///Get the object this event is about AnnGameObject* getObject() const; private: ///Naked pointer to the collider AnnGameObject* col; }; ///Trigger in/out event class AnnDllExport AnnTriggerEvent : public AnnEvent { public: ///Construct a trigger in/out event AnnTriggerEvent(); ///Return true if if there's collision bool getContactStatus() const; ///Pointer to the trigger that have sent this event AnnTriggerObject* getSender() const; private: friend class AnnEventManager; bool contact; AnnTriggerObject* sender; }; ///Internal utility class that represent a timer class AnnDllExport AnnTimer { public: AnnTimerID getID() const; private: friend class AnnEventManager; ///Timer object for the EventMAnager AnnTimer(AnnTimerID id, double delay); ///If timeout bool isTimeout() const; ///Timeout ID AnnTimerID tID; ///Time of timeout double timeoutTime; }; ///Internal utility class that store joystick information. RAII the oisJoystick object given to constructor class AnnDllExport AnnControllerBuffer { public: friend class AnnEventManager; ///Private constructor for AnnEventManager ///Create a Joystick buffer object, increments a static counter of IDs AnnControllerBuffer(OIS::JoyStick* joystick); ///Make class explicitly non construct-copyable AnnControllerBuffer(const AnnControllerBuffer&) = delete; ///Make class explicitly non copyable AnnControllerBuffer& operator=(const AnnControllerBuffer&) = delete; ///Let compiler generate move constructor AnnControllerBuffer(AnnControllerBuffer&& buffer) = default; ///Let compiler generate move operator AnnControllerBuffer& operator=(AnnControllerBuffer&& buffer) = default; ///Delete the OIS stick at destruction time ~AnnControllerBuffer(); void capture() const; private: ///Joystick object from OIS. Deleted by constructor OIS::JoyStick* oisJoystick; ///Array of "bool" for previous buttons std::vector<byte> previousStickButtonStates; ///Get the ID if this stick unsigned int getID() const { return id; } ///The ID unsigned int id; ///The counter static unsigned int idcounter; }; }
28.968553
171
0.72876
[ "object", "vector", "model" ]
1d3e96741a9f2b4511104ef61c64a77c10f2200c
20,478
cpp
C++
Source/PluginPhysics_Ode/Wrapper/Joint.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/PluginPhysics_Ode/Wrapper/Joint.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/PluginPhysics_Ode/Wrapper/Joint.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include "Geometry.h" #include "World.h" #include "Body.h" #include "Geometry.h" #include "Joint.h" using namespace Ode; using namespace Ogre; //------------------------------------------------------------------------------------------------ JointGroup::JointGroup(World *world): _world(world) { _joint_group = dJointGroupCreate(0); _world->AddJoinGroup(this); } //------------------------------------------------------------------------------------------------ dJointGroupID JointGroup::getJointGroupID() const { return _joint_group; } void JointGroup::empty() { dJointGroupEmpty(_joint_group); } JointGroup::~JointGroup() { _world->RemoveJoinGroup(_joint_group); dJointGroupDestroy(_joint_group); } Joint::Joint(World *world, const JointGroup* group): _world(world) { } void Joint::registerJoint() { _world->AddJoint(this); } void Joint::setAnchor(const Vector3& position) { } void Joint::addTorque(Real torque,Real torque2,Real torque3) { } void Joint::addForce(Real force,Real force2,Real force3) { } const Vector3& Joint::getAnchor() { return Vector3::ZERO; } const Vector3& Joint::getAnchorError() { return Vector3::ZERO; } void Joint::setAxis(const Vector3& axis) { } const Vector3& Joint::getAxis() { return Vector3::ZERO; } void Joint::setAdditionalAxis(const Vector3& axis) { } const Vector3& Joint::getAdditionalAxis() { return Vector3::ZERO; } Real Joint::getAngle() { return 0.0; } Real Joint::getAngleRate() { return 0.0; } Real Joint::getPosition() { return 0.0; } Real Joint::getPositionRate() { return 0.0; } Joint::~Joint() { _world->RemoveJoint(_joint); dJointDestroy(_joint); } dWorldID Joint::getWorldID() { return _world->getWorldID(); } dJointGroupID Joint::getJointGroupID(const JointGroup* group) const { return ((group)?group->getJointGroupID():0); } dJointID Joint::getJointID() { return _joint; } JointType Joint::getType() { return (JointType)(dJointGetType(_joint)); } Body* Joint::getFirstBody() { dBodyID b = dJointGetBody(_joint, 0); return ((Body*)dBodyGetData(b)); } Body* Joint::getSecondBody() { dBodyID b = dJointGetBody(_joint,1); return b ? ((Body*)dBodyGetData(b)) : 0; } bool Joint::areConnected(const Body* body_a,const Body* body_b) { return (dAreConnected(body_a->getBodyID(),body_b->getBodyID()))?true:false; } bool Joint::areConnectedExcluding(const Body* body_a, const Body* body_b, JointType joint_type) { return (dAreConnectedExcluding(body_a->getBodyID(),body_b->getBodyID(),(int)joint_type))?true:false; } void Joint::enableFeedback() { dJointSetFeedback(_joint,&_feedback); } void Joint::disableFeedback() { dJointSetFeedback(_joint,0); } void Joint::detach() { dJointAttach(_joint,0,0); } void Joint::attach(const Body* body) { dJointAttach(_joint,body->getBodyID(),0); } void Joint::attach(const Body* body_a,const Body* body_b) { dJointAttach(_joint,body_a->getBodyID(),body_b->getBodyID()); } const Vector3& Joint::getFirstForce() { assert(dJointGetFeedback(_joint) == &_feedback); _first_force.x = (f32)_feedback.f1[0]; _first_force.y = (f32)_feedback.f1[1]; _first_force.z = (f32)_feedback.f1[2]; return _first_force; } const Vector3& Joint::getFirstTorque() { assert(dJointGetFeedback(_joint) == &_feedback); _first_torque.x = (f32)_feedback.t1[0]; _first_torque.y = (f32)_feedback.t1[1]; _first_torque.z = (f32)_feedback.t1[2]; return _first_torque; } const Vector3& Joint::getSecondForce() { assert(dJointGetFeedback(_joint) == &_feedback); _second_force.x = (f32)_feedback.f2[0]; _second_force.y = (f32)_feedback.f2[1]; _second_force.z = (f32)_feedback.f2[2]; return _second_force; } const Vector3& Joint::getSecondTorque() { assert(dJointGetFeedback(_joint) == &_feedback); _second_torque.x = (f32)_feedback.t2[0]; _second_torque.y = (f32)_feedback.t2[1]; _second_torque.z = (f32)_feedback.t2[2]; return _second_torque; } void Joint::setParameter(JointParameter parameter,Real value,int axis) { } Real Joint::getParameter(JointParameter parameter,int axis) { return 0.0f; } BallJoint::BallJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateBall(getWorldID(),getJointGroupID(group)); registerJoint(); } void BallJoint::setAnchor(const Vector3& position) { dJointSetBallAnchor(_joint,(dReal)position.x,(dReal)position.y,(dReal)position.z); } const Vector3& BallJoint::getAnchor() { dVector3 result; dJointGetBallAnchor(_joint,result); _anchor.x = (Real)result[0]; _anchor.y = (Real)result[1]; _anchor.z = (Real)result[2]; return _anchor; } const Vector3& BallJoint::getAnchorError() { dVector3 result1,result2; dJointGetBallAnchor(_joint,result1); dJointGetBallAnchor2(_joint,result2); _anchor_error.x = (Real)(result1[0] - result2[0]); _anchor_error.y = (Real)(result1[1] - result2[1]); _anchor_error.z = (Real)(result1[2] - result2[2]); return _anchor_error; } void BallJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetBallParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real BallJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetBallParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); } BallJoint::~BallJoint() { } HingeJoint::HingeJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateHinge(getWorldID(),getJointGroupID(group)); registerJoint(); } void HingeJoint::setAnchor(const Vector3& position) { dJointSetHingeAnchor(_joint,(dReal)position.x,(dReal)position.y,(dReal)position.z); } void HingeJoint::addTorque(Real torque,Real torque2,Real torque3) { dJointAddHingeTorque(_joint,(dReal)torque); } const Vector3& HingeJoint::getAnchor() { dVector3 result; dJointGetHingeAnchor(_joint,result); _anchor.x = (Real)result[0]; _anchor.y = (Real)result[1]; _anchor.z = (Real)result[2]; return _anchor; } const Vector3& HingeJoint::getAnchorError() { dVector3 result1,result2; dJointGetHingeAnchor(_joint,result1); dJointGetHingeAnchor2(_joint,result2); _anchor_error.x = (Real)(result1[0] - result2[0]); _anchor_error.y = (Real)(result1[1] - result2[1]); _anchor_error.z = (Real)(result1[2] - result2[2]); return _anchor_error; } void HingeJoint::setAxis(const Vector3& axis) { dJointSetHingeAxis(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& HingeJoint::getAxis() { dVector3 result; dJointGetHingeAxis(_joint,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } Real HingeJoint::getAngle() { return (Real)dJointGetHingeAngle(_joint); } Real HingeJoint::getAngleRate() { return (Real)dJointGetHingeAngleRate(_joint); } void HingeJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetHingeParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real HingeJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetHingeParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); } HingeJoint::~HingeJoint() { } SliderJoint::SliderJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateSlider(getWorldID(),getJointGroupID(group)); registerJoint(); } void SliderJoint::setAxis(const Vector3& axis) { dJointSetSliderAxis(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& SliderJoint::getAxis() { dVector3 result; dJointGetSliderAxis(_joint,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } void SliderJoint::addForce(Real force,Real force2,Real force3) { dJointAddSliderForce(_joint,(dReal)force); } Real SliderJoint::getPosition() { return (Real)dJointGetSliderPosition(_joint); } Real SliderJoint::getPositionRate() { return (Real)dJointGetSliderPositionRate(_joint); } void SliderJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetSliderParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real SliderJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetSliderParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); } SliderJoint::~SliderJoint() { } UniversalJoint::UniversalJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateUniversal(getWorldID(),getJointGroupID(group)); registerJoint(); } void UniversalJoint::setAnchor(const Vector3& position) { dJointSetUniversalAnchor(_joint,(dReal)position.x,(dReal)position.y,(dReal)position.z); } void UniversalJoint::addTorque(Real torque,Real torque2,Real torque3) { dJointAddUniversalTorques(_joint,(dReal)torque,(dReal)torque2); } const Vector3& UniversalJoint::getAnchor() { dVector3 result; dJointGetUniversalAnchor(_joint,result); _anchor.x = (Real)result[0]; _anchor.y = (Real)result[1]; _anchor.z = (Real)result[2]; return _anchor; } const Vector3& UniversalJoint::getAnchorError() { dVector3 result1,result2; dJointGetUniversalAnchor(_joint,result1); dJointGetUniversalAnchor2(_joint,result2); _anchor_error.x = (Real)(result1[0] - result2[0]); _anchor_error.y = (Real)(result1[1] - result2[1]); _anchor_error.z = (Real)(result1[2] - result2[2]); return _anchor_error; } void UniversalJoint::setAxis(const Vector3& axis) { dJointSetUniversalAxis1(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& UniversalJoint::getAxis() { dVector3 result; dJointGetUniversalAxis1(_joint,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } void UniversalJoint::setAdditionalAxis(const Vector3& axis) { dJointSetUniversalAxis2(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& UniversalJoint::getAdditionalAxis() { dVector3 result; dJointGetUniversalAxis2(_joint,result); _additional_axis.x = (Real)result[0]; _additional_axis.y = (Real)result[1]; _additional_axis.z = (Real)result[2]; return _additional_axis; } void UniversalJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetUniversalParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real UniversalJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetUniversalParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); } UniversalJoint::~UniversalJoint() { } FixedJoint::FixedJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateFixed(getWorldID(),getJointGroupID(group)); registerJoint(); } void FixedJoint::attach(const Body* body) { Joint::attach(body); dJointSetFixed(_joint); } void FixedJoint::attach(const Body* body_a,const Body* body_b) { Joint::attach(body_a,body_b); dJointSetFixed(_joint); } FixedJoint::~FixedJoint() { } SuspensionJoint::SuspensionJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateHinge2(getWorldID(),getJointGroupID(group)); registerJoint(); } void SuspensionJoint::setAnchor(const Vector3& position) { dJointSetHinge2Anchor(_joint,(dReal)position.x,(dReal)position.y,(dReal)position.z); } void SuspensionJoint::addTorque(Real torque,Real torque2,Real torque3) { dJointAddHinge2Torques(_joint,(dReal)torque,(dReal)torque2); } const Vector3& SuspensionJoint::getAnchor() { dVector3 result; dJointGetHinge2Anchor(_joint,result); _anchor.x = (Real)result[0]; _anchor.y = (Real)result[1]; _anchor.z = (Real)result[2]; return _anchor; } const Vector3& SuspensionJoint::getAdditionalAnchor() { dVector3 result; dJointGetHinge2Anchor2(_joint,result); _anchor2.x = (Real)result[0]; _anchor2.y = (Real)result[1]; _anchor2.z = (Real)result[2]; return _anchor2; } const Vector3& SuspensionJoint::getAnchorError() { dVector3 result1,result2; dJointGetHinge2Anchor(_joint,result1); dJointGetHinge2Anchor2(_joint,result2); _anchor_error.x = (Real)(result1[0] - result2[0]); _anchor_error.y = (Real)(result1[1] - result2[1]); _anchor_error.z = (Real)(result1[2] - result2[2]); return _anchor_error; } void SuspensionJoint::setAxis(const Vector3& axis) { dJointSetHinge2Axis1(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& SuspensionJoint::getAxis() { dVector3 result; dJointGetHinge2Axis1(_joint,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } void SuspensionJoint::setAdditionalAxis(const Vector3& axis) { dJointSetHinge2Axis2(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& SuspensionJoint::getAdditionalAxis() { dVector3 result; dJointGetHinge2Axis2(_joint,result); _additional_axis.x = (Real)result[0]; _additional_axis.y = (Real)result[1]; _additional_axis.z = (Real)result[2]; return _additional_axis; } Real SuspensionJoint::getAngle() { return (Real)dJointGetHinge2Angle1(_joint); } Real SuspensionJoint::getAngleRate() { return (Real)dJointGetHinge2Angle1Rate(_joint); } Real SuspensionJoint::getPositionRate() { return (Real)dJointGetHinge2Angle2Rate(_joint); } void SuspensionJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetHinge2Param(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real SuspensionJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetHinge2Param(_joint,((int)parameter) + dParamGroup * (axis - 1)); } SuspensionJoint::~SuspensionJoint() { } AngularMotorJoint::AngularMotorJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreateAMotor(getWorldID(),getJointGroupID(group)); registerJoint(); } void AngularMotorJoint::setMode(AngularMotorJoint::Mode mode) { dJointSetAMotorMode(_joint,(int)mode); } AngularMotorJoint::Mode AngularMotorJoint::getMode() { return (AngularMotorJoint::Mode)dJointGetAMotorMode(_joint); } void AngularMotorJoint::addTorque(Real torque,Real torque2,Real torque3) { dJointAddAMotorTorques(_joint,(dReal)torque,(dReal)torque2,(dReal)torque3); } void AngularMotorJoint::setAxisCount(int axes) { assert((axes >= 0) && (axes <= 3)); dJointSetAMotorNumAxes(_joint,axes); } int AngularMotorJoint::getAxisCount() { return dJointGetAMotorNumAxes(_joint); } void AngularMotorJoint::setAxis(int axis_number,AngularMotorJoint::RelativeOrientation orientation,const Vector3& axis) { dJointSetAMotorAxis(_joint,axis_number,(int)orientation,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& AngularMotorJoint::getAxis(int axis_number) { dVector3 result; dJointGetAMotorAxis(_joint,axis_number,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } AngularMotorJoint::RelativeOrientation AngularMotorJoint::getAxisRelativeOrientation(int axis_number) { return (AngularMotorJoint::RelativeOrientation)dJointGetAMotorAxisRel(_joint,axis_number); } void AngularMotorJoint::setAngle(int axis,Real angle) { dJointSetAMotorAngle(_joint,axis,(dReal)angle); } Real AngularMotorJoint::getAngle(int axis) { return (Real)dJointGetAMotorAngle(_joint,axis); } Real AngularMotorJoint::getAngleRate(int axis) { return (Real)dJointGetAMotorAngleRate(_joint,axis); } void AngularMotorJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetAMotorParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real AngularMotorJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetAMotorParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); } AngularMotorJoint::~AngularMotorJoint() { } PlanarJoint::PlanarJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreatePlane2D(getWorldID(),getJointGroupID(group)); registerJoint(); } void PlanarJoint::setParameterX(JointParameter parameter,Real value,int axis) { dJointSetPlane2DXParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } void PlanarJoint::setParameterY(JointParameter parameter,Real value,int axis) { dJointSetPlane2DYParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } void PlanarJoint::setParameterAngle(JointParameter parameter,Real value,int axis) { dJointSetPlane2DAngleParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } PlanarJoint::~PlanarJoint() { } SliderHingeJoint::SliderHingeJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreatePR(getWorldID(),getJointGroupID(group)); registerJoint(); } SliderHingeJoint::~SliderHingeJoint() { } void SliderHingeJoint::setAnchor(const Vector3& position) { dJointSetPRAnchor(_joint,(dReal)position.x,(dReal)position.y,(dReal)position.z); } const Vector3& SliderHingeJoint::getAnchor() { dVector3 result; dJointGetPRAnchor(_joint,result); _anchor.x = (Real)result[0]; _anchor.y = (Real)result[1]; _anchor.z = (Real)result[2]; return _anchor; } Real SliderHingeJoint::getPosition() { return (Real)dJointGetPRPosition(_joint); } Real SliderHingeJoint::getPositionRate() { return (Real)dJointGetPRPositionRate(_joint); } void SliderHingeJoint::setAxis(const Vector3& axis) { dJointSetPRAxis1(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& SliderHingeJoint::getAxis() { dVector3 result; dJointGetPRAxis1(_joint,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } void SliderHingeJoint::setAdditionalAxis(const Vector3& axis) { dJointSetPRAxis2(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& SliderHingeJoint::getAdditionalAxis() { dVector3 result; dJointGetPRAxis2(_joint,result); _additional_axis.x = (Real)result[0]; _additional_axis.y = (Real)result[1]; _additional_axis.z = (Real)result[2]; return _additional_axis; } void SliderHingeJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetPRParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real SliderHingeJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetPRParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); } void SliderHingeJoint::addTorque(Real torque,Real torque2,Real torque3) { dJointAddPRTorque(_joint, (dReal)torque); } PistonJoint::PistonJoint(World *world, const JointGroup* group) : Joint(world, group) { _joint = dJointCreatePiston(getWorldID(), getJointGroupID(group)); registerJoint(); } void PistonJoint::setAnchor(const Vector3& position) { dJointSetPistonAnchor(_joint,(dReal)position.x,(dReal)position.y,(dReal)position.z); } const Vector3& PistonJoint::getAnchor() { dVector3 result; dJointGetPistonAnchor(_joint,result); _anchor.x = (Real)result[0]; _anchor.y = (Real)result[1]; _anchor.z = (Real)result[2]; return _anchor; } const Vector3& PistonJoint::getAnchorError() { dVector3 result1,result2; dJointGetPistonAnchor(_joint,result1); dJointGetPistonAnchor2(_joint,result2); _anchor_error.x = (Real)(result1[0] - result2[0]); _anchor_error.y = (Real)(result1[1] - result2[1]); _anchor_error.z = (Real)(result1[2] - result2[2]); return _anchor_error; } void PistonJoint::setAxis(const Vector3& axis) { dJointSetPistonAxis(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z); } const Vector3& PistonJoint::getAxis() { dVector3 result; dJointGetPistonAxis(_joint,result); _axis.x = (Real)result[0]; _axis.y = (Real)result[1]; _axis.z = (Real)result[2]; return _axis; } void PistonJoint::setAxisDelta(const Vector3& axis, const Vector3& initalPosition) { dJointSetPistonAxisDelta(_joint,(dReal)axis.x,(dReal)axis.y,(dReal)axis.z, (dReal)initalPosition.x,(dReal)initalPosition.y,(dReal)initalPosition.z); } Real PistonJoint::getPosition() { return (Real)dJointGetPistonPosition(_joint); } Real PistonJoint::getPositionRate() { return (Real)dJointGetPistonPositionRate(_joint); } Real PistonJoint::getAngle() { return (Real)dJointGetPistonAngle(_joint); } Real PistonJoint::getAngleRate() { return (Real)dJointGetPistonAngleRate(_joint); } void PistonJoint::addForce(Real force,Real force2,Real force3) { dJointAddPistonForce(_joint,(dReal)force); } void PistonJoint::setParameter(JointParameter parameter,Real value,int axis) { dJointSetPistonParam(_joint,((int)parameter) + dParamGroup * (axis - 1),(dReal)value); } Real PistonJoint::getParameter(JointParameter parameter,int axis) { return (Real)dJointGetPistonParam(_joint,((int)parameter) + dParamGroup * (axis - 1)); }
23.060811
119
0.740941
[ "geometry" ]
1d450ce54c27d3e429d18e688401c26ce3ebc152
13,316
hpp
C++
src/strads/ds/spmat.hpp
ForrestGan/public
2cada36c4b523cf80f16a4f0d0fdc01166a69df1
[ "BSD-3-Clause" ]
null
null
null
src/strads/ds/spmat.hpp
ForrestGan/public
2cada36c4b523cf80f16a4f0d0fdc01166a69df1
[ "BSD-3-Clause" ]
null
null
null
src/strads/ds/spmat.hpp
ForrestGan/public
2cada36c4b523cf80f16a4f0d0fdc01166a69df1
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2014, Sailing Lab // 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. Neither the name of the <ORGANIZATION> 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 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. #pragma once #include <map> #include <unordered_map> #include <vector> #include <iostream> #include <iomanip> #include <assert.h> #include <stdlib.h> #include "./include/utility.hpp" class spmat_vector{ public: spmat_vector(){} ~spmat_vector(){} uint64_t size(){ assert(idx.size() == val.size()); return idx.size(); } double add(long unsigned int id, double value){ idx.push_back(id); val.push_back(value); return value; } double add_with_sorting(long unsigned int id, double value){ if(idx.size() == 0){ idx.push_back(id); val.push_back(value); }else{ assert(idx.size() == val.size()); std::vector<long unsigned int>::iterator idxiter = idx.begin(); std::vector<double>::iterator valiter = val.begin(); while(1){ assert(*idxiter != id); if(id < *idxiter) { idx.insert(idxiter, id); val.insert(valiter, value); break; }else if(id > *idxiter){ idxiter++; valiter++; if(idxiter == idx.end()){ assert(valiter == val.end()); idx.push_back(id); val.push_back(value); break; } } // if(id < *idxiter..... }// while(1) ... }// if(idx.size() == 0) return value; } std::vector<long unsigned int> idx; std::vector<double> val; }; // ingredient for vector based sparse matrix /* row major vector based sparse matrix * row is stored in s a vector * empty row is not assgined a vector * dats structure: vector of vector */ class row_vspmat { public: row_vspmat(){ } row_vspmat(long unsigned int n, long unsigned int m) : m_size_n(n), m_size_m(m), m_rows(n) { strads_msg(ERR, "row_vspmat constructor\n"); } ~row_vspmat() {} spmat_vector & row(long unsigned int i) { return m_rows[i]; } double add(long unsigned int i, long unsigned int j, double value) { return m_rows[i].add(j, value); } // row major matrix, and insert column in sorted way double add_with_col_sorting(long unsigned int i, long unsigned int j, double value) { return m_rows[i].add_with_sorting(j, value); // return m_rows[i].add(j, value); } long unsigned int row_size(){ return m_size_n; } long unsigned int col_size(){ return m_size_m; } long unsigned int allocatedentry(void) { long unsigned int alloc=0; for(uint64_t i=0; i < m_size_n; i++){ alloc += m_rows[i].size(); } return alloc; } void resize(long unsigned int const n, long unsigned int const m) { m_size_n = n; m_size_m = m; } private: long unsigned int m_size_n; long unsigned int m_size_m; std::vector<spmat_vector> m_rows; // push_back }; /* column major vector based sparse matrix * each column is stored in a vector * empty column is not assigned a vector * dats structure: vector of vector */ class col_vspmat { public: col_vspmat(){} col_vspmat(long unsigned int n, long unsigned int m) : m_size_n(n), m_size_m(m), m_cols(m) { strads_msg(ERR, "col_vspmat constructor\n"); } ~col_vspmat() {} spmat_vector & col(long unsigned int i) { return m_cols[i]; } double add(long unsigned int i, long unsigned int j, double value) { return m_cols[j].add(i, value); } double add_with_row_sorting(long unsigned int i, long unsigned int j, double value){ return m_cols[j].add_with_sorting(i, value); } long unsigned int row_size(){ return m_size_n; } long unsigned int col_size(){ return m_size_m; } long unsigned int allocatedentry(void) { long unsigned int alloc=0; for(uint64_t i=0; i < m_size_m; i++){ alloc += m_cols[i].size(); } return alloc; } void resize(long unsigned int const n, long unsigned int const m) { m_size_n = n; m_size_m = m; } private: long unsigned int m_size_n; long unsigned int m_size_m; std::vector<spmat_vector> m_cols; }; /* row major listed based sparse matrix * each row is represented in a map * empty row is not assigned a map * data structure vector of map */ class row_spmat { public: typedef typename std::vector<std::unordered_map<long unsigned int, double> > row_type; typedef typename row_type::iterator iterator; typedef typename row_type::const_iterator const_iterator; row_spmat(): m_range_flag(false) {} row_spmat(long unsigned int n, long unsigned int m) : m_size_n(n), m_size_m(m), m_rows(n), m_range_flag(false) { strads_msg(ERR, "row_spmat constructor\n"); } ~row_spmat() { strads_msg(ERR, "row_spmat destructor is called\n"); for(long unsigned int i=0; i < m_size_n; i++){ m_rows[i].erase(m_rows[i].begin(), m_rows[i].end()); } } std::unordered_map<long unsigned int, double> & row(long unsigned int i) { return m_rows[i]; } std::unordered_map<long unsigned int, double> & operator[](long unsigned int i) { return row(i); } double & operator()(long unsigned int i, long unsigned int j) { return m_rows[i][j]; } double & set(long unsigned int i, long unsigned int j) { return m_rows[i][j]; } long unsigned int row_size(){ return m_size_n; } long unsigned int col_size(){ return m_size_m; } iterator begin() { return m_rows.begin(); } const_iterator begin() const { return m_rows.cbegin(); } const_iterator cbegin() const { return m_rows.cbegin(); } iterator end() { return m_rows.begin(); } const_iterator end() const { return m_rows.cbegin(); } const_iterator cend() const { return m_rows.cbegin(); } double get(long unsigned int const i, long unsigned int const j) { if(m_range_flag){ if( i >= m_row_start && i <= m_row_end){ }else{ strads_msg(ERR, "Out Of ROW Range start: %ld end: %ld \n", m_row_start , m_row_end); } } if(m_rows[i].find(j) != m_rows[i].cend()) { return m_rows[i][j]; } else { return 0.0; } } void set_range(bool const flag, long unsigned int const row_start, long unsigned int const row_end){ m_range_flag = flag; m_row_start = row_start; m_row_end = row_end; } long unsigned int allocatedentry(void) { long unsigned int alloc=0; for(uint64_t i=0; i < m_size_n; i++){ alloc += m_rows[i].size(); } return alloc; } void resize(long unsigned int const n, long unsigned int const m) { m_size_n = n; m_size_m = m; } private: long unsigned int m_size_n; long unsigned int m_size_m; std::vector<std::unordered_map<long unsigned int, double> > m_rows; bool m_range_flag; long unsigned int m_row_start; long unsigned int m_row_end; }; /* column major listed based sparse matrix * each col is represented in a map * empty col is not assigned a map * data structure vector of map */ class col_spmat { public: typedef typename std::vector<std::unordered_map<long unsigned int, double> > col_type; typedef typename col_type::iterator iterator; typedef typename col_type::const_iterator const_iterator; col_spmat(): m_range_flag(false) { } col_spmat(long unsigned int n, long unsigned int m) : m_size_n(n), m_size_m(m), m_cols(m), m_range_flag(false) { strads_msg(ERR, " col_spmat is called m_size_m CONSTRUCTOR %ld \n", m_size_m); } ~col_spmat() { } std::unordered_map<long unsigned int, double> & col(long unsigned int i) { return m_cols[i]; } std::unordered_map<long unsigned int, double> & operator[](long unsigned int i) { return col(i); } double & operator()(long unsigned int i, long unsigned int j) { return m_cols[j][i]; } double & set(long unsigned int i, long unsigned int j) { return m_cols[j][i]; } iterator begin() { return m_cols.begin(); } const_iterator begin() const { return m_cols.cbegin(); } const_iterator cbegin() const { return m_cols.cbegin(); } iterator end() { return m_cols.begin(); } const_iterator end() const { return m_cols.cbegin(); } const_iterator cend() const { return m_cols.cbegin(); } long unsigned int row_size(){ return m_size_n; } long unsigned int col_size(){ return m_size_m; } void resize(long unsigned int const n, long unsigned int const m) { m_size_n = n; m_size_m = m; } double get(long unsigned int const i, long unsigned int const j) { if(m_range_flag){ if( j >= m_col_start && j <= m_col_end){ }else{ // std::cout << "Out Of col Range start: " << m_col_start << " end: " << m_col_end << std::endl; strads_msg(ERR, "Out Of col Range start: %ld end: %ld\n ", m_col_start, m_col_end); } } if(m_cols[j].find(i) != m_cols[j].cend()) { return m_cols[j][i]; } else { return 0.0; } } void set_range(bool const flag, long unsigned int const col_start, long unsigned int const col_end){ m_range_flag = flag; m_col_start = col_start; m_col_end = col_end; } long unsigned int allocatedentry(void) { long unsigned int alloc=0; for(uint64_t i=0; i < m_size_m; i++){ alloc += m_cols[i].size(); } return alloc; } private: long unsigned int m_size_n; long unsigned int m_size_m; std::vector<std::unordered_map<long unsigned int, double> > m_cols; bool m_range_flag; long unsigned int m_col_start; long unsigned int m_col_end; }; /* row major distributed dense matrix * each row is represented in dense array (0-N elements) * empty row is not assigned a dense array * data structure array of array * TODO: add col major one as well */ class dense2dmat { public: dense2dmat() : m_samples_n(0), m_cols_n(0) { // std::cout << "Dense 2 D mat Constructor without memory allocation " << std::endl; strads_msg(ERR, "Dense 2 D mat Constructor without memory allocation\n"); } ~dense2dmat(){ } dense2dmat(unsigned int long rows, unsigned int long cols) : m_samples_n(rows), m_cols_n(cols) { strads_msg(ERR, "Dense 2 D mat Constructor with memory allocation\n"); m_mem = (double **)calloc(m_samples_n, sizeof(double *)); assert(m_mem); for(unsigned int long i=0; i<m_samples_n; i++){ m_mem[i] = (double *)calloc(m_cols_n, sizeof(double)); assert(m_mem[i] != NULL); } strads_msg(ERR, "dense 2dmat is called. memalloc is done m_samples: %ld m_cols: %ld\n", m_samples_n, m_cols_n); } void resize(long unsigned int const n, long unsigned int const m) { m_samples_n = n; m_cols_n = m; m_mem = (double **)calloc(m_samples_n, sizeof(double *)); assert(m_mem); for(unsigned int long i=0; i<m_samples_n; i++){ m_mem[i] = (double *)calloc(m_cols_n, sizeof(double)); assert(m_mem[i] != NULL); } } void resize(long unsigned int const n, long unsigned int const m, long unsigned int row_s, long unsigned int row_e) { m_samples_n = n; m_cols_n = m; m_row_s = row_s; m_row_e = row_e; m_mem = (double **)calloc(m_samples_n, sizeof(double *)); assert(m_mem); for(unsigned int long i=m_row_s; i<=m_row_e; i++){ m_mem[i] = (double *)calloc(m_cols_n, sizeof(double)); assert(m_mem[i] != NULL); } } void droprows(long unsigned int row_s, long unsigned int row_e) { if(row_s != m_row_s || row_e != m_row_e){ strads_msg(ERR, " dense 2dmat drop range does not match ... fatal\n"); assert(0); exit(0); } for(unsigned int long i=m_row_s; i<=m_row_e; i++){ assert(m_mem[i] != NULL); free(m_mem[i]); } m_row_s = 0; m_row_e = 0; } void size() { strads_msg(ERR, "Allocated dense2mat size samples: %ld columns %ld \n", m_samples_n, m_cols_n); } double & operator()(long unsigned int i, long unsigned int j){ return m_mem[i][j]; } double **m_mem; unsigned int long m_samples_n; unsigned int long m_cols_n; unsigned int long m_row_s; unsigned int long m_row_e; };
30.824074
123
0.664989
[ "vector" ]
1d473f47fbedc5fd646ff12fd3a33825c7710f01
2,599
cpp
C++
ESP8266/app/OTA_functions.cpp
lxkarthi/SHARP
60a547966f7d6475ba44346116065f190c9abbb8
[ "Apache-2.0" ]
null
null
null
ESP8266/app/OTA_functions.cpp
lxkarthi/SHARP
60a547966f7d6475ba44346116065f190c9abbb8
[ "Apache-2.0" ]
null
null
null
ESP8266/app/OTA_functions.cpp
lxkarthi/SHARP
60a547966f7d6475ba44346116065f190c9abbb8
[ "Apache-2.0" ]
null
null
null
/* * OTA_functions.cpp * * Created on: Jul 19, 2016 * Author: Karthikeyan Natarajan */ #include <user_config.h> #include <SmingCore/SmingCore.h> #include "common_functions.h" rBootHttpUpdate* otaUpdater = 0; void OtaUpdate_CallBack(bool result) { printTo("In callback...", SERIAL); if(result == true) { // success uint8 slot; slot = rboot_get_current_rom(); if (slot == 0) slot = 1; else slot = 0; // set to boot new rom and then reboot printTo("Firmware updated, rebooting to rom " + String(slot), SERIAL); printTo("Firmware updated, rebooting to rom " + String(slot), MQTT); rboot_set_current_rom(slot); System.restart(); } else { // fail printTo("Firmware update failed!", SERIAL); printTo("Firmware update failed!", MQTT); } } void OtaUpdate(String URL="") { uint8 slot; rboot_config bootconf; Serial.println("Updating..."); // need a clean object, otherwise if run before and failed will not run again if (otaUpdater) delete otaUpdater; otaUpdater = new rBootHttpUpdate(); // select rom slot to flash bootconf = rboot_get_config(); slot = bootconf.current_rom; if (slot == 0) slot = 1; else slot = 0; #ifndef RBOOT_TWO_ROMS if (URL == "") URL = ROM_0_URL; else URL = URL + "/rom0.bin"; #else // flash appropriate rom if (slot == 0) { if (URL == "") URL = ROM_0_URL; else URL = URL + "/rom0.bin"; } else { if (URL == "") URL = ROM_1_URL; else URL = URL + "/rom1.bin"; } #endif printTo("update URL: " + URL, SERIAL|MQTT); // flash rom to position indicated in the rBoot config rom table otaUpdater->addItem(bootconf.roms[slot], URL); #ifndef DISABLE_SPIFFS // use user supplied values (defaults for 4mb flash in makefile) if (slot == 0) { otaUpdater->addItem(RBOOT_SPIFFS_0, SPIFFS_URL); } else { otaUpdater->addItem(RBOOT_SPIFFS_1, SPIFFS_URL); } #endif // request switch and reboot on success //otaUpdater->switchToRom(slot); // and/or set a callback (called on failure or success without switching requested) otaUpdater->setCallback(OtaUpdate_CallBack); // start update otaUpdater->start(); } void Switch() { uint8 before, after; before = rboot_get_current_rom(); if (before == 0) after = 1; else after = 0; printTo("Swapping from rom " + String(before) + " to rom " + String(after), SERIAL); printTo("Swapping from rom " + String(before) + " to rom " + String(after), MQTT); rboot_set_current_rom(after); printTo("Restarting...\r\n", SERIAL); printTo("Restarting...\r\n", MQTT); //TODO wait for sometime before restart to know that publish succeeded. System.restart(); }
24.990385
85
0.679107
[ "object" ]
1d495dee938fafce40065af58d83f9b41dfaa8ba
32,766
cxx
C++
IO/IOSS/vtkIOSSModel.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
IO/IOSS/vtkIOSSModel.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
IO/IOSS/vtkIOSSModel.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkIOSSModel.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkIOSSModel.h" #include "vtkArrayDispatch.h" #include "vtkCellData.h" #include "vtkDataArrayRange.h" #include "vtkDataAssembly.h" #include "vtkDummyController.h" #include "vtkIOSSUtilities.h" #include "vtkIOSSWriter.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkMultiProcessController.h" #include "vtkObjectFactory.h" #include "vtkPartitionedDataSet.h" #include "vtkPartitionedDataSetCollection.h" #include "vtkPointData.h" #include "vtkSMPTools.h" #include "vtkSmartPointer.h" #include "vtkUnsignedCharArray.h" #include "vtkUnstructuredGrid.h" #include <vtksys/MD5.h> // Ioss includes #include <vtk_ioss.h> // clang-format off #include VTK_IOSS(Ioss_Assembly.h) #include VTK_IOSS(Ioss_DatabaseIO.h) #include VTK_IOSS(Ioss_EdgeBlock.h) #include VTK_IOSS(Ioss_EdgeSet.h) #include VTK_IOSS(Ioss_ElementBlock.h) #include VTK_IOSS(Ioss_ElementSet.h) #include VTK_IOSS(Ioss_ElementTopology.h) #include VTK_IOSS(Ioss_FaceBlock.h) #include VTK_IOSS(Ioss_FaceSet.h) #include VTK_IOSS(Ioss_IOFactory.h) #include VTK_IOSS(Ioss_NodeBlock.h) #include VTK_IOSS(Ioss_NodeSet.h) #include VTK_IOSS(Ioss_Region.h) #include VTK_IOSS(Ioss_SideBlock.h) #include VTK_IOSS(Ioss_SideSet.h) #include VTK_IOSS(Ioss_StructuredBlock.h) // clang-format on #include <map> #include <set> #include <numeric> namespace { std::set<unsigned int> GetDatasetIndices(vtkDataAssembly* assembly, const char* name) { if (assembly && assembly->GetRootNodeName() && strcmp(assembly->GetRootNodeName(), "IOSS") == 0) { const auto idx = assembly->FindFirstNodeWithName(name); if (idx != -1) { const auto vector = assembly->GetDataSetIndices(assembly->FindFirstNodeWithName(name)); return std::set<unsigned int>{ vector.begin(), vector.end() }; } } return {}; } std::map<unsigned char, int64_t> GetElementCounts( vtkPartitionedDataSet* pd, vtkMultiProcessController* controller) { std::set<unsigned char> cellTypes; auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd); for (auto& ug : datasets) { auto* distinctCellTypes = ug->GetDistinctCellTypesArray(); auto range = vtk::DataArrayValueRange(distinctCellTypes); std::copy(range.begin(), range.end(), std::inserter(cellTypes, cellTypes.end())); } // now reduce this across all ranks as well. if (controller->GetNumberOfProcesses() > 1) { vtkNew<vtkUnsignedCharArray> source; source->SetNumberOfTuples(cellTypes.size()); std::copy(cellTypes.begin(), cellTypes.end(), source->GetPointer(0)); vtkNew<vtkUnsignedCharArray> result; controller->AllGatherV(source, result); auto range = vtk::DataArrayValueRange(result); std::copy(range.begin(), range.end(), std::inserter(cellTypes, cellTypes.end())); } // compute element counts std::map<unsigned char, std::atomic<int64_t>> elementCounts; for (auto& type : cellTypes) { elementCounts[type] = 0; } for (auto& ug : datasets) { vtkSMPTools::For(0, ug->GetNumberOfCells(), [&](vtkIdType start, vtkIdType end) { for (vtkIdType cc = start; cc < end; ++cc) { ++elementCounts[static_cast<unsigned char>(ug->GetCellType(cc))]; } }); } return { elementCounts.begin(), elementCounts.end() }; } Ioss::Field::BasicType GetFieldType(vtkDataArray* array) { if (array->GetDataType() == VTK_DOUBLE || array->GetDataType() == VTK_FLOAT) { return Ioss::Field::DOUBLE; } else if (array->GetDataTypeSize() <= 32) { return Ioss::Field::INT32; } else { return Ioss::Field::INT64; } } std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> GetFields( int association, vtkCompositeDataSet* pdc, vtkMultiProcessController* vtkNotUsed(controller)) { std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> fields; vtkDataSetAttributesFieldList fieldList; for (auto& ds : vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pdc)) { fieldList.IntersectFieldList(ds->GetAttributes(association)); } vtkNew<vtkPointData> tmp; tmp->CopyAllocate(fieldList, 0); for (int idx = 0, max = tmp->GetNumberOfArrays(); idx < max; ++idx) { if (auto* array = tmp->GetArray(idx)) { if (array == tmp->GetGlobalIds()) { // we don't want to add global ids again. continue; } if (strcmp(array->GetName(), "object_id") == 0) { // skip "object_id". that's an array added by Ioss reader. continue; } const auto type = ::GetFieldType(array); fields.emplace_back(array->GetName(), type, array->GetNumberOfComponents()); } } // TODO: reduce in parallel; for non IOSS input, we'll need to explicitly // ensure all blocks have same fields across all ranks. return fields; } template <typename T> struct PutFieldWorker { std::vector<std::vector<T>> Data; size_t Offset{ 0 }; const std::vector<vtkIdType>* SourceIds = nullptr; PutFieldWorker(int numComponents, size_t targetSize) : Data(numComponents) { for (int cc = 0; cc < numComponents; ++cc) { this->Data[cc].resize(targetSize); } } void SetSourceIds(const std::vector<vtkIdType>* ids) { this->SourceIds = ids; } template <typename ArrayType> void operator()(ArrayType* array) { using SourceT = vtk::GetAPIType<ArrayType>; vtkSMPTools::For(0, this->SourceIds->size(), [&](vtkIdType start, vtkIdType end) { SourceT* tuple = new SourceT[this->Data.size()]; for (vtkIdType cc = start; cc < end; ++cc) { array->GetTypedTuple((*this->SourceIds)[cc], tuple); for (size_t comp = 0; comp < this->Data.size(); ++comp) { this->Data[comp][this->Offset + cc] = tuple[comp]; } } delete[] tuple; }); this->Offset += this->SourceIds->size(); } }; template <typename T> struct DisplacementWorker { std::vector<std::vector<T>>& Data; size_t Offset{ 0 }; double Magnitude; const std::vector<vtkIdType>* SourceIds = nullptr; DisplacementWorker(std::vector<std::vector<T>>& data, double magnitude) : Data(data) , Magnitude(magnitude) { } void SetSourceIds(const std::vector<vtkIdType>* ids) { this->SourceIds = ids; } template <typename ArrayType> void operator()(ArrayType* array) { using SourceT = vtk::GetAPIType<ArrayType>; vtkSMPTools::For(0, this->SourceIds->size(), [&](vtkIdType start, vtkIdType end) { SourceT* displ = new SourceT[this->Data.size()]; for (vtkIdType cc = start; cc < end; ++cc) { array->GetTypedTuple((*this->SourceIds)[cc], displ); for (size_t comp = 0; comp < this->Data.size(); ++comp) { this->Data[comp][this->Offset + cc] -= (displ[comp] * this->Magnitude); } } delete[] displ; }); this->Offset += this->SourceIds->size(); } }; struct vtkGroupingEntity { vtkIOSSWriter* Writer = nullptr; vtkGroupingEntity(vtkIOSSWriter* writer) : Writer(writer) { } virtual ~vtkGroupingEntity() = default; virtual void Define(Ioss::Region& region) const = 0; virtual void Model(Ioss::Region& region) const = 0; virtual void DefineTransient(Ioss::Region& region) const = 0; virtual void Transient(Ioss::Region& region) const = 0; virtual void AppendMD5(vtksysMD5* md5) const = 0; protected: template <typename IossGroupingEntityT, typename DatasetT> void PutFields(IossGroupingEntityT* block, const std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>>& fields, const std::vector<std::vector<vtkIdType>>& lIds, const std::vector<DatasetT*>& datasets, int association) const { for (const auto& field : fields) { switch (std::get<1>(field)) { case Ioss::Field::DOUBLE: this->PutField<double>( block, std::get<0>(field), std::get<2>(field), lIds, datasets, association); break; case Ioss::Field::INT32: this->PutField<int32_t>( block, std::get<0>(field), std::get<2>(field), lIds, datasets, association); break; case Ioss::Field::INT64: this->PutField<int64_t>( block, std::get<0>(field), std::get<2>(field), lIds, datasets, association); break; default: vtkLogF(TRACE, "Unsupported field type. Skipping %s", std::get<0>(field).c_str()); break; } } } template <typename T, typename IossGroupingEntityT, typename DatasetT> void PutField(IossGroupingEntityT* block, const std::string& name, int numComponents, const std::vector<std::vector<vtkIdType>>& lIds, const std::vector<DatasetT*>& datasets, int association) const { assert(datasets.size() == lIds.size()); const size_t totalSize = std::accumulate(lIds.begin(), lIds.end(), static_cast<size_t>(0), [](size_t sum, const std::vector<vtkIdType>& ids) { return sum + ids.size(); }); using Dispatcher = vtkArrayDispatch::DispatchByValueType<vtkArrayDispatch::AllTypes>; PutFieldWorker<T> worker(numComponents, totalSize); for (size_t dsIndex = 0; dsIndex < datasets.size(); ++dsIndex) { auto& ds = datasets[dsIndex]; auto& lids = lIds[dsIndex]; worker.SetSourceIds(&lids); Dispatcher::Execute(ds->GetAttributes(association)->GetArray(name.c_str()), worker); } for (int comp = 0; comp < numComponents; ++comp) { const auto fieldName = numComponents == 1 ? name : name + std::to_string(comp + 1); block->put_field_data(fieldName, worker.Data[comp]); } } void DefineFields(Ioss::GroupingEntity* block, const std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>>& fields, Ioss::Field::RoleType role, int64_t elementCount) const { for (const auto& field : fields) { if (std::get<2>(field) == 1) { block->field_add( Ioss::Field(std::get<0>(field), std::get<1>(field), "scalar", role, elementCount)); } else { for (int comp = 0; comp < std::get<2>(field); ++comp) { block->field_add(Ioss::Field(std::get<0>(field) + std::to_string(comp + 1), std::get<1>(field), "scalar", role, elementCount)); } } } } }; } // end namespace {} /** * Builds an Ioss::NodeBlock. Since an exodus file has a single common node * block, we need to build one based on all points from all blocks. * * Another thing to handle is displacements. If input dataset is coming from * IOSS reader, the point coordinates may have been displaced using the * displacement vectors in the dataset. */ struct vtkNodeBlock : vtkGroupingEntity { const std::vector<vtkUnstructuredGrid*> DataSets; const std::string Name; // build a map of ds idx, gid, and lid and use that later. std::vector<int32_t> Ids; std::vector<std::vector<vtkIdType>> IdsRaw; std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> Fields; vtkNodeBlock(vtkPartitionedDataSetCollection* pdc, const std::string& name, vtkMultiProcessController* controller, vtkIOSSWriter* writer) : vtkGroupingEntity(writer) , DataSets{ vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pdc) } , Name(name) { this->IdsRaw.reserve(this->DataSets.size()); std::set<int32_t> id_set; for (auto& ds : this->DataSets) { auto* pd = ds->GetPointData(); auto* gids = vtkIdTypeArray::SafeDownCast(pd->GetGlobalIds()); if (!gids) { throw std::runtime_error("point global ids missing."); } const auto numPoints = ds->GetNumberOfPoints(); assert(gids->GetNumberOfTuples() == numPoints); this->Ids.reserve(this->Ids.size() + numPoints); this->IdsRaw.emplace_back(); this->IdsRaw.back().reserve(numPoints); const vtkIdType gidOffset = writer->GetOffsetGlobalIds() ? 1 : 0; for (vtkIdType cc = 0; cc < numPoints; ++cc) { const auto gid = gids->GetValue(cc); if (id_set.insert(gid).second) { this->Ids.push_back(gid + gidOffset); this->IdsRaw.back().push_back(cc); } } } assert(this->DataSets.size() == this->IdsRaw.size()); this->Fields = ::GetFields(vtkDataObject::POINT, pdc, controller); } void AppendMD5(vtksysMD5* md5) const override { vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&this->Ids[0]), static_cast<int>(sizeof(int32_t) * this->Ids.size())); } void Define(Ioss::Region& region) const override { auto* block = new Ioss::NodeBlock(region.get_database(), this->Name, this->Ids.size(), 3); // block->property_add(Ioss::Property("id", 1)); // block id. region.add(block); } void DefineTransient(Ioss::Region& region) const override { auto* block = region.get_node_block(this->Name); this->DefineFields(block, this->Fields, Ioss::Field::TRANSIENT, this->Ids.size()); } void Model(Ioss::Region& region) const override { auto* block = region.get_node_block(this->Name); block->put_field_data("ids", this->Ids); // add mesh coordinates using Dispatcher = vtkArrayDispatch::DispatchByValueType<vtkArrayDispatch::Reals>; PutFieldWorker<double> worker(3, this->Ids.size()); for (size_t dsIndex = 0; dsIndex < this->DataSets.size(); ++dsIndex) { auto& ds = this->DataSets[dsIndex]; auto& lids = this->IdsRaw[dsIndex]; worker.SetSourceIds(&lids); Dispatcher::Execute(ds->GetPoints()->GetData(), worker); } // if displacement array is present, offset the mesh coordinates by the // provided displacement. const auto displMagnitude = this->DataSets.empty() ? 0.0 : this->Writer->GetDisplacementMagnitude(); const std::string displName = displMagnitude > 0 ? vtkIOSSUtilities::GetDisplacementFieldName(this->DataSets.front()) : ""; if (!displName.empty() && displMagnitude > 0.0) { DisplacementWorker<double> dworker(worker.Data, displMagnitude); for (size_t dsIndex = 0; dsIndex < this->DataSets.size(); ++dsIndex) { auto& ds = this->DataSets[dsIndex]; auto& lids = this->IdsRaw[dsIndex]; dworker.SetSourceIds(&lids); Dispatcher::Execute(ds->GetPointData()->GetArray(displName.c_str()), dworker); } } block->put_field_data("mesh_model_coordinates_x", worker.Data[0]); block->put_field_data("mesh_model_coordinates_y", worker.Data[1]); block->put_field_data("mesh_model_coordinates_z", worker.Data[2]); } void Transient(Ioss::Region& region) const override { auto* block = region.get_node_block(this->Name); this->PutFields(block, this->Fields, this->IdsRaw, this->DataSets, vtkDataObject::POINT); } }; /** * Builds a Ioss::ElementBlock from a vtkPartitionedDataSet. The differences * between the Ioss and VTK data model for the two are handled as follows: * * * We only support vtkPartitionedDataSet comprising of one or more vtkUnstructuredGrids. * All other dataset types are simply ignored. * * * An ElementBlock cannot have multiple "pieces" in the same file. So if a * vtkPartitionedDataSet has multiple datasets, we need to "combine" them into * one. * * * An ElementBlock cannot have elements of different types. However, * vtkUnstructuredGrid supports heterogeneous cells. So if all * vtkUnstructuredGrids in the vtkPartitionedDataSet have more than 1 cell type, * we create multiple element blocks. Each ElementBlock is uniquely named by * using the given block name and the element type as a suffix. * * In MPI world, the cell types are gathered across all ranks to ensure each * ranks creates identical blocks / block names. * */ struct vtkElementBlock : public vtkGroupingEntity { vtkPartitionedDataSet* PartitionedDataSet; std::string RootName; std::map<unsigned char, int64_t> ElementCounts; std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> Fields; vtkElementBlock(vtkPartitionedDataSet* pd, const std::string& name, vtkMultiProcessController* controller, vtkIOSSWriter* writer) : vtkGroupingEntity(writer) , PartitionedDataSet(pd) , RootName{ name } { auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd); for (auto& ug : datasets) { auto* cd = ug->GetCellData(); auto* gids = vtkIdTypeArray::SafeDownCast(cd->GetGlobalIds()); if (!gids) { throw std::runtime_error("cell global ids missing!"); } } this->ElementCounts = ::GetElementCounts(pd, controller); this->Fields = ::GetFields(vtkDataObject::CELL, pd, controller); } void AppendMD5(vtksysMD5* md5) const override { vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->RootName.c_str()), -1); for (auto& pair : this->ElementCounts) { vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&pair.first), static_cast<int>(sizeof(pair.first))); vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&pair.second), static_cast<int>(sizeof(pair.second))); } } void Define(Ioss::Region& region) const override { for (auto& pair : this->ElementCounts) { const int64_t elementCount = pair.second; const unsigned char vtk_cell_type = pair.first; const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type); const auto& elementType = element->name(); const std::string bname = (this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType; auto* block = new Ioss::ElementBlock(region.get_database(), bname, elementType, elementCount); // FIXME: for now, we let IOSS figure out the id; we need to add logic to // preserve input id, if we can. // block->property_add(Ioss::Property("id", id++)); region.add(block); } } void DefineTransient(Ioss::Region& region) const override { for (auto& pair : this->ElementCounts) { unsigned char vtk_cell_type = pair.first; const int64_t elementCount = pair.second; const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type); const auto& elementType = element->name(); const std::string bname = (this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType; auto* block = region.get_element_block(bname); this->DefineFields(block, this->Fields, Ioss::Field::TRANSIENT, elementCount); } } void Model(Ioss::Region& region) const override { auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet); for (auto& pair : this->ElementCounts) { unsigned char vtk_cell_type = pair.first; const int64_t elementCount = pair.second; const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type); const auto& elementType = element->name(); const int nodeCount = element->number_nodes(); const std::string bname = (this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType; auto* block = region.get_element_block(bname); // populate ids. std::vector<int32_t> elementIds; // these are global ids. elementIds.reserve(elementCount); std::vector<int32_t> connectivity; connectivity.reserve(elementCount * nodeCount); const int32_t gidOffset = this->Writer->GetOffsetGlobalIds() ? 1 : 0; for (auto& ug : datasets) { auto* gids = vtkIdTypeArray::SafeDownCast(ug->GetCellData()->GetGlobalIds()); auto* pointGIDs = vtkIdTypeArray::SafeDownCast(ug->GetPointData()->GetGlobalIds()); for (vtkIdType cc = 0, max = ug->GetNumberOfCells(); cc < max; ++cc) { if (ug->GetCellType(cc) == vtk_cell_type) { elementIds.push_back(gidOffset + gids->GetValue(cc)); vtkIdType numPts; vtkIdType const* cellPoints; ug->GetCellPoints(cc, numPts, cellPoints); assert(numPts == nodeCount); // map cell's point to global ids for those points. std::transform(cellPoints, cellPoints + numPts, std::back_inserter(connectivity), [&](vtkIdType ptid) { return gidOffset + pointGIDs->GetValue(ptid); }); } } } assert(elementIds.size() == elementCount); assert(connectivity.size() == elementCount * nodeCount); block->put_field_data("ids", elementIds); block->put_field_data("connectivity", connectivity); } } void Transient(Ioss::Region& region) const override { auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet); for (auto& pair : this->ElementCounts) { unsigned char vtk_cell_type = pair.first; const int64_t elementCount = pair.second; const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type); const auto& elementType = element->name(); const int nodeCount = element->number_nodes(); const std::string bname = (this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType; auto* block = region.get_element_block(bname); // populate ids. std::vector<std::vector<vtkIdType>> lIds; // these are local ids. for (auto& ug : datasets) { lIds.emplace_back(); lIds.back().reserve(ug->GetNumberOfCells()); for (vtkIdType cc = 0, max = ug->GetNumberOfCells(); cc < max; ++cc) { if (ug->GetCellType(cc) == vtk_cell_type) { lIds.back().push_back(cc); } } } // add fields. this->PutFields(block, this->Fields, lIds, datasets, vtkDataObject::CELL); } } }; struct vtkNodeSet : public vtkGroupingEntity { vtkPartitionedDataSet* PartitionedDataSet; std::string Name; int64_t Count{ 0 }; vtkNodeSet(vtkPartitionedDataSet* pd, const std::string& name, vtkMultiProcessController* vtkNotUsed(controller), vtkIOSSWriter* writer) : vtkGroupingEntity(writer) , PartitionedDataSet(pd) , Name(name) { auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd); for (auto& ug : datasets) { auto* gids = vtkIdTypeArray::SafeDownCast(ug->GetPointData()->GetGlobalIds()); if (!gids) { throw std::runtime_error("missing point global ids for nodesets."); } this->Count += ug->GetNumberOfPoints(); } // TODO: identify nodeset-only fields. } void AppendMD5(vtksysMD5* md5) const override { vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->Name.c_str()), -1); vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&this->Count), static_cast<int>(sizeof(this->Count))); } void Define(Ioss::Region& region) const override { auto* nodeset = new Ioss::NodeSet(region.get_database(), this->Name, this->Count); // nodeset->property_add(Ioss::Property("id", id++)); region.add(nodeset); } void DefineTransient(Ioss::Region& vtkNotUsed(region)) const override {} void Model(Ioss::Region& region) const override { auto* nodeset = region.get_nodeset(this->Name); std::vector<int32_t> ids; ids.reserve(this->Count); for (auto& ug : vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet)) { auto* gids = vtkIdTypeArray::SafeDownCast(ug->GetPointData()->GetGlobalIds()); std::copy( gids->GetPointer(0), gids->GetPointer(gids->GetNumberOfTuples()), std::back_inserter(ids)); } nodeset->put_field_data("ids", ids); } void Transient(Ioss::Region& vtkNotUsed(region)) const override {} }; struct vtkSideSet : public vtkGroupingEntity { vtkPartitionedDataSet* PartitionedDataSet; std::string Name; int64_t Count; vtkSideSet(vtkPartitionedDataSet* pd, const std::string& name, vtkMultiProcessController* vtkNotUsed(controller), vtkIOSSWriter* writer) : vtkGroupingEntity(writer) , PartitionedDataSet(pd) , Name(name) , Count{ 0 } { auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd); for (auto& ug : datasets) { auto* cd = ug->GetCellData(); if (vtkIdTypeArray::SafeDownCast(cd->GetGlobalIds()) != nullptr) { throw std::runtime_error("cell global ids present, must not be a sideset."); } if (vtkIntArray::SafeDownCast(cd->GetArray("element_side")) == nullptr) { throw std::runtime_error("missing 'element_side' cell array."); } this->Count += ug->GetNumberOfCells(); } } void AppendMD5(vtksysMD5* md5) const override { vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->Name.c_str()), -1); vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&this->Count), static_cast<int>(sizeof(this->Count))); } void Define(Ioss::Region& region) const override { // for mixed topology blocks, IOSS uses "unknown" const auto* mixed_topo = Ioss::ElementTopology::factory("unknown"); const auto& elementType = mixed_topo->name(); auto* sideblock = new Ioss::SideBlock( region.get_database(), "sideblock_0", elementType, elementType, this->Count); auto* sideset = new Ioss::SideSet(region.get_database(), this->Name); sideset->add(sideblock); region.add(sideset); } void DefineTransient(Ioss::Region& vtkNotUsed(region)) const override {} void Model(Ioss::Region& region) const override { auto* sideset = region.get_sideset(this->Name); auto* sideblock = sideset->get_side_block("sideblock_0"); std::vector<int32_t> elementSide; elementSide.reserve(this->Count * 2); auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet); for (auto& ug : datasets) { for (const auto& tuple : vtk::DataArrayTupleRange( vtkIntArray::SafeDownCast(ug->GetCellData()->GetArray("element_side")))) { for (const auto& comp : tuple) { elementSide.push_back(comp); } } } assert(elementSide.size() == this->Count * 2); sideblock->put_field_data("element_side", elementSide); } void Transient(Ioss::Region& vtkNotUsed(region)) const override {} }; //============================================================================= class vtkIOSSModel::vtkInternals { public: vtkSmartPointer<vtkMultiProcessController> Controller; std::multimap<Ioss::EntityType, std::shared_ptr<vtkGroupingEntity>> EntityGroups; }; //---------------------------------------------------------------------------- vtkIOSSModel::vtkIOSSModel(vtkPartitionedDataSetCollection* dataset, vtkIOSSWriter* writer) : Internals(new vtkIOSSModel::vtkInternals()) { auto* controller = writer->GetController(); auto& internals = (*this->Internals); internals.Controller = controller ? vtk::MakeSmartPointer(controller) : vtk::TakeSmartPointer(vtkMultiProcessController::SafeDownCast(vtkDummyController::New())); auto* assembly = dataset->GetDataAssembly(); const bool isIOSS = writer->GetPreserveInputEntityGroups() && (assembly && assembly->GetRootNodeName() && strcmp(assembly->GetRootNodeName(), "IOSS") == 0); const auto elementBlockIndices = ::GetDatasetIndices(assembly, "element_blocks"); const auto nodeSetIndices = ::GetDatasetIndices(assembly, "node_sets"); const auto sideSetIndices = ::GetDatasetIndices(assembly, "side_sets"); // first things first, determine all information necessary about nodes. // there's just 1 node block for exodus, build that. internals.EntityGroups.emplace(Ioss::EntityType::NODEBLOCK, std::make_shared<vtkNodeBlock>(dataset, "nodeblock_1", internals.Controller, writer)); // process element blocks. // now, if input is not coming for IOSS reader, then all blocks are simply // treated as element blocks, there's no way for us to deduce otherwise. // let's start by simply doing that. for (unsigned int pidx = 0; pidx < dataset->GetNumberOfPartitionedDataSets(); ++pidx) { std::string bname = "block_" + std::to_string(pidx + 1); if (auto info = dataset->GetMetaData(pidx)) { if (info->Has(vtkCompositeDataSet::NAME())) { bname = info->Get(vtkCompositeDataSet::NAME()); } } // now create each type of GroupingEntity. if (!isIOSS || elementBlockIndices.find(pidx) != elementBlockIndices.end()) { try { internals.EntityGroups.emplace(Ioss::EntityType::ELEMENTBLOCK, std::make_shared<vtkElementBlock>( dataset->GetPartitionedDataSet(pidx), bname, internals.Controller, writer)); continue; } catch (std::runtime_error&) { // if isIOSS, raise error...perhaps? break; } } if (sideSetIndices.find(pidx) != sideSetIndices.end()) { try { internals.EntityGroups.emplace(Ioss::EntityType::SIDESET, std::make_shared<vtkSideSet>( dataset->GetPartitionedDataSet(pidx), bname, internals.Controller, writer)); continue; } catch (std::runtime_error&) { break; } } // nodesets are the most forgiving kind, so let's do them last. if (nodeSetIndices.find(pidx) != nodeSetIndices.end()) { try { internals.EntityGroups.emplace(Ioss::EntityType::NODESET, std::make_shared<vtkNodeSet>( dataset->GetPartitionedDataSet(pidx), bname, internals.Controller, writer)); continue; } catch (std::runtime_error&) { break; } } vtkLogF(WARNING, "Skipping block '%s'. Unsure how classify it.", bname.c_str()); } } //---------------------------------------------------------------------------- vtkIOSSModel::~vtkIOSSModel() = default; //---------------------------------------------------------------------------- void vtkIOSSModel::DefineModel(Ioss::Region& region) const { auto& internals = (*this->Internals); region.begin_mode(Ioss::STATE_DEFINE_MODEL); for (auto& entity : internals.EntityGroups) { entity.second->Define(region); } region.end_mode(Ioss::STATE_DEFINE_MODEL); } //---------------------------------------------------------------------------- void vtkIOSSModel::Model(Ioss::Region& region) const { auto& internals = (*this->Internals); region.begin_mode(Ioss::STATE_MODEL); for (auto& entity : internals.EntityGroups) { entity.second->Model(region); } region.end_mode(Ioss::STATE_MODEL); } //---------------------------------------------------------------------------- void vtkIOSSModel::DefineTransient(Ioss::Region& region) const { auto& internals = (*this->Internals); region.begin_mode(Ioss::STATE_DEFINE_TRANSIENT); for (auto& entity : internals.EntityGroups) { entity.second->DefineTransient(region); } region.end_mode(Ioss::STATE_DEFINE_TRANSIENT); } //---------------------------------------------------------------------------- void vtkIOSSModel::Transient(Ioss::Region& region, double time) const { auto& internals = (*this->Internals); region.begin_mode(Ioss::STATE_TRANSIENT); const int step = region.add_state(time); region.begin_state(step); for (auto& entity : internals.EntityGroups) { entity.second->Transient(region); } region.end_state(step); region.end_mode(Ioss::STATE_TRANSIENT); } //---------------------------------------------------------------------------- std::string vtkIOSSModel::MD5() const { unsigned char digest[16]; char md5Hash[33]; vtksysMD5* md5 = vtksysMD5_New(); vtksysMD5_Initialize(md5); const auto& internals = (*this->Internals); size_t numberOfItems = internals.EntityGroups.size(); vtksysMD5_Append( md5, reinterpret_cast<const unsigned char*>(&numberOfItems), static_cast<int>(sizeof(size_t))); for (const auto& entity : internals.EntityGroups) { entity.second->AppendMD5(md5); } vtksysMD5_Finalize(md5, digest); vtksysMD5_DigestToHex(digest, md5Hash); vtksysMD5_Delete(md5); md5Hash[32] = '\0'; return std::string(md5Hash); }
33.606154
100
0.652353
[ "mesh", "vector", "model", "transform" ]
1d52c48446fd2b2ccb4d71e7ad6099f435f0edf1
2,054
cpp
C++
generator/translator.cpp
letko-dmitry/omim
83797b2070e22f8d67f36d9c7e291e31ea2480ea
[ "Apache-2.0" ]
1
2019-05-27T02:45:22.000Z
2019-05-27T02:45:22.000Z
generator/translator.cpp
Mahmoudabdelmobdy/omim
1d444650803b27e507b5e9532551d41bab621a53
[ "Apache-2.0" ]
null
null
null
generator/translator.cpp
Mahmoudabdelmobdy/omim
1d444650803b27e507b5e9532551d41bab621a53
[ "Apache-2.0" ]
null
null
null
#include "generator/translator.hpp" #include "generator/collector_interface.hpp" #include "generator/emitter_interface.hpp" #include "generator/intermediate_data.hpp" #include "generator/osm_element.hpp" #include "base/assert.hpp" namespace generator { Translator::Translator(std::shared_ptr<EmitterInterface> emitter, cache::IntermediateDataReader & cache, std::shared_ptr<FeatureMakerBase> maker, FilterCollection const & filters, CollectorCollection const & collectors) : m_filters(filters) , m_collectors(collectors) , m_tagsEnricher(cache) , m_featureMaker(maker) , m_emitter(emitter) , m_cache(cache) { CHECK(m_emitter, ()); } Translator::Translator(std::shared_ptr<EmitterInterface> emitter, cache::IntermediateDataReader & cache, std::shared_ptr<FeatureMakerBase> maker) : Translator(emitter, cache, maker, {} /* filters */, {} /* collectors */) {} void Translator::Emit(OsmElement & element) { if (!m_filters.IsAccepted(element)) return; Preprocess(element); m_tagsEnricher(element); m_collectors.Collect(element); m_featureMaker->Add(element); FeatureBuilder1 feature; while (m_featureMaker->GetNextFeature(feature)) { if (!m_filters.IsAccepted(feature)) continue; m_collectors.CollectFeature(feature, element); m_emitter->Process(feature); } } bool Translator::Finish() { m_collectors.Save(); return m_emitter->Finish(); } void Translator::GetNames(std::vector<std::string> & names) const { m_emitter->GetNames(names); } void Translator::AddCollector(std::shared_ptr<CollectorInterface> collector) { m_collectors.Append(collector); } void Translator::AddCollectorCollection(CollectorCollection const & collectors) { m_collectors.AddCollection(collectors); } void Translator::AddFilter(std::shared_ptr<FilterInterface> filter) { m_filters.Append(filter); } void Translator::AddFilterCollection(FilterCollection const & filters) { m_filters.AddCollection(filters); } } // namespace generator
25.675
104
0.733204
[ "vector" ]
1d5994c50c3d496c68c63c7693495346e4773779
20,116
cc
C++
components/update_client/ping_manager_unittest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/update_client/ping_manager_unittest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/update_client/ping_manager_unittest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/update_client/ping_manager.h" #include <stdint.h> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/json/json_reader.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "base/version.h" #include "components/update_client/component.h" #include "components/update_client/net/url_loader_post_interceptor.h" #include "components/update_client/protocol_definition.h" #include "components/update_client/protocol_serializer.h" #include "components/update_client/test_configurator.h" #include "components/update_client/update_engine.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/re2/src/re2/re2.h" using std::string; namespace update_client { class PingManagerTest : public testing::Test, public testing::WithParamInterface<bool> { public: PingManagerTest(); ~PingManagerTest() override = default; PingManager::Callback MakePingCallback(); scoped_refptr<UpdateContext> MakeMockUpdateContext() const; // Overrides from testing::Test. void SetUp() override; void TearDown() override; void PingSentCallback(int error, const std::string& response); protected: void Quit(); void RunThreads(); scoped_refptr<TestConfigurator> config_; scoped_refptr<PingManager> ping_manager_; int error_ = -1; std::string response_; private: base::test::TaskEnvironment task_environment_; base::OnceClosure quit_closure_; }; PingManagerTest::PingManagerTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) { config_ = base::MakeRefCounted<TestConfigurator>(); } void PingManagerTest::SetUp() { ping_manager_ = base::MakeRefCounted<PingManager>(config_); } void PingManagerTest::TearDown() { // Run the threads until they are idle to allow the clean up // of the network interceptors on the IO thread. task_environment_.RunUntilIdle(); ping_manager_ = nullptr; } void PingManagerTest::RunThreads() { base::RunLoop runloop; quit_closure_ = runloop.QuitClosure(); runloop.Run(); } void PingManagerTest::Quit() { if (!quit_closure_.is_null()) std::move(quit_closure_).Run(); } PingManager::Callback PingManagerTest::MakePingCallback() { return base::BindOnce(&PingManagerTest::PingSentCallback, base::Unretained(this)); } void PingManagerTest::PingSentCallback(int error, const std::string& response) { error_ = error; response_ = response; Quit(); } scoped_refptr<UpdateContext> PingManagerTest::MakeMockUpdateContext() const { return base::MakeRefCounted<UpdateContext>( config_, false, std::vector<std::string>(), UpdateClient::CrxDataCallback(), UpdateClient::CrxStateChangeCallback(), UpdateEngine::NotifyObserversCallback(), UpdateEngine::Callback(), nullptr); } // This test is parameterized for using JSON or XML serialization. |true| means // JSON serialization is used. INSTANTIATE_TEST_SUITE_P(Parameterized, PingManagerTest, testing::Bool()); TEST_P(PingManagerTest, SendPing) { auto interceptor = std::make_unique<URLLoaderPostInterceptor>( config_->test_url_loader_factory()); EXPECT_TRUE(interceptor); const auto update_context = MakeMockUpdateContext(); { // Test eventresult="1" is sent for successful updates. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.crx_component_->version = base::Version("1.0"); component.state_ = std::make_unique<Component::StateUpdated>(&component); component.previous_version_ = base::Version("1.0"); component.next_version_ = base::Version("2.0"); component.AppendEvent(component.MakeEventUpdateComplete()); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); ASSERT_TRUE(request); EXPECT_TRUE(request->FindKey("@os")); EXPECT_EQ("fake_prodid", request->FindKey("@updater")->GetString()); EXPECT_EQ("crx2,crx3", request->FindKey("acceptformat")->GetString()); EXPECT_TRUE(request->FindKey("arch")); EXPECT_EQ("cr", request->FindKey("dedup")->GetString()); EXPECT_LT(0, request->FindPath({"hw", "physmemory"})->GetInt()); EXPECT_EQ("fake_lang", request->FindKey("lang")->GetString()); EXPECT_TRUE(request->FindKey("nacl_arch")); EXPECT_EQ("fake_channel_string", request->FindKey("prodchannel")->GetString()); EXPECT_EQ("30.0", request->FindKey("prodversion")->GetString()); EXPECT_EQ("3.1", request->FindKey("protocol")->GetString()); EXPECT_TRUE(request->FindKey("requestid")); EXPECT_TRUE(request->FindKey("sessionid")); EXPECT_EQ("fake_channel_string", request->FindKey("updaterchannel")->GetString()); EXPECT_EQ("30.0", request->FindKey("updaterversion")->GetString()); EXPECT_TRUE(request->FindPath({"os", "arch"})->is_string()); EXPECT_EQ("Fake Operating System", request->FindPath({"os", "platform"})->GetString()); EXPECT_TRUE(request->FindPath({"os", "version"})->is_string()); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.0", app.FindKey("version")->GetString()); const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(1, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(3, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); // Check the ping request does not carry the specific extra request headers. const auto headers = std::get<1>(interceptor->GetRequests()[0]); EXPECT_FALSE(headers.HasHeader("X-Goog-Update-Interactivity")); EXPECT_FALSE(headers.HasHeader("X-Goog-Update-Updater")); EXPECT_FALSE(headers.HasHeader("X-Goog-Update-AppId")); interceptor->Reset(); } { // Test eventresult="0" is sent for failed updates. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.crx_component_->version = base::Version("1.0"); component.state_ = std::make_unique<Component::StateUpdateError>(&component); component.previous_version_ = base::Version("1.0"); component.next_version_ = base::Version("2.0"); component.AppendEvent(component.MakeEventUpdateComplete()); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.0", app.FindKey("version")->GetString()); const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(0, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(3, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); interceptor->Reset(); } { // Test the error values and the fingerprints. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.crx_component_->version = base::Version("1.0"); component.state_ = std::make_unique<Component::StateUpdateError>(&component); component.previous_version_ = base::Version("1.0"); component.next_version_ = base::Version("2.0"); component.previous_fp_ = "prev fp"; component.next_fp_ = "next fp"; component.error_category_ = ErrorCategory::kDownload; component.error_code_ = 2; component.extra_code1_ = -1; component.diff_error_category_ = ErrorCategory::kService; component.diff_error_code_ = 20; component.diff_extra_code1_ = -10; component.crx_diffurls_.push_back(GURL("http://host/path")); component.AppendEvent(component.MakeEventUpdateComplete()); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.0", app.FindKey("version")->GetString()); const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(0, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(3, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); EXPECT_EQ(4, event.FindKey("differrorcat")->GetInt()); EXPECT_EQ(20, event.FindKey("differrorcode")->GetInt()); EXPECT_EQ(-10, event.FindKey("diffextracode1")->GetInt()); EXPECT_EQ(0, event.FindKey("diffresult")->GetInt()); EXPECT_EQ(1, event.FindKey("errorcat")->GetInt()); EXPECT_EQ(2, event.FindKey("errorcode")->GetInt()); EXPECT_EQ(-1, event.FindKey("extracode1")->GetInt()); EXPECT_EQ("next fp", event.FindKey("nextfp")->GetString()); EXPECT_EQ("prev fp", event.FindKey("previousfp")->GetString()); interceptor->Reset(); } { // Test an invalid |next_version| is not serialized. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.crx_component_->version = base::Version("1.0"); component.state_ = std::make_unique<Component::StateUpdateError>(&component); component.previous_version_ = base::Version("1.0"); component.AppendEvent(component.MakeEventUpdateComplete()); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.0", app.FindKey("version")->GetString()); const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(0, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(3, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); interceptor->Reset(); } { // Test a valid |previouversion| and |next_version| = base::Version("0") // are serialized correctly under <event...> for uninstall. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.Uninstall(base::Version("1.2.3.4"), 0); component.AppendEvent(component.MakeEventUninstalled()); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.2.3.4", app.FindKey("version")->GetString()); const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(1, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(4, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("1.2.3.4", event.FindKey("previousversion")->GetString()); EXPECT_EQ("0", event.FindKey("nextversion")->GetString()); interceptor->Reset(); } { // Test registrationEvent. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.Registration(base::Version("1.2.3.4")); component.AppendEvent(component.MakeEventRegistration()); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.2.3.4", app.FindKey("version")->GetString()); const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(1, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(2, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("1.2.3.4", event.FindKey("nextversion")->GetString()); interceptor->Reset(); } { // Test the download metrics. Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.crx_component_->version = base::Version("1.0"); component.state_ = std::make_unique<Component::StateUpdated>(&component); component.previous_version_ = base::Version("1.0"); component.next_version_ = base::Version("2.0"); component.AppendEvent(component.MakeEventUpdateComplete()); CrxDownloader::DownloadMetrics download_metrics; download_metrics.url = GURL("http://host1/path1"); download_metrics.downloader = CrxDownloader::DownloadMetrics::kUrlFetcher; download_metrics.error = -1; download_metrics.downloaded_bytes = 123; download_metrics.total_bytes = 456; download_metrics.download_time_ms = 987; component.AppendEvent(component.MakeEventDownloadMetrics(download_metrics)); download_metrics = CrxDownloader::DownloadMetrics(); download_metrics.url = GURL("http://host2/path2"); download_metrics.downloader = CrxDownloader::DownloadMetrics::kBits; download_metrics.error = 0; download_metrics.downloaded_bytes = 1230; download_metrics.total_bytes = 4560; download_metrics.download_time_ms = 9870; component.AppendEvent(component.MakeEventDownloadMetrics(download_metrics)); download_metrics = CrxDownloader::DownloadMetrics(); download_metrics.url = GURL("http://host3/path3"); download_metrics.downloader = CrxDownloader::DownloadMetrics::kBits; download_metrics.error = 0; download_metrics.downloaded_bytes = kProtocolMaxInt; download_metrics.total_bytes = kProtocolMaxInt - 1; download_metrics.download_time_ms = kProtocolMaxInt - 2; component.AppendEvent(component.MakeEventDownloadMetrics(download_metrics)); EXPECT_TRUE(interceptor->ExpectRequest(std::make_unique<AnyMatch>())); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString(); const auto msg = interceptor->GetRequestBody(0); const auto root = base::JSONReader::Read(msg); ASSERT_TRUE(root); const auto* request = root->FindKey("request"); const auto& app = request->FindKey("app")->GetList()[0]; EXPECT_EQ("abc", app.FindKey("appid")->GetString()); EXPECT_EQ("1.0", app.FindKey("version")->GetString()); EXPECT_EQ(4u, app.FindKey("event")->GetList().size()); { const auto& event = app.FindKey("event")->GetList()[0]; EXPECT_EQ(1, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(3, event.FindKey("eventtype")->GetInt()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); } { const auto& event = app.FindKey("event")->GetList()[1]; EXPECT_EQ(0, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(14, event.FindKey("eventtype")->GetInt()); EXPECT_EQ(987, event.FindKey("download_time_ms")->GetDouble()); EXPECT_EQ(123, event.FindKey("downloaded")->GetDouble()); EXPECT_EQ("direct", event.FindKey("downloader")->GetString()); EXPECT_EQ(-1, event.FindKey("errorcode")->GetInt()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); EXPECT_EQ(456, event.FindKey("total")->GetDouble()); EXPECT_EQ("http://host1/path1", event.FindKey("url")->GetString()); } { const auto& event = app.FindKey("event")->GetList()[2]; EXPECT_EQ(1, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(14, event.FindKey("eventtype")->GetInt()); EXPECT_EQ(9870, event.FindKey("download_time_ms")->GetDouble()); EXPECT_EQ(1230, event.FindKey("downloaded")->GetDouble()); EXPECT_EQ("bits", event.FindKey("downloader")->GetString()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); EXPECT_EQ(4560, event.FindKey("total")->GetDouble()); EXPECT_EQ("http://host2/path2", event.FindKey("url")->GetString()); } { const auto& event = app.FindKey("event")->GetList()[3]; EXPECT_EQ(1, event.FindKey("eventresult")->GetInt()); EXPECT_EQ(14, event.FindKey("eventtype")->GetInt()); EXPECT_EQ(9007199254740990, event.FindKey("download_time_ms")->GetDouble()); EXPECT_EQ(9007199254740992, event.FindKey("downloaded")->GetDouble()); EXPECT_EQ("bits", event.FindKey("downloader")->GetString()); EXPECT_EQ("2.0", event.FindKey("nextversion")->GetString()); EXPECT_EQ("1.0", event.FindKey("previousversion")->GetString()); EXPECT_EQ(9007199254740991, event.FindKey("total")->GetDouble()); EXPECT_EQ("http://host3/path3", event.FindKey("url")->GetString()); } interceptor->Reset(); } } // Tests that sending the ping fails when the component requires encryption but // the ping URL is unsecure. TEST_P(PingManagerTest, RequiresEncryption) { config_->SetPingUrl(GURL("http:\\foo\bar")); const auto update_context = MakeMockUpdateContext(); Component component(*update_context, "abc"); component.crx_component_ = CrxComponent(); component.crx_component_->version = base::Version("1.0"); // The default value for |requires_network_encryption| is true. EXPECT_TRUE(component.crx_component_->requires_network_encryption); component.state_ = std::make_unique<Component::StateUpdated>(&component); component.previous_version_ = base::Version("1.0"); component.next_version_ = base::Version("2.0"); component.AppendEvent(component.MakeEventUpdateComplete()); ping_manager_->SendPing(component, MakePingCallback()); RunThreads(); EXPECT_EQ(-2, error_); } } // namespace update_client
42.70913
80
0.689451
[ "vector" ]
1d5a555a009dec096a4d883e900832e7105e334a
1,113
cpp
C++
atcoder/abc165C_many_requirements.cpp
da-edra/kyopro
ad531d15bcccf6aafdaaef3cc69db850b0f7c471
[ "BSD-3-Clause" ]
2
2020-08-31T17:19:07.000Z
2021-01-08T21:35:48.000Z
atcoder/abc165C_many_requirements.cpp
edglaz/kyopro
b8ac4f6873418ad20ad417e46d731c35a8062c0d
[ "BSD-3-Clause" ]
null
null
null
atcoder/abc165C_many_requirements.cpp
edglaz/kyopro
b8ac4f6873418ad20ad417e46d731c35a8062c0d
[ "BSD-3-Clause" ]
null
null
null
// Vicfred & unihernandez22 // https://atcoder.jp/contests/abc165/tasks/abc165_c // dfs, brute force #include <algorithm> #include <iostream> #include <vector> #include <queue> using namespace std; int main() { int n, m, q; cin >> n >> m >> q; vector<int> a(q); vector<int> b(q); vector<int> c(q); vector<int> d(q); for(int i = 0; i < q; i++) cin >> a[i] >> b[i] >> c[i] >> d[i]; queue<vector<int>> A; for(int i = 1; i <= m; ++i) A.push({i}); while(A.front().size() != n) { auto item = A.front(); A.pop(); int size = item.size(); for(int i = item[size-1]; i <= m; i++) { item.push_back(i); A.push(item); item.pop_back(); } } long long maxima = 0LL; while(!A.empty()) { long long local = 0LL; auto item = A.front(); A.pop(); for(int i = 0; i < q; i++) if((item[b[i]-1] - item[a[i]-1]) == c[i]) local += d[i]; maxima = max(maxima, local); } cout << maxima << endl; return 0; }
19.189655
53
0.455526
[ "vector" ]
1d619867d480c7f120788fe8a141f58b3ab655ab
43,463
cpp
C++
indra/llcommon/tests/lltreeiterators_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/llcommon/tests/lltreeiterators_test.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/llcommon/tests/lltreeiterators_test.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file lltreeiterators.cpp * @author Nat Goodspeed * @date 2008-08-20 * @brief Test of lltreeiterators.h * * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ // Precompiled header #include "linden_common.h" // STL headers // std headers #include <iostream> #include <sstream> #include <string> // external library headers #include <boost/bind.hpp> #include <boost/range/iterator_range.hpp> #include <boost/foreach.hpp> // associated header #include "../lltreeiterators.h" #include "../llpointer.h" #include "../test/lltut.h" /***************************************************************************** * tut test group *****************************************************************************/ namespace tut { struct iter_data { }; typedef test_group<iter_data> iter_group; typedef iter_group::object iter_object; tut::iter_group ig("LLTreeIterators"); } // namespace tut /***************************************************************************** * boost::get_pointer() specialization for LLPointer<> *****************************************************************************/ // This specialization of boost::get_pointer() undoubtedly belongs in // llmemory.h. It's used by boost::bind() so that you can pass an // LLPointer<Foo> as well as a Foo* to a functor such as // boost::bind(&Foo::method, _1). //namespace boost //{ template <class NODE> NODE* get_pointer(const LLPointer<NODE>& ptr) { return ptr.get(); } //}; /***************************************************************************** * ScopeLabel *****************************************************************************/ class ScopeLabel { public: ScopeLabel(const std::string& label): mLabel(label) { std::cout << "Entering " << mLabel << '\n'; } ~ScopeLabel() { std::cout << "Leaving " << mLabel << '\n'; } private: std::string mLabel; }; /***************************************************************************** * Cleanup *****************************************************************************/ // Yes, we realize this is redundant with auto_ptr and LLPointer and all // kinds of better mechanisms. But in this particular source file, we need to // test nodes managed with plain old dumb pointers as well as nodes managed // with LLPointer, so we introduce this mechanism. // // In the general case, when we declare a Cleanup for some pointer, delete the // pointer when the Cleanup goes out of scope. template <typename PTRTYPE> struct Cleanup { Cleanup(const PTRTYPE& ptr): mPtr(ptr) {} ~Cleanup() { delete mPtr; } PTRTYPE mPtr; }; // But when the pointer is an LLPointer<something>, Cleanup is a no-op: // LLPointer will handle the cleanup automagically. template <typename NODE> struct Cleanup< LLPointer<NODE> > { Cleanup(const LLPointer<NODE>& ptr) {} ~Cleanup() {} }; /***************************************************************************** * Expected *****************************************************************************/ // Expected is a base class used to capture the expected results -- a sequence // of string node names -- from one of our traversals of this example data. // Its subclasses initialize it with a pair of string iterators. It's not // strictly necessary to customize Expected to model Boost.Range, it's just // convenient. struct Expected { template <typename ITER> Expected(ITER begin, ITER end): strings(begin, end) {} /*------ The following are to make Expected work with Boost.Range ------*/ typedef std::vector<std::string> container_type; typedef container_type::iterator iterator; typedef container_type::const_iterator const_iterator; typedef container_type::size_type size_type; container_type strings; iterator begin() { return strings.begin(); } iterator end() { return strings.end(); } size_type size() { return strings.size(); } const_iterator begin() const { return strings.begin(); } const_iterator end() const { return strings.end(); } }; // We have a couple of generic Expected template subclasses. This list of // strings is used for the "else" case when all specializations fail. const char* bad_strings[] = { "FAIL" }; /***************************************************************************** * verify() *****************************************************************************/ // test function: given (an object modeling) a Boost.Range of tree nodes, // compare the sequence of visited node names with a range of expected name // strings. Report success both with std::cout output and a bool return. The // string desc parameter is to identify the different tests. template <typename NODERANGE, typename STRINGRANGE> bool verify(const std::string& desc, NODERANGE noderange, STRINGRANGE expected) { typename boost::range_iterator<NODERANGE>::type nri = boost::begin(noderange), nrend = boost::end(noderange); typename boost::range_iterator<STRINGRANGE>::type sri = boost::begin(expected), srend = boost::end(expected); // We choose to loop over both sequences explicitly rather than using // std::equal() or std::lexicographical_compare(). The latter tells you // whether one sequence is *less* than the other -- it doesn't tell you // equality. std::equal() needs you to verify the sequence lengths ahead // of time. Anyway, comparing explicitly allows us to report much more // information about any sequence mismatch. for ( ; nri != nrend && sri != srend; ++nri, ++sri) { if ((*nri)->name() != *sri) { std::cout << desc << " mismatch: " << "expected " << *sri << ", got " << (*nri)->name() << "\n"; return false; } } if (nri != nrend) { std::cout << desc << " produced too many items:\n"; for ( ; nri != nrend; ++nri) { std::cout << " " << (*nri)->name() << '\n'; } return false; } if (sri != srend) { std::cout << desc << " produced too few items, omitting:\n"; for ( ; sri != srend; ++sri) { std::cout << " " << *sri << '\n'; } return false; } // std::cout << desc << " test passed\n"; return true; } /***************************************************************************** * PlainNode: LLLinkIter, non-refcounted *****************************************************************************/ class PlainNode { public: PlainNode(const std::string& name, PlainNode* next=NULL): mName(name), mNext(next) {} ~PlainNode() { delete mNext; } std::string name() const { return mName; } PlainNode* next() const { return mNext; } public: // if this were 'private', couldn't bind mNext PlainNode* mNext; private: std::string mName; }; namespace tut { template<> template<> void iter_object::test<1>() { // set_test_name("LLLinkedIter -- non-refcounted class"); PlainNode* last(new PlainNode("c")); PlainNode* second(new PlainNode("b", last)); PlainNode* first(new PlainNode("a", second)); Cleanup<PlainNode*> cleanup(first); static const char* cseq[] = { "a", "b", "c" }; Expected seq(boost::begin(cseq), boost::end(cseq)); std::string desc1("Iterate by public link member"); // std::cout << desc1 << ":\n"; // Try instantiating an iterator with NULL. This test is less about // "did we iterate once?" than "did we avoid blowing up?" for (LLLinkedIter<PlainNode> pni(NULL, boost::bind(&PlainNode::mNext, _1)), end; pni != end; ++pni) { // std::cout << (*pni)->name() << '\n'; ensure("LLLinkedIter<PlainNode>(NULL)", false); } ensure(desc1, verify(desc1, boost::make_iterator_range(LLLinkedIter<PlainNode>(first, boost::bind(&PlainNode::mNext, _1)), LLLinkedIter<PlainNode>()), seq)); std::string desc2("Iterate by next() method"); // std::cout << desc2 << ":\n"; // for (LLLinkedIter<PlainNode> pni(first, boost::bind(&PlainNode::next, _1)); ! (pni == end); ++pni) // std::cout << (**pni).name() << '\n'; ensure(desc2, verify(desc2, boost::make_iterator_range(LLLinkedIter<PlainNode>(first, boost::bind(&PlainNode::next, _1)), LLLinkedIter<PlainNode>()), seq)); { // LLLinkedIter<PlainNode> pni(first, boost::bind(&PlainNode::next, _1)); // std::cout << "First is " << (*pni++)->name() << '\n'; // std::cout << "Second is " << (*pni )->name() << '\n'; } { LLLinkedIter<PlainNode> pni(first, boost::bind(&PlainNode::next, _1)); ensure_equals("first", (*pni++)->name(), "a"); ensure_equals("second", (*pni )->name(), "b"); } } } // tut /***************************************************************************** * RCNode: LLLinkIter, refcounted *****************************************************************************/ class RCNode; typedef LLPointer<RCNode> RCNodePtr; class RCNode: public LLRefCount { public: RCNode(const std::string& name, const RCNodePtr& next=RCNodePtr()): mName(name), mNext(next) { // std::cout << "New RCNode(" << mName << ")\n"; } RCNode(const RCNode& that): mName(that.mName), mNext(that.mNext) { // std::cout << "Copy RCNode(" << mName << ")\n"; } virtual ~RCNode(); std::string name() const { return mName; } RCNodePtr next() const { return mNext; } public: // if this were 'private', couldn't bind mNext RCNodePtr mNext; private: std::string mName; }; std::ostream& operator<<(std::ostream& out, const RCNode& node) { out << "RCNode(" << node.name() << ')'; return out; } // This string contains the node name of the last RCNode destroyed. We use it // to validate that LLLinkedIter<RCNode> in fact contains LLPointer<RCNode>, // and that therefore an outstanding LLLinkedIter to an instance of a // refcounted class suffices to keep that instance alive. std::string last_RCNode_destroyed; RCNode::~RCNode() { // std::cout << "Kill " << *this << "\n"; last_RCNode_destroyed = mName; } namespace tut { template<> template<> void iter_object::test<2>() { // set_test_name("LLLinkedIter -- refcounted class"); LLLinkedIter<RCNode> rcni, end2; { // ScopeLabel label("inner scope"); RCNodePtr head(new RCNode("x", new RCNode("y", new RCNode("z")))); // for (rcni = LLLinkedIter<RCNode>(head, boost::bind(&RCNode::mNext, _1)); rcni != end2; ++rcni) // std::cout << **rcni << '\n'; rcni = LLLinkedIter<RCNode>(head, boost::bind(&RCNode::next, _1)); } // std::cout << "Now the LLLinkedIter<RCNode> is the only remaining reference to RCNode chain\n"; ensure_equals(last_RCNode_destroyed, ""); ensure(rcni != end2); ensure_equals((*rcni)->name(), "x"); ++rcni; ensure_equals(last_RCNode_destroyed, "x"); ensure(rcni != end2); ensure_equals((*rcni)->name(), "y"); ++rcni; ensure_equals(last_RCNode_destroyed, "y"); ensure(rcni != end2); ensure_equals((*rcni)->name(), "z"); ++rcni; ensure_equals(last_RCNode_destroyed, "z"); ensure(rcni == end2); } } /***************************************************************************** * TreeNode *****************************************************************************/ class TreeNode; typedef LLPointer<TreeNode> TreeNodePtr; /** * TreeNode represents a refcounted tree-node class that hasn't (yet) been * modified to incorporate LLTreeIter methods. This illustrates how you can * use tree iterators either standalone, or with free functions. */ class TreeNode: public LLRefCount { public: typedef std::vector<TreeNodePtr> list_type; typedef list_type::const_iterator child_iterator; // To avoid cycles, use a "weak" raw pointer for the parent link TreeNode(const std::string& name, TreeNode* parent=0): mParent(parent), mName(name) {} TreeNodePtr newChild(const std::string& name) { TreeNodePtr child(new TreeNode(name, this)); mChildren.push_back(child); return child; } std::string name() const { return mName; } TreeNodePtr getParent() const { return mParent; } child_iterator child_begin() const { return mChildren.begin(); } child_iterator child_end() const { return mChildren.end(); } private: std::string mName; // To avoid cycles, use a "weak" raw pointer for the parent link TreeNode* mParent; list_type mChildren; }; /** * This is an example of a helper function to facilitate iterating from a * TreeNode up to the root or down from the root (see LLTreeIter::RootIter). * * Example: * @code * BOOST_FOREACH(TreeNodePtr node, getRootRange<LLTreeIter::UP>(somenode)) * { * std::cout << node->name() << '\n'; * } * @endcode */ template <LLTreeIter::RootIter DISCRIM> boost::iterator_range< LLTreeRootIter<DISCRIM, TreeNode> > getRootRange(const TreeNodePtr& node) { typedef LLTreeRootIter<DISCRIM, TreeNode> iter_type; typedef boost::iterator_range<iter_type> range_type; return range_type(iter_type(node, boost::bind(&TreeNode::getParent, _1)), iter_type()); } /** * This is an example of a helper function to facilitate walking a given * TreeNode's subtree in any supported order (see LLTreeIter::WalkIter). * * Example: * @code * BOOST_FOREACH(TreeNodePtr node, getWalkRange<LLTreeIter::DFS_PRE>(root)) * { * std::cout << node->name() << '\n'; * } * @endcode */ template <LLTreeIter::WalkIter DISCRIM> boost::iterator_range< LLTreeWalkIter<DISCRIM, TreeNode, TreeNode::child_iterator> > getWalkRange(const TreeNodePtr& node) { typedef LLTreeWalkIter<DISCRIM, TreeNode, TreeNode::child_iterator> iter_type; typedef boost::iterator_range<iter_type> range_type; return range_type(iter_type(node, boost::bind(&TreeNode::child_begin, _1), boost::bind(&TreeNode::child_end, _1)), iter_type()); } /***************************************************************************** * EnhancedTreeNode *****************************************************************************/ class EnhancedTreeNode; typedef LLPointer<EnhancedTreeNode> EnhancedTreeNodePtr; /** * More typically, you enhance the tree-node class itself with template * methods like the above. This EnhancedTreeNode class illustrates the * technique. Normally, of course, you'd simply add these methods to TreeNode; * we put them in a separate class to preserve the undecorated TreeNode class * to illustrate (and test) the use of plain tree iterators and standalone * helper functions. * * We originally implemented EnhancedTreeNode as a subclass of TreeNode -- but * because TreeNode stores and manipulates TreeNodePtrs and TreeNode*s, * reusing its methods required so much ugly downcast logic that we gave up * and restated the whole class. Bear in mind that logically these aren't two * separate classes; logically they're two snapshots of the @em same class at * different moments in time. */ class EnhancedTreeNode: public LLRefCount { public: /*-------------- The following is restated from TreeNode ---------------*/ typedef std::vector<EnhancedTreeNodePtr> list_type; typedef list_type::const_iterator child_iterator; // To avoid cycles, use a "weak" raw pointer for the parent link EnhancedTreeNode(const std::string& name, EnhancedTreeNode* parent=0): mParent(parent), mName(name) {} EnhancedTreeNodePtr newChild(const std::string& name) { EnhancedTreeNodePtr child(new EnhancedTreeNode(name, this)); mChildren.push_back(child); return child; } std::string name() const { return mName; } EnhancedTreeNodePtr getParent() const { return mParent; } child_iterator child_begin() const { return mChildren.begin(); } child_iterator child_end() const { return mChildren.end(); } private: std::string mName; // To avoid cycles, use a "weak" raw pointer for the parent link EnhancedTreeNode* mParent; list_type mChildren; public: /*----- End of TreeNode; what follows is new with EnhancedTreeNode -----*/ /** * Because the type of the iterator range returned by getRootRange() * depends on the discriminator enum value, instead of a simple typedef we * use a templated struct. Example usage: * * @code * for (EnhancedTreeNode::root_range<LLTreeIter::UP>::type range = * somenode->getRootRange<LLTreeIter::UP>(); * range.first != range.second; ++range.first) * { * std::cout << (*range.first)->name() << '\n'; * } * @endcode */ template <LLTreeIter::RootIter DISCRIM> struct root_range { typedef boost::iterator_range< LLTreeRootIter<DISCRIM, EnhancedTreeNode> > type; }; /** * Helper method for walking up to (or down from) the tree root. See * LLTreeIter::RootIter. * * Example usage: * @code * BOOST_FOREACH(EnhancedTreeNodePtr node, somenode->getRootRange<LLTreeIter::UP>()) * { * std::cout << node->name() << '\n'; * } * @endcode */ template <LLTreeIter::RootIter DISCRIM> typename root_range<DISCRIM>::type getRootRange() const { typedef typename root_range<DISCRIM>::type range_type; typedef typename range_type::iterator iter_type; return range_type(iter_type(const_cast<EnhancedTreeNode*>(this), boost::bind(&EnhancedTreeNode::getParent, _1)), iter_type()); } /** * Because the type of the iterator range returned by getWalkRange() * depends on the discriminator enum value, instead of a simple typedef we * use a templated stuct. Example usage: * * @code * for (EnhancedTreeNode::walk_range<LLTreeIter::DFS_PRE>::type range = * somenode->getWalkRange<LLTreeIter::DFS_PRE>(); * range.first != range.second; ++range.first) * { * std::cout << (*range.first)->name() << '\n'; * } * @endcode */ template <LLTreeIter::WalkIter DISCRIM> struct walk_range { typedef boost::iterator_range< LLTreeWalkIter<DISCRIM, EnhancedTreeNode, EnhancedTreeNode::child_iterator> > type; }; /** * Helper method for walking a given node's subtree in any supported * order (see LLTreeIter::WalkIter). * * Example usage: * @code * BOOST_FOREACH(EnhancedTreeNodePtr node, somenode->getWalkRange<LLTreeIter::DFS_PRE>()) * { * std::cout << node->name() << '\n'; * } * @endcode */ template <LLTreeIter::WalkIter DISCRIM> typename walk_range<DISCRIM>::type getWalkRange() const { typedef typename walk_range<DISCRIM>::type range_type; typedef typename range_type::iterator iter_type; return range_type(iter_type(const_cast<EnhancedTreeNode*>(this), boost::bind(&EnhancedTreeNode::child_begin, _1), boost::bind(&EnhancedTreeNode::child_end, _1)), iter_type()); } }; /***************************************************************************** * PlainTree *****************************************************************************/ struct PlainTree { PlainTree(const std::string& name, PlainTree* parent=0): mName(name), mParent(parent), mNextSibling(0), mFirstChild(0) { mLastChildLink = &mFirstChild; } ~PlainTree() { delete mNextSibling; delete mFirstChild; } PlainTree* newChild(const std::string& name) { PlainTree* child(new PlainTree(name, this)); *mLastChildLink = child; mLastChildLink = &child->mNextSibling; return child; } std::string name() const { return mName; } std::string mName; PlainTree* mParent; PlainTree* mNextSibling; PlainTree* mFirstChild; PlainTree** mLastChildLink; }; // This "classic" tree tracks each node's children with a linked list anchored // at the parent's mFirstChild and linked through each child's mNextSibling. // LLTreeDFSIter<> and LLTreeBFSIter<> need functors to return begin()/end() // iterators over a given node's children. But because this tree's children // aren't stored in an STL container, we can't just export that container's // begin()/end(). Instead we'll use LLLinkedIter<> to view the hand-maintained // linked list as an iterator range. The straightforward way to do that would // be to add child_begin() and child_end() methods. But let's say (for the // sake of argument) that this struct is so venerable we don't dare modify it // even to add new methods. Well, we can use free functions (or functors) too. LLLinkedIter<PlainTree> PlainTree_child_begin(PlainTree* node) { return LLLinkedIter<PlainTree>(node->mFirstChild, boost::bind(&PlainTree::mNextSibling, _1)); } LLLinkedIter<PlainTree> PlainTree_child_end(PlainTree* node) { return LLLinkedIter<PlainTree>(); } /** * This is an example of a helper function to facilitate iterating from a * PlainTree up to the root or down from the root (see LLTreeIter::RootIter). * Note that we're simply overloading the same getRootRange() helper function * name we used for TreeNode. * * Example: * @code * BOOST_FOREACH(PlainTree* node, getRootRange<LLTreeIter::UP>(somenode)) * { * std::cout << node->name() << '\n'; * } * @endcode */ template <LLTreeIter::RootIter DISCRIM> boost::iterator_range< LLTreeRootIter<DISCRIM, PlainTree> > getRootRange(PlainTree* node) { typedef LLTreeRootIter<DISCRIM, PlainTree> iter_type; typedef boost::iterator_range<iter_type> range_type; return range_type(iter_type(node, boost::bind(&PlainTree::mParent, _1)), iter_type()); } /** * This is an example of a helper function to facilitate walking a given * PlainTree's subtree in any supported order (see LLTreeIter::WalkIter). Note * that we're simply overloading the same getWalkRange() helper function name * we used for TreeNode. * * Example: * @code * BOOST_FOREACH(PlainTree* node, getWalkRange<LLTreeIter::DFS_PRE>(root)) * { * std::cout << node->name() << '\n'; * } * @endcode */ template <LLTreeIter::WalkIter DISCRIM> boost::iterator_range< LLTreeWalkIter<DISCRIM, PlainTree, LLLinkedIter<PlainTree> > > getWalkRange(PlainTree* node) { typedef LLTreeWalkIter<DISCRIM, PlainTree, LLLinkedIter<PlainTree> > iter_type; typedef boost::iterator_range<iter_type> range_type; return range_type(iter_type(node, PlainTree_child_begin, PlainTree_child_end), iter_type()); } // We could go through the exercise of writing EnhancedPlainTree containing // root_range, getRootRange(), walk_range and getWalkRange() members -- but we // won't. See EnhancedTreeNode for examples. /***************************************************************************** * Generic tree test data *****************************************************************************/ template <class NODE> typename LLPtrTo<NODE>::type example_tree() { typedef typename LLPtrTo<NODE>::type NodePtr; NodePtr root(new NODE("root")); NodePtr A(root->newChild("A")); NodePtr A1(A->newChild("A1")); /* NodePtr A1a*/(A1->newChild("A1a")); /* NodePtr A1b*/(A1->newChild("A1b")); /* NodePtr A1c*/(A1->newChild("A1c")); NodePtr A2(A->newChild("A2")); /* NodePtr A2a*/(A2->newChild("A2a")); /* NodePtr A2b*/(A2->newChild("A2b")); /* NodePtr A2c*/(A2->newChild("A2c")); NodePtr A3(A->newChild("A3")); /* NodePtr A3a*/(A3->newChild("A3a")); /* NodePtr A3b*/(A3->newChild("A3b")); /* NodePtr A3c*/(A3->newChild("A3c")); NodePtr B(root->newChild("B")); NodePtr B1(B->newChild("B1")); /* NodePtr B1a*/(B1->newChild("B1a")); /* NodePtr B1b*/(B1->newChild("B1b")); /* NodePtr B1c*/(B1->newChild("B1c")); NodePtr B2(B->newChild("B2")); /* NodePtr B2a*/(B2->newChild("B2a")); /* NodePtr B2b*/(B2->newChild("B2b")); /* NodePtr B2c*/(B2->newChild("B2c")); NodePtr B3(B->newChild("B3")); /* NodePtr B3a*/(B3->newChild("B3a")); /* NodePtr B3b*/(B3->newChild("B3b")); /* NodePtr B3c*/(B3->newChild("B3c")); NodePtr C(root->newChild("C")); NodePtr C1(C->newChild("C1")); /* NodePtr C1a*/(C1->newChild("C1a")); /* NodePtr C1b*/(C1->newChild("C1b")); /* NodePtr C1c*/(C1->newChild("C1c")); NodePtr C2(C->newChild("C2")); /* NodePtr C2a*/(C2->newChild("C2a")); /* NodePtr C2b*/(C2->newChild("C2b")); /* NodePtr C2c*/(C2->newChild("C2c")); NodePtr C3(C->newChild("C3")); /* NodePtr C3a*/(C3->newChild("C3a")); /* NodePtr C3b*/(C3->newChild("C3b")); /* NodePtr C3c*/(C3->newChild("C3c")); return root; } // WalkExpected<WalkIter> is the list of string node names we expect from a // WalkIter traversal of our example_tree() data. template <LLTreeIter::WalkIter DISCRIM> struct WalkExpected: public Expected { // Initialize with bad_strings: we don't expect to use this generic case, // only the specializations. Note that for a classic C-style array we must // pass a pair of iterators rather than extracting boost::begin() and // boost::end() within the target constructor: a template ctor accepts // these classic C-style arrays as char** rather than char*[length]. Oh well. WalkExpected(): Expected(boost::begin(bad_strings), boost::end(bad_strings)) {} }; // list of string node names we expect from traversing example_tree() in // DFS_PRE order const char* dfs_pre_strings[] = { "root", "A", "A1", "A1a", "A1b", "A1c", "A2", "A2a", "A2b", "A2c", "A3", "A3a", "A3b", "A3c", "B", "B1", "B1a", "B1b", "B1c", "B2", "B2a", "B2b", "B2c", "B3", "B3a", "B3b", "B3c", "C", "C1", "C1a", "C1b", "C1c", "C2", "C2a", "C2b", "C2c", "C3", "C3a", "C3b", "C3c" }; // specialize WalkExpected<DFS_PRE> with the expected strings template <> struct WalkExpected<LLTreeIter::DFS_PRE>: public Expected { WalkExpected(): Expected(boost::begin(dfs_pre_strings), boost::end(dfs_pre_strings)) {} }; // list of string node names we expect from traversing example_tree() in // DFS_POST order const char* dfs_post_strings[] = { "A1a", "A1b", "A1c", "A1", "A2a", "A2b", "A2c", "A2", "A3a", "A3b", "A3c", "A3", "A", "B1a", "B1b", "B1c", "B1", "B2a", "B2b", "B2c", "B2", "B3a", "B3b", "B3c", "B3", "B", "C1a", "C1b", "C1c", "C1", "C2a", "C2b", "C2c", "C2", "C3a", "C3b", "C3c", "C3", "C", "root" }; // specialize WalkExpected<DFS_POST> with the expected strings template <> struct WalkExpected<LLTreeIter::DFS_POST>: public Expected { WalkExpected(): Expected(boost::begin(dfs_post_strings), boost::end(dfs_post_strings)) {} }; // list of string node names we expect from traversing example_tree() in BFS order const char* bfs_strings[] = { "root", "A", "B", "C", "A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3", "A1a", "A1b", "A1c", "A2a", "A2b", "A2c", "A3a", "A3b", "A3c", "B1a", "B1b", "B1c", "B2a", "B2b", "B2c", "B3a", "B3b", "B3c", "C1a", "C1b", "C1c", "C2a", "C2b", "C2c", "C3a", "C3b", "C3c" }; // specialize WalkExpected<BFS> with the expected strings template <> struct WalkExpected<LLTreeIter::BFS>: public Expected { WalkExpected(): Expected(boost::begin(bfs_strings), boost::end(bfs_strings)) {} }; // extract a particular "arbitrary" node from the example_tree() data: the // second (middle) node at each child level template <class NODE, typename CHILDITER> typename LLPtrTo<NODE>::type get_B2b(const typename LLPtrTo<NODE>::type& root, const boost::function<CHILDITER(const typename LLPtrTo<NODE>::type&)>& child_begin) { typedef typename LLPtrTo<NODE>::type NodePtr; CHILDITER Bi(child_begin(root)); ++Bi; NodePtr B(*Bi); CHILDITER B2i(child_begin(B)); ++B2i; NodePtr B2(*B2i); CHILDITER B2bi(child_begin(B2)); ++B2bi; NodePtr B2b(*B2bi); return B2b; } // RootExpected<RootIter> is the list of string node names we expect from a // RootIter traversal of our example_tree() data. template <LLTreeIter::RootIter DISCRIM> struct RootExpected: public Expected { // Initialize with bad_strings: we don't expect to use this generic case, // only the specializations. RootExpected(): Expected(boost::begin(bad_strings), boost::end(bad_strings)) {} }; // list of string node names we expect from traversing UP from // example_tree()'s B2b node const char* up_from_B2b[] = { "B2b", "B2", "B", "root" }; // specialize RootExpected<UP> with the expected strings template <> struct RootExpected<LLTreeIter::UP>: public Expected { RootExpected(): Expected(boost::begin(up_from_B2b), boost::end(up_from_B2b)) {} }; // list of string node names we expect from traversing DOWN to // example_tree()'s B2b node const char* down_to_B2b[] = { "root", "B", "B2", "B2b" }; // specialize RootExpected<DOWN> with the expected strings template <> struct RootExpected<LLTreeIter::DOWN>: public Expected { RootExpected(): Expected(boost::begin(down_to_B2b), boost::end(down_to_B2b)) {} }; /***************************************************************************** * Generic tree test functions *****************************************************************************/ template<LLTreeIter::RootIter DISCRIM, class NODE, typename PARENTFUNC> bool LLTreeRootIter_test(const std::string& itername, const std::string& nodename, const typename LLPtrTo<NODE>::type& node, PARENTFUNC parentfunc) { std::ostringstream desc; desc << itername << '<' << nodename << "> from " << node->name(); if (! verify(desc.str(), boost::make_iterator_range(LLTreeRootIter<DISCRIM, NODE>(node, parentfunc), LLTreeRootIter<DISCRIM, NODE>()), RootExpected<DISCRIM>())) return false; // std::cout << desc.str() << '\n'; // Try instantiating an iterator with NULL (that is, a default-constructed // node pointer). This test is less about "did we iterate once?" than "did // we avoid blowing up?" for (LLTreeRootIter<DISCRIM, NODE> hri = LLTreeRootIter<DISCRIM, NODE>(typename LLPtrTo<NODE>::type(), parentfunc), hrend; hri != hrend; /* ++hri */) // incrementing is moot, and MSVC complains { // std::cout << nodename << '(' << (*hri)->name() << ")\n"; std::cout << itername << '<' << nodename << ">(NULL)\n"; return false; } return true; } template<class NODE, typename CHILDITER, typename PARENTFUNC, typename CHILDFUNC> bool LLTreeUpIter_test(const std::string& nodename, PARENTFUNC parentfunc, CHILDFUNC childfunc) { bool success = true; typedef typename LLPtrTo<NODE>::type ptr_type; ptr_type root(example_tree<NODE>()); Cleanup<ptr_type> cleanup(root); ptr_type B2b(get_B2b<NODE, CHILDITER>(root, childfunc)); if (! LLTreeRootIter_test<LLTreeIter::UP, NODE>("LLTreeUpIter", nodename, B2b, parentfunc)) success = false; if (! LLTreeRootIter_test<LLTreeIter::DOWN, NODE>("LLTreeDownIter", nodename, B2b, parentfunc)) success = false; return success; } template <LLTreeIter::WalkIter DISCRIM, class NODE, typename CHILDITER, typename CHILDBEGINFUNC, typename CHILDENDFUNC> bool LLTreeWalkIter_test(const std::string& itername, const std::string& nodename, CHILDBEGINFUNC childbegin, CHILDENDFUNC childend) { typename LLPtrTo<NODE>::type root(example_tree<NODE>()); Cleanup<typename LLPtrTo<NODE>::type> cleanup(root); std::ostringstream desc; desc << itername << '<' << nodename << "> from " << root->name(); if (! verify(desc.str(), boost::make_iterator_range(LLTreeWalkIter<DISCRIM, NODE, CHILDITER>(root, childbegin, childend), LLTreeWalkIter<DISCRIM, NODE, CHILDITER>()), WalkExpected<DISCRIM>())) return false; // Try instantiating an iterator with NULL (that is, a default-constructed // node pointer). This test is less about "did we iterate once?" than "did // we avoid blowing up?" for (LLTreeWalkIter<DISCRIM, NODE, CHILDITER> twi = LLTreeWalkIter<DISCRIM, NODE, CHILDITER>(typename LLPtrTo<NODE>::type(), childbegin, childend), twend; twi != twend; /* ++twi */) // incrementing is moot, and MSVC complains { std::cout << itername << '<' << nodename << ">(NULL)\n"; return false; } return true; } template <class NODE, typename CHILDITER, typename PARENTFUNC, typename CHILDBEGINFUNC, typename CHILDENDFUNC> bool LLTreeIter_tests(const std::string& nodename, PARENTFUNC parentfunc, CHILDBEGINFUNC childbegin, CHILDENDFUNC childend) { bool success = true; if (! LLTreeUpIter_test<NODE, CHILDITER>(nodename, parentfunc, childbegin)) success = false; /*==========================================================================*| LLTreeIter_test<NODE, LLTreeDFSIter<NODE, CHILDITER> >("LLTreeDFSIter", nodename, childbegin, childend); LLTreeIter_test<NODE, LLTreeDFSPostIter<NODE, CHILDITER> >("LLTreeDFSPostIter", nodename, childbegin, childend); LLTreeIter_test<NODE, LLTreeBFSIter<NODE, CHILDITER> >("LLTreeBFSIter", nodename, childbegin, childend); |*==========================================================================*/ if (! LLTreeWalkIter_test<LLTreeIter::DFS_PRE, NODE, CHILDITER>("LLTreeDFSIter", nodename, childbegin, childend)) success = false; if (! LLTreeWalkIter_test<LLTreeIter::DFS_POST, NODE, CHILDITER>("LLTreeDFSPostIter", nodename, childbegin, childend)) success = false; if (! LLTreeWalkIter_test<LLTreeIter::BFS, NODE, CHILDITER>("LLTreeBFSIter", nodename, childbegin, childend)) success = false; return success; } namespace tut { template<> template<> void iter_object::test<3>() { // set_test_name("LLTreeIter tests"); ensure(LLTreeIter_tests<TreeNode, TreeNode::child_iterator> ("TreeNode", boost::bind(&TreeNode::getParent, _1), boost::bind(&TreeNode::child_begin, _1), boost::bind(&TreeNode::child_end, _1))); ensure(LLTreeIter_tests<PlainTree, LLLinkedIter<PlainTree> > ("PlainTree", boost::bind(&PlainTree::mParent, _1), PlainTree_child_begin, PlainTree_child_end)); } template<> template<> void iter_object::test<4>() { // set_test_name("getRootRange() tests"); // This test function illustrates the looping techniques described in the // comments for the getRootRange() free function, the // EnhancedTreeNode::root_range template and the // EnhancedTreeNode::getRootRange() method. Obviously the BOOST_FOREACH() // forms are more succinct. TreeNodePtr tnroot(example_tree<TreeNode>()); TreeNodePtr tnB2b(get_B2b<TreeNode, TreeNode::child_iterator> (tnroot, boost::bind(&TreeNode::child_begin, _1))); std::string desc1("BOOST_FOREACH(TreeNodePr, getRootRange<LLTreeIter::UP>(tnB2b))"); // std::cout << desc1 << "\n"; // Although we've commented out the output statement, ensure that the // loop construct is still valid, as promised by the getRootRange() // documentation. BOOST_FOREACH(TreeNodePtr node, getRootRange<LLTreeIter::UP>(tnB2b)) { // std::cout << node->name() << '\n'; } ensure(desc1, verify(desc1, getRootRange<LLTreeIter::UP>(tnB2b), RootExpected<LLTreeIter::UP>())); EnhancedTreeNodePtr etnroot(example_tree<EnhancedTreeNode>()); EnhancedTreeNodePtr etnB2b(get_B2b<EnhancedTreeNode, EnhancedTreeNode::child_iterator> (etnroot, boost::bind(&EnhancedTreeNode::child_begin, _1))); // std::cout << "EnhancedTreeNode::root_range<LLTreeIter::DOWN>::type range =\n" // << " etnB2b->getRootRange<LLTreeIter::DOWN>();\n" // << "for (EnhancedTreeNode::root_range<LLTreeIter::DOWN>::type::iterator ri = range.begin();\n" // << " ri != range.end(); ++ri)\n"; EnhancedTreeNode::root_range<LLTreeIter::DOWN>::type range = etnB2b->getRootRange<LLTreeIter::DOWN>(); for (EnhancedTreeNode::root_range<LLTreeIter::DOWN>::type::iterator ri = range.begin(); ri != range.end(); ++ri) { // std::cout << (*ri)->name() << '\n'; } std::string desc2("BOOST_FOREACH(EnhancedTreeNodePtr node, etnB2b->getRootRange<LLTreeIter::UP>())"); // std::cout << desc2 << '\n'; BOOST_FOREACH(EnhancedTreeNodePtr node, etnB2b->getRootRange<LLTreeIter::UP>()) { // std::cout << node->name() << '\n'; } ensure(desc2, verify(desc2, etnB2b->getRootRange<LLTreeIter::UP>(), RootExpected<LLTreeIter::UP>())); } template<> template<> void iter_object::test<5>() { // set_test_name("getWalkRange() tests"); // This test function doesn't illustrate the looping permutations for // getWalkRange(); see getRootRange_tests() for such examples. This // function simply verifies that they all work. // TreeNode, using helper function TreeNodePtr tnroot(example_tree<TreeNode>()); std::string desc_tnpre("getWalkRange<LLTreeIter::DFS_PRE>(tnroot)"); ensure(desc_tnpre, verify(desc_tnpre, getWalkRange<LLTreeIter::DFS_PRE>(tnroot), WalkExpected<LLTreeIter::DFS_PRE>())); std::string desc_tnpost("getWalkRange<LLTreeIter::DFS_POST>(tnroot)"); ensure(desc_tnpost, verify(desc_tnpost, getWalkRange<LLTreeIter::DFS_POST>(tnroot), WalkExpected<LLTreeIter::DFS_POST>())); std::string desc_tnb("getWalkRange<LLTreeIter::BFS>(tnroot)"); ensure(desc_tnb, verify(desc_tnb, getWalkRange<LLTreeIter::BFS>(tnroot), WalkExpected<LLTreeIter::BFS>())); // EnhancedTreeNode, using method EnhancedTreeNodePtr etnroot(example_tree<EnhancedTreeNode>()); std::string desc_etnpre("etnroot->getWalkRange<LLTreeIter::DFS_PRE>()"); ensure(desc_etnpre, verify(desc_etnpre, etnroot->getWalkRange<LLTreeIter::DFS_PRE>(), WalkExpected<LLTreeIter::DFS_PRE>())); std::string desc_etnpost("etnroot->getWalkRange<LLTreeIter::DFS_POST>()"); ensure(desc_etnpost, verify(desc_etnpost, etnroot->getWalkRange<LLTreeIter::DFS_POST>(), WalkExpected<LLTreeIter::DFS_POST>())); std::string desc_etnb("etnroot->getWalkRange<LLTreeIter::BFS>()"); ensure(desc_etnb, verify(desc_etnb, etnroot->getWalkRange<LLTreeIter::BFS>(), WalkExpected<LLTreeIter::BFS>())); // PlainTree, using helper function PlainTree* ptroot(example_tree<PlainTree>()); Cleanup<PlainTree*> cleanup(ptroot); std::string desc_ptpre("getWalkRange<LLTreeIter::DFS_PRE>(ptroot)"); ensure(desc_ptpre, verify(desc_ptpre, getWalkRange<LLTreeIter::DFS_PRE>(ptroot), WalkExpected<LLTreeIter::DFS_PRE>())); std::string desc_ptpost("getWalkRange<LLTreeIter::DFS_POST>(ptroot)"); ensure(desc_ptpost, verify(desc_ptpost, getWalkRange<LLTreeIter::DFS_POST>(ptroot), WalkExpected<LLTreeIter::DFS_POST>())); std::string desc_ptb("getWalkRange<LLTreeIter::BFS>(ptroot)"); ensure(desc_ptb, verify(desc_ptb, getWalkRange<LLTreeIter::BFS>(ptroot), WalkExpected<LLTreeIter::BFS>())); } } // tut
35.801483
128
0.577319
[ "object", "vector", "model" ]
1d680e75bbc653b04f13d22de379e3b8d3fb5f9c
12,697
cpp
C++
samples/lightingDemo.cpp
baherramzy/b-engine
70a52826843362b44f287457202706d9cc84be4d
[ "MIT" ]
null
null
null
samples/lightingDemo.cpp
baherramzy/b-engine
70a52826843362b44f287457202706d9cc84be4d
[ "MIT" ]
null
null
null
samples/lightingDemo.cpp
baherramzy/b-engine
70a52826843362b44f287457202706d9cc84be4d
[ "MIT" ]
null
null
null
#include <glad/glad.h> #include <glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include "../lib/Shader/shader.cpp" #include "../lib/Texture/texture.cpp" #include "../lib/Camera/camera.cpp" const unsigned int width = 800, height = 600; Camera camera; float frameDeltaTime = 0.0f; float lastFrameTimestamp = 0.0f; float lastFrameMouseX = width / 2; float lastFrameMouseY = height / 2; bool isFirstMouseMovement = true; unsigned int VAO, lightVAO; void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void handleKeyboardEvents(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float currentFrameTimestamp = glfwGetTime(); frameDeltaTime = currentFrameTimestamp - lastFrameTimestamp; lastFrameTimestamp = currentFrameTimestamp; float cameraSpeed = 4.0f * frameDeltaTime; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.moveForward(cameraSpeed); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.moveBackward(cameraSpeed); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.moveLeft(cameraSpeed); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.moveRight(cameraSpeed); } void mouse_movement_callback(GLFWwindow *window, double xPos, double yPos) { if (isFirstMouseMovement) { lastFrameMouseX = xPos; lastFrameMouseY = yPos; isFirstMouseMovement = false; } float xOffset = xPos - lastFrameMouseX; float yOffset = lastFrameMouseY - yPos; lastFrameMouseX = xPos; lastFrameMouseY = yPos; camera.processMouseMovement(xOffset, yOffset); } void defineCube() { float vertices[] = { /* Vertex Position */ /* Normal Vector */ /* Texture Co-ordinates */ -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; unsigned int VBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(VAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(sizeof(float) * 3)); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(sizeof(float) * 6)); glEnableVertexAttribArray(2); glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)0); glEnableVertexAttribArray(0); } glm::mat4 getMVPMatrix(glm::vec3 startPos) { glm::mat4 model, view, proj; model = view = proj = glm::mat4(1.0f); model = glm::translate(model, startPos); model = glm::scale(model, glm::vec3(0.2f)); view = camera.getViewMatrix(); proj = glm::perspective(glm::radians(45.0f), (float)(width / height), 0.1f, 100.0f); return proj * view * model; } int main(void) { GLFWwindow* window; if (!glfwInit()) return -1; window = glfwCreateWindow(width, height, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(window, mouse_movement_callback); gladLoadGL(); glEnable(GL_DEPTH_TEST); defineCube(); Shader lightingShader("shaders/lighting.vert", "shaders/lighting.frag"); lightingShader.use(); // Light source properties lightingShader.setVec3("light.ambient", glm::vec3(0.2f, 0.2f, 0.2f)); lightingShader.setVec3("light.diffuse", glm::vec3(0.5f, 0.5f, 0.5f)); lightingShader.setVec3("light.specular", glm::vec3(1.0f, 1.0f, 1.0f)); // Light attenuation parameters lightingShader.setFloat("light.attConstant", 1.0f); lightingShader.setFloat("light.attLinear", 0.07f); lightingShader.setFloat("light.attQuadratic", 0.017f); // Material light reflection properties lightingShader.setVec3("material.specular", glm::vec3(0.628281f, 0.555802f, 0.366065f)); lightingShader.setFloat("material.shine", 0.4f * 128.0f); // Load diffuse map texture Texture diffuseMap; const unsigned int diffuseMapID = diffuseMap.load("assets/Textures/diffuse_wood_container.png", 500, 500); lightingShader.setInt("material.diffuse", 0); // Load specular map texture Texture specularMap; const unsigned int specularMapID = specularMap.load("assets/Textures/specular_wood_container.png", 500, 500); lightingShader.setInt("material.specular", 1); glm::vec3 pointLightPositions[] = { glm::vec3( 0.7f, 0.2f, 2.0f), glm::vec3( 2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, 2.0f, -12.0f), glm::vec3( 0.0f, 0.0f, -3.0f) }; // Individual point light definitions lightingShader.setVec3("pointLights[0].position", pointLightPositions[0]); lightingShader.setVec3("pointLights[0].ambient", glm::vec3(0.05f, 0.05f, 0.05f)); lightingShader.setVec3("pointLights[0].diffuse", glm::vec3(0.8f, 0.8f, 0.8f)); lightingShader.setVec3("pointLights[0].specular", glm::vec3(1.0f, 1.0f, 1.0f)); lightingShader.setFloat("pointLights[0].attConstant", 1.0f); lightingShader.setFloat("pointLights[0].attLinear", 0.09); lightingShader.setFloat("pointLights[0].attQuadratic", 0.032); lightingShader.setVec3("pointLights[1].position", pointLightPositions[1]); lightingShader.setVec3("pointLights[1].ambient", glm::vec3(0.05f, 0.05f, 0.05f)); lightingShader.setVec3("pointLights[1].diffuse", glm::vec3(0.8f, 0.8f, 0.8f)); lightingShader.setVec3("pointLights[1].specular", glm::vec3(1.0f, 1.0f, 1.0f)); lightingShader.setFloat("pointLights[1].attConstant", 1.0f); lightingShader.setFloat("pointLights[1].attLinear", 0.09); lightingShader.setFloat("pointLights[1].attQuadratic", 0.032); lightingShader.setVec3("pointLights[2].position", pointLightPositions[2]); lightingShader.setVec3("pointLights[2].ambient", glm::vec3(0.05f, 0.05f, 0.05f)); lightingShader.setVec3("pointLights[2].diffuse",glm::vec3( 0.8f, 0.8f, 0.8f)); lightingShader.setVec3("pointLights[2].specular", glm::vec3(1.0f, 1.0f, 1.0f)); lightingShader.setFloat("pointLights[2].attConstant", 1.0f); lightingShader.setFloat("pointLights[2].attLinear", 0.09); lightingShader.setFloat("pointLights[2].attQuadratic", 0.032); lightingShader.setVec3("pointLights[3].position", pointLightPositions[3]); lightingShader.setVec3("pointLights[3].ambient", glm::vec3(0.05f, 0.05f, 0.05f)); lightingShader.setVec3("pointLights[3].diffuse", glm::vec3(0.8f, 0.8f, 0.8f)); lightingShader.setVec3("pointLights[3].specular", glm::vec3(1.0f, 1.0f, 1.0f)); lightingShader.setFloat("pointLights[3].attConstant", 1.0f); lightingShader.setFloat("pointLights[3].attLinear", 0.09); lightingShader.setFloat("pointLights[3].attQuadratic", 0.032); lightingShader.setVec3("dirLight.direction", glm::vec3(-0.2f, -1.0f, -0.3f)); lightingShader.setVec3("dirLight.ambient", glm::vec3(0.05f, 0.05f, 0.05f)); lightingShader.setVec3("dirLight.diffuse", glm::vec3(0.4f, 0.4f, 0.4f)); lightingShader.setVec3("dirLight.specular", glm::vec3(0.5f, 0.5f, 0.5f)); Shader lampShader("shaders/lamp.vert", "shaders/lamp.frag"); while (!glfwWindowShouldClose(window)) { handleKeyboardEvents(window); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; glm::mat4 model, view, proj; view = proj = glm::mat4(1.0f); view = camera.getViewMatrix(); proj = glm::perspective(glm::radians(45.0f), (float)(width / height), 0.1f, 100.0f); // glm::vec3 lightPos(sin(glfwGetTime() * 1.2f) * 2.0f, sin(glfwGetTime() * 1.2f) * 1.5f, cos(glfwGetTime() * 1.2f) * 2.0f); glm::vec3 lightPos(1.0f, 2.0f, 2.0f); lightingShader.use(); lightingShader.setVec3("light.position", camera.pos); lightingShader.setVec3("light.direction", camera.front); lightingShader.setFloat("light.cutOff", glm::cos(glm::radians(12.5f))); lightingShader.setFloat("light.outerCutOff", glm::cos(glm::radians(17.5f))); lightingShader.setVec3("cameraPos", camera.pos); lightingShader.setMat4("view", view); lightingShader.setMat4("proj", proj); // Diffuse map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMapID); // Specular map glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMapID); glBindVertexArray(VAO); for(int i = 0; i < 10; ++i) { model = glm::mat4(1.0f); model = glm::translate(model, cubePositions[i]); lightingShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } lampShader.use(); lampShader.setMat4("view", view); lampShader.setMat4("proj", proj); // model = glm::translate(model, lightPos); // model = glm::scale(model, glm::vec3(0.2f)); // lampShader.setMat4("model", model); for(int i = 0; i < 4; ++i) { model = glm::mat4(1.0f); model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f)); lampShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
37.125731
132
0.605261
[ "vector", "model" ]
1d6bc6008c457251713132d3e6a9b06609ed22df
40,395
cxx
C++
TPC/TPCsim/AliTPCDigitizer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
TPC/TPCsim/AliTPCDigitizer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
2
2016-11-25T08:40:56.000Z
2019-10-11T12:29:29.000Z
TPC/TPCsim/AliTPCDigitizer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /* Class for creating of the sumable digits and digits from MC data // The input : ideal signals (Hits->Diffusion->Attachment -Ideal signal) The output: "raw digits" Effect implemented: 1. Pad by pad gain map 2. Noise map 3. The dead channels identified - zerro noise for corresponding pads In this case the outpu equal zerro */ #include <stdlib.h> #include <TTree.h> #include <TObjArray.h> #include <TFile.h> #include <TDirectory.h> #include <Riostream.h> #include <TParameter.h> #include "AliTPCDigitizer.h" #include "AliTPC.h" #include "AliTPCParam.h" #include "AliTPCParamSR.h" #include "AliRun.h" #include "AliLoader.h" #include "AliPDG.h" #include "AliDigitizationInput.h" #include "AliSimDigits.h" #include "AliLog.h" #include "AliTPCcalibDB.h" #include "AliTPCCalPad.h" #include "AliTPCCalROC.h" #include "TTreeStream.h" #include "AliTPCReconstructor.h" #include <TGraphErrors.h> #include "AliTPCSAMPAEmulator.h" AliTPCSAMPAEmulator * AliTPCDigitizer::fgSAMPAEmulator=0; using std::cout; using std::cerr; using std::endl; ClassImp(AliTPCDigitizer) //___________________________________________ AliTPCDigitizer::AliTPCDigitizer() :AliDigitizer(),fDebug(0), fDebugStreamer(0) { // // Default ctor - don't use it // } //___________________________________________ AliTPCDigitizer::AliTPCDigitizer(AliDigitizationInput* digInput) :AliDigitizer(digInput),fDebug(0), fDebugStreamer(0) { // // ctor which should be used // AliDebug(2,"(AliDigitizationInput* digInput) was processed"); if (AliTPCReconstructor::StreamLevel()>0) fDebugStreamer = new TTreeSRedirector("TPCDigitDebug.root","recreate"); } //------------------------------------------------------------------------ AliTPCDigitizer::~AliTPCDigitizer() { // Destructor if (fDebugStreamer) delete fDebugStreamer; } //------------------------------------------------------------------------ Bool_t AliTPCDigitizer::Init() { // Initialization return kTRUE; } //------------------------------------------------------------------------ void AliTPCDigitizer::Digitize(Option_t* option) { //DigitizeFast(option); DigitizeWithTailAndCrossTalk(option); } //------------------------------------------------------------------------ void AliTPCDigitizer::DigitizeFast(Option_t* option) { // merge input tree's with summable digits //output stored in TreeTPCD char s[100]; char ss[100]; TString optionString = option; if (!strcmp(optionString.Data(),"deb")) { cout<<"AliTPCDigitizer:::DigitizeFast called with option deb "<<endl; fDebug = 3; } //get detector and geometry AliRunLoader *rl, *orl; AliLoader *gime, *ogime; if (gAlice == 0x0) { Warning("DigitizeFast","gAlice is NULL. Loading from input 0"); rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(0)); if (rl == 0x0) { Error("DigitizeFast","Can not find Run Loader for input 0. Can not proceed."); return; } rl->LoadgAlice(); rl->GetAliRun(); } AliTPC *pTPC = (AliTPC *) gAlice->GetModule("TPC"); AliTPCParam * param = pTPC->GetParam(); const Bool_t useGlitchFilter=param->GetUseGlitchFilter(); //sprintf(s,param->GetTitle()); snprintf(s,100,"%s",param->GetTitle()); //sprintf(ss,"75x40_100x60"); snprintf(ss,100,"75x40_100x60"); if(strcmp(s,ss)==0){ printf("2 pad-length geom hits with 3 pad-lenght geom digits...\n"); delete param; param=new AliTPCParamSR(); } else{ //sprintf(ss,"75x40_100x60_150x60"); snprintf(ss,100,"75x40_100x60_150x60"); if(strcmp(s,ss)!=0) { printf("No TPC parameters found...\n"); exit(2); } } pTPC->GenerNoise(500000, kFALSE); //create table with noise // Int_t nInputs = fDigInput->GetNinputs(); Int_t * masks = new Int_t[nInputs]; for (Int_t i=0; i<nInputs;i++) masks[i]= fDigInput->GetMask(i); Short_t **pdig= new Short_t*[nInputs]; //pointers to the expanded digits array Int_t **ptr= new Int_t*[nInputs]; //pointers to the expanded tracks array Bool_t *active= new Bool_t[nInputs]; //flag for active input segments Char_t phname[100]; //create digits array for given sectors // make indexes // //create branch's in TPC treeD orl = AliRunLoader::GetRunLoader(fDigInput->GetOutputFolderName()); ogime = orl->GetLoader("TPCLoader"); TTree * tree = ogime->TreeD(); AliSimDigits * digrow = new AliSimDigits; if (tree == 0x0) { ogime->MakeTree("D"); tree = ogime->TreeD(); } tree->Branch("Segment","AliSimDigits",&digrow); // AliSimDigits ** digarr = new AliSimDigits*[nInputs]; for (Int_t i1=0;i1<nInputs; i1++) { digarr[i1]=0; // intree[i1] rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i1)); gime = rl->GetLoader("TPCLoader"); gime->LoadSDigits("read"); TTree * treear = gime->TreeS(); if (!treear) { cerr<<"AliTPCDigitizer: Input tree with SDigits not found in" <<" input "<< i1<<endl; for (Int_t i2=0;i2<i1+1; i2++){ if(digarr[i2]) delete digarr[i2]; } delete [] digarr; delete [] active; delete []masks; delete []pdig; delete []ptr; return; } //sprintf(phname,"lhcphase%d",i1); snprintf(phname,100,"lhcphase%d",i1); TParameter<float> *ph = (TParameter<float>*)treear->GetUserInfo() ->FindObject("lhcphase0"); if(!ph){ cerr<<"AliTPCDigitizer: LHC phase not found in" <<" input "<< i1<<endl; for (Int_t i2=0;i2<i1+1; i2++){ if(digarr[i2]) delete digarr[i2]; } delete [] digarr; delete [] active; delete []masks; delete []pdig; delete []ptr; return; } tree->GetUserInfo()->Add(new TParameter<float>(phname,ph->GetVal())); // if (treear->GetIndex()==0) treear->BuildIndex("fSegmentID","fSegmentID"); treear->GetBranch("Segment")->SetAddress(&digarr[i1]); } // Int_t zerosup = param->GetZeroSup(); AliTPCCalPad * gainTPC = AliTPCcalibDB::Instance()->GetDedxGainFactor(); AliTPCCalPad * noiseTPC = AliTPCcalibDB::Instance()->GetPadNoise(); // //Loop over segments of the TPC for (Int_t segmentID=0; segmentID<param->GetNRowsTotal(); segmentID++) { Int_t sector, padRow; if (!param->AdjustSectorRow(segmentID,sector,padRow)) { cerr<<"AliTPC warning: invalid segment ID ! "<<segmentID<<endl; continue; } AliTPCCalROC * gainROC = gainTPC->GetCalROC(sector); // pad gains per given sector AliTPCCalROC * noiseROC = noiseTPC->GetCalROC(sector); // noise per given sector digrow->SetID(segmentID); Int_t nTimeBins = 0; Int_t nPads = 0; Bool_t digitize = kFALSE; for (Int_t i=0;i<nInputs; i++) { rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i)); gime = rl->GetLoader("TPCLoader"); if (gime->TreeS()->GetEntryWithIndex(segmentID,segmentID) >= 0) { digarr[i]->ExpandBuffer(); digarr[i]->ExpandTrackBuffer(); nTimeBins = digarr[i]->GetNRows(); nPads = digarr[i]->GetNCols(); active[i] = kTRUE; if (!GetRegionOfInterest() || (i == 0)) digitize = kTRUE; } else { active[i] = kFALSE; } if (GetRegionOfInterest() && !digitize) break; } if (!digitize) continue; digrow->Allocate(nTimeBins,nPads); digrow->AllocateTrack(3); Float_t q=0; Int_t label[1000]; //stack for 300 events Int_t labptr = 0; Int_t nElems = nTimeBins*nPads; for (Int_t i=0;i<nInputs; i++) if (active[i]) { pdig[i] = digarr[i]->GetDigits(); ptr[i] = digarr[i]->GetTracks(); } Short_t *pdig1= digrow->GetDigits(); Int_t *ptr1= digrow->GetTracks() ; for (Int_t elem=0;elem<nElems; elem++) { q=0; labptr=0; // looop over digits for (Int_t i=0;i<nInputs; i++) if (active[i]) { // q += digarr[i]->GetDigitFast(rows,col); q += *(pdig[i]); for (Int_t tr=0;tr<3;tr++) { // Int_t lab = digarr[i]->GetTrackIDFast(rows,col,tr); Int_t lab = ptr[i][tr*nElems]; if ( (lab > 1) && *(pdig[i])>zerosup) { label[labptr]=lab+masks[i]; labptr++; } } pdig[i]++; ptr[i]++; } q/=16.; //conversion factor Float_t gain = gainROC->GetValue(padRow,elem/nTimeBins); // get gain for given - pad-row pad //if (gain<0.5){ //printf("problem\n"); //} q*= gain; Float_t noisePad = noiseROC->GetValue(padRow,elem/nTimeBins); // Float_t noise = gRandom->Gaus(0,param->GetNoise()*param->GetNoiseNormFac()); Float_t noise = pTPC->GetNoise(); q+=noise*noisePad; q=TMath::Nint(q); if (q > zerosup) { if(q >= param->GetADCSat()) q = (Short_t)(param->GetADCSat() - 1); //digrow->SetDigitFast((Short_t)q,rows,col); *pdig1 =Short_t(q); for (Int_t tr=0;tr<3;tr++) { if (tr<labptr) ptr1[tr*nElems] = label[tr]; } } pdig1++; ptr1++; } // // glitch filter // if (useGlitchFilter) digrow->GlitchFilter(); // digrow->CompresBuffer(1,zerosup); digrow->CompresTrackBuffer(1); tree->Fill(); if (fDebug>0) cerr<<sector<<"\t"<<padRow<<"\n"; } //for (Int_t n=0; n<param->GetNRowsTotal(); n++) orl = AliRunLoader::GetRunLoader(fDigInput->GetOutputFolderName()); ogime = orl->GetLoader("TPCLoader"); ogime->WriteDigits("OVERWRITE"); //fDigInput->GetTreeDTPC()->Write(0,TObject::kOverwrite); delete digrow; for (Int_t i1=0;i1<nInputs; i1++) delete digarr[i1]; delete []masks; delete []pdig; delete []ptr; delete []active; delete []digarr; } //------------------------------------------------------------------------ void AliTPCDigitizer::DigitizeSave(Option_t* option) { // // Merge input tree's with summable digits // Output digits stored in TreeTPCD // // Not active for long time. // Before adding modification (for ion tail calucation and for the crorsstalk) it should be // checked one by one with currenlty used AliTPCDigitizer::DigitizeFast // TString optionString = option; if (!strcmp(optionString.Data(),"deb")) { cout<<"AliTPCDigitizer::Digitize: called with option deb "<<endl; fDebug = 3; } //get detector and geometry AliRunLoader *rl, *orl; AliLoader *gime, *ogime; orl = AliRunLoader::GetRunLoader(fDigInput->GetOutputFolderName()); ogime = orl->GetLoader("TPCLoader"); rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(0)); //gime = rl->GetLoader("TPCLoader"); rl->GetLoader("TPCLoader"); rl->LoadgAlice(); AliRun* alirun = rl->GetAliRun(); AliTPC *pTPC = (AliTPC *) alirun->GetModule("TPC"); AliTPCParam * param = pTPC->GetParam(); pTPC->GenerNoise(500000); //create teble with noise printf("noise %f \n", param->GetNoise()*param->GetNoiseNormFac()); // Int_t nInputs = fDigInput->GetNinputs(); // stupid protection... if (nInputs <= 0) return; // Int_t * masks = new Int_t[nInputs]; for (Int_t i=0; i<nInputs;i++) masks[i]= fDigInput->GetMask(i); AliSimDigits ** digarr = new AliSimDigits*[nInputs]; for(Int_t ii=0;ii<nInputs;ii++) digarr[ii]=0; for (Int_t i1=0;i1<nInputs; i1++) { //digarr[i1]=0; // intree[i1] rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i1)); gime = rl->GetLoader("TPCLoader"); TTree * treear = gime->TreeS(); // if (!treear) { cerr<<" TPC - not existing input = \n"<<i1<<" "; delete [] masks; for(Int_t i=0; i<nInputs; i++) delete digarr[i]; delete [] digarr; return; } // TBranch * br = treear->GetBranch("fSegmentID"); if (br) br->GetFile()->cd(); treear->GetBranch("Segment")->SetAddress(&digarr[i1]); } rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(0)); gime = rl->GetLoader("TPCLoader"); Stat_t nentries = gime->TreeS()->GetEntries(); //create branch's in TPC treeD AliSimDigits * digrow = new AliSimDigits; TTree * tree = ogime->TreeD(); tree->Branch("Segment","AliSimDigits",&digrow); Int_t zerosup = param->GetZeroSup(); //Loop over segments of the TPC AliTPCCalPad * gainTPC = AliTPCcalibDB::Instance()->GetDedxGainFactor(); AliTPCCalPad * noiseTPC = AliTPCcalibDB::Instance()->GetPadNoise(); for (Int_t n=0; n<nentries; n++) { rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(0)); gime = rl->GetLoader("TPCLoader"); gime->TreeS()->GetEvent(n); digarr[0]->ExpandBuffer(); digarr[0]->ExpandTrackBuffer(); for (Int_t i=1;i<nInputs; i++){ // fDigInput->GetInputTreeTPCS(i)->GetEntryWithIndex(digarr[0]->GetID(),digarr[0]->GetID()); rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i)); gime = rl->GetLoader("TPCLoader"); gime->TreeS()->GetEntryWithIndex(digarr[0]->GetID(),digarr[0]->GetID()); digarr[i]->ExpandBuffer(); digarr[i]->ExpandTrackBuffer(); if ((digarr[0]->GetID()-digarr[i]->GetID())>0) printf("problem\n"); } Int_t sector, padRow; if (!param->AdjustSectorRow(digarr[0]->GetID(),sector,padRow)) { cerr<<"AliTPC warning: invalid segment ID ! "<<digarr[0]->GetID()<<endl; continue; } AliTPCCalROC * gainROC = gainTPC->GetCalROC(sector); // pad gains per given sector AliTPCCalROC * noiseROC = noiseTPC->GetCalROC(sector); // noise per given sector digrow->SetID(digarr[0]->GetID()); Int_t nTimeBins = digarr[0]->GetNRows(); Int_t nPads = digarr[0]->GetNCols(); digrow->Allocate(nTimeBins,nPads); digrow->AllocateTrack(3); Float_t q=0; Int_t label[1000]; //stack for 300 events Int_t labptr = 0; for (Int_t iTimeBin=0;iTimeBin<nTimeBins; iTimeBin++){ // iTimeBin for (Int_t iPad=0;iPad<nPads; iPad++){ // pad q=0; labptr=0; // looop over digits for (Int_t i=0;i<nInputs; i++){ q += digarr[i]->GetDigitFast(iTimeBin,iPad); //q += *(pdig[i]); for (Int_t tr=0;tr<3;tr++) { Int_t lab = digarr[i]->GetTrackIDFast(iTimeBin,iPad,tr); //Int_t lab = ptr[i][tr*nElems]; if ( (lab > 1) ) { label[labptr]=lab+masks[i]; labptr++; } } // pdig[i]++; //ptr[i]++; } q/=16.; //conversion factor // Float_t noise = gRandom->Gaus(0,param->GetNoise()*param->GetNoiseNormFac()); Float_t gain = gainROC->GetValue(padRow,iPad); q*= gain; Float_t noisePad = noiseROC->GetValue(padRow, iPad); Float_t noise = pTPC->GetNoise(); q+=noise*noisePad; // // here we can get digits from past and add signal // // //for (Int_t jTimeBin=0; jTimeBin<iTimeBin; jTimeBin++) // q+=ionTail // q=TMath::Nint(q); if (q > zerosup){ if(q >= param->GetADCSat()) q = (Short_t)(param->GetADCSat() - 1); digrow->SetDigitFast((Short_t)q,iTimeBin,iPad); // *pdig1 =Short_t(q); for (Int_t tr=0;tr<3;tr++){ if (tr<labptr) ((AliSimDigits*)digrow)->SetTrackIDFast(label[tr],iTimeBin,iPad,tr); //ptr1[tr*nElems] = label[tr]; //else // ((AliSimDigits*)digrow)->SetTrackIDFast(-1,iTimeBin,iPad,tr); // ptr1[tr*nElems] = 1; } } //pdig1++; //ptr1++; } } digrow->CompresBuffer(1,zerosup); digrow->CompresTrackBuffer(1); tree->Fill(); if (fDebug>0) cerr<<sector<<"\t"<<padRow<<"\n"; } // printf("end TPC merging - end -Tree %s\t%p\n",fDigInput->GetInputTreeH(0)->GetName(),fDigInput->GetInputTreeH(0)->GetListOfBranches()->At(3)); //fDigInput->GetTreeDTPC()->Write(0,TObject::kOverwrite); ogime->WriteDigits("OVERWRITE"); for (Int_t i=1;i<nInputs; i++) { rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i)); gime = rl->GetLoader("TPCLoader"); gime->UnloadSDigits(); } ogime->UnloadDigits(); delete digrow; for (Int_t i1=0;i1<nInputs; i1++) delete digarr[i1]; delete [] masks; delete [] digarr; } //------------------------------------------------------------------------ void AliTPCDigitizer::DigitizeWithTailAndCrossTalk(Option_t* option) { // Modified version of the digitization function // Modification: adding the ion tail and crosstalk: // // pcstream used in order to visually inspect data // // // Crosstalk simulation: // 1.) Calculate per time bin mean charge (per pad) within anode wire segment // 2.) Subsract for the clusters at given time bin fraction of (mean charge) normalized by add hoc constant // AliTPCRecoParam::GetCrosstalkCorrection() (0 if not crosstalk, 1 if ideal crosstalk) // for simplicity we are assuming that wire segents are related to pad-rows // Wire segmentationn is obtatined from the // AliTPCParam::GetWireSegment(Int_t sector, Int_t row); // to be implemented // AliTPCParam::GetNPadsPerSegment(Int_t segmentID); // to be implemented // 3.) Substract form the signal contribution from the previous tracks - Ion tail in case speified in the AliTPCRecoParam // AliTPCRecoParam::GetUseIonTailCorrection() // // Ion tail simulation: // 1.) Needs signal from pad+-1, taking signal from history // merge input tree's with summable digits // output stored in TreeTPCD // AliTPCcalibDB* const calib=AliTPCcalibDB::Instance(); // AliTPCRecoParam *recoParam = calib->GetRecoParam(0); AliTPCRecoParam *recoParam = calib->GetRecoParamFromGRP(); // RS event specie will be selected according to GRP AliDebug(1, Form(" recoParam->GetCrosstalkCorrection() = %f", recoParam->GetCrosstalkCorrection())); AliDebug(1,Form(" recoParam->GetUseIonTailCorrection() = %d ", recoParam->GetUseIonTailCorrection())); Int_t nROCs = 72; char s[100]; char ss[100]; TString optionString = option; if (!strcmp(optionString.Data(),"deb")) { cout<<"AliTPCDigitizer:::DigitizeFast called with option deb "<<endl; fDebug = 3; } // ======== get detector and geometry ======= AliRunLoader *rl, *orl; AliLoader *gime, *ogime; if (gAlice == 0x0) { Warning("DigitizeFast","gAlice is NULL. Loading from input 0"); rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(0)); if (rl == 0x0) { Error("DigitizeFast","Can not find Run Loader for input 0. Can not proceed."); return; } rl->LoadgAlice(); rl->GetAliRun(); } AliTPC *pTPC = (AliTPC *) gAlice->GetModule("TPC"); AliTPCParam * param = pTPC->GetParam(); const Bool_t useGlitchFilter=param->GetUseGlitchFilter(); //sprintf(s,param->GetTitle()); snprintf(s,100,"%s",param->GetTitle()); //sprintf(ss,"75x40_100x60"); snprintf(ss,100,"75x40_100x60"); if(strcmp(s,ss)==0){ printf("2 pad-length geom hits with 3 pad-lenght geom digits...\n"); delete param; param=new AliTPCParamSR(); } else { //sprintf(ss,"75x40_100x60_150x60"); snprintf(ss,100,"75x40_100x60_150x60"); if(strcmp(s,ss)!=0) { printf("No TPC parameters found...\n"); exit(2); } } pTPC->GenerNoise(500000); //create table with noise // Int_t nInputs = fDigInput->GetNinputs(); Int_t * masks = new Int_t[nInputs]; for (Int_t i=0; i<nInputs;i++) masks[i]= fDigInput->GetMask(i); Short_t **pdig= new Short_t*[nInputs]; //pointers to the expanded digits array Int_t **ptr= new Int_t*[nInputs]; //pointers to the expanded tracks array Bool_t *active= new Bool_t[nInputs]; //flag for active input segments Char_t phname[100]; //create digits array for given sectors // make indexes // //create branch's in TPC treeD orl = AliRunLoader::GetRunLoader(fDigInput->GetOutputFolderName()); ogime = orl->GetLoader("TPCLoader"); TTree * tree = ogime->TreeD(); AliSimDigits * digrow = new AliSimDigits; if (tree == 0x0) { ogime->MakeTree("D"); tree = ogime->TreeD(); } tree->Branch("Segment","AliSimDigits",&digrow); // AliSimDigits ** digarr = new AliSimDigits*[nInputs]; for (Int_t i1=0;i1<nInputs; i1++) { digarr[i1]=0; // intree[i1] rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i1)); gime = rl->GetLoader("TPCLoader"); gime->LoadSDigits("read"); TTree * treear = gime->TreeS(); if (!treear) { cerr<<"AliTPCDigitizer: Input tree with SDigits not found in" <<" input "<< i1<<endl; for (Int_t i2=0;i2<i1+1; i2++){ if(digarr[i2]) delete digarr[i2]; } delete [] digarr; delete [] active; delete []masks; delete []pdig; delete []ptr; return; } //sprintf(phname,"lhcphase%d",i1); snprintf(phname,100,"lhcphase%d",i1); TParameter<float> *ph = (TParameter<float>*)treear->GetUserInfo() ->FindObject("lhcphase0"); if(!ph) { cerr<<"AliTPCDigitizer: LHC phase not found in" <<" input "<< i1<<endl; for (Int_t i2=0;i2<i1+1; i2++){ if(digarr[i2]) delete digarr[i2]; } delete [] digarr; delete [] active; delete []masks; delete []pdig; delete []ptr; return; } tree->GetUserInfo()->Add(new TParameter<float>(phname,ph->GetVal())); // if (treear->GetIndex()==0) treear->BuildIndex("fSegmentID","fSegmentID"); treear->GetBranch("Segment")->SetAddress(&digarr[i1]); } // // zero supp, take gain and noise map of TPC from OCDB Int_t zerosup = param->GetZeroSup(); AliTPCCalPad * gainTPC = AliTPCcalibDB::Instance()->GetDedxGainFactor(); AliTPCCalPad * noiseTPC = AliTPCcalibDB::Instance()->GetPadNoise(); // // Cache the ion tail objects form OCDB // TObjArray *ionTailArr = (TObjArray*)AliTPCcalibDB::Instance()->GetIonTailArray(); if (!ionTailArr) {AliFatal("TPC - Missing IonTail OCDB object");} // TObject *rocFactorIROC = ionTailArr->FindObject("factorIROC"); // TObject *rocFactorOROC = ionTailArr->FindObject("factorOROC"); // Float_t factorIROC = (atof(rocFactorIROC->GetTitle())); // Float_t factorOROC = (atof(rocFactorOROC->GetTitle())); Int_t nIonTailBins =0; TObjArray timeResFunc(nROCs); for (Int_t isec = 0;isec<nROCs;isec++){ //loop overs sectors // Array of TGraphErrors for a given sector TGraphErrors ** graphRes = new TGraphErrors *[20]; Float_t * trfIndexArr = new Float_t[20]; for (Int_t icache=0; icache<20; icache++) { graphRes[icache] = NULL; trfIndexArr[icache] = 0; } if (!AliTPCcalibDB::Instance()->GetTailcancelationGraphs(isec,graphRes,trfIndexArr)) continue; // fill all TGraphErrors of trfs (time response function) of a given sector to a TObjArray TObjArray *timeResArr = new TObjArray(20); timeResArr -> SetOwner(kTRUE); for (Int_t ires = 0;ires<20;ires++) timeResArr->AddAt(graphRes[ires],ires); timeResFunc.AddAt(timeResArr,isec); // Fill all trfs into a single TObjArray nIonTailBins = graphRes[3]->GetN(); } // // 1.) Make first loop to calculate mean amplitude per pad per segment for cross talk // TObjArray crossTalkSignalArray(nROCs); // for 36 sectors TVectorD * qTotSector = new TVectorD(nROCs); TVectorD * nTotSector = new TVectorD(nROCs); Float_t qTotTPC = 0.; Float_t qTotPerSector = 0.; Float_t nTotPerSector = 0.; Int_t nTimeBinsAll = 1100; Int_t nWireSegments=11; // 1.a) crorstalk matrix initialization for (Int_t sector=0; sector<nROCs; sector++){ TMatrixD *pcrossTalkSignal = new TMatrixD(nWireSegments,nTimeBinsAll); for (Int_t imatrix = 0; imatrix<11; imatrix++) for (Int_t jmatrix = 0; jmatrix<nTimeBinsAll; jmatrix++){ (*pcrossTalkSignal)[imatrix][jmatrix]=0.; } crossTalkSignalArray.AddAt(pcrossTalkSignal,sector); } // // main loop over rows of whole TPC for (Int_t globalRowID=0; globalRowID<param->GetNRowsTotal(); globalRowID++) { Int_t sector, padRow; if (!param->AdjustSectorRow(globalRowID,sector,padRow)) { cerr<<"AliTPC warning: invalid segment ID ! "<<globalRowID<<endl; continue; } // Calculate number of pads in a anode wire segment for normalization Int_t wireSegmentID = param->GetWireSegment(sector,padRow); Float_t nPadsPerSegment = (Float_t)(param->GetNPadsPerSegment(wireSegmentID)); // structure with mean signal per pad to be filled for each timebin in first loop (11 anodeWireSegment and 1100 timebin) TMatrixD &crossTalkSignal = *((TMatrixD*)crossTalkSignalArray.At(sector)); AliTPCCalROC * gainROC = gainTPC->GetCalROC(sector); // pad gains per given sector // digrow->SetID(globalRowID); Int_t nTimeBins = 0; Int_t nPads = 0; Bool_t digitize = kFALSE; for (Int_t i=0;i<nInputs; i++){ //here we can have more than one input - merging of separate events, signal1+signal2+background rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i)); gime = rl->GetLoader("TPCLoader"); if (gime->TreeS()->GetEntryWithIndex(globalRowID,globalRowID) >= 0) { digarr[i]->ExpandBuffer(); digarr[i]->ExpandTrackBuffer(); nTimeBins = digarr[i]->GetNRows(); nPads = digarr[i]->GetNCols(); active[i] = kTRUE; if (!GetRegionOfInterest() || (i == 0)) digitize = kTRUE; } else { active[i] = kFALSE; } if (GetRegionOfInterest() && !digitize) break; } if (!digitize) continue; //digrow->Allocate(nTimeBins,nPads); Float_t q = 0; Int_t labptr = 0; Int_t nElems = nTimeBins*nPads; // element is a unit of a given row's pad-timebin space for (Int_t i=0;i<nInputs; i++) if (active[i]) { pdig[i] = digarr[i]->GetDigits(); } // // loop over elements i.e pad-timebin space of a row, "padNumber=elem/nTimeBins", "timeBin=elem%nTimeBins" // for (Int_t elem=0;elem<nElems; elem++) { q=0; labptr=0; // looop over digits for (Int_t i=0;i<nInputs; i++) if (active[i]) { q += *(pdig[i]); pdig[i]++; } if (q<=0) continue; Int_t padNumber = elem/nTimeBins; Int_t timeBin = elem%nTimeBins; Float_t gain = gainROC->GetValue(padRow,padNumber); // get gain for given - pad-row pad q*= gain; crossTalkSignal[wireSegmentID][timeBin]+= q/nPadsPerSegment; // Qtot per segment for a given timebin qTotSector -> GetMatrixArray()[sector] += q; // Qtot for each sector nTotSector -> GetMatrixArray()[sector] += 1; // Ntot digit counter for each sector qTotTPC += q; // Qtot for whole TPC } // end of q loop } // end of global row loop // // 1.b) Dump the content of the crossTalk signal to the debug stremer - to be corealted later with the same crosstalk correction // assumed during reconstruction // if ((AliTPCReconstructor::StreamLevel()&kStreamCrosstalk)>0) { // // dump the crosstalk matrices to tree for further investigation // a.) to estimate fluctuation of pedestal in indiviula wire segments // b.) to check correlation between regions // c.) to check relative conribution of signal below threshold to crosstalk for (Int_t isector=0; isector<nROCs; isector++){ //set all ellemts of crosstalk matrix to 0 TMatrixD * crossTalkMatrix = (TMatrixD*)crossTalkSignalArray.At(isector); //TMatrixD * crossTalkMatrixBelow = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs); TVectorD vecAll(crossTalkMatrix->GetNrows()); //TVectorD vecBelow(crossTalkMatrix->GetNrows()); // for (Int_t itime=0; itime<crossTalkMatrix->GetNcols(); itime++){ for (Int_t iwire=0; iwire<crossTalkMatrix->GetNrows(); iwire++){ vecAll[iwire]=(*crossTalkMatrix)(iwire,itime); //vecBelow[iwire]=(*crossTalkMatrixBelow)(iwire,itime); } (*fDebugStreamer)<<"crosstalkMatrix"<< "sector="<<isector<< "itime="<<itime<< "vecAll.="<<&vecAll<< // crosstalk charge + charge below threshold //"vecBelow.="<<&vecBelow<< // crosstalk contribution from signal below threshold "\n"; } } } // // 2.) Loop over segments (padrows) of the TPC // // TTree * treeStreamer=0; for (Int_t globalRowID=0; globalRowID<param->GetNRowsTotal(); globalRowID++) { Int_t sector, padRow; if (!param->AdjustSectorRow(globalRowID,sector,padRow)) { cerr<<"AliTPC warning: invalid segment ID ! "<<globalRowID<<endl; continue; } TObjArray *arrTRF = (TObjArray*)timeResFunc.At(sector); // TGraphErrors *graphTRF = (TGraphErrors*)arrTRF->At(1); Int_t wireSegmentID = param->GetWireSegment(sector,padRow); Float_t nPadsPerSegment = (Float_t)(param->GetNPadsPerSegment(wireSegmentID)); // const Float_t ampfactor = (sector<36)?factorIROC:factorOROC; // factor for the iontail which is ROC type dependent AliTPCCalROC * gainROC = gainTPC->GetCalROC(sector); // pad gains per given sector AliTPCCalROC * noiseROC = noiseTPC->GetCalROC(sector); // noise per given sector digrow->SetID(globalRowID); Int_t nTimeBins = 0; Int_t nPads = 0; Bool_t digitize = kFALSE; for (Int_t i=0;i<nInputs; i++) { //here we can have more than one input - merging of separate events, signal1+signal2+background rl = AliRunLoader::GetRunLoader(fDigInput->GetInputFolderName(i)); gime = rl->GetLoader("TPCLoader"); if (gime->TreeS()->GetEntryWithIndex(globalRowID,globalRowID) >= 0) { digarr[i]->ExpandBuffer(); digarr[i]->ExpandTrackBuffer(); nTimeBins = digarr[i]->GetNRows(); nPads = digarr[i]->GetNCols(); active[i] = kTRUE; if (!GetRegionOfInterest() || (i == 0)) digitize = kTRUE; } else { active[i] = kFALSE; } if (GetRegionOfInterest() && !digitize) break; } if (!digitize) continue; digrow->Allocate(nTimeBins,nPads); digrow->AllocateTrack(3); Int_t localPad = 0; Float_t q = 0.; Float_t qXtalk = 0.; Float_t qIonTail = 0.; Float_t qOrig = 0.; Int_t label[1000]; //stack for 300 events Int_t labptr = 0; Int_t nElems = nTimeBins*nPads; // element is a unit of a given row's pad-timebin space for (Int_t i=0;i<nInputs; i++) if (active[i]) { pdig[i] = digarr[i]->GetDigits(); ptr[i] = digarr[i]->GetTracks(); } Short_t *pdig1= digrow->GetDigits(); Int_t *ptr1= digrow->GetTracks() ; // loop over elements i.e pad-timebin space of a row for (Int_t elem=0;elem<nElems; elem++) { q=0; labptr=0; // looop over digits for (Int_t i=0;i<nInputs; i++) if (active[i]){ q += *(pdig[i]); for (Int_t tr=0;tr<3;tr++) { Int_t lab = ptr[i][tr*nElems]; if ( (lab > 1) && *(pdig[i])>zerosup) { label[labptr]=lab+masks[i]; labptr++; } } pdig[i]++; ptr[i]++; } Int_t padNumber = elem/nTimeBins; Int_t timeBin = elem%nTimeBins; localPad = padNumber-nPads/2; Float_t gain = gainROC->GetValue(padRow,padNumber); // get gain for given - pad-row pad //if (gain<0.5){ //printf("problem\n"); //} q*= gain; qOrig = q; Float_t noisePad = noiseROC->GetValue(padRow,padNumber); Float_t noise = pTPC->GetNoise()*noisePad; if ( (q/16.+noise)> zerosup || ((AliTPCReconstructor::StreamLevel()&kStreamSignalAll)>0)){ // Crosstalk correction qXtalk = (*(TMatrixD*)crossTalkSignalArray.At(sector))[wireSegmentID][timeBin]; qTotPerSector = qTotSector -> GetMatrixArray()[sector]; nTotPerSector = nTotSector -> GetMatrixArray()[sector]; // Ion tail correction: being elem=padNumber*nTimeBins+timeBin; Int_t lowerElem=elem-nIonTailBins; Int_t zeroElem =(elem/nTimeBins)*nTimeBins; if (zeroElem<0) zeroElem=0; if (lowerElem<zeroElem) lowerElem=zeroElem; // qIonTail=0; if (q>0 && recoParam->GetUseIonTailCorrection()){ for (Int_t i=0;i<nInputs; i++) if (active[i]){ Short_t *pdigC= digarr[i]->GetDigits(); if (padNumber==0) continue; if (padNumber>=nPads-1) continue; for (Int_t dpad=-1; dpad<=1; dpad++){ // calculate iontail due signals from neigborhood pads for (Int_t celem=elem-1; celem>lowerElem; celem--){ Int_t celemPad=celem+dpad*nTimeBins; Double_t qCElem=pdigC[celemPad]; if ( qCElem<=0) continue; //here we substract ion tail Double_t COG=0; if (celemPad-nTimeBins>nTimeBins && celemPad+nTimeBins<nElems){ // COG calculation in respect to current pad in pad units Double_t sumAmp=pdigC[celemPad-nTimeBins]+pdigC[celemPad]+pdigC[celemPad+nTimeBins]; COG=(-1.0*pdigC[celemPad-nTimeBins]+pdigC[celemPad+nTimeBins])/sumAmp; } Int_t indexTRFPRF = (TMath::Nint(TMath::Abs(COG*10.))%20); TGraphErrors *graphTRFPRF = (TGraphErrors*)arrTRF->At(indexTRFPRF); if (graphTRFPRF==NULL) continue; // here we should get index and point of TRF corresponding to given COG position if (graphTRFPRF->GetY()[elem-celem]<0)qIonTail+=qCElem*graphTRFPRF->GetY()[elem-celem]; } } } } } // q -= qXtalk*recoParam->GetCrosstalkCorrection(); q+=qIonTail; q/=16.; //conversion factor q+=noise; q=TMath::Nint(q); // round to the nearest integer // fill info for degugging if ( ((AliTPCReconstructor::StreamLevel()&kStreamSignal)>0) && ((qOrig > zerosup)||((AliTPCReconstructor::StreamLevel()&kStreamSignalAll)>0) )) { TTreeSRedirector &cstream = *fDebugStreamer; UInt_t uid = AliTPCROC::GetTPCUniqueID(sector, padRow, padNumber); qXtalk = (*(TMatrixD*)crossTalkSignalArray.At(sector))[wireSegmentID][timeBin]; // if (treeStreamer==0){ cstream <<"ionTailXtalk"<< "uid="<<uid<< // globla unique identifier "sector="<< sector<< "globalRowID="<<globalRowID<< "padRow="<< padRow<< //pad row "wireSegmentID="<< wireSegmentID<< //wire segment 0-11, 0-3 in IROC 4-10 in OROC "localPad="<<localPad<< // pad number -npads/2 .. npads/2 "padNumber="<<padNumber<< // pad number 0..npads "timeBin="<< timeBin<< // time bin "nPadsPerSegment="<<nPadsPerSegment<<// number of pads per wire segment "qTotPerSector="<<qTotPerSector<< // total charge in sector "nTotPerSector="<<nTotPerSector<< // total number of digit (above threshold) in sector // "noise="<<noise<< // electornic noise contribution "qTotTPC="<<qTotTPC<< // acumulated charge without crosstalk and ion tail in full TPC "qOrig="<< qOrig<< // charge in given pad-row,pad,time-bin "q="<<q<< // q=qOrig-qXtalk-qIonTail - to check sign of the effects "qXtalk="<<qXtalk<< // crosstal contribtion at given position "qIonTail="<<qIonTail<< // ion tail cotribution from past signal "\n"; treeStreamer=(cstream <<"ionTailXtalk").GetTree(); }else{ treeStreamer->Fill(); } // dump the results to the debug streamer if in debug mode } if (q > zerosup || fgSAMPAEmulator!=NULL){ if(q >= param->GetADCSat()) q = (Short_t)(param->GetADCSat() - 1); //digrow->SetDigitFast((Short_t)q,rows,col); *pdig1 =Short_t(q); for (Int_t tr=0;tr<3;tr++) { if (tr<labptr) ptr1[tr*nElems] = label[tr]; } } if (fgSAMPAEmulator && (timeBin==nTimeBins-1)) { // pocess Emulator for given pad // TVectorD vecSAMPAIn(nTimeBins); // allocate workin array for SAMPA emulator processing (if set) TVectorD vecSAMPAOut(nTimeBins); // allocate workin array for SAMPA emulator processing (if set) Double_t baseline=0; for (Int_t itime=0; itime<nTimeBins;itime++) vecSAMPAIn[itime]=pdig1[1+itime-nTimeBins]; // set workin array for SAMPA emulator for (Int_t itime=0; itime<nTimeBins;itime++) vecSAMPAOut[itime]=pdig1[1+itime-nTimeBins]; // set workin array for SAMPA emulator fgSAMPAEmulator->DigitalFilterFloat(nTimeBins, vecSAMPAOut.GetMatrixArray(), baseline); // if ( ((AliTPCReconstructor::StreamLevel()&kStreamSignal)>0)){ (*fDebugStreamer)<<"sampaEmulator"<< "sector="<< sector<< "globalRowID="<<globalRowID<< "padRow="<< padRow<< //pad row "wireSegmentID="<< wireSegmentID<< //wire segment 0-11, 0-3 in IROC 4-10 in OROC "localPad="<<localPad<< // pad number -npads/2 .. npads/2 "padNumber="<<padNumber<< // pad number 0..npads "timeBin="<< timeBin<< // time bin "nPadsPerSegment="<<nPadsPerSegment<<// number of pads per wire segment "qTotPerSector="<<qTotPerSector<< // total charge in sector "nTotPerSector="<<nTotPerSector<< // total number of digit (above threshold) in sector "vSAMPAin.="<<&vecSAMPAIn<< // input data "vSAMPAout.="<<&vecSAMPAOut<< // ouptut data "\n"; } for (Int_t itime=0; itime<nTimeBins;itime++) { if ( TMath::Nint(vecSAMPAOut[itime]) < zerosup) pdig1[1+itime-nTimeBins]=0; else{ pdig1[1+itime-nTimeBins]=TMath::Nint(vecSAMPAOut[itime]); } } } pdig1++; ptr1++; } // // glitch filter // if (useGlitchFilter) digrow->GlitchFilter(); // digrow->CompresBuffer(1,zerosup); digrow->CompresTrackBuffer(1); tree->Fill(); if (fDebug>0) cerr<<sector<<"\t"<<padRow<<"\n"; if (padRow==0 && fDebugStreamer) { ((*fDebugStreamer)<<"ionTailXtalk").GetTree()->FlushBaskets(); ((*fDebugStreamer)<<"ionTailXtalk").GetTree()->Write(); (fDebugStreamer->GetFile())->Flush(); } } //for (Int_t n=0; n<param->GetNRowsTotal(); n++) orl = AliRunLoader::GetRunLoader(fDigInput->GetOutputFolderName()); ogime = orl->GetLoader("TPCLoader"); ogime->WriteDigits("OVERWRITE"); //fDigInput->GetTreeDTPC()->Write(0,TObject::kOverwrite); delete digrow; for (Int_t i1=0;i1<nInputs; i1++) delete digarr[i1]; delete []masks; delete []pdig; delete []ptr; delete []active; delete []digarr; }
34.733448
151
0.603243
[ "geometry", "object" ]
1d70f3da56596e86ad16947cfc87add616cf57d0
9,277
cpp
C++
Source/Core/CPU/HostCore/HostCore.cpp
woachk/FEX
66dc5ebc54f3ff9b51eed714eb37bff34a0a82e6
[ "MIT" ]
1
2020-05-24T22:00:46.000Z
2020-05-24T22:00:46.000Z
Source/Core/CPU/HostCore/HostCore.cpp
Sonicadvance1/FEX
d84b536c4a2f785870a714bd5ed9f914dff735a3
[ "MIT" ]
null
null
null
Source/Core/CPU/HostCore/HostCore.cpp
Sonicadvance1/FEX
d84b536c4a2f785870a714bd5ed9f914dff735a3
[ "MIT" ]
null
null
null
#include "Common/MathUtils.h" #include "Core/CPU/CPUBackend.h" #include "Core/CPU/CPUCore.h" #include "Core/CPU/DebugData.h" #include "Core/CPU/IR.h" #include "Core/CPU/IntrusiveIRList.h" #include "Core/CPU/HostCore/HostCore.h" #include "LogManager.h" #include <ucontext.h> #include <cassert> #include <iostream> #include <sys/mman.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/ptrace.h> #include <errno.h> #include <sys/user.h> #include <stdint.h> namespace FEX::CPU { class HostCore final : public CPUBackend { public: explicit HostCore(FEX::ThreadState *Thread); ~HostCore() override = default; std::string GetName() override { return "Host Stepper"; } void* CompileCode(FEX::IR::IntrusiveIRList const *ir, FEX::CPU::DebugData *DebugData) override; void *MapRegion(void *HostPtr, uint64_t GuestPtr, uint64_t Size) override { // Map locally to unprotected printf("Mapping Guest Ptr: 0x%lx\n", GuestPtr); void *Mem = LocalMemoryMapper.MapRegionFlags(GuestPtr, Size, PROT_READ | PROT_WRITE | PROT_EXEC); memset(Mem, 0xCC, Size); return HostPtr; } void ExecuteCode(FEX::ThreadState *Thread); void SignalHandler(int sig, siginfo_t *info, void *RawContext); bool NeedsOpDispatch() override { return false; } private: void HandleSyscall(); void ExecutionThreadFunction(); void InstallSignalHandler(); FEX::ThreadState *ThreadState; FEX::Config::Value<bool> ConfigMultiblock{"Multiblock", false}; std::thread ExecutionThread; Memmap LocalMemoryMapper{}; pid_t ChildPid; struct sigaction OldSigAction_SEGV; struct sigaction OldSigAction_TRAP; int PipeFDs[2]; std::atomic_bool ShouldStart{false}; }; static HostCore *GlobalCore; static void SigAction_SEGV(int sig, siginfo_t* info, void* RawContext) { GlobalCore->SignalHandler(sig, info, RawContext); } HostCore::HostCore(FEX::ThreadState *Thread) : ThreadState {Thread} { GlobalCore = this; LocalMemoryMapper.AllocateSHMRegion(1ULL << 36); ExecutionThread = std::thread(&HostCore::ExecutionThreadFunction, this); } static void HostExecution(FEX::ThreadState *Thread) { HostCore *Core = reinterpret_cast<HostCore*>(Thread->CPUBackend.get()); Core->ExecuteCode(Thread); } void HostCore::SignalHandler(int sig, siginfo_t *info, void *RawContext) { ucontext_t* Context = (ucontext_t*)RawContext; uint64_t HostToEmuRIP = (uint64_t)Context->uc_mcontext.gregs[REG_RIP] - LocalMemoryMapper.GetBaseOffset<uint64_t>(0); printf("We hecked up and faulted! %d Emu:0x%lx Host:0x%lx\n", sig, HostToEmuRIP, (uint64_t)Context->uc_mcontext.gregs[REG_RIP]); static uint64_t LastEMURip = ~0ULL; static uint64_t LastInstSize = 0; if (sig == SIGSEGV) { // RIP == Base instruction } else if (sig == SIGTRAP) { HostToEmuRIP -= 1; // 0xCC moves us ahead by one } uint8_t *LocalData = LocalMemoryMapper.GetPointer<uint8_t*>(HostToEmuRIP); uint8_t *ActualData = ThreadState->CPUCore->MemoryMapper->GetPointer<uint8_t*>(HostToEmuRIP); uint64_t TotalInstructionsLength {0}; ThreadState->CPUCore->FrontendDecoder.DecodeInstructionsInBlock(ActualData, HostToEmuRIP); auto DecodedOps = ThreadState->CPUCore->FrontendDecoder.GetDecodedInsts(); if (sig == SIGSEGV) { for (size_t i = 0; i < DecodedOps.second; ++i) { FEX::X86Tables::DecodedInst const* DecodedInfo {nullptr}; DecodedInfo = &DecodedOps.first->at(i); auto CheckOp = [&](char const* Name, FEX::X86Tables::DecodedOperand const &Operand) { if (Operand.TypeNone.Type != FEX::X86Tables::DecodedOperand::TYPE_NONE && Operand.TypeNone.Type != FEX::X86Tables::DecodedOperand::TYPE_LITERAL && Operand.TypeNone.Type != FEX::X86Tables::DecodedOperand::TYPE_GPR) { printf("Operand type is %d\n", Operand.TypeNone.Type); const std::vector<unsigned> EmulatorToSystemContext = { offsetof(mcontext_t, gregs[REG_RAX]), offsetof(mcontext_t, gregs[REG_RBX]), offsetof(mcontext_t, gregs[REG_RCX]), offsetof(mcontext_t, gregs[REG_RDX]), offsetof(mcontext_t, gregs[REG_RSI]), offsetof(mcontext_t, gregs[REG_RDI]), offsetof(mcontext_t, gregs[REG_RBP]), offsetof(mcontext_t, gregs[REG_RSP]), offsetof(mcontext_t, gregs[REG_R8]), offsetof(mcontext_t, gregs[REG_R9]), offsetof(mcontext_t, gregs[REG_R10]), offsetof(mcontext_t, gregs[REG_R11]), offsetof(mcontext_t, gregs[REG_R12]), offsetof(mcontext_t, gregs[REG_R13]), offsetof(mcontext_t, gregs[REG_R14]), offsetof(mcontext_t, gregs[REG_R15]), }; // Modify the registers to match the memory operands necessary. // This will propagate some addresses if (Operand.TypeNone.Type == FEX::X86Tables::DecodedOperand::TYPE_GPR_DIRECT) { uint64_t *GPR = (uint64_t*)((uintptr_t)&Context->uc_mcontext + EmulatorToSystemContext[Operand.TypeGPR.GPR]); uint64_t HostPointer = LocalMemoryMapper.GetPointer<uint64_t>(*GPR); printf("Changing host pointer from 0x%lx to %lx\n", *GPR, HostPointer); *GPR = HostPointer; } else { OldSigAction_SEGV.sa_sigaction(sig, info, RawContext); return; } } }; printf("Insts: %ld\n", DecodedOps.second); CheckOp("Dest", DecodedInfo->Dest); CheckOp("Src1", DecodedInfo->Src1); CheckOp("Src2", DecodedInfo->Src2); // Reset RIP to the start of the instruction Context->uc_mcontext.gregs[REG_RIP] = (uint64_t)LocalData; return; } OldSigAction_SEGV.sa_sigaction(sig, info, RawContext); return; } else if (sig == SIGTRAP) { for (size_t i = 0; i < DecodedOps.second; ++i) { FEX::X86Tables::DecodedInst const* DecodedInfo {nullptr}; DecodedInfo = &DecodedOps.first->at(i); TotalInstructionsLength += DecodedInfo->InstSize; } if (LastEMURip != ~0ULL) { uint8_t *PreviousLocalData = LocalMemoryMapper.GetPointer<uint8_t*>(LastEMURip); memset(PreviousLocalData, 0xCC, LastInstSize); } LastInstSize = TotalInstructionsLength; printf("\tHit an instruction of length %ld 0x%lx 0x%lx 0x%lx\n", TotalInstructionsLength, (uint64_t)Context->uc_mcontext.gregs[REG_RIP], (uint64_t)LocalData, (uint64_t)ActualData); memcpy(LocalData, ActualData, TotalInstructionsLength); printf("\tData Source:"); for (uint64_t i = 0; i < TotalInstructionsLength; ++i) { printf("%02x ", ActualData[i]); } printf("\n"); // Reset RIP to the start of the instruction Context->uc_mcontext.gregs[REG_RIP] = (uint64_t)LocalData; } } void HostCore::InstallSignalHandler() { struct sigaction sa; sa.sa_handler = nullptr; sa.sa_sigaction = &SigAction_SEGV; sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); // We use sigsegv to capture invalid memory accesses // We then patch the GPR state of that instruction to point to the correct location sigaction(SIGSEGV, &sa, &OldSigAction_SEGV); // We use trapping to determine when we've stepped to a new instruction sigaction(SIGTRAP, &sa, &OldSigAction_TRAP); } void HostCore::ExecutionThreadFunction() { printf("Host Core created\n"); if (pipe(PipeFDs) == -1) { LogMan::Msg::A("Couldn't pipe"); return; } ChildPid = fork(); if (ChildPid == 0) { // Child // Set that we want to be traced if (ptrace(PTRACE_TRACEME, 0, 0, 0)) { LogMan::Msg::A("Couldn't start trace"); } raise(SIGSTOP); InstallSignalHandler(); close(PipeFDs[1]); using Ptr = void (*)(); read(PipeFDs[0], &ThreadState->CPUState, sizeof(FEX::X86State::State)); printf("Child is running! 0x%lx\n", ThreadState->CPUState.rip); Ptr Loc = LocalMemoryMapper.GetPointer<Ptr>(ThreadState->CPUState.rip); Loc(); printf("Oh Snap. We returned in the child\n"); } else { // Parent // Parent will be the ptrace control thread int status; close(PipeFDs[0]); waitpid(ChildPid, &status, 0); if (WIFSTOPPED(status) && WSTOPSIG(status) == 19) { // Attach to child ptrace(PTRACE_ATTACH, ChildPid, 0, 0); ptrace(PTRACE_CONT, ChildPid, 0, 0); } while (!ShouldStart.load()); printf("Telling child to go!\n"); write(PipeFDs[1], &ThreadState->CPUState, sizeof(FEX::X86State::State)); while (1) { ShouldStart.store(false); waitpid(ChildPid, &status, 0); if (WIFEXITED(status)) { return; } if (WIFSTOPPED(status) && WSTOPSIG(status) == 5) { ptrace(PTRACE_CONT, ChildPid, 0, 5); } if (WIFSTOPPED(status) && WSTOPSIG(status) == 11) { ptrace(PTRACE_DETACH, ChildPid, 0, 11); break; } } } } void* HostCore::CompileCode([[maybe_unused]] FEX::IR::IntrusiveIRList const* ir, FEX::CPU::DebugData *DebugData) { printf("Attempting to compile: 0x%lx\n", ThreadState->CPUState.rip); return reinterpret_cast<void*>(HostExecution); } void HostCore::ExecuteCode(FEX::ThreadState *Thread) { ShouldStart = true; while(1); } FEX::CPU::CPUBackend *CreateHostCore(FEX::ThreadState *Thread) { return new HostCore(Thread); } }
34.486989
184
0.673278
[ "vector" ]
1d735bb0e5e0fee1d6646acb802f031701da4365
4,574
cpp
C++
src/Initializer/InitialFieldProjection.cpp
ivotron/SeisSol
51c2935566998480f948caf2b66b27b80df4b2c4
[ "BSD-3-Clause" ]
null
null
null
src/Initializer/InitialFieldProjection.cpp
ivotron/SeisSol
51c2935566998480f948caf2b66b27b80df4b2c4
[ "BSD-3-Clause" ]
null
null
null
src/Initializer/InitialFieldProjection.cpp
ivotron/SeisSol
51c2935566998480f948caf2b66b27b80df4b2c4
[ "BSD-3-Clause" ]
null
null
null
/** * @file * This file is part of SeisSol. * * @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.) * * @section LICENSE * Copyright (c) 2019, SeisSol Group * 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. Neither the name of the copyright holder 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 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. * * @section DESCRIPTION * **/ #include "InitialFieldProjection.h" #include <Numerical_aux/Quadrature.h> #include <Numerical_aux/BasisFunction.h> #include <Numerical_aux/Transformation.h> #include <generated_code/kernel.h> #include <generated_code/tensor.h> void seissol::initializers::projectInitialField( std::vector<physics::InitialField*> const& iniFields, GlobalData const& globalData, MeshReader const& meshReader, LTS const& lts, Lut const& ltsLut ) { auto const& vertices = meshReader.getVertices(); auto const& elements = meshReader.getElements(); constexpr auto quadPolyDegree = CONVERGENCE_ORDER+1; constexpr auto numQuadPoints = quadPolyDegree * quadPolyDegree * quadPolyDegree; double quadraturePoints[numQuadPoints][3]; double quadratureWeights[numQuadPoints]; seissol::quadrature::TetrahedronQuadrature(quadraturePoints, quadratureWeights, quadPolyDegree); #ifdef _OPENMP #pragma omp parallel { #endif real iniCondData[tensor::iniCond::size()] __attribute__((aligned(ALIGNMENT))) = {}; auto iniCond = init::iniCond::view::create(iniCondData); std::vector<std::array<double, 3>> quadraturePointsXyz; quadraturePointsXyz.resize(numQuadPoints); kernel::projectIniCond krnl; krnl.projectQP = globalData.projectQPMatrix; krnl.iniCond = iniCondData; #if NUMBER_OF_RELAXATION_MECHANISMS > 0 krnl.selectAneFull = init::selectAneFull::Values; krnl.selectElaFull = init::selectElaFull::Values; #endif #ifdef _OPENMP #pragma omp for schedule(static) #endif for (unsigned int meshId = 0; meshId < elements.size(); ++meshId) { double const* elementCoords[4]; for (size_t v = 0; v < 4; ++v) { elementCoords[v] = vertices[elements[meshId].vertices[ v ] ].coords; } for (size_t i = 0; i < numQuadPoints; ++i) { seissol::transformations::tetrahedronReferenceToGlobal(elementCoords[0], elementCoords[1], elementCoords[2], elementCoords[3], quadraturePoints[i], quadraturePointsXyz[i].data()); } #ifdef MULTIPLE_SIMULATIONS for (int s = 0; s < MULTIPLE_SIMULATIONS; ++s) { auto sub = iniCond.subtensor(s, yateto::slice<>(), yateto::slice<>()); iniFields[s % iniFields.size()]->evaluate(0.0, quadraturePointsXyz, sub); } #else iniFields[0]->evaluate(0.0, quadraturePointsXyz, iniCond); #endif krnl.Q = ltsLut.lookup(lts.dofs, meshId); #if NUMBER_OF_RELAXATION_MECHANISMS > 0 krnl.Qane = ltsLut.lookup(lts.dofsAne, meshId); #endif krnl.execute(); } #ifdef _OPENMP } #endif }
40.122807
185
0.690424
[ "vector" ]
1d78d5b7bc962b71c6ff79a948a585166f9fa88a
101,896
hpp
C++
DynRleWithValue.hpp
itomomoti/OnlineRlbwt
602bcd37b1effb660dcf6dba54d59be0879600a3
[ "MIT" ]
11
2018-05-10T16:37:28.000Z
2021-04-29T12:08:42.000Z
DynRleWithValue.hpp
itomomoti/OnlineRLBWT
602bcd37b1effb660dcf6dba54d59be0879600a3
[ "MIT" ]
null
null
null
DynRleWithValue.hpp
itomomoti/OnlineRLBWT
602bcd37b1effb660dcf6dba54d59be0879600a3
[ "MIT" ]
1
2019-05-27T04:20:05.000Z
2019-05-27T04:20:05.000Z
/*! * Copyright (c) 2017 Tomohiro I * * This program is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ /*! * @file DynRleWithValue.hpp * @brief Dynamic Run-length encoding with value. * @author Tomohiro I * @date 2017-12-16 */ #ifndef INCLUDE_GUARD_DynRleWithValue #define INCLUDE_GUARD_DynRleWithValue #include <stdint.h> #include <iostream> #include <algorithm> #include <cassert> #include <string> #include <fstream> #include <sstream> // include from Basics #include "BitsUtil.hpp" #include "StepCode.hpp" #include "MemUtil.hpp" // include from BTree #include "BTree.hpp" #include "PSumWithValue.hpp" #include "TagRelabelAlgo.hpp" namespace itmmti { template<uint8_t kB> class BTreeNode; /*! * @brief Dynamic partial sum data structure implemented by B+tree, where each leaf is associated with value. * @tparam kB Arity for internal node of B+tree, which should be in {32, 64, 128}. * @tparam kBtmB Arity for bottom node of B+tree, which should be in {32, 64, 128}. * @par Notation * - T: Current string represented by RLE. * - Mixed tree: B+tree representing RLE of T. * - btmM: Index of bottom node of B+tree on the array-based implementation. * Each bottom node "btmM" can have "kBtmB" children, which correspond to indexes [btmM * kBtmB, (btmM+1) * kBtmB). * - idxM: Indexes that are corresponding to children of "btmM". * - Separated tree: B+tree separately representing runs for each character. * - btmS: Index of bottom node of B+tree on the array-based implementation (all separated trees share arrays). * Each bottom node "btmS" can have "kBtmB" children, which correspond to indexes [btmS * kBtmB, (btmS+1) * kBtmB). * - idxS: Indexes that are corresponding to children of "btmS". */ template<uint8_t param_kB, uint8_t param_kBtmB> class DynRleWithValue { public: // Public constant, alias etc. static constexpr uint8_t kB{param_kB}; static constexpr uint8_t kBtmB{param_kBtmB}; using BTreeNodeT = BTreeNode<kB>; private: // Inner class class BtmNode { public: //// Private member variables. uint64_t btmVal_; //! TRA-label for btmM and character for btmS. BTreeNodeT * parent_; uint64_t * links_; //!< w-bit packed links storing idxM or idxS StepCodeCore<kBtmB> stcc_; //!< Storing weights (for MTree) or leaf values (for STree) uint16_t stccCapacity_; //!< Current bit capacity of stcc_ uint16_t stccSize_; //!< Current bit size of stcc_ uint8_t numChildren_; //!< Current size (number of elements). uint8_t w_; //!< Bit-width for "links_" uint8_t idxInSibling_; //!< idxInSibling uint8_t wCodesAuxM_[kBtmB / StepCodeUtil::kWCNum - 1]; BtmNode ( uint16_t initStccCapacity = 0 ) : btmVal_(0), parent_(nullptr), links_(nullptr), stcc_(), stccCapacity_(0), stccSize_(0), numChildren_(0), w_(0), idxInSibling_(0) { assert(initStccCapacity <= UINT16_MAX - 64); reserveBitCapacity(initStccCapacity); } ~BtmNode() { memutil::safefree(links_); // stcc_ is freed. } uint16_t getStccSize() const noexcept { return stccSize_; } uint16_t getStccCapacity() const noexcept { return stccCapacity_; } uint16_t getNumChildren() const noexcept { return numChildren_; } uint16_t getIdxInSibling() const noexcept { return idxInSibling_; } uint64_t getBtmVal() const noexcept { return btmVal_; } void setBtmVal ( uint64_t val ) noexcept { btmVal_ = val; } uint8_t getW() const noexcept { return w_; } BTreeNodeT * getParent() const noexcept { return parent_; } BtmNode * getPrevBtmNode() const noexcept { auto ret = this->getParent()->getPrevBtm(this->getIdxInSibling()); if (reinterpret_cast<uintptr_t>(ret) != BTreeNodeT::NOTFOUND) { return reinterpret_cast<BtmNode *>(ret); } else { return nullptr; } } BtmNode * getNextBtmNode() const noexcept { auto ret = this->getParent()->getNextBtm_DirectJump(this->getIdxInSibling()); if (reinterpret_cast<uintptr_t>(ret) != BTreeNodeT::NOTFOUND) { return reinterpret_cast<BtmNode *>(ret); } else { return nullptr; } } uint64_t readStccVal ( const uint8_t idx //!< in [0..numChildren_) ) const noexcept { assert(idx < numChildren_); return stcc_.read(idx); } uint64_t readLink ( const uint8_t idx //!< in [0..numChildren_) ) const noexcept { assert(idx < numChildren_); return bits::readWBits(links_, static_cast<uint64_t>(idx) * w_, w_, bits::UINTW_MAX(w_)); } void writeLink ( const uint64_t val, //!< in [0, 2^{w_}). const uint8_t idx //!< in [0, capacity_). ) noexcept { assert(idx < kBtmB); assert(val <= bits::UINTW_MAX(w_)); bits::writeWBits(val, links_, static_cast<uint64_t>(idx) * w_, w_, bits::UINTW_MAX(w_)); } void increaseW ( uint8_t minSupportW //!< New bit-width is at least minSupportW ) noexcept { assert(0 < minSupportW && minSupportW <= 64); if (minSupportW <= w_) { return; } const size_t oldLen = (kBtmB * w_ + 63) / 64; // +63 for roundup const size_t minLen = (kBtmB * minSupportW + 63) / 64; // +63 for roundup if (minLen > oldLen) { memutil::realloc_AbortOnFail(links_, minLen); minSupportW = minLen * 64 / kBtmB; // Set minSupportW here } for (uint64_t i = numChildren_ - 1; i != UINT64_MAX; --i) { bits::writeWBits(bits::readWBits(links_, i * w_, w_, bits::UINTW_MAX(w_)), links_, i * minSupportW, minSupportW, bits::UINTW_MAX(minSupportW)); } w_ = minSupportW; } /*! * @brief Calculate the beginning bit-pos of "idx"-th value in stcc_. */ uint16_t calcBitPos ( const uint8_t idx //!< in [0..numChildren_] ) const noexcept { assert(idx <= numChildren_); if (idx < numChildren_) { return static_cast<uint16_t>(stcc_.calcBitPos(idx, wCodesAuxM_)); } else { return stccSize_; } } /*! * @brief Get read-only array pointer. */ const StepCodeCore<kBtmB> & getConstRef_stcc() const noexcept { return stcc_; } /*! * @brief Get read-only array pointer. */ const uint64_t * getConstPtr_vals() const noexcept { return stcc_.getConstPtr_vals(); } /*! * @brief Get read-only wCodes_ array pointer. */ const uint64_t * getConstPtr_wCodes() const noexcept { return stcc_.getConstPtr_wCodes(); } void reserveBitCapacity ( uint16_t givenBitCapacity ) { if (givenBitCapacity > this->stccCapacity_) { size_t newSize = (static_cast<size_t>(givenBitCapacity) / kUnitBits + 2) * kUnitBits; this->stccCapacity_ = static_cast<uint16_t>(this->stcc_.setBitCapacity(static_cast<size_t>(givenBitCapacity))); } } void shrinkBitCapacity() { if (this->stccCapacity_ - this->stccSize_ > kUnitBits) { this->stccCapacity_ = static_cast<uint16_t>(stcc_.setBitCapacity(static_cast<size_t>(this->stccSize_))); } } void setParentRef ( BTreeNodeT * newParent, uint8_t newIdxInSibling ) noexcept { this->parent_ = newParent; this->idxInSibling_ = newIdxInSibling; } /*! * @brief Resize "numChildren_" to "newSize". * @note * It does not change bitCapacity. */ void resize ( const uint8_t newSize ) noexcept { assert(newSize <= kBtmB); numChildren_ = newSize; } /*! * @brief update wCodesAuxM. */ void updateWCodesAuxM ( const uint16_t idxBeg, const uint16_t idxEnd ) noexcept { assert(idxBeg < idxEnd); const uint64_t beg = idxBeg / StepCodeUtil::kWCNum; const uint64_t end = (idxEnd - 1) / StepCodeUtil::kWCNum + (idxEnd <= (kBtmB - StepCodeUtil::kWCNum)); // std::cerr << __FUNCTION__ << ": " << idxBeg << "->" << beg << ", " << idxEnd << "->" << end << std::endl; stcc_.updateWCodesAuxM(wCodesAuxM_, beg, end); } /*! * @brief Replace values. */ void replace ( const uint64_t * newVals, //!< Storing stcc values that replace existing stcc values const uint8_t num, //!< Number of elements to replace. const uint8_t idx //!< in [0..numChildren_). Beginning idx of tgt. ) { assert(idx + num <= numChildren_); const uint16_t bitPos0 = this->calcBitPos(idx); uint16_t bitPos = bitPos0; uint16_t sumW_ins = 0; uint16_t sumW_del = 0; for (uint16_t i = idx; i < idx + num; ++i) { const uint8_t w_old = stcc_.readW(i); const uint8_t w_new = StepCodeUtil::calcSteppedW(newVals[i - idx]); sumW_del += w_old; sumW_ins += w_new; stcc_.writeWCode(StepCodeUtil::calcWCodeFromSteppedW(w_new), i); bitPos += w_old; } this->updateWCodesAuxM(idx, idx + num); if (sumW_ins != sumW_del) { const uint16_t newStccSize = this->stccSize_ + sumW_ins - sumW_del; if (newStccSize != this->stccSize_) { this->reserveBitCapacity(newStccSize); this->stcc_.mvVals(this->stcc_.getConstPtr_vals(), bitPos, bitPos0 + sumW_ins, this->stccSize_ - bitPos); } this->stccSize_ = newStccSize; } bitPos = bitPos0; for (uint16_t i = idx; i < idx + num; ++i) { uint8_t w = this->stcc_.readW(i); this->stcc_.writeWBits(newVals[i - idx], bitPos, w); bitPos += w; } } //////////////////////////////// statistics size_t calcMemBytes ( bool includeThis = true ) const noexcept { size_t size = sizeof(*this) * includeThis; return size + calcMemBytesStccDynArray() + calcMemBytesLinksArray(); } size_t calcMemBytesStccDynArray() const noexcept { return stccCapacity_ / 8; } size_t calcMemBytesLinksArray() const noexcept { return (w_ * kBtmB) / 8; } void printStatistics ( std::ostream & os, const bool verbose ) const noexcept { os << "DynRleWithValue::BtmNode object (" << this << ") " << __func__ << "(" << verbose << ") BEGIN" << std::endl; os << "BTree arity for bottom node = " << static_cast<int>(kBtmB) << ", btmVal = " << btmVal_ << std::endl; os << "parent = " << parent_ << ", idxInSibling = " << (int)idxInSibling_ << ", numChildren = " << static_cast<uint64_t>(numChildren_) << std::endl; os << "bit size = " << stccSize_ << ", bit capacity = " << stccCapacity_ << ", bit-width for links = " << (int)w_ << std::endl; os << "Total: " << calcMemBytes() << " bytes" << std::endl; os << "dynamic array of step code: " << calcMemBytesStccDynArray() << " bytes" << std::endl; os << "dynamic array of links: " << calcMemBytesLinksArray() << " bytes" << std::endl; os << "DynRleWithValue::BtmNode object (" << this << ") " << __func__ << "(" << verbose << ") END" << std::endl; } void printDebugInfo ( std::ostream & os, const bool verbose ) const noexcept { os << "DynRleWithValue::BtmNode object (" << this << ") " << __func__ << "(" << verbose << ") BEGIN" << std::endl; os << "BTree arity for bottom node = " << static_cast<int>(kBtmB) << ", btmVal = " << btmVal_ << std::endl; os << "parent = " << parent_ << ", idxInSibling = " << (int)idxInSibling_ << ", numChildren = " << static_cast<uint64_t>(numChildren_) << std::endl; os << "bit size = " << stccSize_ << ", bit capacity = " << stccCapacity_ << ", bit-width for links = " << (int)w_ << std::endl; os << "Total: " << calcMemBytes() << " bytes" << std::endl; os << "dynamic array of step code: " << calcMemBytesStccDynArray() << " bytes" << std::endl; os << "dynamic array of links: " << calcMemBytesLinksArray() << " bytes" << std::endl; { os << "dump bit witdth stored in wCodes (" << stcc_.getConstPtr_wCodes() << ")" << std::endl; for (uint8_t i = 0; i < numChildren_; ++i) { os << (uint64_t)(stcc_.readW(i)) << " "; } os << std::endl; } { os << "dump values" << std::endl; for (uint8_t i = 0; i < numChildren_; ++i) { os << stcc_.read(i) << " "; } os << std::endl; } { os << "dump bits in vals_ (" << stcc_.getConstPtr_vals() << ")" << std::endl; for (uint64_t i = 0; i < (stccSize_ + 63) / 64; ++i) { os << "(" << i << ")"; for (uint64_t j = 0; j < 64; ++j) { os << bits::readWBits_S(stcc_.getConstPtr_vals(), 64 * i + 63 - j, ctcbits::UINTW_MAX(1)); } os << " "; } os << std::endl; } { os << "dump links_ (" << links_ << ")" << std::endl; for (uint64_t i = 0; i < this->numChildren_; ++i) { os << this->readLink(i) << ", "; } os << std::endl; } os << "DynRleWithValue::BtmNode object (" << this << ") " << __func__ << "(" << verbose << ") END" << std::endl; } void printDebugInfo ( std::ostream & os, const bool verbose, const DynRleWithValue<kB, kBtmB> & obj, const bool nodeMorS ) const noexcept { uint64_t btmIdx = obj.calcIdxBase(this, obj.btmPtrs_[!nodeMorS]); os << "[" << btmIdx << "~" << btmIdx + kBtmB << ")DynRleWithValue::BtmNode object " << ((nodeMorS == obj.kM) ? "kM" : "kS") << " (" << this << ") " << __func__ << "(" << verbose << ") BEGIN" << std::endl; os << "BTree arity for bottom node = " << static_cast<int>(kBtmB); if (nodeMorS == obj.kM) { os << ", SumOfWeight = " << obj.calcSumOfWeightOfBtmNodeM(this) << ", label = " << btmVal_ << std::endl; } else { os << ", SumOfWeight = " << obj.calcSumOfWeightOfBtmNodeS(this) << ", ch = " << btmVal_ << "(" << (char)btmVal_ << ")" << std::endl; } os << "parent = " << parent_ << ", idxInSibling = " << (int)idxInSibling_ << ", numChildren = " << static_cast<uint64_t>(numChildren_) << std::endl; os << "bit size = " << stccSize_ << ", bit capacity = " << stccCapacity_ << ", bit-width for links = " << (int)w_ << std::endl; os << "Total: " << calcMemBytes() << " bytes, dynamic array of step code: " << calcMemBytesStccDynArray() << " bytes, dynamic array of links: " << calcMemBytesLinksArray() << " bytes" << std::endl; { os << "dump bit witdth stored in wCodes (" << stcc_.getConstPtr_wCodes() << ")" << std::endl; for (uint8_t i = 0; i < numChildren_; ++i) { os << (uint64_t)(stcc_.readW(i)) << " "; } os << std::endl; } { os << "dump values" << std::endl; for (uint8_t i = 0; i < numChildren_; ++i) { os << stcc_.read(i) << " "; } os << std::endl; } { os << "dump bits in vals_ (" << stcc_.getConstPtr_vals() << ")" << std::endl; for (uint64_t i = 0; i < (stccSize_ + 63) / 64; ++i) { os << "(" << i << ")"; for (uint64_t j = 0; j < 64; ++j) { os << bits::readWBits_S(stcc_.getConstPtr_vals(), 64 * i + 63 - j, ctcbits::UINTW_MAX(1)); } os << " "; } os << std::endl; } { os << "dump links_ (" << links_ << ")" << std::endl; for (uint64_t i = 0; i < this->numChildren_; ++i) { os << this->readLink(i) << ", "; } os << std::endl; } os << "[" << btmIdx << "~" << btmIdx + kBtmB << ")DynRleWithValue::BtmNode object " << ((nodeMorS == obj.kM) ? "kM" : "kS") << " (" << this << ") " << __func__ << "(" << verbose << ") END" << std::endl; } }; // end of BtmNode public: // Public constant, alias etc. static constexpr size_t kUnitBits{kBtmB * 8}; static constexpr bool kM{0}; static constexpr bool kS{1}; private: typename BTreeNodeT::SuperRootT srootM_; //!< Super root of mixed tree typename BTreeNodeT::SuperRootT srootA_; //!< Super root of alphabet tree BtmNode ** btmPtrs_[2]; //!< Pointers to BtmNodes "btmPtrs_[0]" for MTree and "btmPtrs_[1]" for STree uint64_t capacity_[2]; //!< capacities of btmPtrs_ arrays uint64_t size_[2]; //!< sizes of btmPtrs_ arrays uint8_t traCode_; //!< traCode in [9..16) public: DynRleWithValue ( const size_t initNumBtms = 0 ) : srootM_(), srootA_(), traCode_(9) { btmPtrs_[0] = nullptr; btmPtrs_[1] = nullptr; capacity_[0] = 0; capacity_[1] = 0; size_[0] = 0; size_[1] = 0; if (initNumBtms) { init(initNumBtms); } } ~DynRleWithValue() { clearAll(); } /*! * @brief Reserve space to accomodate 'initNumBtms' bottoms, and init. */ void init ( const size_t initNumBtms ) { assert(initNumBtms > 0); if (isReady()) { clearAll(); } reserveBtmM(initNumBtms); reserveBtmS(initNumBtms); auto firstBtmNodeM = new BtmNode(); setNewBtmNode(firstBtmNodeM, kM); srootM_.setRoot(new BTreeNodeT(firstBtmNodeM, true, true, true, true)); srootM_.root_->putFirstBtm(firstBtmNodeM, 0); firstBtmNodeM->setParentRef(srootM_.root_, 0); firstBtmNodeM->increaseW(8); const uint64_t newVals[] = {0}; const uint64_t newLinks[] = {0}; insertNewElem(0, 0, newVals, newLinks, 1, 0, kM); // sentinel // isRoot = true, isBorder = true, isJumpToBtm = true, isUnderSuperRoot = false, isDummy = true auto * dummyRootS = new BTreeNodeT(nullptr, true, true, true, false, true); dummyRootS->putFirstBtm(nullptr, 0); srootA_.setRoot(new BTreeNodeT(dummyRootS, true, true, true, true)); srootA_.root_->pushbackBTreeNode(dummyRootS); } /*! * @brief Free/delete all allocated objects. */ void clearAll() { if (!isReady()) { // already cleared return; } for (uint64_t i = 0; i < size_[kM]; ++i) { delete btmPtrs_[kM][i]; } for (uint64_t i = 0; i < size_[kS]; ++i) { delete btmPtrs_[kS][i]; } memutil::safefree(btmPtrs_[kM]); memutil::safefree(btmPtrs_[kS]); { // delete separated tree auto * rootS = srootA_.root_->getLmBtm_DirectJump(); while (reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND) { auto * next = getNextRootS(rootS); delete rootS; rootS = next; } } memutil::safedelete(srootM_.root_); memutil::safedelete(srootA_.root_); traCode_ = 9; } /*! * @brief Return if data structure is ready. */ bool isReady() const noexcept { return (srootM_.root_ != nullptr); } /*! * @brief Return if given "idxM" corresponds to valid run. */ bool isValidIdxM(const uint64_t idxM) const noexcept { return (isReady() && (idxM / kBtmB) < size_[kM] && (idxM % kBtmB) < btmPtrs_[kM][idxM / kBtmB]->getNumChildren()); } /*! * @brief Return if given "idxS" corresponds to valid run. */ bool isValidIdxS(const uint64_t idxS) const noexcept { return (isReady() && (idxS / kBtmB) < size_[kS] && (idxS % kBtmB) < btmPtrs_[kS][idxS / kBtmB]->getNumChildren()); } /*! * @brief Get rootM_. */ const auto rootM() const noexcept { return srootM_.root_; } auto rootM() noexcept { return srootM_.root_; } //////////////////////////////// Get values stored for each bottom node via "btm" and "btmNode" //////////////// Get parent /*! * @brief Get parent of "btmM" */ const auto getParentFromBtmM(const uint64_t btmM) const noexcept { return btmPtrs_[kM][btmM]->getParent(); } auto getParentFromBtmM(const uint64_t btmM) noexcept { return btmPtrs_[kM][btmM]->getParent(); } /*! * @brief Get parent of "btmS" */ const auto getParentFromBtmS(const uint64_t btmS) const noexcept { return btmPtrs_[kS][btmS]->getParent(); } auto getParentFromBtmS(const uint64_t btmS) noexcept { return btmPtrs_[kS][btmS]->getParent(); } /*! * @brief Get parent of "btmNode" */ const auto getParentFromBtmNode ( const void * btmNode //!< Pointer to BtmNode. ) const noexcept { return static_cast<BtmNode *>(btmNode)->getParent(); } auto getParentFromBtmNode ( void * btmNode //!< Pointer to BtmNode. ) noexcept { return static_cast<BtmNode *>(btmNode)->getParent(); } //////////////// Get idxInSibling /*! * @brief Get idxInSibling of "btmM" */ auto getIdxInSiblingFromBtmM(const uint64_t btmM) const noexcept { return btmPtrs_[kM][btmM]->getIdxInSibling(); } /*! * @brief Get idxInSibling of "btmS" */ auto getIdxInSiblingFromBtmS(const uint64_t btmS) const noexcept { return btmPtrs_[kS][btmS]->getIdxInSibling(); } /*! * @brief Get idxInSibling of "btmNode" */ auto getIdxInSiblingFromBtmNode ( const void * btmNode //!< Pointer to BtmNode. ) const noexcept { return static_cast<BtmNode *>(btmNode)->getIdxInSibling(); } //////////////// Get numChildren /*! * @brief Get numChildren of "btmM" */ auto getNumChildrenFromBtmM(const uint64_t btmM) const noexcept { return btmPtrs_[kM][btmM]->getNumChildren(); } /*! * @brief Get numChildren of "btmS" */ auto getNumChildrenFromBtmS(const uint64_t btmS) const noexcept { return btmPtrs_[kS][btmS]->getNumChildren(); } /*! * @brief Get num of "btmNode" */ auto getNumChildrenFromBtmNode ( const void * btmNode //!< Pointer to BtmNode. ) const noexcept { return static_cast<const BtmNode *>(btmNode)->getNumChildren(); } //////////////////////////////// Get value stored for each bottom node via "idx" /*! * @brief Get char of run corresponding to "idxM" */ uint64_t getCharFromIdxM(uint64_t idxM) const noexcept { // {//debug // std::cerr << __func__ << ": idxM = " << idxM << std::endl; // } assert(isValidIdxM(idxM)); return getCharFromIdxS(idxM2S(idxM)); } /*! * @brief Get char of run corresponding to "idxS" */ uint64_t getCharFromIdxS(uint64_t idxS) const noexcept { assert(isValidIdxS(idxS)); return btmPtrs_[kS][idxS / kBtmB]->getBtmVal(); } /*! * @brief Get TRA-label of run corresponding to "idxM" */ uint64_t getLabelFromIdxM(uint64_t idxM) const noexcept { assert(isValidIdxM(idxM)); return btmPtrs_[kM][idxM / kBtmB]->getBtmVal(); } //////////////////////////////// Get value stored for each leaf //////////////// Get link /*! * @brief Get "idxS" from "idxM". */ uint64_t idxM2S(const uint64_t idxM) const noexcept { assert(isValidIdxM(idxM)); return btmPtrs_[kM][idxM / kBtmB]->readLink(idxM % kBtmB); } /*! * @brief Get "idxM" from "idxS". */ uint64_t idxS2M(const uint64_t idxS) const noexcept { assert(isValidIdxS(idxS)); return btmPtrs_[kS][idxS / kBtmB]->readLink(idxS % kBtmB); } /*! * @brief Get link from "btmNodeM" */ uint64_t getLinkFromBtmNodeM ( const void * btmNodeM, //!< Pointer to BtmNode for MTree const uint8_t childIdx //!< in [0..numChildren of btmNode) ) const noexcept { return static_cast<BtmNode *>(btmNodeM)->readLink(childIdx); } /*! * @brief Get link from "btmNodeS" */ uint64_t getLinkFromBtmNodeS ( const void * btmNodeS, //!< Pointer to BtmNode for STree const uint8_t childIdx //!< in [0..numChildren of btmNode) ) const noexcept { return static_cast<BtmNode *>(btmNodeS)->readLink(childIdx); } //////////////// Get leafVal /*! * @brief Get leafVal from "idxM" */ uint64_t getLeafValFromIdxM(uint64_t idxM) const noexcept { assert(isValidIdxM(idxM)); return getLeafValFromIdxS(idxM2S(idxM)); } /*! * @brief Get leafVal from "idxS" */ uint64_t getLeafValFromIdxS(uint64_t idxS) const noexcept { assert(isValidIdxS(idxS)); return btmPtrs_[kS][idxS / kBtmB]->readStccVal(idxS % kBtmB); } /*! * @brief Get leafVal from "btmNodeM" */ uint64_t getLeafValFromBtmNodeM ( const void * btmNodeM, //!< Pointer to BtmNode for MTree const uint8_t childIdx //!< in [0..numChildren of btmNode) ) const noexcept { return getLeafValFromIdxS(static_cast<BtmNode *>(btmNodeM)->readLink(childIdx)); } /*! * @brief Get leafVal from "btmNodeS" */ uint64_t getLeafValFromBtmNodeS ( const void * btmNodeS, //!< Pointer to BtmNode for STree const uint8_t childIdx //!< in [0..numChildren of btmNode) ) const noexcept { return static_cast<const BtmNode *>(btmNodeS)->readStccVal(childIdx); } //////////////// Get weight /*! * @brief Get length of run corresponding to "idxM" */ uint64_t getWeightFromIdxM(uint64_t idxM) const noexcept { assert(isValidIdxM(idxM)); return btmPtrs_[kM][idxM / kBtmB]->readStccVal(idxM % kBtmB); } /*! * @brief Get length of run corresponding to "idxS" */ uint64_t getWeightFromIdxS(uint64_t idxS) const noexcept { assert(isValidIdxS(idxS)); return getWeightFromIdxM(idxS2M(idxS)); } /*! * @brief Get weight from "btmNodeM" */ uint64_t getWeightFromBtmNodeM ( const void * btmNodeM, //!< Pointer to BtmNode for MTree const uint8_t childIdx //!< in [0..numChildren of btmNode) ) const noexcept { return static_cast<BtmNode *>(btmNodeM)->readStccVal(childIdx); } /*! * @brief Get weight from "btmNodeS" */ uint64_t getWeightFromBtmNodeS ( const void * btmNodeS, //!< Pointer to BtmNode for STree const uint8_t childIdx //!< in [0..numChildren of btmNode) ) const noexcept { return getWeightFromIdxM(static_cast<BtmNode *>(btmNodeS)->readLink(childIdx)); } //////////////////////////////// Get something from BTreeNode /*! * @brief Get character corresponding to a node of separated tree. */ uint64_t getCharFromNodeS(const BTreeNodeT * nodeS) const noexcept { assert(isReady()); assert(nodeS); // nodeS should be valid node return reinterpret_cast<const BtmNode *>(nodeS->getLmBtm_DirectJump())->getBtmVal(); } //////////////////////////////// Get sum of weights /*! * @brief Return |T|. */ size_t getSumOfWeight() const noexcept { assert(isReady()); return srootM_.root_->getSumOfWeight(); } /*! * @brief Compute num of occ of "ch" in T */ size_t getSumOfWeight(const uint64_t ch) const noexcept { assert(isReady()); const auto * retRootS = searchCharA(ch); if (retRootS->isDummy() || getCharFromNodeS(retRootS) != ch) { return 0; } return retRootS->getSumOfWeight(); } uint64_t calcSumOfWeightOfBtmNodeM ( const void * btmNodeM //!< Pointer to BtmNode for MTree ) const noexcept { const auto & stcc = static_cast<const BtmNode *>(btmNodeM)->getConstRef_stcc(); const auto num = static_cast<const BtmNode *>(btmNodeM)->getNumChildren(); uint64_t sum = 0; uint64_t bitPos = 0; for (uint64_t i = 0; i < num; ++i) { const auto w = stcc.readW(i); sum += stcc.readWBits(bitPos, w); bitPos += w; } return sum; } uint64_t calcSumOfWeightOfBtmM ( const uint64_t btmM ) const noexcept { assert(isValidIdxM(kBtmB * btmM)); return calcSumOfWeightOfBtmNodeM(btmPtrs_[kM][btmM]); } uint64_t calcSumOfWeightOfBtmNodeM ( const void * btmNodeM, //!< Pointer to BtmNode for MTree const uint8_t childIdx_beg, const uint8_t childIdx_end ) const noexcept { const auto & stcc = static_cast<const BtmNode *>(btmNodeM)->getConstRef_stcc(); uint64_t bitPos = static_cast<const BtmNode *>(btmNodeM)->calcBitPos(childIdx_beg); uint64_t sum = 0; for (uint16_t i = childIdx_beg; i < childIdx_end; ++i) { const auto w = stcc.readW(i); sum += stcc.readWBits(bitPos, w); bitPos += w; } return sum; } uint64_t calcSumOfWeightOfBtmM ( const uint64_t btmM, const uint8_t childIdx_beg, const uint8_t childIdx_end ) const noexcept { assert(isValidIdxM(kBtmB * btmM)); assert(childIdx_beg < childIdx_end); assert(childIdx_end <= getNumChildrenFromBtmM(btmM)); return calcSumOfWeightOfBtmNodeM(btmPtrs_[kM][btmM], childIdx_beg, childIdx_end); } uint64_t calcSumOfWeightOfBtmNodeS ( const void * btmNodeS //!< Pointer to BtmNode for STree ) const noexcept { uint64_t sum = 0; for (uint64_t i = 0; i < getNumChildrenFromBtmNode(btmNodeS); ++i) { const auto idxM = static_cast<const BtmNode *>(btmNodeS)->readLink(i); sum += getWeightFromIdxM(idxM); } return sum; } uint64_t calcSumOfWeightOfBtmS ( const uint64_t btmS ) const noexcept { assert(isValidIdxS(kBtmB * btmS)); return calcSumOfWeightOfBtmNodeS(btmPtrs_[kS][btmS]); } uint64_t calcSumOfWeightOfBtmNodeS ( const void * btmNodeS, //!< Pointer to BtmNode for STree uint8_t childIdx_beg, uint8_t childIdx_end ) const noexcept { uint64_t sum = 0; for (uint16_t i = childIdx_beg; i < childIdx_end; ++i) { const auto idxM = static_cast<const BtmNode *>(btmNodeS)->readLink(i); sum += getWeightFromIdxM(idxM); } return sum; } uint64_t calcSumOfWeightOfBtmS ( const uint64_t btmS, uint8_t childIdx_beg, uint8_t childIdx_end ) const noexcept { assert(isValidIdxM(kBtmB * btmS)); assert(childIdx_beg < childIdx_end); assert(childIdx_end <= getNumChildrenFromBtmS(btmS)); return calcSumOfWeightBtmNodeS(btmPtrs_[kS][btmS], childIdx_beg, childIdx_end); } uint64_t calcSumOfWeightOfBtmNode ( const void * btmNode, //!< Pointer to BtmNode const bool nodeMorS ) const noexcept { return (nodeMorS == kM) ? calcSumOfWeightOfBtmNodeM(btmNode) : calcSumOfWeightOfBtmNodeS(btmNode); } uint64_t calcSumOfWeightOfBtmNode ( const void * btmNode, //!< Pointer to BtmNode uint8_t childIdx_beg, uint8_t childIdx_end, const bool nodeMorS ) const noexcept { return (nodeMorS == kM) ? calcSumOfWeightOfBtmNodeM(btmNode, childIdx_beg, childIdx_end) : calcSumOfWeightOfBtmNodeS(btmNode, childIdx_beg, childIdx_end); } uint64_t calcSumOfWeightOfBtm ( const uint64_t btm, const bool nodeMorS ) const noexcept { return (nodeMorS == kM) ? calcSumOfWeightOfBtmM(btm) : calcSumOfWeightOfBtmS(btm); } uint64_t calcSumOfWeightOfBtm ( const uint64_t btm, uint8_t childIdx_beg, uint8_t childIdx_end, const bool nodeMorS ) const noexcept { return (nodeMorS == kM) ? calcSumOfWeightOfBtmM(btm, childIdx_beg, childIdx_end) : calcSumOfWeightOfBtmS(btm, childIdx_beg, childIdx_end); } //////////////////////////////// rank/select /*! * @brief Compute rank_{ch}[0..pos], i.e., num of ch in T[0..pos]. */ uint64_t rank ( const uint64_t ch, //!< 64bit-char. uint64_t pos, //!< Pos (0base) < |T|. const bool calcTotalRank //!< If true, compute 'rank_{ch}[0..pos] + num of occ of characters in T smaller than ch'. ) const noexcept { assert(isReady()); assert(pos < srootM_.root_->getSumOfWeight()); const auto idxM = searchPosM(pos); // pos is modified to relative pos return rank(ch, idxM, pos, calcTotalRank); } /*! * @brief Variant of rank function, where pos is specified by 'idxM' and 'relativePos'. */ uint64_t rank ( const uint64_t ch, //!< 64bit-char. const uint64_t idxM, //!< Valid idxM. const uint64_t relativePos, //!< Relative pos (0base) < |T|. const bool calcTotalRank //!< If true, compute 'rank_{ch}[0..pos] + num of occ of characters in T smaller than ch'. ) const noexcept { // {//debug // std::cerr << __func__ << ": ch = " << ch << ", idxM = " << idxM << ", relativePos = " << relativePos << std::endl; // } assert(isValidIdxM(idxM)); assert(relativePos < calcSumOfWeightOfBtmM(idxM / kBtmB)); const auto chNow = getCharFromIdxM(idxM); uint64_t ret = 0; uint64_t idxS; if (ch == chNow) { ret = relativePos + 1; idxS = idxM2S(idxM); } else { const auto * retRootS = searchCharA(ch); if (retRootS->isDummy() || getCharFromNodeS(retRootS) != ch) { return 0; } idxS = getPredIdxSFromIdxM(retRootS, ch, idxM); } const auto btmNodeS = btmPtrs_[kS][idxS / kBtmB]; for (uint8_t i = 0; i < (idxS % kBtmB) + (ch != chNow); ++i) { ret += getWeightFromIdxM(btmNodeS->readLink(i)); } if (calcTotalRank) { BTreeNodeT * root; ret += btmNodeS->getParent()->calcPSum(btmNodeS->getIdxInSibling(), root); return ret + root->getParent()->calcPSum(root->getIdxInSibling()); } else { return ret + btmNodeS->getParent()->calcPSum(btmNodeS->getIdxInSibling()); } } /*! * @brief Compute smallest pos (0base) s.t. 'rank == rank_{ch}[0..pos]'. * @attention Rank is 1base. */ uint64_t select ( const BTreeNodeT * rootS, //!< Root of separated tree for 'ch'. const uint64_t rank //!< Rank > 0. ) const noexcept { assert(rank > 0); assert(rootS); // rootS should be valid node if (rank > rootS->getSumOfWeight()) { return BTreeNodeT::NOTFOUND; } auto pos = rank - 1; // -1 for translating rank into 0base pos. const auto idxS = searchPosS(pos, rootS); // pos is modified to the relative pos const auto idxM = idxS2M(idxS); const auto btmNodeM = btmPtrs_[kM][idxM / kBtmB]; pos += calcSumOfWeightOfBtmM(btmNodeM, 0, idxM % kBtmB); return pos + btmNodeM->getParent()->calcPSum(btmNodeM->getIdxInSibling()); } /*! * @brief Compute smallest pos s.t. 'rank == rank_{ch}[0..pos]'. * @attention Rank is 1base. */ uint64_t select ( const uint64_t ch, //!< character for select query. const uint64_t rank //!< Rank > 0. ) const noexcept { assert(rank > 0); const auto * retRootS = searchCharA(ch); if (retRootS->isDummy() || getCharFromNodeS(retRootS) != ch) { return BTreeNodeT::NOTFOUND; } return select(retRootS, rank); } /*! * @brief Compute smallest pos s.t. 'totalRank == totalRank_{ch}[0..pos]'. * @attention TotalRank is 1base. */ uint64_t select ( const uint64_t totalRank //!< TotalRank > 0. ) const noexcept { assert(totalRank > 0); if (totalRank > srootA_.root_->getSumOfWeight()) { return BTreeNodeT::NOTFOUND; } auto pos = totalRank - 1; const auto * retRootS = searchPosA(pos); return select(retRootS, pos + 1); // +1 for 1base rank } /*! * @brief Output string represented by current RLE to std::ofstream. */ void printString(std::ofstream & ofs) const noexcept { assert(isReady()); uint64_t pos = 0; for (auto idxM = searchPosM(pos); idxM != BTreeNodeT::NOTFOUND; idxM = getNextIdxM(idxM)) { const size_t exponent = getWeightFromIdxM(idxM); char ch = getCharFromIdxM(idxM); for (size_t i = 0; i < exponent; ++i) { ofs.put(ch); } } } public: //////////////////////////////// Public search functions /*! * @brief Return 'idxM' corresponding to the run containing 'pos'-th character (0base). * @attention 'pos' is modified to be the relative position (0base) from the beginning of the run. */ uint64_t searchPosM ( uint64_t & pos //!< [in,out] Give position to search (< |T|). It is modified to relative position. ) const noexcept { // {//debug // std::cerr << __func__ << ": pos = " << posidxM << std::endl; // } assert(isReady()); assert(pos < srootM_.root_->getSumOfWeight()); const auto btmNodeM = reinterpret_cast<BtmNode *>(srootM_.root_->searchPos(pos)); const auto & stcc = btmNodeM->getConstRef_stcc(); uint8_t i = 0; uint64_t bitPos = 0; while (true) { const auto w = stcc.readW(i); const auto weight = stcc.readWBits(bitPos, w); if (pos < weight) { break; } ++i; bitPos += w; pos -= weight; } return calcIdxBase(btmNodeM, btmPtrs_[kS]) + i; } /*! * @brief Search root of separated tree of the largest character that is smaller or equal to 'ch'. */ const BTreeNodeT * searchCharA ( const uint64_t ch ) const noexcept { assert(isReady()); auto * nodeA = srootA_.root_; while (true) { const bool nowOnBorder = nodeA->isBorder(); uint8_t lb = 0; uint8_t ub = nodeA->getNumChildren(); while (lb+1 != ub) { // invariant: the answer is in [lb..ub) uint8_t mid = (lb + ub) / 2; if (ch < getCharFromNodeA(nodeA->getChildPtr(mid), nowOnBorder)) { ub = mid; } else { lb = mid; } } nodeA = nodeA->getChildPtr(lb); if (nowOnBorder) { return nodeA; } } } /*! * @brief Search root of separated tree of the largest character that is smaller or equal to 'ch'. */ BTreeNodeT * searchCharA ( const uint64_t ch ) noexcept { assert(isReady()); return const_cast<BTreeNodeT *>(static_cast<const DynRleWithValue &>(*this).searchCharA(ch)); } uint64_t searchPosS ( uint64_t & pos, const BTreeNodeT * rootS ) const noexcept { assert(isReady()); assert(rootS); // rootS should be valid node assert(pos < rootS->getSumOfWeight()); const auto btmNodeS = reinterpret_cast<BtmNode *>(rootS->searchPos(pos)); uint8_t idx = 0; while (true) { const uint64_t idxM = btmNodeS->readLink(idx); auto weight = getWeightFromIdxM(idxM); if (pos >= weight) { pos -= weight; ++idx; } else { return calcIdxBase(btmNodeS, btmPtrs_[kM]) + idx; } } } /*! * @brief Search idxS having the largest label that is smaller or equal to "label". */ uint64_t searchLabelS ( const uint64_t label, const BTreeNodeT * rootS ) const noexcept { assert(isReady()); assert(rootS); // rootS should be valid node const auto * nodeS = rootS; while (true) { const bool nowOnBorder = nodeS->isBorder(); uint8_t lb = 0; uint8_t ub = nodeS->getNumChildren(); while (lb+1 != ub) { uint8_t mid = (lb + ub) / 2; if (label < getLabelFromNodeS(nodeS->getChildPtr(mid), nowOnBorder)) { ub = mid; } else { lb = mid; } } nodeS = nodeS->getChildPtr(lb); if (nowOnBorder) { break; } } const auto btmNodeS = reinterpret_cast<const BtmNode *>(nodeS); uint8_t lb = 0; uint8_t ub = btmNodeS->getNumChildren(); while (lb+1 != ub) { uint8_t mid = (lb + ub) / 2; if (label < getLabelFromIdxM(btmNodeS->readLink(mid))) { ub = mid; } else { lb = mid; } } return calcIdxBase(btmNodeS, btmPtrs_[kM]) + lb; } uint64_t getPredIdxSFromIdxM ( const BTreeNodeT * rootS, const uint64_t ch, const uint64_t idxM ) const noexcept { // {//debug // std::cerr << __FUNCTION__ << " ch = " << ch << "(" << (char)(ch) << "), idxM = " << idxM << std::endl; // } const uint64_t btmM = idxM / kBtmB; const auto btmNodeM = btmPtrs_[kM][btmM]; uint8_t i = (idxM % kBtmB) - 1; if (btmM) { // If btmM is not 0 (0 means btmM is the first btm in the mixed tree). while (i < kBtmB && getCharFromIdxS(btmNodeM->readLink(i)) != ch) { // "i < kBtmB" holds when "i becomes below 0" --i; } if (i < kBtmB) { return btmNodeM->readLink(i); } else { return searchLabelS(btmNodeM->getBtmVal() - 1, rootS); // -1 is needed. } } else { // btmM == 0: dummy idx (== 0) should be ignored. while (i > 0 && getCharFromIdxS(btmNodeM->readLink(i)) != ch) { --i; } if (i > 0) { return btmNodeM->readLink(i); } else { return calcIdxBase(reinterpret_cast<const BtmNode *>(rootS->getLmBtm_DirectJump()), btmPtrs_[kM]); } } } public: //////////////////////////////// Iterator like functions /*! * @brief Get previous idxM. */ uint64_t getPrevIdxM ( const uint64_t idxM //!< Valid idxM. ) const noexcept { assert(isValidIdxM(idxM)); if (idxM % kBtmB) { return idxM - 1; } const auto btmNodeM = btmPtrs_[kM][idxM / kBtmB]; const auto prev = btmNodeM->getPrevBtmNode(); if (prev != nullptr) { return calcIdxBase(prev, btmPtrs_[kS]) + prev->getNumChildren() - 1; } return BTreeNodeT::NOTFOUND; } /*! * @brief Get next idxM. */ uint64_t getNextIdxM ( const uint64_t idxM //!< Valid idxM. ) const noexcept { assert(isValidIdxM(idxM)); const auto btmNodeM = btmPtrs_[kM][idxM / kBtmB]; if ((idxM % kBtmB) + 1 < btmNodeM->getNumChildren()) { return idxM + 1; } const auto next = btmNodeM->getNextBtmNode(); if (next != nullptr) { return calcIdxBase(next, btmPtrs_[kS]); } return BTreeNodeT::NOTFOUND; } /*! * @brief Get first root of separated tree that is not dummy. */ const BTreeNodeT * getFstRootS() const noexcept { assert(isReady()); return getNextRootS(srootA_.root_->getLmBtm_DirectJump()); } /*! * @brief Get first root of separated tree that is not dummy. */ BTreeNodeT * getFstRootS() noexcept { assert(isReady()); return const_cast<BTreeNodeT *>(static_cast<const DynRleWithValue &>(*this).getFstRootS()); } /*! * @brief Get root of separated tree for previous character. */ const BTreeNodeT * getPrevRootS(const BTreeNodeT * node) const noexcept { assert(isReady()); assert(node); // rootS should be valid node while (!node->isRoot()) { node = node->getParent(); } return node->getParent()->getPrevBtm(node->getIdxInSibling()); } BTreeNodeT * getPrevRootS(BTreeNodeT * nodeS) noexcept { assert(isReady()); assert(nodeS); // nodeS should be valid node return const_cast<BTreeNodeT *>(static_cast<const DynRleWithValue &>(*this).getPrevRootS(nodeS)); } /*! * @brief Get root of separated tree for next character. */ const BTreeNodeT * getNextRootS(const BTreeNodeT * nodeS) const noexcept { assert(isReady()); assert(nodeS); // nodeS should be valid node while (!nodeS->isRoot()) { nodeS = nodeS->getParent(); } return nodeS->getParent()->getNextBtm_DirectJump(nodeS->getIdxInSibling()); } /*! * @brief Get root of separated tree for next character. */ BTreeNodeT * getNextRootS(BTreeNodeT * nodeS) noexcept { assert(isReady()); assert(nodeS); // nodeS should be valid node return const_cast<BTreeNodeT *>(getNextRootS(static_cast<const BTreeNodeT *>(nodeS))); } uint64_t getPrevIdxS(const uint64_t idxS) const noexcept { assert(isValidIdxS(idxS)); if (idxS % kBtmB) { return idxS - 1; } const auto prev = btmPtrs_[kS][idxS / kBtmB]->getNextBtmNode(); if (prev != nullptr) { return calcIdxBase(prev, btmPtrs_[kM]) + prev->getNumChildren() - 1; } return BTreeNodeT::NOTFOUND; } uint64_t getNextIdxS(const uint64_t idxS) const noexcept { assert(isValidIdxS(idxS)); const auto btmNodeS = btmPtrs_[kS][idxS / kBtmB]; if ((idxS % kBtmB) + 1 < btmNodeS->getNumChildren()) { return idxS + 1; } const auto next = btmNodeS->getNextBtmNode(); if (next != nullptr) { return calcIdxBase(next, btmPtrs_[kM]); } return BTreeNodeT::NOTFOUND; } private: //////////////////////////////// private functions (utilities) /*! * @brief Get idxBase of "btmNode" */ uint64_t calcIdxBase ( const BtmNode * btmNode, BtmNode ** btmPtrs_other ) const noexcept { uint64_t otherIdx = btmNode->readLink(btmNode->getNumChildren() - 1); return btmPtrs_other[otherIdx / kBtmB]->readLink(otherIdx % kBtmB) & ~(kBtmB - 1); } uint64_t getLabelFromNodeS(const BTreeNodeT * nodeS, const bool isChildOfBorder) const noexcept { uint64_t idxM; if (!isChildOfBorder) { idxM = reinterpret_cast<const BtmNode *>(nodeS->getLmBtm_DirectJump())->readLink(0); } else { idxM = reinterpret_cast<const BtmNode *>(nodeS)->readLink(0); } return getLabelFromIdxM(idxM); } uint64_t getCharFromNodeA(const BTreeNodeT * nodeA, const bool isChildOfBorder) const noexcept { if (!isChildOfBorder) { return reinterpret_cast<const BtmNode *>(nodeA->getLmBtm_DirectJump()->getLmBtm_DirectJump())->getBtmVal(); } else { return reinterpret_cast<const BtmNode *>(nodeA->getLmBtm_DirectJump())->getBtmVal(); } } /*! * @brief Return root of separated tree that contains the position 'pos' (0based) in alphabetically sorted array */ BTreeNodeT * searchPosA(uint64_t & pos) const noexcept { return srootA_.root_->searchPos(pos); } void reserveBtmM(const size_t numBtms) { memutil::realloc_AbortOnFail(btmPtrs_[kM], numBtms); capacity_[kM] = numBtms; traCode_ = TagRelabelAlgo::getSmallestTraCode(numBtms); } void reserveBtmS(const size_t numBtms) { memutil::realloc_AbortOnFail(btmPtrs_[kS], numBtms); capacity_[kS] = numBtms; } void expandBtmM() { const uint64_t newNum = 2 * size_[kM]; // number of capacity of bottoms is doubled reserveBtmM(newNum); } void expandBtmS() { const uint64_t newNum = 2 * size_[kS]; // number of capacity of bottoms is doubled reserveBtmS(newNum); } uint64_t setNewBtmNode ( BtmNode * btmNode, const bool nodeMorS //!< kM or kS ) noexcept { assert(btmNode != nullptr); uint64_t retBtmIdx; if (nodeMorS == kM) { retBtmIdx = size_[kM]; if (retBtmIdx == capacity_[kM]) { expandBtmM(); } btmPtrs_[kM][retBtmIdx] = btmNode; size_[kM] = retBtmIdx + 1; } else { retBtmIdx = size_[kS]; if (retBtmIdx == capacity_[kS]) { expandBtmS(); } btmPtrs_[kS][retBtmIdx] = btmNode; size_[kS] = retBtmIdx + 1; } return retBtmIdx; } void asgnLabel ( BtmNode * btmNodeM ) noexcept { auto nextNodeM = btmNodeM->getNextBtmNode(); auto prevNodeM = btmNodeM->getPrevBtmNode(); // assume that prev alwarys exists uint64_t base = (nextNodeM == nullptr) ? TagRelabelAlgo::MAX_LABEL : nextNodeM->getBtmVal(); if (btmNodeM->getBtmVal() < base - 1) { btmNodeM->setBtmVal((prevNodeM->getBtmVal() + base) / 2); return; } base >>= 1; auto tmpNodeM = btmNodeM; uint8_t l = 1; uint64_t num = 1; uint64_t overflowNum = 2; while (true) { while (prevNodeM != nullptr && (prevNodeM->getBtmVal() >> l) == base) { // expand backward ++num; tmpNodeM = prevNodeM; prevNodeM = prevNodeM->getPrevBtmNode(); } while (nextNodeM != nullptr && (nextNodeM->getBtmVal() >> l) == base){ // expand forward ++num; nextNodeM = nextNodeM->getNextBtmNode(); } if (overflowNum >= num) { break; } ++l; base >>= 1; overflowNum = TagRelabelAlgo::getNextOverflowNum(overflowNum, traCode_); } // relabel num labels uint64_t tmpLabel = base << l; const uint64_t interval = (UINT64_C(1) << l) / num; while (true) { tmpNodeM->setBtmVal(tmpLabel); if (--num == 0) { return; } tmpLabel += interval; tmpNodeM = tmpNodeM->getNextBtmNode(); } } void changePSumFromParent ( BtmNode * btmNode, const int64_t change ) const noexcept { btmNode->getParent()->changePSumFrom(btmNode->getIdxInSibling(), change); } uint64_t setupNewSTree ( BTreeNodeT * predNode, const uint64_t ch ) { // {//debug // std::cerr << __FUNCTION__ << " ch = " << ch << "(" << (char)(ch) << ")" << std::endl; // } auto newBtmNodeS = new BtmNode(); auto * newRootS = new BTreeNodeT(newBtmNodeS, true, true, true, false); uint64_t newIdxS = setNewBtmNode(newBtmNodeS, kS) * kBtmB; newRootS->putFirstBtm(newBtmNodeS, 0); newBtmNodeS->setParentRef(newRootS, 0); newBtmNodeS->setBtmVal(ch); newBtmNodeS->increaseW(8); const uint64_t newVals[] = {0}; const uint64_t newLinks[] = {0}; insertNewElem(newIdxS, 0, newVals, newLinks, 1, 0, kS); // dummy idxS newBtmNodeS->writeLink(0, 0); predNode->getParent()->handleSplitOfChild(newRootS, predNode->getIdxInSibling()); return newIdxS; } /*! * @brief Handle split btm node * @post * This function will do the following: * - update * - links from upper nodes (through handleSplitOfBtm()) * - links to upper nodes (in this function) * - labels (by asgnLabel()) for kM * - character for kS */ void handleSplitOfBtmInBtm ( BtmNode * btmNode1, // First half of splitted node BtmNode * btmNode2, // Second half of splitted node const bool nodeMorS // kM or kS ) noexcept { // {//debug // std::cerr << __FUNCTION__ << std::endl; // } auto * uNode = btmNode1->getParent(); const auto idxInSib = btmNode1->getIdxInSibling(); const auto oriNum = uNode->getNumChildren(); const uint8_t numToL = uNode->handleSplitOfBtm(reinterpret_cast<BTreeNodeT *>(btmNode2), calcSumOfWeightOfBtmNode(btmNode2, nodeMorS), idxInSib); if (numToL == 0) { for (uint8_t i = idxInSib + 1; i < uNode->getNumChildren(); ++i) { auto tmpBtmNode = reinterpret_cast<BtmNode *>(uNode->getChildPtr(i)); tmpBtmNode->setParentRef(uNode, i); } if (oriNum == kB) { auto * nextNode = uNode->getNextSib(); for (uint8_t i = 0; i < nextNode->getNumChildren(); ++i) { auto tmpBtmNode = reinterpret_cast<BtmNode *>(nextNode->getChildPtr(i)); tmpBtmNode->setParentRef(nextNode, i); } } } else { for (uint8_t i = 0; i < uNode->getNumChildren(); ++i) { auto tmpBtmNode = reinterpret_cast<BtmNode *>(uNode->getChildPtr(i)); tmpBtmNode->setParentRef(uNode, i); } auto * prevNode = uNode->getPrevSib(); const uint8_t numL = prevNode->getNumChildren(); for (uint8_t i = numL - (numToL + (idxInSib < numToL)); i < numL; ++i) { auto tmpBtmNode = reinterpret_cast<BtmNode *>(prevNode->getChildPtr(i)); tmpBtmNode->setParentRef(prevNode, i); } } if (nodeMorS == kM) { asgnLabel(btmNode2); } else { btmNode2->setBtmVal(btmNode1->getBtmVal()); // set character of the btm node } } void mvIdxRL ( BtmNode * srcBtmNode, BtmNode * tgtBtmNode, const uint64_t tgtIdxBase, const uint8_t srcIdx, const uint8_t tgtIdx, const uint8_t num, const uint8_t minSupportW, BtmNode ** btmPtrs_other ) noexcept { // {//debug // std::cerr << __FUNCTION__ << ": tgtIdxBase = " << tgtIdxBase << ", srcIdx = " << (int)srcIdx << ", tgtIdx = " << (int)tgtIdx << ", num = " << (int)num // << ", minSupportW = " << (int)minSupportW << ", kM? = " << (btmPtrs_other == btmPtrs_[kS]) << std::endl; // } assert(srcIdx + num <= kBtmB); assert(tgtIdx + num <= kBtmB); for (uint8_t i = num; i > 0; --i) { const uint8_t src = srcIdx + i - 1; const uint8_t tgt = tgtIdx + i - 1; const uint64_t idx_other = srcBtmNode->readLink(src); tgtBtmNode->writeLink(idx_other, tgt); auto btmNode_other = btmPtrs_other[idx_other / kBtmB]; // { // std::cerr << __FUNCTION__ << ": idx_other = " << idx_other << std::endl; // btmNode_other->printDebugInfo(std::cerr); // } btmNode_other->increaseW(minSupportW); btmNode_other->writeLink(tgtIdxBase + tgt, idx_other % kBtmB); // { // std::cerr << __FUNCTION__ << ": idx_other after = " << idx_other << std::endl; // btmNode_other->printDebugInfo(std::cerr); // } } } void mvIdxLR ( BtmNode * srcBtmNode, BtmNode * tgtBtmNode, const uint64_t tgtIdxBase, const uint8_t srcIdx, const uint8_t tgtIdx, const uint8_t num, const uint8_t minSupportW, BtmNode ** btmPtrs_other ) noexcept { // {//debug // std::cerr << __FUNCTION__ << ": tgtIdxBase = " << tgtIdxBase << ", srcIdx = " << (int)srcIdx << ", tgtIdx = " << (int)tgtIdx << ", num = " << (int)num // << ", minSupportW = " << (int)minSupportW << ", kM? = " << (btmPtrs_other == btmPtrs_[kS]) << std::endl; // } assert(srcIdx + num <= kBtmB); assert(tgtIdx + num <= kBtmB); for (uint64_t i = 0; i < num; ++i) { const uint8_t src = srcIdx + i; const uint8_t tgt = tgtIdx + i; const uint64_t idx_other = srcBtmNode->readLink(src); tgtBtmNode->writeLink(idx_other, tgt); auto btmNode_other = btmPtrs_other[idx_other / kBtmB]; btmNode_other->increaseW(minSupportW); btmNode_other->writeLink(tgtIdxBase + tgt, idx_other % kBtmB); } } void makeSpaceInOneBtmNode ( const uint64_t idxBase, const uint8_t childIdx, const uint64_t * srcWCodes, const uint16_t sumW_ins, const uint8_t numChild_ins, const uint8_t numChild_del, //!< Length of wCodes of tgt to delete. const bool insertMorS //!< If "insertMorS == kM", insert to M. If "insertMorS == kS", insert to S. ) noexcept { // {//debug // std::cerr << __FUNCTION__ << ": idxBase = " << idxBase << ", childIdx = " << (int)childIdx << ", sumW_ins = " << (int)sumW_ins // << ", numChild_ins = " << (int)numChild_ins << ", numChild_del = " << (int)numChild_del << ", insertMorS = " << insertMorS << std::endl; // // btmPtrs_[insertMorS][idxBase / kBtmB]->printDebugInfo(std::cerr); // } auto btmNode = btmPtrs_[insertMorS][idxBase / kBtmB]; btmNode->increaseW(bits::bitSize(size_[!insertMorS] * kBtmB)); uint16_t sumW_del = 0; for (uint8_t i = 0; i < numChild_del; ++i) { sumW_del = btmNode->stcc_.readW(childIdx + i); } const uint8_t tailNum = btmNode->numChildren_ - (childIdx + numChild_del); // at least 0 by assumption. uint16_t tailW = 0; if (tailNum) { const uint8_t minSupportW = bits::bitSize(size_[insertMorS] * kBtmB); auto btmPtrs_other = btmPtrs_[!insertMorS]; tailW = btmNode->stccSize_ - btmNode->calcBitPos(childIdx + numChild_del); btmNode->stcc_.mvWCodes(btmNode->stcc_.getConstPtr_wCodes(), childIdx + numChild_del, childIdx + numChild_ins, tailNum); if (numChild_ins > numChild_del) { mvIdxRL(btmNode, btmNode, idxBase, childIdx + numChild_del, childIdx + numChild_ins, tailNum, minSupportW, btmPtrs_other); } else { mvIdxLR(btmNode, btmNode, idxBase, childIdx + numChild_del, childIdx + numChild_ins, tailNum, minSupportW, btmPtrs_other); } } btmNode->stcc_.mvWCodes(srcWCodes, 0, childIdx, numChild_ins); btmNode->numChildren_ += numChild_ins - numChild_del; btmNode->updateWCodesAuxM(childIdx, btmNode->numChildren_); if (sumW_ins != sumW_del) { const uint16_t newBitSize = btmNode->stccSize_ + sumW_ins - sumW_del; btmNode->reserveBitCapacity(newBitSize); if (tailNum) { btmNode->stcc_.mvVals(btmNode->stcc_.getConstPtr_vals(), btmNode->stccSize_ - tailW, newBitSize - tailW, tailW); } btmNode->stccSize_ = newBitSize; } } uint64_t overflowToL ( const uint64_t lIdxBase, const uint64_t rIdxBase, const uint8_t childIdx, const uint64_t * srcWCodes, const uint8_t numChild_ins, const uint8_t numChild_del, //!< Length of wCodes of tgt to delete. const bool insertMorS //!< If "insertMorS == kM", insert to M. If "insertMorS == kS", insert to S. ) noexcept { // {//debug // std::cerr << __FUNCTION__ << ": lIdxBase = " << lIdxBase << ", rIdxBase = " << rIdxBase << ", childIdx = " // << (int)childIdx << ", numChild_ins = " << (int)numChild_ins << ", numChild_del = " << (int)numChild_del << ", insertMorS = " << insertMorS << std::endl; // } assert(childIdx + numChild_del <= btmPtrs_[insertMorS][rIdxBase / kBtmB]->getNumChildren()); auto lnode = btmPtrs_[insertMorS][lIdxBase / kBtmB]; auto rnode = btmPtrs_[insertMorS][rIdxBase / kBtmB]; lnode->increaseW(bits::bitSize(size_[!insertMorS] * kBtmB)); rnode->increaseW(bits::bitSize(size_[!insertMorS] * kBtmB)); const uint8_t minSupportW = bits::bitSize(size_[insertMorS] * kBtmB); auto btmPtrs_other = btmPtrs_[!insertMorS]; std::tuple<uint64_t, uint64_t, uint64_t> changeList[2]; uint8_t clSize = 0; const uint8_t numL_old = lnode->getNumChildren(); const uint8_t numR_old = rnode->getNumChildren(); const uint8_t numTotal = numL_old + numR_old + numChild_ins - numChild_del; const uint8_t numL_new = numTotal / 2; const uint8_t numR_new = numTotal - numL_new; const uint8_t numToLeft = numL_new - numL_old; const bool isNewElemInL = childIdx < numToLeft; const bool isNewElemInR = childIdx + numChild_ins > numToLeft; uint16_t sumWL = lnode->stccSize_; uint8_t numL = numL_old; uint8_t curNumAfterDel = 0; uint8_t curNumSrcWCodes = 0; { const auto num = (isNewElemInL)? childIdx : numToLeft; if (num) { const auto w = rnode->calcBitPos(num); changeList[clSize++] = {0, sumWL, w}; sumWL += w; lnode->stcc_.mvWCodes(rnode->getConstPtr_wCodes(), 0, numL, num); mvIdxLR(rnode, lnode, lIdxBase, 0, numL, num, minSupportW, btmPtrs_other); numL += num; } } if (isNewElemInL) { curNumSrcWCodes = std::min(static_cast<uint8_t>(numToLeft - childIdx), numChild_ins); sumWL += StepCodeUtil::sumW(srcWCodes, 0, curNumSrcWCodes); lnode->stcc_.mvWCodes(srcWCodes, 0, numL, curNumSrcWCodes); numL += curNumSrcWCodes; if (numL < numL_new) { // Still need to move elements to left after inserting srcWCodes curNumAfterDel = numL_new - numL; const auto w = rnode->stcc_.sumW(childIdx + numChild_del, childIdx + numChild_del + curNumAfterDel); changeList[clSize++] = {rnode->calcBitPos(childIdx + numChild_del), sumWL, w}; sumWL += w; lnode->stcc_.mvWCodes(rnode->getConstPtr_wCodes(), childIdx + numChild_del, numL, curNumAfterDel); mvIdxLR(rnode, lnode, lIdxBase, childIdx + numChild_del, numL, curNumAfterDel, minSupportW, btmPtrs_other); } } lnode->numChildren_ = numL_new; lnode->updateWCodesAuxM(numL_old, numL_new); { // Update vals of lnode. lnode->reserveBitCapacity(sumWL); for (uint8_t i = 0; i < clSize; ++i) { lnode->stcc_.mvVals(rnode->getConstPtr_vals(), std::get<0>(changeList[i]), std::get<1>(changeList[i]), std::get<2>(changeList[i])); } lnode->stccSize_ = sumWL; } // Update rnode. clSize = 0; const uint16_t bitPosOfLastChunk = rnode->calcBitPos(childIdx + numChild_del + curNumAfterDel); const uint16_t bitSizeOfLastChunk = rnode->stccSize_ - bitPosOfLastChunk; uint16_t sumWR = bitSizeOfLastChunk; if (numToLeft < childIdx) { const uint8_t num = childIdx - numToLeft; const uint16_t bitPos = rnode->calcBitPos(numToLeft); const uint16_t w = rnode->calcBitPos(childIdx) - bitPos; sumWR += w; changeList[clSize++] = {bitPos, 0, w}; rnode->stcc_.mvWCodes(rnode->getConstPtr_wCodes(), numToLeft, 0, num); mvIdxLR(rnode, rnode, rIdxBase, numToLeft, 0, num, minSupportW, btmPtrs_other); } if (isNewElemInR) { sumWR += StepCodeUtil::sumW(srcWCodes, curNumSrcWCodes, numChild_ins); } if (numR_old != childIdx + numChild_del) { // There are remaining children in tail. if (numR_old != numR_new) { // Need shift wCodes of "this" node. const uint8_t srcBeg = childIdx + numChild_del + curNumAfterDel; const uint8_t num = numR_old - srcBeg; const uint8_t tgtBeg = numR_new - num; rnode->stcc_.mvWCodes(rnode->getConstPtr_wCodes(), srcBeg, tgtBeg, num); if (tgtBeg < srcBeg) { mvIdxLR(rnode, rnode, rIdxBase, srcBeg, tgtBeg, num, minSupportW, btmPtrs_other); } else { mvIdxRL(rnode, rnode, rIdxBase, srcBeg, tgtBeg, num, minSupportW, btmPtrs_other); } } changeList[clSize++] = {bitPosOfLastChunk, sumWR - bitSizeOfLastChunk, bitSizeOfLastChunk}; } if (isNewElemInR) { const uint8_t num = numChild_ins - curNumSrcWCodes; rnode->stcc_.mvWCodes(srcWCodes, curNumSrcWCodes, childIdx + curNumSrcWCodes - numToLeft, num); } rnode->numChildren_ = numR_new; rnode->updateWCodesAuxM(0, numR_new); { // Update vals of rnode rnode->reserveBitCapacity(sumWR); for (uint8_t i = 0; i < clSize; ++i) { rnode->stcc_.mvVals(rnode->getConstPtr_vals(), std::get<0>(changeList[i]), std::get<1>(changeList[i]), std::get<2>(changeList[i])); } rnode->stccSize_ = sumWR; } return (isNewElemInL) ? lIdxBase + numL_old + childIdx : rIdxBase + childIdx - numToLeft; } uint64_t overflowToR ( const uint64_t lIdxBase, const uint64_t rIdxBase, const uint8_t childIdx, const uint64_t * srcWCodes, const uint8_t numChild_ins, const uint8_t numChild_del, //!< Length of wCodes of tgt to delete. const bool insertMorS //!< If "insertMorS == kM", insert to M. If "insertMorS == kS", insert to S. ) noexcept { // {//debug // std::cerr << __FUNCTION__ << ": lIdxBase = " << lIdxBase << ", rIdxBase = " << rIdxBase << ", childIdx = " // << (int)childIdx << ", numChild_ins = " << (int)numChild_ins << ", numChild_del = " << (int)numChild_del << ", insertMorS = " << insertMorS << std::endl; // } assert(childIdx + numChild_del <= btmPtrs_[insertMorS][lIdxBase / kBtmB]->getNumChildren()); auto lnode = btmPtrs_[insertMorS][lIdxBase / kBtmB]; auto rnode = btmPtrs_[insertMorS][rIdxBase / kBtmB]; lnode->increaseW(bits::bitSize(size_[!insertMorS] * kBtmB)); rnode->increaseW(bits::bitSize(size_[!insertMorS] * kBtmB)); const uint8_t minSupportW = bits::bitSize(size_[insertMorS] * kBtmB); auto btmPtrs_other = btmPtrs_[!insertMorS]; std::tuple<uint64_t, uint64_t, uint64_t> changeList[2]; uint8_t clSize = 0; const uint8_t numL_old = lnode->getNumChildren(); const uint8_t numR_old = rnode->getNumChildren(); const uint8_t numTotal = numL_old + numR_old + numChild_ins - numChild_del; const uint8_t numL_new = numTotal / 2; const uint8_t numR_new = numTotal - numL_new; const uint8_t numToRight = numR_new - numR_old; uint8_t numSrcWCodesInL = 0; uint8_t numToRight1 = 0; uint8_t numToRight2 = 0; if (childIdx < numL_new) { // new elements are in L if (childIdx + numChild_ins <= numL_new) { // new elements are only in L numSrcWCodesInL = numChild_ins; numToRight2 = numToRight; } else { // new elements are also in R numSrcWCodesInL = numL_new - childIdx; numToRight2 = numL_old - (childIdx + numChild_del); // { // std::cerr << "koko: numToRight2 = " << numToRight2 << std::endl; // } } } else { // new elements are in R numToRight1 = childIdx - numL_new; numToRight2 = numL_old - (childIdx + numChild_del); } if (numR_old) { // shift wCodes of R to make space rnode->stcc_.mvWCodes(rnode->getConstPtr_wCodes(), 0, numToRight, numR_old); mvIdxRL(rnode, rnode, rIdxBase, 0, numToRight, numR_old, minSupportW, btmPtrs_other); } uint8_t numR_increment = 0; uint16_t sumWR_increment = 0; if (numToRight1) { const uint16_t bitPos = lnode->calcBitPos(childIdx - numToRight1); const uint16_t w = lnode->calcBitPos(childIdx) - bitPos; changeList[clSize++] = {bitPos, 0, w}; sumWR_increment += w; rnode->stcc_.mvWCodes(lnode->getConstPtr_wCodes(), childIdx - numToRight1, 0, numToRight1); mvIdxLR(lnode, rnode, rIdxBase, childIdx - numToRight1, 0, numToRight1, minSupportW, btmPtrs_other); numR_increment += numToRight1; } if (numSrcWCodesInL != numChild_ins) { sumWR_increment += StepCodeUtil::sumW(srcWCodes, numSrcWCodesInL, numChild_ins); rnode->stcc_.mvWCodes(srcWCodes, numSrcWCodesInL, numR_increment, numChild_ins - numSrcWCodesInL); numR_increment += (numChild_ins - numSrcWCodesInL); } if (numToRight2) { const uint16_t bitPos = lnode->calcBitPos(numL_old - numToRight2); const uint16_t w = lnode->stccSize_ - bitPos; changeList[clSize++] = {bitPos, sumWR_increment, w}; sumWR_increment += w; rnode->stcc_.mvWCodes(lnode->getConstPtr_wCodes(), numL_old - numToRight2, numR_increment, numToRight2); mvIdxLR(lnode, rnode, rIdxBase, numL_old - numToRight2, numR_increment, numToRight2, minSupportW, btmPtrs_other); } rnode->numChildren_ = numR_new; rnode->updateWCodesAuxM(0, numR_new); { // Update vals of "rnode". rnode->reserveBitCapacity(rnode->stccSize_ + sumWR_increment); if (numR_old) { rnode->stcc_.mvVals(rnode->getConstPtr_vals(), 0, sumWR_increment, rnode->stccSize_); } for (uint8_t i = 0; i < clSize; ++i) { rnode->stcc_.mvVals(lnode->getConstPtr_vals(), std::get<0>(changeList[i]), std::get<1>(changeList[i]), std::get<2>(changeList[i])); } rnode->stccSize_ += sumWR_increment; } if (numSrcWCodesInL) { // { // std::cerr << "numSrcWCodesInL = " << numSrcWCodesInL << std::endl; // } const uint16_t sumWL_ins = static_cast<uint16_t>(StepCodeUtil::sumW(srcWCodes, 0, numSrcWCodesInL)); const uint16_t tailBitPos_new = lnode->calcBitPos(childIdx) + sumWL_ins; lnode->stccSize_ = tailBitPos_new; const uint8_t numTail = numL_new - (childIdx + numSrcWCodesInL); if (numTail) { const uint16_t tailBitPos_old = lnode->calcBitPos(childIdx + numChild_del); const uint16_t w = lnode->calcBitPos(childIdx + numChild_del + numTail) - tailBitPos_old; lnode->stccSize_ += w; if (tailBitPos_new != tailBitPos_old) { lnode->reserveBitCapacity(lnode->stccSize_); lnode->stcc_.mvVals(lnode->getConstPtr_vals(), tailBitPos_old, tailBitPos_new, w); } if (numChild_ins != numChild_del) { lnode->stcc_.mvWCodes(lnode->getConstPtr_wCodes(), childIdx + numChild_del, childIdx + numChild_ins, numTail); if (numChild_ins > numChild_del) { mvIdxRL(lnode, lnode, lIdxBase, childIdx + numChild_del, childIdx + numChild_ins, numTail, minSupportW, btmPtrs_other); } else { mvIdxLR(lnode, lnode, lIdxBase, childIdx + numChild_del, childIdx + numChild_ins, numTail, minSupportW, btmPtrs_other); } } } else { lnode->reserveBitCapacity(lnode->stccSize_); } lnode->stcc_.mvWCodes(srcWCodes, 0, childIdx, numSrcWCodesInL); lnode->updateWCodesAuxM(childIdx, numL_new); } else { // shrink lnode->stccSize_ = lnode->calcBitPos(numL_new); // shrink (just change bitSize) lnode->shrinkBitCapacity(); lnode->updateWCodesAuxM(numL_new - 1, numL_new); } lnode->numChildren_ = numL_new; return (numSrcWCodesInL) ? lIdxBase + childIdx : rIdxBase + childIdx - numL_new; } void writeNewElemInTwo ( BtmNode * lnode, BtmNode * rnode, uint8_t childIdx, //!< Relative idx to write counting from left-end of lnode const uint64_t * newVals, //!< Storing stcc vals to insert const uint64_t * newLinks, //!< Storing new links to insert const uint8_t numChild_ins ) noexcept { // {//debug // std::cerr << __FUNCTION__ << ": lnode = " << lnode << ", rnode = " << rnode // << ", childIdx = " << (int)childIdx << ", numChild_ins = " << (int)numChild_ins << std::endl; // } uint8_t numL = lnode->getNumChildren(); uint8_t numNewElemInL = 0; if (childIdx < numL) { // Insert new elements to lnode uint64_t bitPos = lnode->calcBitPos(childIdx); numNewElemInL = std::min(numChild_ins, static_cast<uint8_t>(numL - childIdx)); // {//debug // std::cerr << "insert to l: (" << lnode << ")" << numNewElemInL << std::endl; // // lnode->printStatistics(std::cerr, true); // } for (uint8_t i = childIdx; i < childIdx + numNewElemInL; ++i) { lnode->writeLink(newLinks[i - childIdx], i); uint8_t w = lnode->stcc_.readW(i); lnode->stcc_.writeWBits(newVals[i - childIdx], bitPos, w); bitPos += w; } } if (numNewElemInL < numChild_ins) { // Insert new elements to rnode // {//debug // std::cerr << "insert to r:" << std::endl; // rnode->printStatistics(std::cerr, true); // } childIdx += numNewElemInL - numL; uint64_t bitPos = rnode->calcBitPos(childIdx); for (uint8_t i = childIdx; i < childIdx + numChild_ins - numNewElemInL; ++i) { rnode->writeLink(newLinks[i - childIdx + numNewElemInL], i); uint8_t w = rnode->stcc_.readW(i); // std::cerr << "ci = " << ci // << ", w = " << (int)w // << ", weight = " << weights[ci - childIdx_ins] << std::endl; rnode->stcc_.writeWBits(newVals[i - childIdx + numNewElemInL], bitPos, w); bitPos += w; } } } /*! * @brief Insert stcc values * @note Weights of BTreeNodes should be changed in advance */ uint64_t insertNewElem ( const uint64_t idxBase, const uint8_t childIdx, const uint64_t * newVals, //!< Storing stcc vals to insert const uint64_t * newLinks, //!< Storing new links to insert const uint8_t numChild_ins, const uint8_t numChild_del, //!< Length of wCodes of tgt to delete const bool insertMorS //!< If "insertMorS == kM", insert to M. If "insertMorS == kS", insert to S. ) noexcept { assert(numChild_ins <= kBtmB); assert(childIdx + numChild_del <= btmPtrs_[insertMorS][idxBase / kBtmB]->getNumChildren()); // could be equal. Especialy "childIdx" could be "numChildren" // {//debug // std::cerr << __FUNCTION__ << " idxBase = " << idxBase << ", childIdx = " << (int)childIdx // << ", numChild_ins = " << (int)numChild_ins << ", numChild_del = " << (int)numChild_del // << ", insertMorS = " << (int)insertMorS << std::endl; // // btmPtrs_[insertMorS][idxBase / kBtmB]->printDebugInfo(std::cerr); // } auto btmNode = btmPtrs_[insertMorS][idxBase / kBtmB]; auto btmPtrs_other = btmPtrs_[!insertMorS]; uint64_t wCodesTemp[kBtmB / StepCodeUtil::kWCNum]; uint16_t sumW_ins = 0; for (uint8_t i = 0; i < numChild_ins; ++i) { uint8_t w = StepCodeUtil::calcSteppedW(newVals[i]); sumW_ins += w; StepCodeUtil::writeWCode(StepCodeUtil::calcWCodeFromSteppedW(w), wCodesTemp, i); } const uint16_t num = static_cast<uint16_t>(btmNode->getNumChildren()) + numChild_ins - numChild_del; if (num <= static_cast<uint16_t>(kBtmB)) { // Easy case: This node can accommodate inserting elements. makeSpaceInOneBtmNode(idxBase, childIdx, wCodesTemp, sumW_ins, numChild_ins, numChild_del, insertMorS); writeNewElemInTwo(btmNode, btmNode, childIdx, newVals, newLinks, numChild_ins); return idxBase + childIdx; } const uint8_t excess = static_cast<uint8_t>(num - kBtmB); auto parent = btmNode->getParent(); const auto idxInSib = btmNode->getIdxInSibling(); if (idxInSib) { // Check previous sibling. auto lnode = reinterpret_cast<BtmNode *>(parent->getChildPtr(idxInSib - 1)); const auto numL = lnode->getNumChildren(); if (kBtmB - numL >= excess) { // Previous sibling can accommodate overflowed elements. const auto retIdx = overflowToL(calcIdxBase(lnode, btmPtrs_other), idxBase, childIdx, wCodesTemp, numChild_ins, numChild_del, insertMorS); writeNewElemInTwo(lnode, btmNode, numL + childIdx, newVals, newLinks, numChild_ins); parent->changePSumAt(idxInSib - 1, parent->getPSum(idxInSib) + calcSumOfWeightOfBtmNode(lnode, numL, lnode->getNumChildren(), insertMorS)); return retIdx; } } if (idxInSib + 1 < parent->getNumChildren()) { // Check next sibling. auto rnode = reinterpret_cast<BtmNode *>(parent->getChildPtr(idxInSib + 1)); const auto numR = rnode->getNumChildren(); if (kBtmB - numR >= excess) { // Next sibling can accommodate overflowed elements. const auto retIdx = overflowToR(idxBase, calcIdxBase(rnode, btmPtrs_other), childIdx, wCodesTemp, numChild_ins, numChild_del, insertMorS); writeNewElemInTwo(btmNode, rnode, childIdx, newVals, newLinks, numChild_ins); parent->changePSumAt(idxInSib, parent->getPSum(idxInSib + 1) - calcSumOfWeightOfBtmNode(rnode, 0, rnode->getNumChildren() - numR, insertMorS)); return retIdx; } } { // This bottom node has to be split auto rnode = new BtmNode(); const auto rBtmIdx = setNewBtmNode(rnode, insertMorS); const auto retIdx = overflowToR(idxBase, rBtmIdx * kBtmB, childIdx, wCodesTemp, numChild_ins, numChild_del, insertMorS); writeNewElemInTwo(btmNode, rnode, childIdx, newVals, newLinks, numChild_ins); handleSplitOfBtmInBtm(btmNode, rnode, insertMorS); return retIdx; } } uint64_t insertRunAfter_each ( const uint64_t idx, const uint64_t val, const uint64_t link, const bool insertMorS ) noexcept { // {//debug // std::cerr << __func__ << " idx = " << idx << ", val = " << val << ", insertMorS = " << (int)insertMorS << std::endl; // } const uint8_t childIdx = (idx % kBtmB) + 1; // +1 is needed to put new run AFTER "idx". "childIdx" could be "kBtmB" const uint64_t newVals[] = {val}; const uint64_t newLinks[] = {link}; return insertNewElem(idx / kBtmB * kBtmB, childIdx, newVals, newLinks, 1, 0, insertMorS); } uint64_t insertRunWithSplitM ( const uint64_t idxM, const uint64_t splitPos, const uint64_t weight ) noexcept { // {//debug // std::cerr << __func__ << " idxM = " << idxM << ", splitPos = " << splitPos << ", weight = " << weight << std::endl; // } auto btmNodeM = btmPtrs_[kM][idxM / kBtmB]; const uint8_t childIdx = idxM % kBtmB; changePSumFromParent(btmNodeM, weight); const uint64_t weight2 = btmNodeM->readStccVal(childIdx) - splitPos; const uint64_t newVals[] = {splitPos, weight, weight2}; const uint64_t newLinks[] = {btmNodeM->readLink(childIdx), 0, 0}; // 0, 0 are dummy return insertNewElem(idxM / kBtmB * kBtmB, childIdx, newVals, newLinks, 3, 1, kM); } public: //////////////////////////////// Public functions (interface) /*! * @brief Change (increase/decrease) length of run at "idxM". */ void changeWeight ( const uint64_t idxM, const int64_t change ) noexcept { // {//debug // std::cerr << __func__ << ": idxM = " << idxM << ", change = " << change << std::endl; // } // update btm node auto btmNodeM = btmPtrs_[kM][idxM / kBtmB]; const uint64_t curWeight = btmNodeM->readStccVal(idxM % kBtmB); assert(curWeight + change > 0); const uint64_t newVals[] = {static_cast<uint64_t>(curWeight + change)}; btmNodeM->replace(newVals, 1, idxM % kBtmB); // update mixed tree changePSumFromParent(btmNodeM, change); // update separated tree AND alphabet tree (they are connected seamlessly) auto btmNodeS = btmPtrs_[kS][idxM2S(idxM) / kBtmB]; changePSumFromParent(btmNodeS, change); } /*! * @brief Change (increase/decrease) length of run at "idxM". */ void setLeafVal ( const uint64_t idxM, const uint64_t newLeafVal ) noexcept { // update btm node const auto idxS = idxM2S(idxM); const uint64_t newVals[] = {newLeafVal}; btmPtrs_[kS][idxS / kBtmB]->replace(newVals, 1, idxS % kBtmB); } /*! * @brief Pushback a run, merging into the last run if possible. */ uint64_t pushbackRun ( const uint64_t ch, //!< 64bit-char. const uint64_t weight, //!< Weight (exponent) of new run. const uint64_t leafVal, uint64_t & pos //!< [out] It is set to relative position of a run. ) { const auto btmNodeM = reinterpret_cast<BtmNode *>(srootM_.root_->getRmBtm()); const auto idxS = btmNodeM->readLink(btmNodeM->getNumChildren() - 1); if (idxS == 0) { // dummy pos = 0; return insertRunAfter(0, weight, leafVal, ch); } const auto btmNodeS = btmPtrs_[kS][idxS / kBtmB]; const auto idxM = btmNodeS->readLink(idxS % kBtmB); if (btmNodeS->getBtmVal() != ch) { pos = 0; return insertRunAfter(idxM, weight, leafVal, ch); } else { // merge into the last run pos = getWeightFromIdxM(idxM); changeWeight(idxM, weight); return idxM; } } /*! * @brief Pushback a run without merge. */ // uint64_t pushbackRunWithoutMerge // ( // const uint64_t ch, //!< 64bit-char. // const uint64_t weight, //!< Weight (exponent) of new run. // const uint64_t leafVal // ) { // const auto btmNodeM = reinterpret_cast<BtmNode *>(srootM_.root_->getRmBtm()); // return insertRunAfter(calcIdxBase(btmNodeM, btmPtrs_[kS]) + btmNodeM->getNumChildrenFromBtmM() - 1, weight, leafVal, ch); // } /*! * @brief Insert run of "ch^{weight}" at "pos", merging into adjacent runs if possible. */ uint64_t insertRun ( const uint64_t ch, //!< 64bit-char. const uint64_t weight, //!< Weight (exponent) of new run. const uint64_t leafVal1, const uint64_t leafVal2, uint64_t & pos //!< [in,out] 0base position where inserted run will start. It is modified to relative position in a run. ) { // {//debug // std::cerr << __func__ << ": ch = " << ch << ", weight = " << weight // << ", leafVal1 = " << leafVal1 << ", leafVal2 = " << leafVal2 << ", pos = " << pos << std::endl; // } if (pos > srootM_.root_->getSumOfWeight()) { return BTreeNodeT::NOTFOUND; } else if (pos == srootM_.root_->getSumOfWeight()) { return pushbackRun(ch, weight, leafVal1, pos); } auto idxM = searchPosM(pos); // 'pos' is modified to be the relative pos in the run of 'idxM'. auto chNow = getCharFromIdxM(idxM); if (ch == chNow) { changeWeight(idxM, weight); } else if (pos == 0) { idxM = getPrevIdxM(idxM); // Move to previous idxM. if (idxM > 0 && ch == getCharFromIdxM(idxM)) { // Check if 'ch' can be merged with the previous run. pos = getWeightFromIdxM(idxM); changeWeight(idxM, weight); } else { idxM = insertRunAfter(idxM, weight, leafVal1, ch); } } else { // Current run is split with fstHalf of weight 'pos'. idxM = insertRunWithSplit(idxM, pos, weight, leafVal1, leafVal2, ch); pos = 0; } return idxM; } /*! * @brief Variant of DynRLE::insertRun for rvalue pos. */ uint64_t insertRun ( const uint64_t ch, //!< 64bit-char. const uint64_t weight, //!< Weight (exponent) of new run. const uint64_t leafVal1, const uint64_t leafVal2, uint64_t && pos //!< 0base position where inserted run will start. ) { auto tmp = pos; return insertRun(ch, weight, leafVal1, leafVal2, tmp); } /*! * @brief Insert new run of character 'ch' and length 'weight' after 'idxM'. * @return IdxM of the inserted run. */ uint64_t insertRunAfter ( const uint64_t idxM, const uint64_t weight, const uint64_t leafVal, const uint64_t ch ) noexcept { // {//debug // std::cerr << __func__ << " idxM = " << idxM << ", weight = " << weight << ", leafVal = " << leafVal << std::endl; // std::cerr << __func__ << ": BEFORE idxM = " << idxM << std::endl; // // btmPtrs_[kM][idxM / kBtmB]->printDebugInfo(std::cerr); // } changePSumFromParent(btmPtrs_[kM][idxM / kBtmB], weight); const auto newIdxM = insertRunAfter_each(idxM, weight, 0, kM); BTreeNodeT * retRootS = searchCharA(ch); uint64_t idxS; if (retRootS->isDummy() || getCharFromNodeS(retRootS) != ch) { idxS = setupNewSTree(retRootS, ch); } else { idxS = getPredIdxSFromIdxM(retRootS, ch, newIdxM); } // {//debug // std::cerr << __FUNCTION__ << ": BEFORE idxS = " << idxS << std::endl; // btmPtrs_[kS][idxS / kBtmB]->printDebugInfo(std::cerr); // } changePSumFromParent(btmPtrs_[kS][idxS / kBtmB], weight); const auto newIdxS = insertRunAfter_each(idxS, leafVal, newIdxM, kS); btmPtrs_[kM][newIdxM / kBtmB]->writeLink(newIdxS, newIdxM % kBtmB); btmPtrs_[kS][newIdxS / kBtmB]->writeLink(newIdxM, newIdxS % kBtmB); // parent->changePSumAt(idxInSib - 1, parent->getPSum(idxInSib) + calcSumOfWeightOfBtmNode(lnode, numL, lnode->getNumChildren(), insertMorS)); // parent->changePSumAt(idxInSib, parent->getPSum(idxInSib + 1) - calcSumOfWeightOfBtmNode(rnode, 0, rnode->getNumChildren() - numR, insertMorS)); // {//debug // std::cerr << __FUNCTION__ << ": AFTER idxS = " << idxS << ", newIdxS = " << newIdxS << std::endl; // std::cerr << __FUNCTION__ << ": AFTER show idxS = " << idxS << std::endl; // btmPtrs_[kS][idxS / kBtmB]->printDebugInfo(std::cerr); // if (idxM / kBtmB != newIdxM / kBtmB) { // std::cerr << __FUNCTION__ << ": AFTER show newIdxS = " << newIdxS << std::endl; // btmPtrs_[kS][newIdxS / kBtmB]->printDebugInfo(std::cerr); // } // } // {//debug // std::cerr << __FUNCTION__ << ": AFTER idxM = " << idxM << ", newIdxM = " << newIdxM << std::endl; // std::cerr << __FUNCTION__ << ": AFTER show idxM = " << idxM << std::endl; // btmPtrs_[kM][idxM / kBtmB]->printDebugInfo(std::cerr); // if (idxM / kBtmB != newIdxM / kBtmB) { // std::cerr << __FUNCTION__ << ": AFTER show newIdxM = " << newIdxM << std::endl; // btmPtrs_[kM][newIdxM / kBtmB]->printDebugInfo(std::cerr); // } // } return newIdxM; } /*! * @brief Insert new run of character 'ch' and length 'weight' splitting run at "idxM". * @return IdxM of the inserted run. * @note Assume that "ch" is different from the one for the splitted run. */ uint64_t insertRunWithSplit ( const uint64_t idxM, const uint64_t splitPos, const uint64_t weight, const uint64_t leafVal1, const uint64_t leafVal2, const uint64_t ch ) noexcept { // {//debug // std::cerr << __FUNCTION__ << " idxM = " << idxM << ", splitPos = " << splitPos // << ", weight = " << weight << ", leafVal1 = " << leafVal1 << ", leafVal2 = " << leafVal2 << std::endl; // } const uint64_t idxS0 = idxM2S(idxM); uint64_t tempIdxM = insertRunWithSplitM(idxM, splitPos, weight); if (idxM != tempIdxM) { btmPtrs_[kS][idxS0 / kBtmB]->increaseW(bits::bitSize(size_[kM] * kBtmB)); btmPtrs_[kS][idxS0 / kBtmB]->writeLink(tempIdxM, idxS0 % kBtmB); } auto * retRootS = searchCharA(ch); uint64_t idxS; if (retRootS->isDummy() || reinterpret_cast<BtmNode *>(retRootS->getLmBtm_DirectJump())->getBtmVal() != ch) { idxS = setupNewSTree(retRootS, ch); } else { idxS = getPredIdxSFromIdxM(retRootS, ch, tempIdxM); } const auto newIdxM = getNextIdxM(tempIdxM); { // insert new run with character "ch" tempIdxM = newIdxM; changePSumFromParent(btmPtrs_[kS][idxS / kBtmB], weight); idxS = insertRunAfter_each(idxS, leafVal1, tempIdxM, kS); btmPtrs_[kM][tempIdxM / kBtmB]->writeLink(idxS, tempIdxM % kBtmB); } { // insert second half of splitted run tempIdxM = getNextIdxM(tempIdxM); idxS = insertRunAfter_each(idxS0, leafVal2, tempIdxM, kS); btmPtrs_[kM][tempIdxM / kBtmB]->writeLink(idxS, tempIdxM % kBtmB); } return newIdxM; } public: //////////////////////////////// statistics size_t calcMemBytesMTree() const noexcept { if (isReady()) { return srootM_.root_->calcMemBytes(); } else { return 0; } } size_t calcMemBytesATree() const noexcept { if (isReady()) { return srootA_.root_->calcMemBytes(); } else { return 0; } } size_t calcMemBytesSTree() const noexcept { size_t size = 0; if (isReady()) { for (const auto * rootS = getFstRootS(); reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND; rootS = getNextRootS(rootS)) { size += rootS->calcMemBytes(); } } return size; } size_t calcMemBytesBtmM() const noexcept { size_t size = 0; for (uint64_t i = 0; i < size_[kM]; ++i) { size += btmPtrs_[kM][i]->calcMemBytes(); } return size; } size_t calcMemBytesBtmS() const noexcept { size_t size = 0; for (uint64_t i = 0; i < size_[kS]; ++i) { size += btmPtrs_[kS][i]->calcMemBytes(); } return size; } size_t calcMemBytesLinks() const noexcept { size_t size = 0; for (uint64_t i = 0; i < size_[kM]; ++i) { size += btmPtrs_[kM][i]->calcMemBytesLinksArray(); } for (uint64_t i = 0; i < size_[kS]; ++i) { size += btmPtrs_[kS][i]->calcMemBytesLinksArray(); } return size; } size_t calcMemBytesBtmWeights() const noexcept { size_t size = 0; for (uint64_t i = 0; i < size_[kM]; ++i) { size += btmPtrs_[kM][i]->calcMemBytesStccDynArray(); } return size; } size_t calcMemBytesLeafVals() const noexcept { size_t size = 0; for (uint64_t i = 0; i < size_[kS]; ++i) { size += btmPtrs_[kS][i]->calcMemBytesStccDynArray(); } return size; } size_t calcMemBytes ( bool includeThis = true ) const noexcept { size_t size = sizeof(*this) * includeThis; size += calcMemBytesBtmM(); size += calcMemBytesBtmS(); size += calcMemBytesMTree(); size += calcMemBytesATree(); size += calcMemBytesSTree(); return size; } size_t calcNumUsedSTree() const noexcept { size_t numUsed = 0; if (isReady()) { for (const auto * rootS = getFstRootS(); reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND; rootS = getNextRootS(rootS)) { numUsed += rootS->calcNumUsed(); } } return numUsed; } size_t calcNumSlotsSTree() const noexcept { size_t numSlots = 0; if (isReady()) { for (const auto * rootS = getFstRootS(); reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND; rootS = getNextRootS(rootS)) { numSlots += rootS->calcNumSlots(); } } return numSlots; } size_t calcNumUsedBtmM() const noexcept { size_t numUsed = 0; for (uint64_t i = 0; i < size_[kM]; ++i) { numUsed += btmPtrs_[kM][i]->getNumChildren(); } return numUsed; } size_t calcNumSlotsBtmM() const noexcept { return size_[kM] * kBtmB; } size_t calcNumUsedBtmS() const noexcept { size_t numUsed = 0; for (uint64_t i = 0; i < size_[kS]; ++i) { numUsed += btmPtrs_[kS][i]->getNumChildren(); } return numUsed; } size_t calcNumSlotsBtmS() const noexcept { return size_[kS] * kBtmB; } size_t calcNumRuns() const noexcept { size_t numRuns = 0; for (size_t i = 0; i < size_[kM]; ++i) { numRuns += getNumChildrenFromBtmM(i); } return numRuns - 1; // -1 due to the first dummy } size_t calcNumAlph() const noexcept { size_t numAlph = 0; if (isReady()) { for (const auto * rootS = getFstRootS(); reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND; rootS = getNextRootS(rootS)) { ++numAlph; } } return numAlph; } void printStatictics(std::ostream & os) const noexcept { if (isReady()) { const size_t totalLen = getSumOfWeight(); const size_t numRuns = calcNumRuns(); const size_t numSlotsM = srootM_.root_->calcNumSlots(); const size_t numUsedM = srootM_.root_->calcNumUsed(); const size_t numSlotsA = srootA_.root_->calcNumSlots(); const size_t numUsedA = srootA_.root_->calcNumUsed(); const size_t numSlotsS = calcNumSlotsSTree(); const size_t numUsedS = calcNumUsedSTree(); const size_t numSlotsBtm = calcNumSlotsBtmM() + calcNumSlotsBtmS(); const size_t numUsedBtm = calcNumUsedBtmM() + calcNumUsedBtmS(); os << "TotalLen = " << totalLen << ", #Runs = " << numRuns << ", Alphabet Size = " << calcNumAlph() << ", BTreeNode arity kB = " << static_cast<uint64_t>(kB) << " BtmNode arity kBtmB = " << static_cast<uint64_t>(kBtmB) << std::endl; os << "MTree bottom array size = " << size_[kM] << ", capacity = " << capacity_[kM] << std::endl; os << "STree bottom array size = " << size_[kS] << ", capacity = " << capacity_[kS] << std::endl; os << "Total: " << calcMemBytes() << " bytes" << std::endl; os << "MTree: " << calcMemBytesMTree() << " bytes, OccuRate = " << ((numSlotsM) ? 100.0 * numUsedM / numSlotsM : 0) << " (= 100*" << numUsedM << "/" << numSlotsM << ")" << std::endl; os << "ATree: " << calcMemBytesATree() << " bytes, OccuRate = " << ((numSlotsA) ? 100.0 * numUsedA / numSlotsA : 0) << " (= 100*" << numUsedA << "/" << numSlotsA << ")" << std::endl; os << "STree: " << calcMemBytesSTree() << " bytes, OccuRate = " << ((numSlotsS) ? 100.0 * numUsedS / numSlotsS : 0) << " (= 100*" << numUsedS << "/" << numSlotsS << ")" << std::endl; os << "BtmNodes: " << calcMemBytesBtmM() + calcMemBytesBtmS() << " bytes, OccuRate = " << ((numSlotsBtm) ? 100.0 * numUsedBtm / numSlotsBtm : 0) << " (= 100*" << numUsedBtm << "/" << numSlotsBtm << ")" << std::endl; os << "Links: " << calcMemBytesLinks() << " bytes" << std::endl; os << "Weights: " << calcMemBytesBtmWeights() << " bytes" << std::endl; os << "LeafVals: " << calcMemBytesLeafVals() << " bytes" << std::endl; } } void printDebugInfo ( std::ostream & os ) const noexcept { os << "size_[kM] = " << size_[kM] << ", capacity_[kM] = " << capacity_[kM] << ", size_[kS] = " << size_[kS] << ", capacity_[kS] = " << capacity_[kS] << ", traCode_ = " << (int)traCode_ << std::endl; if (isReady() && getSumOfWeight() > 0) { { os << "dump btmPtrs_[kM]" << std::endl; for (uint64_t i = 0; i < size_[kM]; ++i) { os << "[" << i << "]" << btmPtrs_[kM][i] << " "; } os << std::endl; os << "dump btmPtrs_[kS]" << std::endl; for (uint64_t i = 0; i < size_[kS]; ++i) { os << "[" << i << "]" << btmPtrs_[kS][i] << " "; } os << std::endl; } // { // os << "dump btmPtrs_[kM] debugInfo" << std::endl; // for (uint64_t i = 0; i < size_[kM]; ++i) { // btmPtrs_[kM][i]->printDebugInfo(os); // } // os << "dump btmPtrs_[kS] debugInfo" << std::endl; // for (uint64_t i = 0; i < size_[kS]; ++i) { // btmPtrs_[kS][i]->printDebugInfo(os); // } // } { // check links of idxM2S and idxS2M for (uint64_t i = 0; i < size_[kM]; ++i) { for (uint64_t j = 0; j < getNumChildrenFromBtmM(i); ++j) { uint64_t idxM = kBtmB * i + j; if (idxM != idxS2M(idxM2S(idxM))) { os << "error!! links of idxM2S and idxS2M: idxM = " << idxM << ", idxS = " << idxM2S(idxM) << std::endl; // WARNING, links are not maintained correctly btmPtrs_[kM][idxM /kBtmB]->printDebugInfo(std::cerr, true, *this, kM); btmPtrs_[kS][idxM2S(idxM) /kBtmB]->printDebugInfo(std::cerr, true, *this, kS); } } } } { // check links of parent-child for M for (uint64_t i = 0; i < size_[kM]; ++i) { uint8_t idx = getIdxInSiblingFromBtmM(i); auto node = getParentFromBtmM(i); bool islmbtm = (idx == 0); if (static_cast<void *>(node->getChildPtr(idx)) != btmPtrs_[kM][i]) { os << "error!! " << "parent-child for btmM = " << i << std::endl; } if (islmbtm && static_cast<void *>(node->getLmJumpNode()) != btmPtrs_[kM][i]) { os << "error!! lmJumNode for btmM = " << i << std::endl; } while (!(node->isRoot())) { idx = node->getIdxInSibling(); islmbtm &= (idx == 0); if (node->getParent()->getChildPtr(idx) != node) { os << "error!! " << "parent-child for child node = " << node << std::endl; } if (islmbtm && static_cast<void *>(node->getLmJumpNode()) != btmPtrs_[kM][i]) { os << "error!! lmJumNode for btmM = " << i << std::endl; } node = node->getParent(); } } } { // check links of parent-child for S for (uint64_t i = 0; i < size_[kS]; ++i) { uint8_t idx = getIdxInSiblingFromBtmS(i); auto node = getParentFromBtmS(i); bool islmbtm = (idx == 0); if (static_cast<void *>(node->getChildPtr(idx)) != btmPtrs_[kS][i]) { os << "error!! " << "parent-child for btmS = " << i << std::endl; } if (islmbtm && static_cast<void *>(node->getLmJumpNode()) != btmPtrs_[kS][i]) { os << "error!! lmJumpNode for btmS = " << i << std::endl; } while (!(node->isRoot())) { idx = node->getIdxInSibling(); islmbtm &= (idx == 0); if (static_cast<void *>(node->getParent()->getChildPtr(idx)) != node) { os << "error!! " << "parent-child for child node = " << node << std::endl; } if (islmbtm && static_cast<void *>(node->getLmJumpNode()) != btmPtrs_[kS][i]) { os << "error!! lmJumNode for btmM = " << i << std::endl; } node = node->getParent(); } } } { // check correctness of runs uint64_t c = UINT64_MAX; os << "check runs:" << std::endl; // std::cerr << srootM_.root_ << " " << srootA_.root_ << std::endl; uint64_t pos = 0; uint64_t len = 0; for (auto idxM = searchPosM(pos); idxM != BTreeNodeT::NOTFOUND; idxM = getNextIdxM(idxM)) { ++pos; len += getWeightFromIdxM(idxM); if (getWeightFromIdxM(idxM) == 0) { os << "error!! detected 0 length run: " << idxM << ", " << pos << std::endl; } if (c == getCharFromIdxM(idxM)) { auto idxM0 = getPrevIdxM(idxM); os << "error!! detected consecutive runs having the same char: " << idxM << ", " << pos << ", (" << c << ", " << getWeightFromIdxM(idxM0) << ")" << ", (" << c << ", " << getWeightFromIdxM(idxM) << ")" << std::endl; } c = getCharFromIdxM(idxM); } std::cerr << "run: " << pos << ", len: " << len << std::endl; } // { // uint64_t pos = 0; // for (auto idxM = searchPosM(pos); idxM != BTreeNodeT::NOTFOUND; idxM = getNextIdxM(idxM)) { // os << "(" << idxM << ":" << getCharFromIdxM(idxM) << "^" << getWeightFromIdxM(idxM) << ", " << getLeafValFromIdxM(idxM) << ") "; // } // os << std::endl; // } // {//MTree // srootM_.root_->printStatistics(std::cerr, true); // } // { // os << "Information on M" << std::endl; // uint64_t pos = 0; // for (auto btmNodeM = reinterpret_cast<const BtmNode *>(srootM_.root_->getLmBtm_DirectJump()); // btmNodeM != nullptr; // btmNodeM = btmNodeM->getNextBtmNode()) { // btmNodeM->printDebugInfo(std::cerr, true, *this, kM); // } // os << std::endl; // } // { // os << "Alphabet: " << std::endl; // for (const auto * rootS = getFstRootS(); // reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND; // rootS = getNextRootS(rootS)) { // os << "(" << getCharFromNodeS(rootS) << ", " << rootS->getSumOfWeight() << ") "; // } // os << std::endl; // os << std::endl; // } // { // os << "Information on S" << std::endl; // for (const auto * rootS = getFstRootS(); // reinterpret_cast<uintptr_t>(rootS) != BTreeNodeT::NOTFOUND; // rootS = getNextRootS(rootS)) { // for (auto btmNodeS = reinterpret_cast<const BtmNode *>(rootS->getLmBtm_DirectJump()); // btmNodeS != nullptr; // btmNodeS = btmNodeS->getNextBtmNode()) { // btmNodeS->printDebugInfo(std::cerr, true, *this, kS); // } // } // } } } }; } // namespace itmmti #endif
34.090331
174
0.573428
[ "object" ]
1d7b0d5c77b9bf9e12fd3616a04f970aef766a38
89,942
cxx
C++
ds/ds/src/ism/trnsprts/smtp/xmitrecv.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/ds/src/ism/trnsprts/smtp/xmitrecv.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/ds/src/ism/trnsprts/smtp/xmitrecv.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1998 Microsoft Corporation. All rights reserved. MODULE NAME: xmitrecv.cxx ABSTRACT: Methods to support send and receive via SMTP for the Intersite Messaging service. DETAILS: CREATED: 3/20/98 Jeff Parham (jeffparh) REVISION HISTORY: Jul 17, 1998 Will Lees (wlees) Restructured and simplified to use CDO V2. 1. Use events as primary means of event notification (polling as backup) 2. Send message data in-line instead of an attachment 3. Combine polling and receiving routines into one Sep 3, 1998 wlees Added support for detecting and eliminating duplicate messages Oct 22, 1998 Duplicate suppression, guid-based mail names --*/ #include <ntdspchx.h> #include <align.h> #include <ismapi.h> #include <debug.h> #include <atlbase.h> // cccomptr #include "cdosys.h" // Jun 8, 1999. #ifdef necessary until new headers checked in #ifdef __cdo_h__ using namespace CDO; #endif // Logging headers. // TODO: better place to put these? typedef ULONG MessageId; typedef ULONG ATTRTYP; //#include "ntdsa.h" //#include "taskq.h" // GetSecondsSince1601() #include "dsevent.h" /* header Audit\Alert logging */ #include "mdcodes.h" /* header for error codes */ #include "dsconfig.h" // Get config param #include <ntrtl.h> // Generic table package #include <fileno.h> #define FILENO FILENO_ISMSERV_XMITRECV #include "common.h" #include "ismsmtp.h" #include "support.hxx" // This is actually a C fragment generated by the IDL compiler // It contains some useful constants for calling CDO #include "cdosys_i.c" // Include the class id for the smtp sink so we can check for it #include "smtpsink_i.c" #define DEBSUB "XMITRECV:" #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) #define QUEUE_DIRECTORY L"Queue" #define QUEUE_DIRECTORY_LEN (ARRAY_SIZE(QUEUE_DIRECTORY)) #define DROP_DIRECTORY L"Drop" #define DROP_DIRECTORY_LEN (ARRAY_SIZE(DROP_DIRECTORY)) #define RCPT_TO_RULE L"RCPT TO=" #define RCPT_TO_RULE_LEN (ARRAY_SIZE(RCPT_TO_RULE)) // Format for the message subject. #define USER_PREFIX L"_IsmService@" #define USER_PREFIX_LEN (ARRAY_SIZE(USER_PREFIX) - 1) #define SUBJECT_PREFIX L"Intersite message for " #define SUBJECT_PREFIX_LEN (ARRAY_SIZE(SUBJECT_PREFIX) - 1) #define SUBJECT_SEPARATOR L": " #define SUBJECT_SEPARATOR_LEN (ARRAY_SIZE(SUBJECT_SEPARATOR) - 1) const WCHAR gszSubjectFormat[] = SUBJECT_PREFIX L"%ls" SUBJECT_SEPARATOR L"%ls"; const DWORD gcchSubjectFormat = ARRAY_SIZE(gszSubjectFormat); #define HR_SHARING_VIOLATION (HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION)) #define HR_FILE_NOT_FOUND (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) #define HR_NOT_ENOUGH_MEMORY (HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY)) #define HR_INVALID_DATA (HRESULT_FROM_WIN32(ERROR_INVALID_DATA)) #define SMTP_MSG_GUID cdoNSMailHeader L"X-MsgGuid" #define SMTP_SUPERSEDES_MSG_GUID cdoNSMailHeader L"X-SupersedesMsgGuid" // How frequently do we log an error if SMTP domain not available #define NO_SMTP_DOMAIN_INTERVAL (24 * 60 * 60) // Once a day typedef LONGLONG DSTIME; extern "C" { // Return seconds since Jan 1, 1601. DSTIME GetSecondsSince1601( void ); } // Forward DWORD configureMailAddress( IN TRANSPORT_INSTANCE * pTransport ); VOID disableMailAddress( IN TRANSPORT_INSTANCE * pTransport ); // Static static GUID zeroGuid = {0}; HRESULT supersedeMessage( IN TRANSPORT_INSTANCE * pTransport, IN LPCWSTR pszRemoteTransportAddress, IN LPCWSTR pszServiceName, IN LPCWSTR pszMessageSubject, IN IMessage * pIMsg ) /*++ Routine Description: This routine writes the necessary fields in the message so that it will supercede a previous message with the same (service,address,subject). This is done by keeping keeping a circular list/cache of most recent triples, and associating with the entry the guid of the last sent message. On the first send, a new guid is used. On a second or later send, the previous guid is set for the "supersede guid", and then a new guid is set in the cache. Note that this cache is a performance optimization. If an entry is bumped out of the cache, it only means that we won't be able to regenerate the previous supersede guid to suppress the previous message. Under certain degenerate circumstances (more than x services, more than y naming contexts), we will start to drop entries out. Note that we depend on the circular nature of the list at the subject level in order to push out old subject entries. We don't get feed back whether we were successful. We depend on the fact that when communication in happening, new subjects get inserted at the front and the old useless subjects get pushed out the back. We limit the number of entries so we won't have to search so many each time. When communication isn't happening, we expect that the size of the circular buffer is enough to contain all the unique subjects that are generated by the application (hopefully small). These limits can be adjusted. Arguments: pTransport - pszRemoteTransportAddress - pszServiceName - pszMessageSubject - pIMsg - Return Value: HRESULT - --*/ { DWORD status; HRESULT hr; CComPtr<Fields> pFields; PSUBJECT_INSTANCE pSubject = NULL; // Look up the (Service, Address, Subject) triple EnterCriticalSection( &(pTransport->Lock) ); __try { status = SmtpTableFindSendSubject( pTransport, pszRemoteTransportAddress, pszServiceName, pszMessageSubject, &pSubject ); } __finally { LeaveCriticalSection( &(pTransport->Lock) ); } if (status != ERROR_SUCCESS) { DPRINT1( 0, "failed to find subject cache, error 0x%x\n", status ); hr = HRESULT_FROM_WIN32( status ); LogUnhandledError( hr ); goto cleanup; } // Now we have a pointer to a subject record, either new or previous hr = pIMsg->get_Fields(&pFields); if (FAILED(hr)) { DPRINT1( 0, "failed to get_Fields, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // if guid is present, ie this is a retry, load the guid into the // supersedes guid filed if (memcmp( &(pSubject->Guid), &zeroGuid, sizeof(GUID) ) != 0) { DPRINT3( 1, "This message supersedes prior message: (%ws,%ws,%ws)\n", pszServiceName, pszRemoteTransportAddress, pszMessageSubject ); hr = putFieldGuid( pFields, SMTP_SUPERSEDES_MSG_GUID, &(pSubject->Guid) ); if (FAILED(hr)) { DPRINT1( 0, "failed to set field guid, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } } // Allocate a new guid, store in subject descriptor status = UuidCreate( &(pSubject->Guid) ); if ( (status != RPC_S_OK) && (status != RPC_S_UUID_LOCAL_ONLY) ) { DPRINT1( 0, "failed to create guid, error %d\n", status ); LogUnhandledError( status ); hr = HRESULT_FROM_WIN32( status ); goto cleanup; } // Load guid into message hr = putFieldGuid( pFields, SMTP_MSG_GUID, &(pSubject->Guid) ); if (FAILED(hr)) { DPRINT1( 0, "failed to set field guid, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } hr = pFields->Update(); if (FAILED(hr)) { DPRINT1( 0, "failed to update fields, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } cleanup: if (pFields) { pFields = NULL; } return hr; } /* supersedeMessage */ VOID addRemoveSmtpSvc( IN TRANSPORT_INSTANCE * pTransport, IN BOOL fIsSmtpSvcPresent ) /*++ Routine Description: Description Arguments: pTransport - fIsSmtpSvcPresent - Return Value: None --*/ { DWORD status, tries, waitCode; if (fIsSmtpSvcPresent) { DPRINT( 1, "SMTPSVC is present\n" ); // Even though SmtpSvc is installed, all the other necessary plumbing // to add a new domain (ADSI) support is not fully there. Give the IIS // install a chance to finish for( tries = 0; tries < 40; tries++ ) { waitCode = WaitForSingleObject( pTransport->hShutdownEvent, 15 * 1000 ); if (pTransport->fShutdownInProgress) { return; } if (SUCCEEDED( CheckSmtpDomainContainerPresent() )) { break; } } if (pTransport->fShutdownInProgress) { return; } EnterCriticalSection( &(pTransport->Lock) ); __try { if ( NULL == pTransport->Smtp.pszSmtpAddress ) { status = configureMailAddress( pTransport ); } } __finally { LeaveCriticalSection( &(pTransport->Lock) ); } } else { // This is where we detect the SmtpSvc being uninstalled. DPRINT( 1, "SMTPSVC is absent\n" ); EnterCriticalSection( &(pTransport->Lock) ); __try { if ( NULL != pTransport->Smtp.pszSmtpAddress ) { disableMailAddress( pTransport ); } } __finally { LeaveCriticalSection( &(pTransport->Lock) ); } } // if fIsSmtpSvcPresent } /* addRemoveSmtpSvc */ unsigned __stdcall SmtpRegistryNotifyThread( void *Argument1 ) /*++ Routine Description: Thread to wait for a registry notification that the Smtp Service has been installed. When we detect that the Smtp Service is present, we configure our mail address so that we may receive mail. This thread exits after the mail address has been set. This thread uses closure of the registry hkey being monitored as a single to terminate. That way we don't need a separate event for that purpose. Arguments: Argument1 - Transport Instance Return Value: void __cdecl - --*/ { TRANSPORT_INSTANCE *pTransport = (PTRANSPORT_INSTANCE) Argument1; DWORD status, waitCode; HKEY hKey = NULL; HANDLE hRegChange = NULL; HANDLE rghWaitHandles[2]; BOOL fIsSmtpSvcPresentOldState, fIsSmtpSvcPresentNewState; DPRINT( 1, "SmtpRegistryNotifyThread is watching...\n" ); InterlockedIncrement( (PLONG) &(pTransport->ReferenceCount) ); // 1 for this thread __try { status = RegOpenKey(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", &hKey); if (status != ERROR_SUCCESS) { DPRINT1(0, "failed to open services key, error %d\n", status); LogUnhandledError(status); __leave; } hRegChange = CreateEvent(NULL, TRUE, FALSE, NULL); if (NULL == hRegChange) { status = GetLastError(); DPRINT1(0, "CreateEvent failed with %d\n", status); LogUnhandledError(status); __leave; } rghWaitHandles[0] = pTransport->hShutdownEvent; rghWaitHandles[1] = hRegChange; // Remember initial state fIsSmtpSvcPresentOldState = servicePresent("SmtpSvc"); // Verify the proper settings on startup every time addRemoveSmtpSvc( pTransport, fIsSmtpSvcPresentOldState ); // Wait in a loop watching for SmtpSvc either coming or going while (!pTransport->fShutdownInProgress) { // Register request for notification of registry change // This call does not wait. // Returns success on handle closure status = RegNotifyChangeKeyValue(hKey, TRUE, // bWatchSubkeys REG_NOTIFY_CHANGE_NAME, hRegChange, TRUE // fAsynchronous ); if (status != ERROR_SUCCESS) { DPRINT1( 0, "RegNotifyChangeValue returned %d\n", status ); LogUnhandledError( status ); __leave; } // Wait for shutdown or a change in the Services portion of the // registry. waitCode = WaitForMultipleObjects(ARRAY_SIZE(rghWaitHandles), rghWaitHandles, FALSE, INFINITE); switch (waitCode) { case WAIT_OBJECT_0: // Shutdown was signalled; bail. __leave; case WAIT_OBJECT_0 + 1: // Services registry change; loop back to the top. break; case WAIT_FAILED: default: // Unexpected error return; log and bail. status = GetLastError(); LogUnhandledError(waitCode); LogUnhandledError(status); __leave; } fIsSmtpSvcPresentNewState = servicePresent("SmtpSvc"); if (fIsSmtpSvcPresentOldState != fIsSmtpSvcPresentNewState) { addRemoveSmtpSvc( pTransport, fIsSmtpSvcPresentNewState ); fIsSmtpSvcPresentOldState = fIsSmtpSvcPresentNewState; } // If OldState != NewState } // while ! shutdown } __finally { DPRINT( 1, "SmtpRegistryNotifyThread exit\n" ); if (NULL != hRegChange) { CloseHandle(hRegChange); } if (NULL != hKey) { RegCloseKey(hKey); } InterlockedDecrement( (PLONG) &(pTransport->ReferenceCount) ); // 1 for this thread } if (pTransport->fShutdownInProgress) { // Normal thread termination. status = 0; } return status; } /* SmtpRegistryNotifyThread */ DWORD configureMailAddress( IN TRANSPORT_INSTANCE * pTransport ) /*++ Routine Description: This routine initializes the mail address for this server, and prepares the SMTP server to receive mail on this system. This routine does nothing if SMTP is not installed. This routine performs several functions: 1. Generates a mail address for this server and writes it to the mailAddress attribute if necessary 2. Initializes the transport mail address 3. Adds the Smtp mail routing domain for the guid-based name on this server 4. Register the event sink dll as a COM dll if necessary 5. Bind the event sink to SMTP/CDO The administrator is no longer required to manually assign a mail address for the server. This is created automatically based on the guid-based name of the server. Arguments: pTransport - The Smtp.pszSmtpAddress field in the transport is updated Return Value: DWORD - success if smtp not installed, otherwise hresult error if anything goes wrong --*/ { HRESULT hr; DWORD status; LPWSTR pszDomain, pszOfficialMailAddress = NULL; BOOL fIsGuidBasedName = FALSE; BOOL fMailAddressSyntaxIsBad = FALSE; LPWSTR pwzRule = NULL; BSTR bstrRule = NULL; Assert( NULL == pTransport->Smtp.pszSmtpAddress ); Assert( OWN_CRIT_SEC(pTransport->Lock) ); if (pTransport->fShutdownInProgress) { return ERROR_SHUTDOWN_IN_PROGRESS; } // SMTP must be installed (not nec. running) in order to set up if ( (!servicePresent("SmtpSvc")) || (!servicePresent("IisAdmin")) ) { DPRINT( 1, "Dependent services not present, SMTP not configured.\n" ); hr = S_OK; goto cleanup; } // SMTP administrative namespace must be available // If this fails, either IIS is disabled, or misconfigured // Warn the administrator infrequently if (FAILED(hr = CheckSmtpDomainContainerPresent())) { static DSTIME timeLastFailureLogged = 0; DSTIME timeCurrent = GetSecondsSince1601(); if ((timeCurrent < timeLastFailureLogged) || (timeCurrent > (timeLastFailureLogged + NO_SMTP_DOMAIN_INTERVAL))) { // Log event to alert admin that we have no domain. timeLastFailureLogged = timeCurrent; LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_NO_SMTP_DOMAIN, szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL, NULL ); } DPRINT1( 0, "Smtp Domain configuration not available, error 0x%x, SMTP not configured.\n", hr); hr = S_OK; goto cleanup; } // This check was needed before CDO was a regular part of the NT build. // CDOSYS.DLL sanity check. This dll should always be present if ( (!classPresent( &CLSID_Message )) || (!classPresent( &CLSID_Configuration )) || (!classPresent( &CLSID_DropDirectory )) ) { DPRINT(0,"One or more CDO classes not found - CDO not registered\n" ); hr = REGDB_E_CLASSNOTREG; LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_CDO_CLASS_MISSING, szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL, NULL ); goto cleanup; } // Calculate official mail address status = DirGetServerSmtpAttributes( pTransport, &pszOfficialMailAddress ); if (status != ERROR_SUCCESS) { // Error already logged DPRINT1( 0, "failed to get server mail address, error %d\n", status ); hr = HRESULT_FROM_WIN32( status ); goto cleanup; } // See if we have a mail address attribute already set status = DirReadServerSmtpAttributes( pTransport ); if (status != ERROR_SUCCESS) { // Error already logged DPRINT1( 0, "failed to read server mail address, error %d\n", status ); hr = HRESULT_FROM_WIN32( status ); goto cleanup; } // Check if it is a guid-based name and syntax is correct if (pTransport->Smtp.pszSmtpAddress) { #define UUID_STRING_LENGTH 36 LPWSTR p1, p2; DWORD length; WCHAR szServerUuid[UUID_STRING_LENGTH + 1]; UUID uuidServer; p1 = wcschr( pTransport->Smtp.pszSmtpAddress, L'@' ); if (p1) { p1++; p2 = wcschr( p1, L'.' ); if (p2) { length = (DWORD) (p2 - p1); } else { length = 0; } } else { fMailAddressSyntaxIsBad = TRUE; length = 0; } if (length == UUID_STRING_LENGTH) { // Note: wcsncpy does not null-terminate the string; we do it manually wcsncpy(szServerUuid, p1, length); szServerUuid[length] = L'\0'; status = UuidFromStringW(szServerUuid, &uuidServer); fIsGuidBasedName = (status == ERROR_SUCCESS); } // Check that addressee is correct if (!fMailAddressSyntaxIsBad) { fMailAddressSyntaxIsBad = (_wcsnicmp( pTransport->Smtp.pszSmtpAddress, USER_PREFIX, USER_PREFIX_LEN ) != 0 ); } } // If we don't, set one up // If we have an address, if it is guid-based, check that it is correct // Otherwise, leave the address alone. This allows a user-provided // mail address to override the official form. if ( (!pTransport->Smtp.pszSmtpAddress) || ( (fIsGuidBasedName || fMailAddressSyntaxIsBad) && (_wcsicmp( pTransport->Smtp.pszSmtpAddress, pszOfficialMailAddress ) != 0 ) ) ) { // This call writes the new address and makes it the default status = DirWriteServerSmtpAttributes( pTransport, pszOfficialMailAddress); if (status != ERROR_SUCCESS) { DPRINT1(0,"Failed to auto configure mail address, error %d\n", status ); // Error already logged hr = HRESULT_FROM_WIN32( status ); goto cleanup; } else if (!pTransport->Smtp.pszSmtpAddress) { status = ERROR_INCORRECT_ADDRESS; hr = HRESULT_FROM_WIN32( status ); goto cleanup; } else { DPRINT1( 1, "This server was assigned mail address %ws\n", pTransport->Smtp.pszSmtpAddress ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_MAIL_ADDRESS, szInsertWC(pTransport->Smtp.pszSmtpAddress ), NULL, NULL, NULL, NULL, NULL, NULL, NULL); } } // Make sure guid-based mail routing domain is known to SMTP pszDomain = wcschr( pTransport->Smtp.pszSmtpAddress, L'@' ); if (pszDomain == NULL) { DPRINT1( 0, "Smtp address %ws is malformed\n", pTransport->Smtp.pszSmtpAddress); hr = E_INVALIDARG; LogUnhandledError( hr ); goto cleanup; } pszDomain++; // skip separator hr = AddSmtpDomainIfNeeded( pszDomain, pTransport->Smtp.bstrDropDirectory ); if (FAILED(hr)) { DPRINT1( 0, "AddSmtpDomain failed with error 0x%x\n", hr ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_DOMAIN_ADD_FAILURE, szInsertWC(pszDomain), szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL ); goto cleanup; } // See if our event sink is already registered // Note that ismsink.dll has a registration dependency on seo.dll // This will only work if IIS is installed, which is implied by smtp check // TODO: how do we deregister when we demote? if (!classPresent( &CLSID_IsmSink1 )) { hr = registerInterfaceDll( "ismsink.dll", TRUE /* register */ ); if (FAILED(hr)) { DPRINT1( 0, "Failed to register ismsink.dll, error 0x%x\n", hr ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_SINK_REG_FAILURE, szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL, NULL ); goto cleanup; } else { DPRINT( 1, "Successfully registered COM server ismsink.dll.\n" ); } } // Create a filter rule to use with our binding // The rule is: // RCPT TO=_IsmService@guid-based-domain // This will fire for mail addressed to us, and returned mail from the postmaster. // It will not fire for mail being routed through this system destined // for other servers pwzRule = NEW_TYPE_ARRAY( (DWORD)(RCPT_TO_RULE_LEN + wcslen( pTransport->Smtp.pszSmtpAddress ) + 1), WCHAR ); if (pwzRule == NULL) { hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); LogUnhandledError( hr ); goto cleanup; } wcscpy( pwzRule, RCPT_TO_RULE ); wcscat( pwzRule, pTransport->Smtp.pszSmtpAddress ); bstrRule = SysAllocString( pwzRule ); if (bstrRule == NULL) { hr = E_OUTOFMEMORY; DPRINT( 0, "Failed to allocate from bstr\n" ); LogUnhandledError( hr ); goto cleanup; } // Bind our event sink to SMTPSVC, if necessary // We check this everytime we start in case IIS has been removed and re-added // TODO: When do we call unbind? hr = HrIsmSinkBinding( TRUE /* register */, bstrRule ); if (FAILED(hr)) { DPRINT1( 0, "Failed to bind event sink, error 0x%x\n", hr ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_SINK_BIND_FAILURE, szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL, NULL ); goto cleanup; } hr = S_OK; cleanup: if (pwzRule) { FREE_TYPE( pwzRule ); } if (bstrRule) { SysFreeString( bstrRule ); } if (pszOfficialMailAddress) { FREE_TYPE( pszOfficialMailAddress ); } if (FAILED(hr)) { if (NULL != pTransport->Smtp.pszSmtpAddress) { FREE_TYPE( pTransport->Smtp.pszSmtpAddress ); pTransport->Smtp.pszSmtpAddress = NULL; } } return hr; } /* configureMailAddress */ VOID removeMailAddress( IN TRANSPORT_INSTANCE * pTransport ) /*++ Routine Description: Undo the effects of configureMailAddress. Cleanup permanent changes to environment prior to service removal Environment: fShutdownInProgress is TRUE CDO Messages have been released COM is still running pTransport is largely intact At the time this is running, LDAP is not available. We do not try to remove the transport specific mail address. It is largely irrelevant now since if this server is being demoted, it will not have a NT-DSA object and will not be a subject for replication. Arguments: pTransport - Transport state object Return Value: None. --*/ { HRESULT hr; LPWSTR pszDomain, pszEnd; WIN32_FIND_DATAW FindFileData; HANDLE hFind; BOOL fMoreFound, fFilesRemaining; WCHAR szFileName[MAX_PATH]; // Remove the smtp domain (if configured) if (pTransport->Smtp.pszSmtpAddress) { pszDomain = wcschr( pTransport->Smtp.pszSmtpAddress, L'@' ); if (pszDomain == NULL) { DPRINT1( 0, "Smtp address %ws is malformed\n", pTransport->Smtp.pszSmtpAddress); hr = E_INVALIDARG; LogUnhandledError( hr ); } else { pszDomain++; // Skip @ hr = RemoveSmtpDomain( pszDomain ); if (FAILED(hr)) { DPRINT1( 0, "RemoveSmtpDomain failed with error 0x%x\n", hr ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_DOMAIN_REMOVE_FAILURE, szInsertWC(pszDomain), szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL ); // Keep going } else { DPRINT1(0, "Removed Smtp Domain %ls\n", pszDomain ); } } } // Remove any files in the Drop directory wcscpy( szFileName, pTransport->Smtp.bstrDropDirectory); pszEnd = szFileName + wcslen(pTransport->Smtp.bstrDropDirectory); *pszEnd++ = L'\\'; wcscpy( pszEnd, L"*" ); fFilesRemaining = FALSE; hFind = FindFirstFileW( szFileName, &FindFileData ); if (hFind != INVALID_HANDLE_VALUE) { fMoreFound = TRUE; while ( fMoreFound ) { if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { wcscpy( pszEnd, FindFileData.cFileName ); if (!DeleteFileW( szFileName )) { DPRINT1(0, "Failed to delete %ls\n", szFileName ); fFilesRemaining = TRUE; // We don't log this error } else { DPRINT1(1, "Deleted %ls\n", szFileName ); } } fMoreFound = FindNextFileW( hFind, &FindFileData ); } FindClose(hFind); } // Remove the drop directory itself // Don't even try if the directory is not empty if ( !fFilesRemaining ) { if (!RemoveDirectoryW(pTransport->Smtp.bstrDropDirectory)) { DPRINT1(0, "Failed to delete directory %ls\n", pTransport->Smtp.bstrDropDirectory); fFilesRemaining = TRUE; } else { DPRINT1(1, "Deleted %ls\n", pTransport->Smtp.bstrDropDirectory); } } if (fFilesRemaining) { LogEvent(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_DROP_DIR_NOT_REMOVED, szInsertWC(pTransport->Smtp.bstrDropDirectory), NULL, NULL ); } } /* removeMailAddress */ VOID disableMailAddress( IN TRANSPORT_INSTANCE * pTransport ) /*++ Routine Description: Reset our configuration when SMTP service has been removed We leave the drop directory in place since this is tied to our service, not SMTPSVC. The SMTP domain registration was lost when SMTPSVC was deinstalled, so we don't try to remove it here. We need to handle the following removal scenarios 1. We were configured, had a mail address attribute 2. We are not configured, no mail address attribute 3. We are not configured, lingering mail address attribute Removing the mail address attribute does not solve the problem. Without SMTP, there is no way for knowledge of the removal to replicate off the system. Arguments: pTransport - Return Value: None --*/ { // Mark ourselves as unconfigured so we will try again later if (NULL != pTransport->Smtp.pszSmtpAddress) { FREE_TYPE( pTransport->Smtp.pszSmtpAddress ); pTransport->Smtp.pszSmtpAddress = NULL; } // Warn the user once at removal time LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_NO_MAIL_ADDRESS, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); } /* disableMailAddress */ HRESULT getDropDirectoryPath( BSTR *pbstrDropDirectory ) /*++ Routine Description: Calculate the drop directory for the system and return it as a BSTR. The drop directory is recalculated each startup according to the base NTDS directories in the registry. Here is the algorithm: 1. If the MAILPATH_KEY is present, it's value is used as an override 2. Otherwise we start with the LOGPATH_KEY. We want the mail files to follow the ntds files so they all stay together. The reason the mail files follow the log and not the main database is that I figure they are both secondary, supporting files to the main database. Also, if the main database is getting full, we want these files to migrate away as well. 2a. Prepend "Drop" as the subdirectory Note that we expect these registry keys to only change between boots. You can currently only change these keys during directory safe mode. Arguments: pbstrDropDirectory - Return Value: HRESULT - --*/ { DWORD status; HRESULT hr, dwFileAttributes; WCHAR wzPath[MAX_PATH]; Assert( pbstrDropDirectory ); // Construct the drop directory path // It comes from the mail path key, or if not defined, from the concatenation // of the logging path and the name Drop if (GetConfigParamW( MAKE_WIDE(MAILPATH_KEY), wzPath, MAX_PATH)){ if (status = GetConfigParamW( MAKE_WIDE(LOGPATH_KEY), wzPath, MAX_PATH)){ DPRINT1( 0, "LOGPATH_KEY not present, error %d\n", status ); hr = HRESULT_FROM_WIN32( status ); goto cleanup; } wcscat( wzPath, L"\\" ); wcscat( wzPath, DROP_DIRECTORY ); } // Make sure it exists dwFileAttributes = GetFileAttributesW( wzPath ); if (dwFileAttributes == 0xffffffff) { status = GetLastError(); if ( (status == ERROR_FILE_NOT_FOUND) || (status == ERROR_PATH_NOT_FOUND) ) { if (!CreateDirectoryW( wzPath, NULL )) { status = GetLastError(); DPRINT2( 0, "CreateDirectory(%ws) failed, error %d\n", wzPath, status ); hr = HRESULT_FROM_WIN32( status ); goto cleanup; } LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_DROP_DIRECTORY, szInsertWC(wzPath), NULL, NULL, NULL, NULL, NULL, NULL, NULL); } else { status = GetLastError(); DPRINT2( 0, "GetFileAttributes(%ws) failed, error %d\n", wzPath, status ); hr = HRESULT_FROM_WIN32( status ); goto cleanup; } } else if ( (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 ) { DPRINT1( 0, "File %ws already exists, but is not a directory!\n", wzPath ); hr = HRESULT_FROM_WIN32( ERROR_FILE_EXISTS ); goto cleanup; } // Allocate a return string for it *pbstrDropDirectory = SysAllocString( wzPath ); if (*pbstrDropDirectory == NULL) { hr = E_OUTOFMEMORY; DPRINT( 0, "Failed to allocate from bstr\n" ); LogUnhandledError( hr ); goto cleanup; } DPRINT1( 1, "This server is using drop directory %ws\n", wzPath ); hr = S_OK; cleanup: return hr; } /* getDropDirectoryPath */ HRESULT SmtpInitialize( IN TRANSPORT_INSTANCE * pTransport ) /*++ Routine Description: Initialize the Smtp specific aspects of the transport. In this case, initialize COM so that we can use CDO V2 This is called by the Startup() entry point. If things are amiss, IsmServ will unload the dll and log a message. PERF: Create one long lived drop directory object for the life of the dll? Arguments: pTransport - Return Value: HRESULT - --*/ { HRESULT hr; BOOLEAN fComInit = FALSE; // NOTE: This code must return success when SMTP not installed // Initialize COM for multi-threaded application hr = CoInitializeEx( NULL, COINIT_MULTITHREADED ); if ( (hr != S_OK) && (hr != S_FALSE) ) { DPRINT1( 0, "CoInitializeEx failed with error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } fComInit = TRUE; // We no longer call configureMailAddress at this point because it takes // too long. It will be called the first time the Receive or Send entry // points are called. // Calculate the drop directory pTransport->Smtp.bstrDropDirectory = NULL; hr = getDropDirectoryPath( &(pTransport->Smtp.bstrDropDirectory) ); if (FAILED(hr)) { DPRINT1(0, "Failed to get drop directory, error 0x%x.\n", hr); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_DROP_DIR_MISSING, szInsertWin32Msg(hr), szInsertHResultCode(hr), NULL, NULL, NULL, NULL, NULL, NULL ); goto cleanup; } hr = S_OK; fComInit = FALSE; // Don't clean this up cleanup: if (fComInit) { CoUninitialize(); } return hr; } /* SmtpInitialize */ HRESULT SmtpTerminate( IN TRANSPORT_INSTANCE * pTransport, IN BOOL fRemoval ) /*++ Routine Description: Terminate the smtp transport functions Arguments: pTransport - Transport object fRemoval - Whether service is being removed Return Value: HRESULT - --*/ { DPRINT( 1, "Enter SmtpTerminate\n" ); if (NULL != pTransport->Smtp.pvCurrentCollection) { IMessages *pIMessages = (IMessages *)pTransport->Smtp.pvCurrentCollection; pIMessages->Release(); pTransport->Smtp.pvCurrentCollection = NULL; pTransport->Smtp.lCount = 0; } if (fRemoval) { DPRINT( 1, "Removal of ISMSERV/ISMSMTP requested.\n" ); removeMailAddress( pTransport ); } CoUninitialize(); (VOID) ListDestroyList( SmtpServiceDestruct, &(pTransport->ServiceListHead), &(pTransport->ServiceCount) ); if (NULL != pTransport->Smtp.pszSmtpAddress) { FREE_TYPE( pTransport->Smtp.pszSmtpAddress ); } if (pTransport->Smtp.bstrDropDirectory) { SysFreeString( pTransport->Smtp.bstrDropDirectory ); } if (pTransport->Smtp.pvGuidTable) { SmtpDestroyGuidTable( (PGUID_TABLE) pTransport->Smtp.pvGuidTable ); } MEMORY_CHECK_ALL(); DPRINT( 1, "Exit SmtpTerminate\n" ); return S_OK; } /* SmtpTerminate */ HRESULT attachMessageData( IN OUT CComPtr<IMessage> pIMsg, IN const ISM_MSG * pMsg ) /*++ Routine Description: Attach the ISM message data. Arguments: pIMsg - pMsg - Return Value: HRESULT - --*/ { HRESULT hr; CComPtr<_Stream> pStream; CComPtr<IBodyPart> pIBodyPart; VARIANT vBuffer; SAFEARRAY *psaData = NULL; // Allocate an array to describe the binary data hr = SafeArrayAllocDescriptor( 1, &psaData ); if FAILED(hr) { DPRINT1(0, "Unable to SafeArrayAllocDescriptor, error 0x%x.\n", hr); LogUnhandledError( hr ); goto exit; } // Initialize the array. We construct the array manually so we can use // our own data which has been already allocated. psaData->cbElements = sizeof( char ); psaData->pvData = pMsg->pbData; psaData->rgsabound[0].lLbound = 0; psaData->rgsabound[0].cElements = pMsg->cbData; // Set the body part options for binary data hr = pIMsg->get_BodyPart( &pIBodyPart ); if FAILED(hr) { DPRINT1(0, "Unable to get_BodyPart, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } hr = pIBodyPart->put_ContentTransferEncoding(cdoBase64); if FAILED(hr) { DPRINT1(0, "Unable to put_ContentTransferEncoding, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } hr = pIBodyPart->put_ContentMediaType(cdoGif); if FAILED(hr) { DPRINT1(0, "Unable to put_ContentMediaType, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } hr = pIBodyPart->GetDecodedContentStream(&pStream); if FAILED(hr) { DPRINT1(0, "Unable to GetDecodedContentStream, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } hr = pStream->put_Type(adTypeBinary); if FAILED(hr) { DPRINT1(0, "Unable to put_Type, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } // Write the binary data into the body VariantInit( &vBuffer ); vBuffer.vt = VT_ARRAY | VT_UI1; vBuffer.parray = psaData; hr = pStream->Write(vBuffer); if FAILED(hr) { DPRINT1(0, "Unable to WriteStream, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } hr = pStream->Flush(); if FAILED(hr) { DPRINT1(0, "Unable to Commit, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } exit: if (psaData != NULL) { HRESULT hr1; psaData->pvData = NULL; hr1 = SafeArrayDestroyDescriptor( psaData ); if (FAILED(hr1)) { DPRINT1(0, "Unable to SafeArrayDestroyDescriptor, error 0x%x.\n", hr); LogUnhandledError( hr1 ); } } if (pIBodyPart) { pIBodyPart = NULL; } if (pStream) { pStream = NULL; } return hr; } /* attachMessageData */ HRESULT getDropMessages( BSTR bstrDropDirectory, IDropDirectory **ppIDropDir, IMessages **ppIMessages, LONG *pCount ) /*++ Routine Description: Helper routine to initialize a drop directory object, get the message collection, and get the count of messages. Note, drop directory and message collection must be freed by the caller! Arguments: ppIDropDir - Returned pointer to drop directory object ppIMessages - Return pointer to message collection pCount - Returned count of messgaes Return Value: HRESULT - --*/ { HRESULT hr; Assert( ppIDropDir ); Assert( ppIMessages ); Assert( *ppIDropDir == NULL ); Assert( *ppIMessages == NULL ); // Create the drop directory object hr = CoCreateInstance(CLSID_DropDirectory, NULL, CLSCTX_INPROC_SERVER, IID_IDropDirectory, (void**) ppIDropDir); if (FAILED(hr)) { DPRINT1(0, "CoCreateInstance(DropDirectory) failed, error 0x%x\n", hr); DPRINT(0, "Check that CDOSYS.DLL is registered via regsvc32\n" ); LogCdoError( hr ); goto cleanup; } // Get the object representing the list of all messages hr = (*ppIDropDir)->GetMessages(bstrDropDirectory, ppIMessages); if (FAILED(hr)) { DPRINT1(0, "getMessages() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } // Get count of messages *pCount = 0; hr = (*ppIMessages)->get_Count( pCount ); if (FAILED(hr)) { DPRINT1(0, "get_Count() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } DPRINT2( 1, "Found %d messages in the drop directory %ws\n", *pCount, bstrDropDirectory ? bstrDropDirectory : L"default" ); return S_OK; cleanup: if (*ppIMessages) { (*ppIMessages)->Release(); *ppIMessages = NULL; } if (*ppIDropDir) { (*ppIDropDir)->Release(); *ppIDropDir = NULL; } return hr; } /* getDropMessages */ DWORD SmtpSend( IN TRANSPORT_INSTANCE * pTransport, IN LPCWSTR pszRemoteTransportAddress, IN LPCWSTR pszServiceName, IN const ISM_MSG * pMsg ) /*++ Routine Description: Send a message using the smtp transport. Message is sent as a binary blob. Our approach is to keep the dll running even when the smtp service is not running. The dll can operate without the smtp service running since the CDO library only uses the file system for communication. We check for valid conditions when the ism server tries to use the dll for sending or receiving. CDO provides three ways to send a message: 1. Send by pickup directory. That is the default and what we are doing. The mail is actually "relayed", in the sense that it is received by here, queued, and sent to the destination when possible. Triggers OnArrival routine as a mail receiption on localhost as well as ultimate destination host. Benefit: if the destination is down, it will resend. 2. Send to local host and port. Same as #1. The mail is received, queued, and sent on when possible. 3. Send to destination host, using port number. The destination must be up. OnArrival routine on triggered on destination. No queuing on localhost. Arguments: pTransport - pszRemoteTransportAddress - pszServiceName - pMsg - Return Value: DWORD - --*/ { DWORD status; HRESULT hr; LPWSTR pszSubject, pszMessageSubject, pszServer; DWORD cchSubject; CComPtr<IMessage> pIMsg; BSTR bstrFrom = NULL, bstrTo = NULL, bstrSubj = NULL; if ( (!pTransport) || (!pszRemoteTransportAddress) || (!pszServiceName) || (!pMsg) ) { status = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); LogUnhandledError( status ); return status; } DPRINT4( 1, "SmtpSend, addr = %ws, serv = %ws, subj = %ws, size = %d\n", pszRemoteTransportAddress, pszServiceName, pMsg->pszSubject, pMsg->cbData ); MEMORY_CHECK_ALL(); // If we don't have a mail address, try to auto configure // A mailAddress attribute has to have been written in order for the KCC // to have created a mail-based replica. EnterCriticalSection( &(pTransport->Lock) ); __try { if ( NULL == pTransport->Smtp.pszSmtpAddress ) { hr = configureMailAddress( pTransport ); } else { hr = S_OK; } } __finally { LeaveCriticalSection( &(pTransport->Lock) ); } if ( ( hr == S_OK ) && ( NULL == pTransport->Smtp.pszSmtpAddress ) ) { // SMTP not installed hr = HRESULT_FROM_WIN32( ERROR_SERVICE_DOES_NOT_EXIST ); } if (FAILED(hr)) { static DSTIME timeLastNoSmtpLogged = 0; DSTIME timeCurrent = GetSecondsSince1601(); if ((timeCurrent < timeLastNoSmtpLogged) || (timeCurrent > (timeLastNoSmtpLogged + NO_SMTP_DOMAIN_INTERVAL))) { // Log event to alert admin we have no SMTP transport timeLastNoSmtpLogged = timeCurrent; DPRINT( 0, "Cannot send: SMTP transport not installed.\n" ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_NO_MAIL_ADDRESS, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); } return hr; } // CDO does not depend on any services to queue the message. // Some service needs to be running in order for the messages to get off // the machine. // That service could be SmtpSvc or Exchange //*************************************************************************** // Create an instance of the message object hr = CoCreateInstance(CLSID_Message, NULL, CLSCTX_INPROC_SERVER, IID_IMessage, (void**) &pIMsg); if FAILED(hr) { DPRINT1(0, "Unable to create CLSID_Message object, error 0x%x.\n", hr); DPRINT(0, "Check that CDOSYS.DLL is registered via regsvc32\n" ); LogCdoError( hr ); goto exit; } Assert( pTransport->Smtp.pszSmtpAddress ); // Set the 'From' property. bstrFrom = SysAllocString( pTransport->Smtp.pszSmtpAddress ); if (bstrFrom == NULL) { hr = E_OUTOFMEMORY; DPRINT( 0, "Failed to allocate from bstr\n" ); LogUnhandledError( hr ); goto exit; } hr = pIMsg->put_From( bstrFrom ); if FAILED(hr) { DPRINT1(0, "Unable to put_From, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } // Determine the server to send to pszServer = wcschr( pszRemoteTransportAddress, L'@' ); if (pszServer == NULL) { DPRINT1( 0, "Remote transport address %ws is malformed\n", pszRemoteTransportAddress); hr = E_INVALIDARG; LogUnhandledError( hr ); goto exit; } pszServer++; // Skip separator // Set the 'To' property. bstrTo = SysAllocString( pszRemoteTransportAddress ); if (bstrTo == NULL) { hr = E_OUTOFMEMORY; DPRINT( 0, "Failed to allocate to bstr\n" ); LogUnhandledError( hr ); goto exit; } hr = pIMsg->put_To( bstrTo ); if FAILED(hr) { DPRINT1(0, "Unable to put_To, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } // This field may be null pszMessageSubject = pMsg->pszSubject ? pMsg->pszSubject : L""; // Set the 'Subject' property. cchSubject = gcchSubjectFormat + wcslen(pszServiceName) + wcslen( pszMessageSubject ); __try { pszSubject = (LPWSTR) alloca(cchSubject * sizeof(*pszSubject)); } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_OUTOFMEMORY; goto exit; } swprintf(pszSubject, gszSubjectFormat, pszServiceName, pszMessageSubject); bstrSubj = SysAllocString( pszSubject ); if (bstrSubj == NULL) { hr = E_OUTOFMEMORY; DPRINT( 0, "Failed to allocate subj bstr\n" ); LogUnhandledError( hr ); goto exit; } hr = pIMsg->put_Subject( bstrSubj ); if FAILED(hr) { DPRINT1(0, "Unable to put_Subject, error 0x%x.\n", hr); LogCdoError( hr ); goto exit; } // Attach the data hr = attachMessageData( pIMsg, pMsg ); if (FAILED(hr)) { DPRINT1(0, "Unable to attach message data, error 0x%x.\n", hr); // Event already logged at lower layer goto exit; } hr = supersedeMessage( pTransport, pszRemoteTransportAddress, pszServiceName, pszMessageSubject, pIMsg ); if (FAILED(hr)) { DPRINT1(0, "Unable to supersede message, error 0x%x.\n", hr); // Keep going, not fatal } //*************************************************************************** // Serialize access to queue directory, by this dll anyway EnterCriticalSection(&QueueDirectoryLock); __try { // queue the message locally hr = pIMsg->Send(); } __finally { LeaveCriticalSection(&QueueDirectoryLock); } if (FAILED(hr)) { DPRINT1(0, "Unable to Send(), error 0x%x.\n", hr); // Error will be logged at a higher level goto exit; } exit: if (bstrFrom) { SysFreeString( bstrFrom ); } if (bstrTo) { SysFreeString( bstrTo ); } if (bstrSubj) { SysFreeString( bstrSubj ); } MEMORY_CHECK_ALL(); // IsmServ will log the send failure if (pIMsg) { pIMsg = NULL; } return hr; } /* SmtpSend */ HRESULT getIsmMsgFromAttachment( CComPtr<IMessage> pIMsg, OUT ISM_MSG ** ppMsg, LPWSTR pszMessageSubject ) /*++ Routine Description: Read the contents of a message. The message is read into the message descriptor Arguments: pIMsg - CDO message object ppMsg - New message descriptor allocated to repesent the decoded message Return Value: HRESULT - --*/ { HRESULT hr; CComPtr<IBodyPart> pIBodyPart; CComPtr<_Stream> pStream; VARIANT vBuffer; SAFEARRAY *psaData; ULONG cbData, cbDataAligned, len, subjectLength; BYTE *ptr; int i = 0; if (!pszMessageSubject) { hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); LogUnhandledError( hr ); return hr; } DPRINT1( 4, "getIsmMsgFromAttachment, subj=%ws\n", pszMessageSubject ); VariantInit( &vBuffer ); hr = pIMsg->get_BodyPart( &pIBodyPart ); if (FAILED(hr)) { DPRINT1(0, "get_BodyPart() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } hr = pIBodyPart->GetDecodedContentStream(&pStream); if (FAILED(hr)) { DPRINT1(0, "get_GetDecodedContentStream() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } hr = pStream->Read(adReadAll, &vBuffer); if (FAILED(hr)) { DPRINT1(0, "Read() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } if (vBuffer.vt != (VT_ARRAY | VT_UI1)) { hr = E_INVALIDARG; DPRINT1(0, "ismsmtp, Body part type %d was not expected!\n", vBuffer.vt ); LogUnhandledError( hr ); goto cleanup; } psaData = vBuffer.parray; cbData = psaData->rgsabound[0].cElements; cbDataAligned = ROUND_UP_COUNT( cbData, ALIGN_WCHAR ); subjectLength = wcslen( pszMessageSubject ); // wlees Sep 1, 1998. Getting mysterious AVs while freeing messages. Switch // to simpler buffer management until we can track this down #ifdef NO_COPY // Minimize the number of data copies by extracting the binary data right out // of the returned safe array. We free the array descriptor manually. Later, // when we free the message, we use the right OLE api to free the data // Allocate an ISM_MSG to hold the data *ppMsg = NEW_TYPE( ISM_MSG ); if (NULL == *ppMsg) { hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); goto cleanup; } // Steal the data chuck out of the safe array. (*ppMsg)->cbData = cbData; (*ppMsg)->pbData = (BYTE *) psaData->pvData; // Free the descriptor manually. psaData->rgsabound[0].cElements = 0; psaData->pvData = NULL; hr = SafeArrayDestroyDescriptor( psaData ); if (FAILED(hr)) { DPRINT1(0, "SafeArrayDestroyDescriptor() failed, error 0x%x\n", hr); // keep going } // No need to free this now vBuffer.vt = VT_EMPTY; vBuffer.parray = NULL; // Allocate a subject (*ppMsg)->pszSubject = NEW_TYPE_ARRAY( subjectLength + 1, WCHAR ); wcscpy( (*ppMsg)->pszSubject, pszMessageSubject ); #else // Allocate a buffer for the ISM_MSG, the data, and the subject string len = sizeof( ISM_MSG ) + cbDataAligned + (subjectLength + 1) * sizeof( WCHAR ); *ppMsg = (ISM_MSG *) NEW_TYPE_ARRAY( len, CHAR ); if (NULL == *ppMsg) { hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); LogUnhandledError( hr ); goto cleanup; } (*ppMsg)->cbData = cbData; ptr = (BYTE *) &( (*ppMsg)[1] ); // point past struct (*ppMsg)->pbData = ptr; // PERF: this is a data copy memcpy( ptr, psaData->pvData, cbData ); ptr += cbDataAligned; Assert( POINTER_IS_ALIGNED( ptr, ALIGN_WCHAR ) ); (*ppMsg)->pszSubject = (LPWSTR) ptr; wcscpy( (*ppMsg)->pszSubject, pszMessageSubject ); #endif hr = NOERROR; cleanup: if (pIBodyPart) { pIBodyPart = NULL; } if (pStream) { pStream = NULL; } if (vBuffer.vt != VT_EMPTY) { VariantClear( &vBuffer ); } if FAILED(hr) { Assert(NULL == *ppMsg); } else { Assert(NULL != *ppMsg); } if (FAILED(hr)) { DPRINT1( 0, "NTDS ISM SMTP failed to read a message stream, error 0x%x\n", hr ); } return hr; } /* getIsmMsgFromAttachment */ VOID SmtpFreeMessage( IN ISM_MSG *pMsg ) /*++ Routine Description: Free the message alllocated by SmtpReceive. This routine has the actual knowledge of how the data should be deallocated. Arguments: pMsg - ism message descriptor Return Value: None --*/ { HRESULT hr; SAFEARRAY saData; Assert( pMsg ); Assert( pMsg->pbData ); DPRINT1( 3, "SmtpFreeMessage, size = %d\n", pMsg->cbData ); #ifdef NO_COPY // Whip up a phony safe array descriptor to describe the data // Try to use it to deallocate the data // Hope that this descriptor is close enough to the one originally // allocated. Note if we have problems, we may need to see what the // "features" field had at time of allocation, and set accordingly. ZeroMemory( &saData, sizeof( SAFEARRAY ) ); saData.cDims = 1; saData.cbElements = sizeof( char ); saData.pvData = pMsg->pbData; saData.rgsabound[0].lLbound = 0; saData.rgsabound[0].cElements = pMsg->cbData; hr = SafeArrayDestroyData( &saData ); if (FAILED(hr)) { DPRINT1( 0, "SafeArrayDestroyData failed with error 0x%x\n", hr ); } if (pMsg->pszSubject) { FREE_TYPE( pMsg->pszSubject ); } #else // In this mode, data allocated with the msg descriptor #endif pMsg->cbData = 0; pMsg->pbData = NULL; FREE_TYPE( pMsg ); } /* SmtpFreeMessage */ BOOL messageIsDuplicate( PGUID_TABLE pGuidTable, BSTR bstrFrom, BSTR bstrSubject, IMessage *pIMsg ) /*++ Routine Description: We can take advantage of the fact that all messages have a message guid, and that retried messages have a supersedes guid. As we receive messages, we record the message guid in a guid table. The guid table is only for the current drop directory. If the message we receive has a supersedes guid, we check to see if that superseded guid is in the table. If so, then we have recently seen the predecessor of the current message, and we do not have to process the current message. The reason that we only consider messages in the current drop directory to be candidates for recently seen messages is that mail delivery is unreliable. The fact that we have seen a request mail doesn't mean the reply was delivered. The requestor may send us the same request again for legitimate reasons and we don't want to drop it on the floor. The current drop directory becomes a kind of simple grouping mechanism: all messages in the same drop directory instance we received together in time and can be treated as equivalent. Arguments: pGuidTable - Table of guid's recently seen bstrFrom - From field from message bstrSubject - Subject field from message pIMsg - Current message object Return Value: BOOL - --*/ { HRESULT hr; BOOL fResult = FALSE; // say no if not sure CComPtr<Fields> pFields; GUID guidMessage, guidSupersedes; hr = pIMsg->get_Fields(&pFields); if (FAILED(hr)) { DPRINT1( 0, "failed to get_Fields, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // Record that we have seen this message // Note that we record the message as seen regardless of whether we later // decide to discard it as a duplicate. This is because of the transitive // nature of the supersedes guid: // message A // message B, supersedes A // message C, supersedes B // A is accepted, B is a duplicate of A, and in order to suppress C, // we must note B as seen, which it was transitively. hr = getFieldGuid( pFields, SMTP_MSG_GUID, &guidMessage ); if (FAILED(hr)) { DPRINT1( 0, "failed to guid field guid, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // If the message has a guid if (memcmp( &guidMessage, &zeroGuid, sizeof(GUID) ) != 0) { // Insert in table of guids that have been seen #if DBG LPWSTR pszUuid; UuidToStringW( &guidMessage, &pszUuid ); DPRINT1( 4, "Message contains messageGuid %ws\n", pszUuid ); RpcStringFreeW( &pszUuid ); #endif if (!SmtpGuidInsertInTable( pGuidTable, &guidMessage )) { DPRINT( 0, "Failed to insert msg guid into table\n" ); // Keep going } } else { DPRINT2( 0, "Warning: Message from %ws, subject %ws lacks a message guid.\n", bstrFrom, bstrSubject ); } // See if there is a supersedes guid in the message hr = getFieldGuid( pFields, SMTP_SUPERSEDES_MSG_GUID, &guidSupersedes ); if (FAILED(hr)) { DPRINT1( 0, "failed to guid field guid, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } if (memcmp( &guidSupersedes, &zeroGuid, sizeof(GUID) ) != 0) { // See if we've seen the prior message #if DBG LPWSTR pszUuid; UuidToStringW( &guidSupersedes, &pszUuid ); DPRINT1( 4, "Message contains supersedesGuid %ws\n", pszUuid ); RpcStringFreeW( &pszUuid ); #endif if (SmtpGuidPresentInTable( pGuidTable, &guidSupersedes )) { // It is a duplicate of a message we have seen recently fResult = TRUE; goto cleanup; } } cleanup: if (pFields) { pFields = NULL; } return fResult; } /* messageIsDuplicate */ HRESULT parseDeliveryStatus( CComPtr<IBodyPart> pBodyPart, LPWSTR pszExpectedContentType, BSTR *pbstrText ) /*++ Routine Description: This is a helper routine to parse the delivery status section of a delivery status report. Arguments: pBodyPart - pszExpectedContentType - pbstrText - Return Value: HRESULT - --*/ { HRESULT hr; BSTR bstrContentType = NULL; CComPtr<_Stream> pStream; StreamTypeEnum streamType; DWORD length; BSTR bstrCharset = NULL; hr = pBodyPart->get_ContentMediaType(&bstrContentType); if (FAILED(hr)) { DPRINT1( 0, "Failed to get_ContentMediaType, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } if (_wcsicmp( bstrContentType, pszExpectedContentType ) != 0) { hr = E_INVALIDARG; DPRINT2( 0, "DSN does not have expected content type, expected = %ws, actual = %ws\n", pszExpectedContentType, bstrContentType ); // Do not log goto cleanup; } // Get the content stream hr = pBodyPart->GetDecodedContentStream(&pStream); if (FAILED(hr)) { DPRINT1(0, "get_GetDecodedContentStream() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } // Check the stream type hr = pStream->get_Type( &streamType ); if (FAILED(hr)) { DPRINT1(0, "get_Type() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } if (streamType != adTypeText) { hr = E_INVALIDARG; DPRINT1(0, "ismsmtp, ndr, Stream type %d was not expected!\n", streamType ); LogCdoError( hr ); goto cleanup; } // Check the character set. Adjust if not correct. // This works around a problem where body parts are incorrectly marked // with the wrong character set. hr = pStream->get_Charset( &bstrCharset ); if (FAILED(hr)) { DPRINT1(0, "get_Charset() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } if (_wcsicmp( bstrCharset, cdoISO_8859_1 ) != 0) { SysFreeString(bstrCharset); bstrCharset = SysAllocString( cdoISO_8859_1 ); if (bstrCharset == NULL) { hr = E_OUTOFMEMORY; DPRINT( 0, "Failed to allocate from bstr\n" ); LogUnhandledError( hr ); goto cleanup; } hr = pStream->put_Charset( bstrCharset ); if (FAILED(hr)) { DPRINT1(0, "set_Charset() failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } } // Read it into a bstr hr = pStream->ReadText( adReadAll, pbstrText ); if (FAILED(hr)) { DPRINT1(0, "ReadText(All) failed, error 0x%x\n", hr); LogCdoError( hr ); goto cleanup; } hr = S_OK; cleanup: if (bstrCharset) { SysFreeString(bstrCharset); } if (bstrContentType) { SysFreeString(bstrContentType); } if (pStream) { pStream = NULL; } return hr; } /* parseDeliveryStatus */ HRESULT parseNondeliveryReport( BSTR bstrSubject, CComPtr<IMessage> pIMsg ) /*++ Routine Description: Decode a Nondelivery report. It is encoded as a hierarchy of body parts: root body part body part 1 - plain text, the session transcript body part 2 - message/delivery-status ... n-1 body part n - message/rfc822, the original message Warning, this may change in the future. To accomodate this, we don't log when we encounter unexpected syntax. We simply stop parsing. The caller won't delete the report and the user can dispose of it himself. Note that we do log function errors, since they should not happen. We are only interested in the first and second parts Arguments: pIMsg - Return Value: HRESULT - --*/ { #define CDO_CONTENT_TYPE_MULTIPART_REPORT L"multipart/report" #define CDO_CONTENT_TYPE_DELIVERY_STATUS L"message/delivery-status" DWORD win32Status; HRESULT hr; LONG count, i; CComPtr<IBodyPart> pRootBodyPart; CComPtr<IBodyParts> pBodyParts; BSTR bstrContentType = NULL; CComPtr<IBodyPart> pBodyPart; BSTR bstrText = NULL; LPWSTR pwzErrorString; // Get the root body part hr = pIMsg->get_BodyPart(&pRootBodyPart); if (FAILED(hr)) { DPRINT1( 0, "Failed to get root body part, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // Get content type of whole message hr = pRootBodyPart->get_ContentMediaType(&bstrContentType); if (FAILED(hr)) { DPRINT1( 0, "Failed to get_ContentMediaType, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // It better be a multi-part report if (_wcsicmp( bstrContentType, CDO_CONTENT_TYPE_MULTIPART_REPORT ) != 0) { hr = E_INVALIDARG; DPRINT2( 0, "DSN does not have expected content type, expected = %ws, actual = %ws\n", CDO_CONTENT_TYPE_MULTIPART_REPORT, bstrContentType ); // Do not log goto cleanup; } // Get the collection of 1st level body parts hr = pRootBodyPart->get_BodyParts(&pBodyParts); if (FAILED(hr)) { DPRINT1( 0, "Failed to get_BodyParts, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // See how many there are hr = pBodyParts->get_Count(&count); if (FAILED(hr)) { DPRINT1( 0, "Failed to get_Count, error 0x%x\n", hr ); LogCdoError( hr ); goto cleanup; } // Should be atleast one if (count < 3) { hr = E_INVALIDARG; DPRINT( 0, "Malformed DSN doesn't have enough parts!\n" ); // Do not log goto cleanup; } //DPRINT1( 0, "NDR has %d body parts\n", count ); // *********************************************************************** DPRINT1( 1, "ISM SMTP %ws:\n", bstrSubject ); // Skip the first and the last count--; for( i = 2; i <= count; i++ ) { pBodyPart = NULL; bstrText = NULL; hr = pBodyParts->get_Item(i,&pBodyPart); if (FAILED(hr)) { DPRINT1( 0, "Failed to get_Item, error 0x%x\n", hr ); LogCdoError( hr ); goto loop_cleanup; } hr = parseDeliveryStatus( pBodyPart, (i == 1) ? cdoTextPlain : CDO_CONTENT_TYPE_DELIVERY_STATUS, &bstrText ); if (FAILED(hr)) { DPRINT1( 0, "parseDeliveryStatus failed, error 0x%x\n", hr ); // don't log goto loop_cleanup; } // This string is static and doesn't need to be freed pwzErrorString = parseStatus( bstrText, &win32Status ); DPRINT4( 1, "\t(%d): Status: 0x%x - %ws\nText: %ws\n", i, win32Status, pwzErrorString, bstrText ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_DSN, szInsertWin32Msg(win32Status), szInsertWC(pwzErrorString), szInsertWC(bstrText), szInsertWin32ErrCode(win32Status), NULL, NULL, NULL, NULL ); loop_cleanup: pBodyPart = NULL; if(bstrText) { SysFreeString(bstrText); } } hr = S_OK; cleanup: if(bstrContentType) { SysFreeString(bstrContentType); } pBodyParts = NULL; pRootBodyPart = NULL; return hr; } /* parseNondeliveryReport */ HRESULT scanMessages( IN TRANSPORT_INSTANCE *pTransport, IN IMessages *pIMessages, IN LPCWSTR pszServiceName, IN OUT LONG *plCount, IN OUT PGUID_TABLE pGuidTable, OUT ISM_MSG **ppMsg ) /*++ Routine Description: Enumerate the messages in the drop directory. Return the first one. Duplicates are eliminated as they are encountered in the drop directory. If we encounter any nondelivery reports for ISM messages, we log and delete. We loop through the messages in the drop directory. We read the first message each time. At the end of the loop we delete the first message, making the next one the first. If we can dispose of the message in the loop because it is a notification or a duplicate, we do so. On the first valid message, we break out of the loop and return. If we can't read a message, we log an event and delete it. There is no notion of skipped messages. We don't track unreadable messages still in the collection. Our current reading position is always at the start and we expect we can delete each message as we go. There are no errors returned out of this routine. We always delete the message or return it. When we exit the routine there are no messages left, or we are returning a valid message. Arguments: pTransport - Transport object pIMessages - Collection of messages pszServiceName - Name of server we are looking for plCount - Pointer to count of how many left to read. This is updated as we read each so we don't read them again next time pGuidTable - pointer to guid table to track duplicates ppMsg - Pointer to receive a message Return Value: HRESULT - --*/ { HRESULT hr, hr1; CComPtr<IMessage> pIMsg; BSTR bstrSubject, bstrTo, bstrFrom; LPWSTR pszMsgForServiceName, pszMessageSubject; BOOL done, exitScan; DPRINT1( 2, "scanning message collection entry, %d unread\n", *plCount ); Assert( pIMessages ); Assert( plCount ); Assert( *plCount >= 1 ); Assert( ppMsg ); Assert( *ppMsg == NULL ); // Initial conditions: not done, not busy and atleast one message // Note the structure of this loop. We have to go through the next_ // message processing at the bottom to free the resources. The only way // out is through the for test at the bottom of the loop. done = exitScan = FALSE; do { DWORD busyTries = 0, waitCode; bstrSubject = bstrTo = bstrFrom = NULL; // We always read the first message // Each time we delete message 1, moving the rest up // If shutdown detected exit immediately if (pTransport->fShutdownInProgress) { DPRINT(2, "Message was skipped due to shutdown\n"); hr = S_OK; exitScan = TRUE; goto next_message; } // NOTE: Busy retry loop could be avoided with an improved ismsink.dll // paragdigm -- see bug 88430: ISM SMTP sink should pre-process received // messages. // Read a message with retry // Deal with contention with writer process. This is a fact of life since // we will try to read a new file as soon as it appears in the directory. while (1) { hr = pIMessages->get_Item(1,&pIMsg); if (FAILED(hr)) { DPRINT1(0, "get_Item(1) failed, error 0x%x\n", hr); LogCdoError( hr ); goto next_message; } // This is the first field we read from the message. If something is going // to fail, this is where it happens hr = pIMsg->get_To( &bstrTo ); // Workaround. It appears that CDO will succeed with an empty value // when there is a sharing violation. However, it is also possible that // the message simply does not have a To field. We have no way of // distinguishing these two cases. if ( (SUCCEEDED(hr)) && ((bstrTo == NULL) || (wcslen(bstrTo) == 0)) ) { DPRINT( 1, "get_To returned empty string, treating as busy.\n" ); hr = HR_SHARING_VIOLATION; } if ( (hr != HR_SHARING_VIOLATION) || (busyTries > 4) || (pTransport->fShutdownInProgress) ) { break; } busyTries++; DPRINT1( 1, "get_To returned busy, try %d\n", busyTries ); pIMsg = NULL; // Cleanup old instance // Sleep while watching for shutdown waitCode = WaitForSingleObject( pTransport->hShutdownEvent, 15 * 1000 ); if (waitCode == WAIT_OBJECT_0) { // Shutdown detected. exitScan = TRUE; break; } } if (FAILED(hr)) { if (hr == HRESULT_FROM_WIN32( ERROR_SHARING_VIOLATION )) { // We failed to read the To field, either due to a sharing violation // or due to non-existence of a To field. We will try to delete this // message below. If the message really was busy then the delete // should fail (although admittedly this is a race condition). If the // message did not have a To field then it is invalid and should be deleted. DPRINT(2, "Message was skipped due to a sharing violation or no To field\n"); hr = S_OK; } else { DPRINT1(0, "get_To() failed, error 0x%x\n", hr); LogCdoError( hr ); } goto next_message; } if ( (bstrTo == NULL) || (wcslen( bstrTo ) == 0) ) { DPRINT( 0, "To: field in Ism Message is empty\n" ); hr = HR_INVALID_DATA; goto next_message; } hr = pIMsg->get_Subject( &bstrSubject ); if (FAILED(hr)) { DPRINT1(0, "get_Subject() failed, error 0x%x\n", hr); LogCdoError( hr ); goto next_message; } if ( (bstrSubject == NULL) || (wcslen( bstrSubject ) == 0) ) { DPRINT( 0, "Subj: field in Ism Message is empty\n" ); hr = HR_INVALID_DATA; goto next_message; } hr = pIMsg->get_From( &bstrFrom ); if (FAILED(hr)) { DPRINT1(0, "get_From() failed, error 0x%x\n", hr); LogCdoError( hr ); goto next_message; } if ( (bstrFrom == NULL) || (wcslen( bstrFrom ) == 0) ) { DPRINT( 0, "From: field in Ism Message is empty\n" ); hr = HR_INVALID_DATA; goto next_message; } // See if the message is addressed to us if (!mailAddressMatch( bstrTo, pTransport->Smtp.pszSmtpAddress )) { DPRINT1( 0, "Ism Message not addressed to this DSA: %ws\n", bstrTo ); // We wouldn't be finding the message unless the @domain portion of // the address matches. Mail being sent to the wrong user? hr = HR_INVALID_DATA; goto next_message; } // Sanity check subject for basic syntax if (_wcsnicmp(bstrSubject, SUBJECT_PREFIX, SUBJECT_PREFIX_LEN) != 0) { // Check for delivery status report hr = parseNondeliveryReport( bstrSubject, pIMsg ); if (SUCCEEDED(hr)) { goto next_message; } // Not an ISM message. DPRINT3(0, "IsmSmtp: Ignoring non-ISM message to %ws from %ws with subject \"%ls\".\n", bstrTo, bstrFrom, bstrSubject); hr = HR_INVALID_DATA; goto next_message; } // Check if message is a recently seen duplicate if (messageIsDuplicate( pGuidTable, bstrFrom, bstrSubject, pIMsg)) { DPRINT2( 1, "Duplicate message suppressed: From: \"%ws\", Subject: \"%ws\"\n", bstrFrom, bstrSubject ); // Note that we can get into a tight loop identifying and // deleting duplicates if there are many of them. This will be // true if the machine has been down or the ismserv had been // stopped. We will detect shutdown above. Do we need to return // the thread to the ismserv after every x messages so we don't // hog the thread? goto next_message; } // Looks like an ISM message. pszMsgForServiceName = bstrSubject + SUBJECT_PREFIX_LEN; pszMessageSubject = wcsstr( pszMsgForServiceName, SUBJECT_SEPARATOR ); if (!pszMessageSubject) { // malformed subject line DPRINT1( 0, "Ism message subject line is malformed: %ws\n", pszMsgForServiceName ); hr = HR_INVALID_DATA; goto next_message; } *pszMessageSubject = L'\0'; pszMessageSubject += SUBJECT_SEPARATOR_LEN; // Skip over DPRINT2(3, "Message appears to be for service \"%ls\", from %ws.\n", pszMsgForServiceName, bstrFrom); // It is implicit in the design of this message loop that there is only // one type of service per drop directory. This is fine in product 1 // where the only client of ISM SMTP is NTDS Replication. In the future we // will need to have child drop directories, one per service. This is not // hard: the sink needs to save the incoming message in the right child. // That means we don't need a private domain either. if (_wcsicmp(pszServiceName, pszMsgForServiceName)) { // Not for us DPRINT1( 0, "Ism message is in wrong drop directory, claiming to be for service %ws\n", pszMsgForServiceName ); hr = HR_INVALID_DATA; goto next_message; } hr = getIsmMsgFromAttachment( pIMsg, ppMsg, pszMessageSubject ); if (FAILED(hr)) { DPRINT1( 0, "Failed to decode message, error 0x%x\n", hr ); goto next_message; } Assert( *ppMsg ); DPRINT3( 1, "SmtpReceive, from %ws, subj %ws, size %d bytes.\n", pszServiceName, (*ppMsg)->pszSubject, (*ppMsg)->cbData ); done = TRUE; next_message: // Log an event on failure to read a message // Note, pIMsg may be NULL at this point // The insert params are in this order for compat with prev releases if (FAILED(hr)) { LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_MSG_UNREADABLE, szInsertUL(1), szInsertWC( pTransport->Smtp.bstrDropDirectory ), szInsertWin32Msg(hr), szInsertHResultCode(hr), szInsertWC( bstrTo ), szInsertWC( bstrFrom ), szInsertWC( bstrSubject ), NULL ); } if( ! exitScan ) { // Try to remove a message we read. If we fail, abort the message scan. hr1 = pIMessages->Delete( 1 ); if (SUCCEEDED(hr1)) { (*plCount)--; } else { // Note we can be in the strange position of having a valid message // but not being able to delete it. We don't want to return a // message we can't delete, since we will read it again, causing // duplicates. DPRINT1(0, "Delete() failed, error 0x%x\n", hr1); if (hr1 != HRESULT_FROM_WIN32( ERROR_SHARING_VIOLATION )) { LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_MSG_DELETE_FAILURE, szInsertUL(1), szInsertWC( pTransport->Smtp.bstrDropDirectory ), szInsertWin32Msg(hr1), szInsertHResultCode(hr1), szInsertWC( bstrTo ), szInsertWC( bstrFrom ), szInsertWC( bstrSubject ), NULL ); } done = FALSE; // don't return message exitScan = TRUE; // exit message loop } } // Since this can take a while to work through a large backlog, let // the user know the progress we've made if ( ( *plCount >= 1 ) && ((*plCount % 50) == 0) ) { DPRINT1( 0, "There are %d SMTP messages remaining to be processed.\n", *plCount ); LogEvent(DS_EVENT_CAT_ISM, DS_EVENT_SEV_MINIMAL, DIRLOG_ISM_SMTP_MESSAGE_COUNT, szInsertUL(*plCount), szInsertWC(pTransport->Smtp.bstrDropDirectory), NULL ); } // Clean up if necessary if ( (!done) && (*ppMsg) ) { SmtpFreeMessage( *ppMsg ); *ppMsg = NULL; } if (pIMsg) { pIMsg = NULL; } if (bstrSubject != NULL) { SysFreeString( bstrSubject ); } if (bstrTo != NULL) { SysFreeString( bstrTo ); } if (bstrFrom != NULL) { SysFreeString( bstrFrom ); } } while ((!done) && (!exitScan) && (*plCount)); // Termination conditions: Assert( (*plCount == 0) || (done) && (*ppMsg) || (exitScan) ); DPRINT1( 2, "scanning message collection exit, %d remaining\n", *plCount ); hr = S_OK; return hr; } /* scanMessages */ HRESULT getMailMessage( IN TRANSPORT_INSTANCE * pTransport, IN LPCWSTR pszServiceName, OUT ISM_MSG ** ppMsg ) /*++ Routine Description: This is a wrapper around the scanMessages function. It handles caching of the current collection. We only get a collection once from the drop directory, and eliminate duplicates once. Arguments: pTransport - pszServiceName - ppMsg - Return Value: HRESULT - --*/ { HRESULT hr; CComPtr<IDropDirectory> pIDropDir; IMessages *pIMessages = (IMessages *) pTransport->Smtp.pvCurrentCollection; PGUID_TABLE pGuidTable = (PGUID_TABLE) pTransport->Smtp.pvGuidTable; Assert( ppMsg ); Assert( *ppMsg == NULL ); // we don't have a message yet // If we already have a collection in progress, use it if (pIMessages) { hr = scanMessages( pTransport, pIMessages, pszServiceName, &(pTransport->Smtp.lCount), pGuidTable, ppMsg ); // If we got a message, return it if ( (SUCCEEDED(hr)) && (*ppMsg) ) { goto cleanup; } // No message left in current collection, get rid of it pIMessages->Release(); pIMessages = NULL; pTransport->Smtp.lCount = 0; SmtpDestroyGuidTable( pGuidTable); pGuidTable = NULL; } // We don't have a current collection Assert( pTransport->Smtp.lCount == 0); // Get the collection of messages hr = getDropMessages( pTransport->Smtp.bstrDropDirectory, &pIDropDir, &pIMessages, &(pTransport->Smtp.lCount) ); if (FAILED(hr)) { DPRINT1(0, "getDropMessages failed, error 0x%x\n", hr); // Status already logged goto cleanup; } Assert( pIDropDir ); Assert( pIMessages ); // The way the notification mechanism works, we may receive a notification // before the file appears in the drop directory. We delay here in order // to give time for the file to arrive. A better approach would be to have // the sink write the file itself before signalling the event. // // See bug 88430: ISM SMTP sink should pre-process received messages. // Only wait when no messages pending, so that under load we pay no penelty if (pTransport->Smtp.lCount == 0) { DWORD waitCode; // Call destructors pIMessages->Release(); pIMessages= NULL; pIDropDir = NULL; // Sleep( 10 * 1000 ) while waiting for shutdown waitCode = WaitForSingleObject( pTransport->hShutdownEvent, 10 * 1000 ); if (waitCode == WAIT_OBJECT_0) { // Shutdown requested hr = S_OK; goto cleanup; } hr = getDropMessages( pTransport->Smtp.bstrDropDirectory, &pIDropDir, &pIMessages, &(pTransport->Smtp.lCount) ); if (FAILED(hr)) { DPRINT1(0, "getDropMessages failed, error 0x%x\n", hr); // Message already logged goto cleanup; } Assert( pIMessages ); // Sorry, no mail today if (pTransport->Smtp.lCount == 0) { hr = S_OK; goto cleanup; } } Assert( pTransport->Smtp.lCount >= 1 ); // Create a new guid table for tracking duplicates pGuidTable = SmtpCreateGuidTable(); if (pGuidTable == NULL) { DPRINT( 0, "failed to allocate guid table\n" ); hr = HR_NOT_ENOUGH_MEMORY; LogUnhandledError( hr ); goto cleanup; } // Try to get one out hr = scanMessages( pTransport, pIMessages, pszServiceName, &(pTransport->Smtp.lCount), pGuidTable, ppMsg ); cleanup: // Update context if ( (SUCCEEDED(hr)) && (pTransport->Smtp.lCount > 0) ) { pTransport->Smtp.pvCurrentCollection = pIMessages; pIMessages = NULL; // don't free pTransport->Smtp.pvGuidTable = pGuidTable; pGuidTable = NULL; // don't free } else { pTransport->Smtp.pvCurrentCollection = NULL; pTransport->Smtp.lCount = 0; pTransport->Smtp.pvGuidTable = NULL; } // Free resources if necessary if (pIMessages) { pIMessages->Release(); pIMessages= NULL; } if (pIDropDir) { pIDropDir = NULL; } if (pGuidTable) { SmtpDestroyGuidTable( pGuidTable ); pGuidTable = NULL; } return hr; } /* getMailMessage */ DWORD SmtpReceive( IN TRANSPORT_INSTANCE * pTransport, IN LPCWSTR pszServiceName, OUT ISM_MSG ** ppMsg ) /*++ Routine Description: API called by the server to retrieve a message. This routine needs to return success if we are not configured yet. Arguments: pTransport - pszServiceName - ppMsg - pointer to receive allocated message structure If NULL, notify instead of return a message Return Value: DWORD - --*/ { HRESULT hr; DWORD winError; DPRINT1( 3, "SmtpReceive, serv = %ws\n", pszServiceName ); MEMORY_CHECK_ALL(); if ( (NULL == ppMsg) || (NULL == pszServiceName) ) { return E_INVALIDARG; } // Default to "none waiting." *ppMsg = NULL; // If not configured, try to do so now EnterCriticalSection( &(pTransport->Lock) ); __try { if ( NULL == pTransport->Smtp.pszSmtpAddress ) { hr = configureMailAddress( pTransport ); } else { hr = S_OK; } } __finally { LeaveCriticalSection( &(pTransport->Lock) ); } if (FAILED(hr)) { DPRINT1( 0, "Failed to configure mail address, error 0x%x\n", hr ); LogEvent8(DS_EVENT_CAT_ISM, DS_EVENT_SEV_ALWAYS, DIRLOG_ISM_SMTP_NO_MAIL_ADDRESS, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); return hr; } // Smtp not installed, its ok if ( NULL == pTransport->Smtp.pszSmtpAddress ) { DPRINT( 3, "SMTP not present, returning no messages\n"); return S_OK; } // Synchronize access to drop directory EnterCriticalSection(&DropDirectoryLock); __try { hr = getMailMessage( pTransport, pszServiceName, ppMsg ); } __finally { LeaveCriticalSection(&DropDirectoryLock); } MEMORY_CHECK_ALL(); return hr; } /* SmtpReceive */
30.232605
149
0.576038
[ "object" ]
1d7d81662f3b8bef47b6dd5b168767bdcd7ac0cc
1,365
cpp
C++
leetcode/474.ones-and-zeroes.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
177
2017-08-21T08:57:43.000Z
2020-06-22T03:44:22.000Z
leetcode/474.ones-and-zeroes.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
2
2018-09-06T13:39:12.000Z
2019-06-03T02:54:45.000Z
leetcode/474.ones-and-zeroes.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
23
2017-08-23T06:01:28.000Z
2020-04-20T03:17:36.000Z
// f[i][j][k] = max(f[i - 1][j][k], f[i - 1][j - count0[i - 1]][k - count1[i - 1]] + 1 where j >=S0 and k >= S1 class Solution { public: int findMaxForm(vector<string>& strs, int m, int n) { int size = strs.size(); vector<int> count0(size, 0); vector<int> count1(size, 0); for (auto i = 0; i < strs.size(); ++i) { for (auto j = 0; j < strs[i].size(); ++j) { if (strs[i][j] == '0') { count0[i] += 1; } else { count1[i] += 1; } } } vector<vector<vector<int>>> table(size + 1, vector<vector<int>>(m + 1, vector<int>(n + 1, 0))); for (auto i = 1; i <= size; ++i) { for (auto j = 0; j <= m; ++j) { for (auto k = 0; k <= n; ++k) { table[i][j][k] = table[i - 1][j][k]; if (j >= count0[i - 1] && k >= count1[i - 1]) { table[i][j][k] = max(table[i][j][k], table[i - 1][j - count0[i - 1]][k - count1[i - 1]] + 1); } } } } return table[size][m][n]; } };
29.673913
117
0.312088
[ "vector" ]
1d8473d957cfa4efacf176804a8729ff532a902e
7,162
hpp
C++
include/cpl/math/simplex.hpp
dieram3/competitive-programming-library
29bd0204d00c08e56d1f7fedc5c6c3603c4e5121
[ "BSL-1.0" ]
25
2016-05-03T02:08:58.000Z
2022-01-11T03:49:28.000Z
include/cpl/math/simplex.hpp
dieram3/competitive-programming-library
29bd0204d00c08e56d1f7fedc5c6c3603c4e5121
[ "BSL-1.0" ]
22
2016-04-26T04:46:17.000Z
2016-12-06T03:53:32.000Z
include/cpl/math/simplex.hpp
dieram3/competitive-programming-library
29bd0204d00c08e56d1f7fedc5c6c3603c4e5121
[ "BSL-1.0" ]
5
2017-04-04T16:10:42.000Z
2019-12-05T08:22:30.000Z
// Copyright Diego Ramirez 2015 // 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) #ifndef CPL_MATH_SIMPLEX_HPP #define CPL_MATH_SIMPLEX_HPP #include <cpl/utility/matrix.hpp> // matrix2 #include <algorithm> // min_element, find #include <cassert> // assert #include <cmath> // fabs #include <cstddef> // size_t #include <cstdint> // SIZE_MAX #include <iterator> // begin, end #include <limits> // numeric_limits #include <numeric> // iota #include <type_traits> // is_floating_point #include <utility> // swap #include <vector> // vector namespace cpl { template <typename T> class simplex_solver { static_assert(std::is_floating_point<T>::value, "Must be floating-point"); public: using vec_t = std::vector<T>; using mat_t = matrix<T>; public: /// \brief Changes the epsilon value used to compare floats. /// /// \param val The new epsilon value. /// /// \pre <tt>eps >= std::numeric_limits<T>::epsilon()</tt> /// void set_eps(T val) { eps = val; } /// \brief Finds the optimal value of the given linear program. /// /// Uses the simplex algorithm to find the optimal solution of a linear /// program. The implementation is guaranteed to converge. /// /// The program must be given as follows: /// /// \li Maximize <tt>c^T*x</tt> /// \li Subject to <tt>A*x <= b</tt> /// \li and <tt>x >= 0</tt> /// /// \param a Matrix of \c m rows and \c n columns. /// \param b An <tt>m</tt>-dimensional vector. /// \param c An <tt>n</tt>-dimensional vector. /// \param[out] x Vector where the optimal solution will be stored. /// /// /// \returns The optimal value. If the objetive function is unbounded, returns /// <tt>std::numeric_limits<T>::infinity()</tt>. If no feasible solution /// exists, returns <tt>std::numeric_limits<T>::quiet_NaN()</tt>. /// T maximize(const mat_t& a, const vec_t& b, const vec_t& c, vec_t& x) { const size_t m = a.num_rows(); const size_t n = a.num_cols(); // Build tableau. tableau.resize({m + 2, n + 2}); for (size_t i = 0; i < m; ++i) { for (size_t j = 0; j < n; ++j) tableau[i][j] = a[i][j]; tableau[i][n] = -1; tableau[i][n + 1] = b[i]; } for (size_t j = 0; j < n; ++j) { tableau[m][j] = -c[j]; // Row m is the phase2 problem. tableau[m + 1][j] = 0; // Row m+1 is the phase1 problem. } tableau[m][n] = 0, tableau[m][n + 1] = 0; tableau[m + 1][n] = 1, tableau[m + 1][n + 1] = 0; nonbasic.resize(n + 1); // n variables plus 1 artificial variable initially. basic.resize(m); // m slack variables initially. std::iota(begin(nonbasic), end(nonbasic), size_t{0}); std::iota(begin(basic), end(basic), nonbasic.size()); pivcol.resize(tableau.num_rows()); // 'n' is the artificial variable. const size_t min_b = std::min_element(begin(b), end(b)) - begin(b); // Main invariant: right-hand side is always kept positive. if (is_neg(b[min_b])) { // Phase 1 is required. pivot(min_b, n); // Pivot to make RHS positive. simplex(1); if (!is_zero(tableau[m + 1][n + 1])) return std::numeric_limits<T>::quiet_NaN(); // Infeasible. const auto it = std::find(begin(basic), end(basic), n); if (it != basic.end()) { // Make 'n' a nonbasic variable. const size_t row = it - begin(basic); assert(is_zero(tableau[row][n + 1])); size_t col; for (col = 0; col <= n; ++col) if (!is_zero(tableau[row][col])) break; assert(col <= n); pivot(row, col); } } const size_t art_pos = std::find(begin(nonbasic), end(nonbasic), n) - begin(nonbasic); assert(art_pos < nonbasic.size()); for (size_t i = 0; i < tableau.num_rows(); ++i) tableau[i][art_pos] = 0; // Nullify the artificial column. if (!simplex(2)) return std::numeric_limits<T>::infinity(); // Unbounded. x.assign(n, T{0}); for (size_t i = 0; i < m; ++i) if (basic[i] < n) x[basic[i]] = tableau[i][n + 1]; return tableau[m][n + 1]; } private: enum search_result { must_pivot, optimized, unbounded }; // Requires: A feasible solution must exist. bool simplex(const int phase) { size_t r{}, c{}; search_result res; while ((res = find_pivot(r, c, phase)) == must_pivot) pivot(r, c); assert(!(phase == 1 && res == unbounded)); // Phase 1 can't be unbounded. return res == optimized; } // Bland's rule pivot selecting. search_result find_pivot(size_t& r, size_t& c, const int phase) { const size_t m = tableau.num_rows() - 2; const size_t n = tableau.num_cols() - 2; const size_t objrow = phase == 1 ? m + 1 : m; // SIZE_MAX => NIL // Find entering variable: c = SIZE_MAX; for (size_t j = 0; j <= n; ++j) { if (!is_neg(tableau[objrow][j])) continue; if (c == SIZE_MAX || nonbasic[j] < nonbasic[c]) c = j; } if (c == SIZE_MAX) return optimized; // Find leaving variable: auto ratio_less = [&](const size_t r1, const size_t r2) { const auto ratio1 = tableau[r1][n + 1] / tableau[r1][c]; const auto ratio2 = tableau[r2][n + 1] / tableau[r2][c]; if (approx(ratio1, ratio2)) return basic[r1] < basic[r2]; return ratio1 < ratio2; }; r = SIZE_MAX; for (size_t i = 0; i < m; ++i) { if (!is_pos(tableau[i][c])) continue; if (r == SIZE_MAX || ratio_less(i, r)) r = i; } if (r == SIZE_MAX) return unbounded; return must_pivot; } void pivot(const size_t r, const size_t c) { for (size_t i = 0; i < tableau.num_rows(); ++i) { pivcol[i] = tableau[i][c]; tableau[i][c] = 0; } tableau[r][c] = 1; multiply_row(r, 1 / pivcol[r]); for (size_t i = 0; i < tableau.num_rows(); ++i) if (i != r) add_row(r, -pivcol[i], i); std::swap(basic[r], nonbasic[c]); } void multiply_row(size_t i, const T mult) { for (size_t j = 0; j < tableau.num_cols(); ++j) tableau[i][j] *= mult; } void add_row(size_t row_from, const T mult, size_t row_to) { assert(row_from != row_to); for (size_t j = 0; j < tableau.num_cols(); ++j) tableau[row_to][j] += mult * tableau[row_from][j]; } bool is_pos(T val) const { return val > eps; } bool is_neg(T val) const { return val < -eps; } bool is_zero(T val) const { return std::fabs(val) <= eps; } bool approx(T v1, T v2) const { return std::fabs(v1 - v2) <= eps; } private: mat_t tableau; // Part of the tableau with information. vec_t pivcol; // Temporal storage to pivot. std::vector<size_t> basic, nonbasic; // Basic and nonbasic variables. T eps = std::numeric_limits<T>::epsilon(); }; } // end namespace cpl #endif // Header guard
31.13913
80
0.568556
[ "vector" ]
1d8bd2411a6cc0f1961d543f19253069806e65b9
17,698
hpp
C++
include/UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem_-RunChildren-d__16.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem_-RunChildren-d__16.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem_-RunChildren-d__16.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem #include "UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem.hpp" // Including type: System.Collections.Generic.IEnumerable`1 #include "System/Collections/Generic/IEnumerable_1.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" // Including type: System.Collections.Generic.List`1/System.Collections.Generic.Enumerator #include "System/Collections/Generic/List_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::TestRunner::NUnitExtensions::Runner namespace UnityEngine::TestRunner::NUnitExtensions::Runner { // Forward declaring type: UnityWorkItem class UnityWorkItem; } // Forward declaring namespace: System::Collections namespace System::Collections { // Skipping declaration: IEnumerator because it is already included! } // Completed forward declares // Type namespace: UnityEngine.TestRunner.NUnitExtensions.Runner namespace UnityEngine::TestRunner::NUnitExtensions::Runner { // WARNING Size may be invalid! // Autogenerated type: UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem/UnityEngine.TestRunner.NUnitExtensions.Runner.<RunChildren>d__16 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class CompositeWorkItem::$RunChildren$d__16 : public ::Il2CppObject/*, public System::Collections::Generic::IEnumerable_1<::Il2CppObject*>, public System::Collections::Generic::IEnumerator_1<::Il2CppObject*>*/ { public: // private System.Int32 <>1__state // Size: 0x4 // Offset: 0x10 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // private System.Object <>2__current // Size: 0x8 // Offset: 0x18 ::Il2CppObject* $$2__current; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // private System.Int32 <>l__initialThreadId // Size: 0x4 // Offset: 0x20 int $$l__initialThreadId; // Field size check static_assert(sizeof(int) == 0x4); // public UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem <>4__this // Size: 0x8 // Offset: 0x28 UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem* $$4__this; // Field size check static_assert(sizeof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem*) == 0x8); // private System.Int32 <childCount>5__2 // Size: 0x4 // Offset: 0x30 int $childCount$5__2; // Field size check static_assert(sizeof(int) == 0x4); // private System.Collections.Generic.List`1/System.Collections.Generic.Enumerator<UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem> <>7__wrap2 // Size: 0xFFFFFFFF // Offset: 0x38 typename System::Collections::Generic::List_1<UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem*>::Enumerator $$7__wrap2; // private UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem <child>5__4 // Size: 0x8 // Offset: 0x50 UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem* $child$5__4; // Field size check static_assert(sizeof(UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem*) == 0x8); // private System.Collections.IEnumerator <enumerable>5__5 // Size: 0x8 // Offset: 0x58 System::Collections::IEnumerator* $enumerable$5__5; // Field size check static_assert(sizeof(System::Collections::IEnumerator*) == 0x8); // Creating value type constructor for type: $RunChildren$d__16 $RunChildren$d__16(int $$1__state_ = {}, ::Il2CppObject* $$2__current_ = {}, int $$l__initialThreadId_ = {}, UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem* $$4__this_ = {}, int $childCount$5__2_ = {}, typename System::Collections::Generic::List_1<UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem*>::Enumerator $$7__wrap2_ = {}, UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem* $child$5__4_ = {}, System::Collections::IEnumerator* $enumerable$5__5_ = {}) noexcept : $$1__state{$$1__state_}, $$2__current{$$2__current_}, $$l__initialThreadId{$$l__initialThreadId_}, $$4__this{$$4__this_}, $childCount$5__2{$childCount$5__2_}, $$7__wrap2{$$7__wrap2_}, $child$5__4{$child$5__4_}, $enumerable$5__5{$enumerable$5__5_} {} // Creating interface conversion operator: operator System::Collections::Generic::IEnumerable_1<::Il2CppObject*> operator System::Collections::Generic::IEnumerable_1<::Il2CppObject*>() noexcept { return *reinterpret_cast<System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>(this); } // Creating interface conversion operator: operator System::Collections::Generic::IEnumerator_1<::Il2CppObject*> operator System::Collections::Generic::IEnumerator_1<::Il2CppObject*>() noexcept { return *reinterpret_cast<System::Collections::Generic::IEnumerator_1<::Il2CppObject*>*>(this); } // Get instance field: private System.Int32 <>1__state int _get_$$1__state(); // Set instance field: private System.Int32 <>1__state void _set_$$1__state(int value); // Get instance field: private System.Object <>2__current ::Il2CppObject* _get_$$2__current(); // Set instance field: private System.Object <>2__current void _set_$$2__current(::Il2CppObject* value); // Get instance field: private System.Int32 <>l__initialThreadId int _get_$$l__initialThreadId(); // Set instance field: private System.Int32 <>l__initialThreadId void _set_$$l__initialThreadId(int value); // Get instance field: public UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem <>4__this UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem* _get_$$4__this(); // Set instance field: public UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem <>4__this void _set_$$4__this(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem* value); // Get instance field: private System.Int32 <childCount>5__2 int _get_$childCount$5__2(); // Set instance field: private System.Int32 <childCount>5__2 void _set_$childCount$5__2(int value); // Get instance field: private System.Collections.Generic.List`1/System.Collections.Generic.Enumerator<UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem> <>7__wrap2 typename System::Collections::Generic::List_1<UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem*>::Enumerator _get_$$7__wrap2(); // Set instance field: private System.Collections.Generic.List`1/System.Collections.Generic.Enumerator<UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem> <>7__wrap2 void _set_$$7__wrap2(typename System::Collections::Generic::List_1<UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem*>::Enumerator value); // Get instance field: private UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem <child>5__4 UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem* _get_$child$5__4(); // Set instance field: private UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem <child>5__4 void _set_$child$5__4(UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem* value); // Get instance field: private System.Collections.IEnumerator <enumerable>5__5 System::Collections::IEnumerator* _get_$enumerable$5__5(); // Set instance field: private System.Collections.IEnumerator <enumerable>5__5 void _set_$enumerable$5__5(System::Collections::IEnumerator* value); // private System.Object System.Collections.Generic.IEnumerator<System.Object>.get_Current() // Offset: 0x11EE0C0 ::Il2CppObject* System_Collections_Generic_IEnumerator$System_Object$_get_Current(); // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0x11EE128 ::Il2CppObject* System_Collections_IEnumerator_get_Current(); // public System.Void .ctor(System.Int32 <>1__state) // Offset: 0x11EB620 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static CompositeWorkItem::$RunChildren$d__16* New_ctor(int $$1__state) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<CompositeWorkItem::$RunChildren$d__16*, creationType>($$1__state))); } // private System.Void System.IDisposable.Dispose() // Offset: 0x11ED8D4 void System_IDisposable_Dispose(); // private System.Boolean MoveNext() // Offset: 0x11ED948 bool MoveNext(); // private System.Void <>m__Finally1() // Offset: 0x11ED8F0 void $$m__Finally1(); // private System.Void System.Collections.IEnumerator.Reset() // Offset: 0x11EE0C8 void System_Collections_IEnumerator_Reset(); // private System.Collections.Generic.IEnumerator`1<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator() // Offset: 0x11EE130 System::Collections::Generic::IEnumerator_1<::Il2CppObject*>* System_Collections_Generic_IEnumerable$System_Object$_GetEnumerator(); // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0x11EE1DC System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator(); }; // UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem/UnityEngine.TestRunner.NUnitExtensions.Runner.<RunChildren>d__16 // WARNING Not writing size check since size may be invalid! } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*, "UnityEngine.TestRunner.NUnitExtensions.Runner", "CompositeWorkItem/<RunChildren>d__16"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_Generic_IEnumerator$System_Object$_get_Current // Il2CppName: System.Collections.Generic.IEnumerator<System.Object>.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_Generic_IEnumerator$System_Object$_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "System.Collections.Generic.IEnumerator<System.Object>.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_IEnumerator_get_Current // Il2CppName: System.Collections.IEnumerator.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_IEnumerator_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "System.Collections.IEnumerator.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_IDisposable_Dispose // Il2CppName: System.IDisposable.Dispose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_IDisposable_Dispose)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "System.IDisposable.Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::$$m__Finally1 // Il2CppName: <>m__Finally1 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::$$m__Finally1)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "<>m__Finally1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_IEnumerator_Reset // Il2CppName: System.Collections.IEnumerator.Reset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_IEnumerator_Reset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "System.Collections.IEnumerator.Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_Generic_IEnumerable$System_Object$_GetEnumerator // Il2CppName: System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::IEnumerator_1<::Il2CppObject*>* (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_Generic_IEnumerable$System_Object$_GetEnumerator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_IEnumerable_GetEnumerator // Il2CppName: System.Collections.IEnumerable.GetEnumerator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::IEnumerator* (UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::*)()>(&UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16::System_Collections_IEnumerable_GetEnumerator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::$RunChildren$d__16*), "System.Collections.IEnumerable.GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
76.284483
772
0.763589
[ "object", "vector" ]
1d8d3c88f1405d551a95b0e8db86b9e1a23a1bef
4,155
cpp
C++
Source/Game/Components/Animation.cpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Game/Components/Animation.cpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Game/Components/Animation.cpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
#include "Precompiled.hpp" #include "Animation.hpp" #include "Render.hpp" #include "Game/ComponentSystem.hpp" using namespace Game; using namespace Components; Animation::Animation() : m_render(nullptr), m_currentAnimation(nullptr), m_currentFrame(nullptr), m_frameIndex(0), m_frameTime(0.0f), m_playing(false), m_loop(false), m_update(false) { } Animation::~Animation() { } bool Animation::Finalize(EntityHandle self, const Context& context) { // Get required systems. ComponentSystem* componentSystem = context[ContextTypes::Game].Get<ComponentSystem>(); if(componentSystem == nullptr) return false; // Get required components. m_render = componentSystem->Lookup<Render>(self); if(m_render == nullptr) return false; return true; } void Animation::SetAnimationList(AnimationListPtr animationList) { this->Stop(); m_animationList = animationList; m_currentAnimation = nullptr; m_currentFrame = nullptr; } const Animation::AnimationListPtr& Animation::GetAnimationList() const { return m_animationList; } void Animation::Update(float timeDelta) { if(m_playing) { assert(m_currentAnimation != nullptr); assert(m_currentFrame != nullptr); // Update animation frame. while(m_frameTime > m_currentFrame->duration) { // Substract time of already played frame. m_frameTime -= m_currentFrame->duration; // Advance to the next frame. ++m_frameIndex; // Check if we are past the last frame. if(m_frameIndex >= m_currentAnimation->frames.size()) { if(m_loop) { // Go back to the first frame if looped. m_currentFrame = &m_currentAnimation->frames[0]; m_frameIndex = 0; } else { // Stop playing the animation. m_playing = false; return; } } else { // Set the next animation frame. m_currentFrame = &m_currentAnimation->frames[m_frameIndex]; } // Set frame change state. m_update = true; } // Set the animation frame sprite. if(m_update) { assert(m_render != nullptr); m_render->SetTexture(m_animationList->GetTexture()); m_render->SetRectangle(m_currentFrame->rectangle); m_render->SetOffset(m_currentFrame->offset); m_update = false; } // Increment frame time. m_frameTime += timeDelta; } } void Animation::Play(std::string name, PlayFlags::Type flags) { if(m_animationList == nullptr) return; // Get the animation. const auto* animation = m_animationList->GetAnimation(name); if(animation == nullptr) return; // Check if it's the current animation. if(m_currentAnimation == animation) { // Ignore the request to play the same animation again // if we didn't specify that we want to reset it. if(!(flags & PlayFlags::Reset)) return; } // Play the animation. bool continueAnimation = (flags & PlayFlags::Continue) != 0; continueAnimation = continueAnimation && m_currentAnimation == animation; continueAnimation = continueAnimation && m_frameIndex < m_currentAnimation->frames.size(); if(continueAnimation) { // Change animation but preserve the frame index and time. m_currentAnimation = animation; m_currentFrame = &animation->frames[m_frameIndex]; } else { // Start new animation. m_currentAnimation = animation; m_currentFrame = &animation->frames[0]; m_frameIndex = 0; m_frameTime = 0.0f; } m_loop = flags & PlayFlags::Loop; m_playing = true; m_update = true; } void Animation::Stop() { m_playing = false; } bool Animation::IsPlaying() const { return m_playing; }
25.335366
94
0.596149
[ "render" ]
1d8f6bc69e117d6e3c5d60ba64ce6fcf3d17d120
2,239
cpp
C++
test/parsers/gdsii/test_driver.cpp
RedFantom/limbo
8d3e0d484a809fb4b3ff8aa72fd972d16cdab405
[ "MIT" ]
74
2017-10-19T03:10:52.000Z
2022-03-28T17:51:54.000Z
test/parsers/gdsii/test_driver.cpp
RedFantom/limbo
8d3e0d484a809fb4b3ff8aa72fd972d16cdab405
[ "MIT" ]
3
2017-12-06T01:49:21.000Z
2020-06-22T00:08:12.000Z
test/parsers/gdsii/test_driver.cpp
RedFantom/limbo
8d3e0d484a809fb4b3ff8aa72fd972d16cdab405
[ "MIT" ]
26
2017-11-07T10:32:54.000Z
2021-10-02T02:22:37.000Z
/** * @file gdsii/test_gdsdb.cpp * @brief test @ref GdsParser::GdsDriver * @author Yibo Lin * @date Nov 2014 */ #include <iostream> #include <limbo/parsers/gdsii/stream/GdsDriver.h> using std::cout; using std::endl; /// @brief a database for GdsParser::GdsDriver struct DataBase : public GdsParser::GdsDriverDataBase { /// @brief constructor DataBase() { cout << "constructing DataBase" << endl; } ///////////////////// required callbacks ///////////////////// /// @brief add GDSII library /// @param lib GDSII library virtual void add_gds_lib(GdsParser::GdsLib const& lib) { cout << "library name = " << lib.lib_name << endl; cout << "library unit = " << lib.unit[0] << ", " << lib.unit[1] << endl; cout << "# CELL = " << lib.vCell.size() << endl; if (!lib.vCell.empty()) { cout << "# BOUNDARY = " << lib.vCell.front().vBoundary.size() << endl; cout << "cell name = " << lib.vCell.front().cell_name << endl; vector<GdsParser::GdsBoundary> const& vBoundary = lib.vCell.front().vBoundary; for (unsigned int i = 0; i < vBoundary.size(); ++i) { cout << ">> BOUNDARY" << endl; cout << "XY: "; for (unsigned int j = 0; j < vBoundary[i].vPoint.size(); ++j) { cout << vBoundary[i].vPoint[j][0] << ", " << vBoundary[i].vPoint[j][1] << endl; } } vector<GdsParser::GdsText> const& vText = lib.vCell.front().vText; for (unsigned int i = 0; i < vText.size(); ++i) { cout << ">> TEXT" << endl; cout << "STRING: " << vText[i].content << endl; cout << "XY: " << vText[i].position[0] << ", " << vText[i].position[1] << endl; } vector<GdsParser::GdsSref> const& vSref = lib.vCell.front().vSref; for (unsigned int i = 0; i < vSref.size(); ++i) { cout << ">> SREF" << endl; cout << "SNAME: " << vSref[i].sname << endl; cout << "XY: " << vSref[i].position[0] << ", " << vSref[i].position[1] << endl; } } } }; /// @brief main function /// @param argc number of arguments /// @param argv values of arguments /// @return 0 if succeed int main(int argc, char** argv) { DataBase db; if (argc > 1) cout << GdsParser::read(db, argv[1]) << endl; else cout << "at least 1 argument is required" << endl; return 0; }
30.256757
84
0.570344
[ "vector" ]
1d8f851a6e3a9837ef6bf4e9e43bd54cbf156843
3,964
hpp
C++
src/config/ParseError.hpp
Seally/wba
5342152a13938afa5404bd72de089f438461b3a4
[ "MIT" ]
1
2021-12-27T18:49:41.000Z
2021-12-27T18:49:41.000Z
src/config/ParseError.hpp
Seally/wba
5342152a13938afa5404bd72de089f438461b3a4
[ "MIT" ]
null
null
null
src/config/ParseError.hpp
Seally/wba
5342152a13938afa5404bd72de089f438461b3a4
[ "MIT" ]
1
2021-12-27T18:49:43.000Z
2021-12-27T18:49:43.000Z
#pragma once #include <exception> #include <string> #include <string_view> #include <unordered_map> #include <variant> class ParseError : public std::runtime_error { public: explicit ParseError(const std::string& message) : std::runtime_error(message) {} explicit ParseError(const char* message) : std::runtime_error(message) {} }; using KeyType = std::variant<std::size_t, std::string>; class EntryError : public ParseError { public: const KeyType key; explicit EntryError(KeyType key, const std::string& message) : ParseError(message) , key(key) {} explicit EntryError(KeyType key, const char* message) : ParseError(message) , key(key) {} }; enum class ValueType { Integer, String, Array, Table, }; class InvalidEntryValueTypeError : public EntryError { public: const KeyType key; const ValueType expectedType; explicit InvalidEntryValueTypeError( KeyType key, ValueType expectedType, const std::string& message) : EntryError(key, message) , expectedType(expectedType) {} explicit InvalidEntryValueTypeError( KeyType key, ValueType expectedType, const char* message) : EntryError(key, message) , expectedType(expectedType) {} }; class EntryRange { using Value = std::variant<std::string, int>; public: enum class Type { Enumerated, Between, Equals, }; const Type type; const std::vector<Value> values; explicit EntryRange(Value expected) : type(EntryRange::Type::Equals) , values{expected} {} explicit EntryRange(Value min, Value max) : type(EntryRange::Type::Between) , values{min, max} {} explicit EntryRange(std::initializer_list<Value> values) : type(EntryRange::Type::Enumerated) , values(values) {} }; class EntryValueOutOfRangeError : public EntryError { public: const EntryRange expectedRange; explicit EntryValueOutOfRangeError( KeyType key, const EntryRange& expectedRange, const std::string& message) : EntryError(key, message) , expectedRange(expectedRange) {} explicit EntryValueOutOfRangeError( KeyType key, const EntryRange& expectedRange, const char* message) : EntryError(key, message) , expectedRange(expectedRange) {} }; class ArrayEntryError : public EntryError { public: enum class Type { InvalidSize, DuplicateEntries, }; const Type type; protected: explicit ArrayEntryError(KeyType key, Type type, const std::string& message) : EntryError(key, message) , type(type) {} }; class ArrayDuplicateEntriesError : public ArrayEntryError { public: explicit ArrayDuplicateEntriesError(KeyType key, const std::string& message) : ArrayEntryError(key, ArrayEntryError::Type::DuplicateEntries, message) {} explicit ArrayDuplicateEntriesError(KeyType key, const char* message) : ArrayEntryError(key, ArrayEntryError::Type::DuplicateEntries, message) {} }; class ArrayInvalidSizeError : public ArrayEntryError { public: const EntryRange expectedRange; explicit ArrayInvalidSizeError( KeyType key, const EntryRange& expectedRange, const std::string& message) : ArrayEntryError(key, ArrayEntryError::Type::InvalidSize, message) , expectedRange(expectedRange) {} explicit ArrayInvalidSizeError( KeyType key, const EntryRange& expectedRange, const char* message) : ArrayEntryError(key, ArrayEntryError::Type::InvalidSize, message) , expectedRange(expectedRange) {} };
24.621118
81
0.628406
[ "vector" ]
1da0662539fd8d4119276644430f8104595ec534
33,016
cpp
C++
frameworks/cocos2d-x/cocos/2d/CCDrawNode.cpp
darkdukey/cocos2dx-lite
4222c11990cf88fb80c1ef9dc6970afef0939de5
[ "MIT" ]
56
2016-05-29T11:47:07.000Z
2022-02-04T12:53:56.000Z
frameworks/cocos2d-x/cocos/2d/CCDrawNode.cpp
darkdukey/cocos2dx-lite
4222c11990cf88fb80c1ef9dc6970afef0939de5
[ "MIT" ]
32
2016-07-06T06:22:18.000Z
2020-08-02T04:02:32.000Z
frameworks/cocos2d-x/cocos/2d/CCDrawNode.cpp
darkdukey/cocos2dx-lite
4222c11990cf88fb80c1ef9dc6970afef0939de5
[ "MIT" ]
25
2016-07-07T16:30:23.000Z
2021-04-19T17:27:57.000Z
/* Copyright (c) 2012 Scott Lembcke and Howling Moon Software * Copyright (c) 2012 cocos2d-x.org * Copyright (c) 2013-2016 Chukong Technologies Inc. * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. * * 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 "2d/CCDrawNode.h" #include "base/CCEventType.h" #include "base/CCConfiguration.h" #include "renderer/CCRenderer.h" #include "renderer/ccGLStateCache.h" #include "renderer/CCGLProgramState.h" #include "renderer/CCGLProgramCache.h" #include "base/CCDirector.h" #include "base/CCEventListenerCustom.h" #include "base/CCEventDispatcher.h" #include "2d/CCActionCatmullRom.h" #include "platform/CCGL.h" NS_CC_BEGIN static inline Tex2F v2ToTex2F(const Vec2 &v) { return {v.x, v.y}; } static const float EPSILON=0.0000000001f; float Triangulate::computeArea(const Vec2 *verts,int n) { float A=0.0f; for(int p=n-1,q=0; q<n; p=q++) { A+= verts[p].x*verts[q].y - verts[q].x*verts[p].y; } return A*0.5f; } /* isInsideTriangle decides if a point P is Inside of the triangle defined by A, B, C. */ bool Triangulate::isInsideTriangle(float Ax, float Ay, float Bx, float By, float Cx, float Cy, float Px, float Py) { float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; float cCROSSap, bCROSScp, aCROSSbp; ax = Cx - Bx; ay = Cy - By; bx = Ax - Cx; by = Ay - Cy; cx = Bx - Ax; cy = By - Ay; apx= Px - Ax; apy= Py - Ay; bpx= Px - Bx; bpy= Py - By; cpx= Px - Cx; cpy= Py - Cy; aCROSSbp = ax*bpy - ay*bpx; cCROSSap = cx*apy - cy*apx; bCROSScp = bx*cpy - by*cpx; return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); } bool Triangulate::checkSnip(const Vec2 *verts,int u,int v,int w,int n,int *V) { int p; float Ax, Ay, Bx, By, Cx, Cy, Px, Py; Ax = verts[V[u]].x; Ay = verts[V[u]].y; Bx = verts[V[v]].x; By = verts[V[v]].y; Cx = verts[V[w]].x; Cy = verts[V[w]].y; if ( EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) ) return false; for (p=0;p<n;p++) { if( (p == u) || (p == v) || (p == w) ) continue; Px = verts[V[p]].x; Py = verts[V[p]].y; if (isInsideTriangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py)) return false; } return true; } V2F_C4B_T2F_Triangle * Triangulate::processTriangles(const Vec2 *verts,V2F_C4B_T2F_Triangle * triangles,int n,const Color4F &fillColor) { if ( n < 3 ) return triangles; std::vector<int> V(n); /* we want a counter-clockwise polygon in V */ if ( 0.0f < computeArea(verts,n) ) { for (int v=0; v<n; v++) V[v] = v; } else { // if area is zero, simply fill triangles. for (int i = 0; i < n-2; i++) { V2F_C4B_T2F_Triangle tmp = { {verts[0], Color4B(fillColor), v2ToTex2F(Vec2::ZERO)}, {verts[i+1], Color4B(fillColor), v2ToTex2F(Vec2::ZERO)}, {verts[i+2], Color4B(fillColor), v2ToTex2F(Vec2::ZERO)}, }; *triangles++ = tmp; } return triangles; } int nv = n; /* remove nv-2 Vertices, creating 1 triangle every time */ int count = 2*nv; /* error detection */ for(int m=0, v=nv-1; nv>2; ) { /* if we loop, it is probably a non-simple polygon */ if (0 >= (count--)) { //** Triangulate: ERROR - probable bad polygon! return triangles; } /* three consecutive vertices in current polygon, <u,v,w> */ int u = v ; if (nv <= u) u = 0; /* previous */ v = u+1; if (nv <= v) v = 0; /* new v */ int w = v+1; if (nv <= w) w = 0; /* next */ if ( checkSnip(verts,u,v,w,nv,V.data()) ) { int a,b,c,s,t; /* true names of the vertices */ a = V[u]; b = V[v]; c = V[w]; V2F_C4B_T2F_Triangle tmp = { {verts[a], Color4B(fillColor), v2ToTex2F(Vec2::ZERO)}, {verts[b], Color4B(fillColor), v2ToTex2F(Vec2::ZERO)}, {verts[c], Color4B(fillColor), v2ToTex2F(Vec2::ZERO)}, }; *triangles++ = tmp; m++; /* remove v from remaining polygon */ for(s=v,t=v+1;t<nv;s++,t++) V[s] = V[t]; nv--; /* resest error detection counter */ count = 2*nv; } } return triangles; } // implementation of DrawNode DrawNode::DrawNode(GLfloat lineWidth) : _lineWidth(lineWidth) , _defaultLineWidth(lineWidth) { _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; #if CC_ENABLE_CACHE_TEXTURE_DATA // Need to listen the event only when not use batchnode, because it will use VBO auto listener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, [this](EventCustom* event){ /** listen the event that renderer was recreated on Android/WP8 */ this->setupBuffer(); }); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); #endif } DrawNode::~DrawNode() { free(_buffer); _buffer = nullptr; free(_bufferGLPoint); _bufferGLPoint = nullptr; free(_bufferGLLine); _bufferGLLine = nullptr; glDeleteBuffers(1, &_vbo); glDeleteBuffers(1, &_vboGLLine); glDeleteBuffers(1, &_vboGLPoint); _vbo = 0; _vboGLPoint = 0; _vboGLLine = 0; if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(0); glDeleteVertexArrays(1, &_vao); glDeleteVertexArrays(1, &_vaoGLLine); glDeleteVertexArrays(1, &_vaoGLPoint); _vao = _vaoGLLine = _vaoGLPoint = 0; } } DrawNode* DrawNode::create(GLfloat defaultLineWidth) { DrawNode* ret = new (std::nothrow) DrawNode(defaultLineWidth); if (ret && ret->init()) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } void DrawNode::ensureCapacity(int count) { CCASSERT(count>=0, "capacity must be >= 0"); if(_bufferCount + count > _bufferCapacity) { _bufferCapacity += MAX(_bufferCapacity, count); _buffer = (V2F_C4B_T2F*)realloc(_buffer, _bufferCapacity*sizeof(V2F_C4B_T2F)); } } void DrawNode::ensureCapacityGLPoint(int count) { CCASSERT(count>=0, "capacity must be >= 0"); if(_bufferCountGLPoint + count > _bufferCapacityGLPoint) { _bufferCapacityGLPoint += MAX(_bufferCapacityGLPoint, count); _bufferGLPoint = (V2F_C4B_T2F*)realloc(_bufferGLPoint, _bufferCapacityGLPoint*sizeof(V2F_C4B_T2F)); } } void DrawNode::ensureCapacityGLLine(int count) { CCASSERT(count>=0, "capacity must be >= 0"); if(_bufferCountGLLine + count > _bufferCapacityGLLine) { _bufferCapacityGLLine += MAX(_bufferCapacityGLLine, count); _bufferGLLine = (V2F_C4B_T2F*)realloc(_bufferGLLine, _bufferCapacityGLLine*sizeof(V2F_C4B_T2F)); } } void DrawNode::setupBuffer() { if (Configuration::getInstance()->supportsShareableVAO()) { glGenVertexArrays(1, &_vao); GL::bindVAO(_vao); glGenBuffers(1, &_vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)* _bufferCapacity, _buffer, GL_STREAM_DRAW); // vertex glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); // color glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); // texcoord glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORD); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); glGenVertexArrays(1, &_vaoGLLine); GL::bindVAO(_vaoGLLine); glGenBuffers(1, &_vboGLLine); glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacityGLLine, _bufferGLLine, GL_STREAM_DRAW); // vertex glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); // color glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); // texcoord glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORD); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); glGenVertexArrays(1, &_vaoGLPoint); GL::bindVAO(_vaoGLPoint); glGenBuffers(1, &_vboGLPoint); glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacityGLPoint, _bufferGLPoint, GL_STREAM_DRAW); // vertex glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); // color glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); // Texture coord as pointsize glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORD); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); GL::bindVAO(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } else { glGenBuffers(1, &_vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)* _bufferCapacity, _buffer, GL_STREAM_DRAW); glGenBuffers(1, &_vboGLLine); glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacityGLLine, _bufferGLLine, GL_STREAM_DRAW); glGenBuffers(1, &_vboGLPoint); glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacityGLPoint, _bufferGLPoint, GL_STREAM_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } CHECK_GL_ERROR_DEBUG(); } bool DrawNode::init() { _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR)); ensureCapacity(512); ensureCapacityGLPoint(64); ensureCapacityGLLine(256); setupBuffer(); _dirty = true; _dirtyGLLine = true; _dirtyGLPoint = true; return true; } void DrawNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) { if(_bufferCount) { _customCommand.init(_globalZOrder, transform, flags); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this, transform, flags); renderer->addCommand(&_customCommand); } if(_bufferCountGLPoint) { _customCommandGLPoint.init(_globalZOrder, transform, flags); _customCommandGLPoint.func = CC_CALLBACK_0(DrawNode::onDrawGLPoint, this, transform, flags); renderer->addCommand(&_customCommandGLPoint); } if(_bufferCountGLLine) { _customCommandGLLine.init(_globalZOrder, transform, flags); _customCommandGLLine.func = CC_CALLBACK_0(DrawNode::onDrawGLLine, this, transform, flags); renderer->addCommand(&_customCommandGLLine); } } void DrawNode::onDraw(const Mat4 &transform, uint32_t /*flags*/) { getGLProgramState()->apply(transform); auto glProgram = this->getGLProgram(); glProgram->setUniformLocationWith1f(glProgram->getUniformLocation("u_alpha"), _displayedOpacity / 255.0); GL::blendFunc(_blendFunc.src, _blendFunc.dst); if (_dirty) { glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacity, _buffer, GL_STREAM_DRAW); _dirty = false; } if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(_vao); } else { GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); glBindBuffer(GL_ARRAY_BUFFER, _vbo); // vertex glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); // color glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); // texcoord glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); } glDrawArrays(GL_TRIANGLES, 0, _bufferCount); glBindBuffer(GL_ARRAY_BUFFER, 0); if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(0); } CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, _bufferCount); CHECK_GL_ERROR_DEBUG(); } void DrawNode::onDrawGLLine(const Mat4 &transform, uint32_t /*flags*/) { auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR); glProgram->use(); glProgram->setUniformsForBuiltins(transform); glProgram->setUniformLocationWith1f(glProgram->getUniformLocation("u_alpha"), _displayedOpacity / 255.0); GL::blendFunc(_blendFunc.src, _blendFunc.dst); if (_dirtyGLLine) { glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacityGLLine, _bufferGLLine, GL_STREAM_DRAW); _dirtyGLLine = false; } if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(_vaoGLLine); } else { glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); // vertex glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); // color glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); // texcoord glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); } glLineWidth(_lineWidth); glDrawArrays(GL_LINES, 0, _bufferCountGLLine); if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(0); } glBindBuffer(GL_ARRAY_BUFFER, 0); CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,_bufferCountGLLine); CHECK_GL_ERROR_DEBUG(); } void DrawNode::onDrawGLPoint(const Mat4 &transform, uint32_t /*flags*/) { auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_COLOR_TEXASPOINTSIZE); glProgram->use(); glProgram->setUniformsForBuiltins(transform); glProgram->setUniformLocationWith1f(glProgram->getUniformLocation("u_alpha"), _displayedOpacity / 255.0); GL::blendFunc(_blendFunc.src, _blendFunc.dst); if (_dirtyGLPoint) { glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacityGLPoint, _bufferGLPoint, GL_STREAM_DRAW); _dirtyGLPoint = false; } if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(_vaoGLPoint); } else { glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); } glDrawArrays(GL_POINTS, 0, _bufferCountGLPoint); if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(0); } glBindBuffer(GL_ARRAY_BUFFER, 0); CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,_bufferCountGLPoint); CHECK_GL_ERROR_DEBUG(); } void DrawNode::drawPoint(const Vec2& position, const float pointSize, const Color4F &color) { ensureCapacityGLPoint(1); V2F_C4B_T2F *point = _bufferGLPoint + _bufferCountGLPoint; *point = {position, Color4B(color), Tex2F(pointSize,0)}; _bufferCountGLPoint += 1; _dirtyGLPoint = true; } void DrawNode::drawPoints(const Vec2 *position, unsigned int numberOfPoints, const Color4F &color) { drawPoints(position, numberOfPoints, 1.0, color); } void DrawNode::drawPoints(const Vec2 *position, unsigned int numberOfPoints, const float pointSize, const Color4F &color) { ensureCapacityGLPoint(numberOfPoints); V2F_C4B_T2F *point = _bufferGLPoint + _bufferCountGLPoint; for(unsigned int i=0; i < numberOfPoints; i++,point++) { *point = {position[i], Color4B(color), Tex2F(pointSize,0)}; } _bufferCountGLPoint += numberOfPoints; _dirtyGLPoint = true; } void DrawNode::drawLine(const Vec2 &origin, const Vec2 &destination, const Color4F &color) { ensureCapacityGLLine(2); V2F_C4B_T2F *point = _bufferGLLine + _bufferCountGLLine; *point = {origin, Color4B(color), Tex2F(0.0, 0.0)}; *(point + 1) = {destination, Color4B(color), Tex2F(0.0, 0.0)}; _bufferCountGLLine += 2; _dirtyGLLine = true; } void DrawNode::drawRect(const Vec2 &origin, const Vec2 &destination, const Color4F &color) { drawLine(origin, Vec2(destination.x, origin.y), color); drawLine(Vec2(destination.x, origin.y), destination, color); drawLine(destination, Vec2(origin.x, destination.y), color); drawLine(Vec2(origin.x, destination.y), origin, color); } void DrawNode::drawPoly(const Vec2 *poli, unsigned int numberOfPoints, bool closePolygon, const Color4F &color) { unsigned int vertex_count; if(closePolygon) { vertex_count = 2 * numberOfPoints; ensureCapacityGLLine(vertex_count); } else { vertex_count = 2 * (numberOfPoints - 1); ensureCapacityGLLine(vertex_count); } V2F_C4B_T2F *point = _bufferGLLine + _bufferCountGLLine; unsigned int i = 0; for(; i < numberOfPoints - 1; i++) { *point = {poli[i], Color4B(color), Tex2F(0.0, 0.0)}; *(point + 1) = {poli[i + 1], Color4B(color), Tex2F(0.0, 0.0)}; point += 2; } if(closePolygon) { *point = {poli[i], Color4B(color), Tex2F(0.0, 0.0)}; *(point + 1) = {poli[0], Color4B(color), Tex2F(0.0, 0.0)}; } _bufferCountGLLine += vertex_count; } void DrawNode::drawCircle(const Vec2& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY, const Color4F &color) { const float coef = 2.0f * (float)M_PI/segments; Vec2 *vertices = new (std::nothrow) Vec2[segments+2]; if( ! vertices ) return; for(unsigned int i = 0;i <= segments; i++) { float rads = i*coef; GLfloat j = radius * cosf(rads + angle) * scaleX + center.x; GLfloat k = radius * sinf(rads + angle) * scaleY + center.y; vertices[i].x = j; vertices[i].y = k; } if(drawLineToCenter) { vertices[segments+1].x = center.x; vertices[segments+1].y = center.y; drawPoly(vertices, segments+2, true, color); } else drawPoly(vertices, segments+1, true, color); CC_SAFE_DELETE_ARRAY(vertices); } void DrawNode::drawCircle(const Vec2 &center, float radius, float angle, unsigned int segments, bool drawLineToCenter, const Color4F &color) { drawCircle(center, radius, angle, segments, drawLineToCenter, 1.0f, 1.0f, color); } void DrawNode::drawQuadBezier(const Vec2 &origin, const Vec2 &control, const Vec2 &destination, unsigned int segments, const Color4F &color) { Vec2* vertices = new (std::nothrow) Vec2[segments + 1]; if( ! vertices ) return; float t = 0.0f; for(unsigned int i = 0; i < segments; i++) { vertices[i].x = powf(1 - t, 2) * origin.x + 2.0f * (1 - t) * t * control.x + t * t * destination.x; vertices[i].y = powf(1 - t, 2) * origin.y + 2.0f * (1 - t) * t * control.y + t * t * destination.y; t += 1.0f / segments; } vertices[segments].x = destination.x; vertices[segments].y = destination.y; drawPoly(vertices, segments+1, false, color); CC_SAFE_DELETE_ARRAY(vertices); } void DrawNode::drawCubicBezier(const Vec2 &origin, const Vec2 &control1, const Vec2 &control2, const Vec2 &destination, unsigned int segments, const Color4F &color) { Vec2* vertices = new (std::nothrow) Vec2[segments + 1]; if( ! vertices ) return; float t = 0; for (unsigned int i = 0; i < segments; i++) { vertices[i].x = powf(1 - t, 3) * origin.x + 3.0f * powf(1 - t, 2) * t * control1.x + 3.0f * (1 - t) * t * t * control2.x + t * t * t * destination.x; vertices[i].y = powf(1 - t, 3) * origin.y + 3.0f * powf(1 - t, 2) * t * control1.y + 3.0f * (1 - t) * t * t * control2.y + t * t * t * destination.y; t += 1.0f / segments; } vertices[segments].x = destination.x; vertices[segments].y = destination.y; drawPoly(vertices, segments+1, false, color); CC_SAFE_DELETE_ARRAY(vertices); } void DrawNode::drawCardinalSpline(PointArray *config, float tension, unsigned int segments, const Color4F &color) { Vec2* vertices = new (std::nothrow) Vec2[segments + 1]; if( ! vertices ) return; ssize_t p; float lt; float deltaT = 1.0f / config->count(); for( unsigned int i=0; i < segments+1;i++) { float dt = (float)i / segments; // border if( dt == 1 ) { p = config->count() - 1; lt = 1; } else { p = dt / deltaT; lt = (dt - deltaT * (float)p) / deltaT; } // Interpolate Vec2 pp0 = config->getControlPointAtIndex(p-1); Vec2 pp1 = config->getControlPointAtIndex(p+0); Vec2 pp2 = config->getControlPointAtIndex(p+1); Vec2 pp3 = config->getControlPointAtIndex(p+2); Vec2 newPos = ccCardinalSplineAt( pp0, pp1, pp2, pp3, tension, lt); vertices[i].x = newPos.x; vertices[i].y = newPos.y; } drawPoly(vertices, segments+1, false, color); CC_SAFE_DELETE_ARRAY(vertices); } void DrawNode::drawCatmullRom(PointArray *points, unsigned int segments, const Color4F &color) { drawCardinalSpline( points, 0.5f, segments, color); } void DrawNode::drawDot(const Vec2 &pos, float radius, const Color4F &color) { unsigned int vertex_count = 2*3; ensureCapacity(vertex_count); V2F_C4B_T2F a = {Vec2(pos.x - radius, pos.y - radius), Color4B(color), Tex2F(-1.0, -1.0) }; V2F_C4B_T2F b = {Vec2(pos.x - radius, pos.y + radius), Color4B(color), Tex2F(-1.0, 1.0) }; V2F_C4B_T2F c = {Vec2(pos.x + radius, pos.y + radius), Color4B(color), Tex2F( 1.0, 1.0) }; V2F_C4B_T2F d = {Vec2(pos.x + radius, pos.y - radius), Color4B(color), Tex2F( 1.0, -1.0) }; V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount); V2F_C4B_T2F_Triangle triangle0 = {a, b, c}; V2F_C4B_T2F_Triangle triangle1 = {a, c, d}; triangles[0] = triangle0; triangles[1] = triangle1; _bufferCount += vertex_count; _dirty = true; } void DrawNode::drawRect(const Vec2 &p1, const Vec2 &p2, const Vec2 &p3, const Vec2& p4, const Color4F &color) { drawLine(p1, p2, color); drawLine(p2, p3, color); drawLine(p3, p4, color); drawLine(p4, p1, color); } void DrawNode::drawSegment(const Vec2 &from, const Vec2 &to, float radius, const Color4F &color) { unsigned int vertex_count = 6*3; ensureCapacity(vertex_count); Vec2 a = from; Vec2 b = to; Vec2 n = ((b - a).getPerp()).getNormalized(); Vec2 t = n.getPerp(); Vec2 nw = n * radius; Vec2 tw = t * radius; Vec2 v0 = b - (nw + tw); Vec2 v1 = b + (nw - tw); Vec2 v2 = b - nw; Vec2 v3 = b + nw; Vec2 v4 = a - nw; Vec2 v5 = a + nw; Vec2 v6 = a - (nw - tw); Vec2 v7 = a + (nw + tw); V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount); V2F_C4B_T2F_Triangle triangles0 = { {v0, Color4B(color), v2ToTex2F(-(n + t))}, {v1, Color4B(color), v2ToTex2F(n - t)}, {v2, Color4B(color), v2ToTex2F(-n)}, }; triangles[0] = triangles0; V2F_C4B_T2F_Triangle triangles1 = { {v3, Color4B(color), v2ToTex2F(n)}, {v1, Color4B(color), v2ToTex2F(n - t)}, {v2, Color4B(color), v2ToTex2F(-n)}, }; triangles[1] = triangles1; V2F_C4B_T2F_Triangle triangles2 = { {v3, Color4B(color), v2ToTex2F(n)}, {v4, Color4B(color), v2ToTex2F(-n)}, {v2, Color4B(color), v2ToTex2F(-n)}, }; triangles[2] = triangles2; V2F_C4B_T2F_Triangle triangles3 = { {v3, Color4B(color), v2ToTex2F(n)}, {v4, Color4B(color), v2ToTex2F(-n)}, {v5, Color4B(color), v2ToTex2F(n) }, }; triangles[3] = triangles3; V2F_C4B_T2F_Triangle triangles4 = { {v6, Color4B(color), v2ToTex2F(t - n)}, {v4, Color4B(color), v2ToTex2F(-n) }, {v5, Color4B(color), v2ToTex2F(n)}, }; triangles[4] = triangles4; V2F_C4B_T2F_Triangle triangles5 = { {v6, Color4B(color), v2ToTex2F(t - n)}, {v7, Color4B(color), v2ToTex2F(t + n)}, {v5, Color4B(color), v2ToTex2F(n)}, }; triangles[5] = triangles5; _bufferCount += vertex_count; _dirty = true; } void DrawNode::drawPolygon(const Vec2 *verts, int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) { CCASSERT(count >= 0, "invalid count value"); bool outline = (borderColor.a > 0.0f && borderWidth > 0.0f); auto triangle_count = outline ? (3*count - 2) : (count - 2); auto vertex_count = 3*triangle_count; ensureCapacity(vertex_count); V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount); V2F_C4B_T2F_Triangle *cursor = triangles; cursor = Triangulate::processTriangles(verts,cursor,count,fillColor); if(outline) { struct ExtrudeVerts {Vec2 offset, n;}; ExtrudeVerts* extrude = (ExtrudeVerts *)malloc(sizeof(ExtrudeVerts) * count); for (int i = 0; i < count; i++) { Vec2 v0 = verts[(i-1+count)%count]; Vec2 v1 = verts[i]; Vec2 v2 = verts[(i+1)%count]; Vec2 n1 = ((v1 - v0).getPerp()).getNormalized(); Vec2 n2 = ((v2 - v1).getPerp()).getNormalized(); Vec2 offset = (n1 + n2) * (1.0f / (Vec2::dot(n1, n2) + 1.0f)); extrude[i] = {offset, n2}; } for(int i = 0; i < count; i++) { int j = (i+1)%count; Vec2 v0 = verts[i]; Vec2 v1 = verts[j]; Vec2 n0 = extrude[i].n; Vec2 offset0 = extrude[i].offset; Vec2 offset1 = extrude[j].offset; Vec2 inner0 = v0 - offset0 * borderWidth; Vec2 inner1 = v1 - offset1 * borderWidth; Vec2 outer0 = v0 + offset0 * borderWidth; Vec2 outer1 = v1 + offset1 * borderWidth; V2F_C4B_T2F_Triangle tmp1 = { {inner0, Color4B(borderColor), v2ToTex2F(-n0)}, {inner1, Color4B(borderColor), v2ToTex2F(-n0)}, {outer1, Color4B(borderColor), v2ToTex2F(n0)} }; *cursor++ = tmp1; V2F_C4B_T2F_Triangle tmp2 = { {inner0, Color4B(borderColor), v2ToTex2F(-n0)}, {outer0, Color4B(borderColor), v2ToTex2F(n0)}, {outer1, Color4B(borderColor), v2ToTex2F(n0)} }; *cursor++ = tmp2; } free(extrude); } _bufferCount += vertex_count; _dirty = true; } void DrawNode::drawSolidRect(const Vec2 &origin, const Vec2 &destination, const Color4F &color) { Vec2 vertices[] = { origin, Vec2(destination.x, origin.y), destination, Vec2(origin.x, destination.y) }; drawSolidPoly(vertices, 4, color); } void DrawNode::drawSolidPoly(const Vec2 *poli, unsigned int numberOfPoints, const Color4F &color) { drawPolygon(poli, numberOfPoints, color, 0.0, Color4F()); } void DrawNode::drawSolidCircle(const Vec2& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY, const Color4F &color) { const float coef = 2.0f * (float)M_PI/segments; Vec2 *vertices = new (std::nothrow) Vec2[segments]; if( ! vertices ) return; for(unsigned int i = 0;i < segments; i++) { float rads = i*coef; GLfloat j = radius * cosf(rads + angle) * scaleX + center.x; GLfloat k = radius * sinf(rads + angle) * scaleY + center.y; vertices[i].x = j; vertices[i].y = k; } drawSolidPoly(vertices, segments, color); CC_SAFE_DELETE_ARRAY(vertices); } void DrawNode::drawSolidCircle( const Vec2& center, float radius, float angle, unsigned int segments, const Color4F& color) { drawSolidCircle(center, radius, angle, segments, 1.0f, 1.0f, color); } void DrawNode::drawTriangle(const Vec2 &p1, const Vec2 &p2, const Vec2 &p3, const Color4F &color) { unsigned int vertex_count = 3; ensureCapacity(vertex_count); Color4B col = Color4B(color); V2F_C4B_T2F a = {p1, col, Tex2F(0.0, 0.0) }; V2F_C4B_T2F b = {p2, col, Tex2F(0.0, 0.0) }; V2F_C4B_T2F c = {p3, col, Tex2F(0.0, 0.0) }; V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount); V2F_C4B_T2F_Triangle triangle = {a, b, c}; triangles[0] = triangle; _bufferCount += vertex_count; _dirty = true; } void DrawNode::drawQuadraticBezier(const Vec2& from, const Vec2& control, const Vec2& to, unsigned int segments, const Color4F &color) { drawQuadBezier(from, control, to, segments, color); } void DrawNode::clear() { _bufferCount = 0; _dirty = true; _bufferCountGLLine = 0; _dirtyGLLine = true; _bufferCountGLPoint = 0; _dirtyGLPoint = true; _lineWidth = _defaultLineWidth; } const BlendFunc& DrawNode::getBlendFunc() const { return _blendFunc; } void DrawNode::setBlendFunc(const BlendFunc &blendFunc) { _blendFunc = blendFunc; } void DrawNode::setLineWidth(GLfloat lineWidth) { _lineWidth = lineWidth; } GLfloat DrawNode::getLineWidth() { return this->_lineWidth; } void DrawNode::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags) { if (_isolated) { //ignore `parentTransform` from parent Node::visit(renderer, Mat4::IDENTITY, parentFlags); } else { Node::visit(renderer, parentTransform, parentFlags); } } NS_CC_END
32.9501
168
0.64287
[ "vector", "transform" ]