hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
704c927c2bbd2973fbf5ae0ae6aaff4785688780
6,873
cpp
C++
XivAlexander/AutoLoadAsDependencyModule.cpp
retaker/XivAlexander
03b64118500c3e6e7c3a035af473ef2bd0303bff
[ "Apache-2.0" ]
345
2021-02-08T18:11:24.000Z
2022-03-25T04:01:23.000Z
XivAlexander/AutoLoadAsDependencyModule.cpp
retaker/XivAlexander
03b64118500c3e6e7c3a035af473ef2bd0303bff
[ "Apache-2.0" ]
376
2021-02-12T07:23:57.000Z
2022-03-31T00:05:35.000Z
XivAlexander/AutoLoadAsDependencyModule.cpp
retaker/XivAlexander
03b64118500c3e6e7c3a035af473ef2bd0303bff
[ "Apache-2.0" ]
65
2021-02-12T05:47:14.000Z
2022-03-25T03:08:23.000Z
#include "pch.h" #define DIRECTINPUT_VERSION 0x0800 // NOLINT(cppcoreguidelines-macro-usage) #include <dinput.h> #include <XivAlexander/XivAlexander.h> #include <XivAlexanderCommon/Sqex_CommandLine.h> #include <XivAlexanderCommon/Utils_Win32.h> #include "App_ConfigRepository.h" #include "DllMain.h" static WORD s_wLanguage = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL); static Utils::Win32::LoadedModule EnsureOriginalDependencyModule(const char* szDllName, std::filesystem::path originalDllPath); static std::set<std::filesystem::path> s_ignoreDlls; static bool s_useSystemDll = false; template<typename T_Fn, typename Ret> Ret ChainCall(const char* szDllName, const char* szFunctionName, std::vector<std::filesystem::path> chainLoadDlls, std::function<Ret(T_Fn, bool discardImmediately)> cb) { const auto systemDll = Utils::Win32::GetSystem32Path() / szDllName; if (s_useSystemDll) { chainLoadDlls.clear(); } else { std::vector<std::filesystem::path> temp; for (auto& path : chainLoadDlls) if (!path.empty()) temp.emplace_back(App::Config::Config::TranslatePath(path)); chainLoadDlls = std::move(temp); } if (chainLoadDlls.empty()) chainLoadDlls.emplace_back(systemDll); for (size_t i = 0; i < chainLoadDlls.size(); ++i) { const auto& dll = chainLoadDlls[i]; const auto isLast = i == chainLoadDlls.size() - 1; if (s_ignoreDlls.find(dll) != s_ignoreDlls.end()) continue; try { const auto mod = Utils::Win32::LoadedModule(dll); const auto pOriginalFunction = EnsureOriginalDependencyModule(szDllName, dll).GetProcAddress<T_Fn>(szFunctionName, true); mod.SetPinned(); if (isLast) return cb(pOriginalFunction, !isLast); else cb(pOriginalFunction, !isLast); } catch (const std::exception& e) { const auto activationContextCleanup = Dll::ActivationContext().With(); const auto choice = Dll::MessageBoxF( Dll::FindGameMainWindow(false), MB_ICONWARNING | MB_ABORTRETRYIGNORE, L"Failed to load {}.\nReason: {}\n\nPress Abort to exit.\nPress Retry to keep on loading.\nPress Ignore to skip right ahead to system DLL.", dll, e.what()); switch (choice) { case IDRETRY: s_ignoreDlls.insert(dll); return ChainCall(szDllName, szFunctionName, std::move(chainLoadDlls), cb); case IDIGNORE: s_useSystemDll = true; chainLoadDlls = {systemDll}; i = static_cast<size_t>(-1); break; case IDABORT: TerminateProcess(GetCurrentProcess(), -1); } } if (isLast && std::ranges::find(chainLoadDlls, systemDll) == chainLoadDlls.end()) chainLoadDlls.emplace_back(systemDll); } const auto activationContextCleanup = Dll::ActivationContext().With(); Dll::MessageBoxF( Dll::FindGameMainWindow(false), MB_ICONERROR, L"Failed to load any of the possible {}. Aborting.", szDllName); TerminateProcess(GetCurrentProcess(), -1); ExitProcess(-1); // Mark noreturn } #if INTPTR_MAX == INT64_MAX #include <d3d11.h> #include <dxgi1_3.h> HRESULT WINAPI FORWARDER_D3D11CreateDevice( IDXGIAdapter* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT Flags, const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT SDKVersion, ID3D11Device** ppDevice, D3D_FEATURE_LEVEL* pFeatureLevel, ID3D11DeviceContext** ppImmediateContext ) { return ChainCall<decltype(&D3D11CreateDevice), HRESULT>("d3d11.dll", "D3D11CreateDevice", App::Config::Acquire()->Runtime.ChainLoadPath_d3d11.Value(), [&](auto pfn, auto discardImmediately) { const auto res = pfn(pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext); if (res == S_OK && discardImmediately) { if (ppDevice) (*ppDevice)->Release(); if (ppImmediateContext) (*ppImmediateContext)->Release(); } return res; }); } HRESULT WINAPI FORWARDER_CreateDXGIFactory( REFIID riid, IDXGIFactory** ppFactory ) { return ChainCall<decltype(&CreateDXGIFactory), HRESULT>("dxgi.dll", "CreateDXGIFactory", App::Config::Acquire()->Runtime.ChainLoadPath_dxgi.Value(), [&](auto pfn, auto discardImmediately) { const auto res = pfn(riid, reinterpret_cast<void**>(ppFactory)); if (res == S_OK && discardImmediately) { if (ppFactory) (*ppFactory)->Release(); } return res; }); } HRESULT WINAPI FORWARDER_CreateDXGIFactory1( REFIID riid, IDXGIFactory1** ppFactory ) { return ChainCall<decltype(&CreateDXGIFactory1), HRESULT>("dxgi.dll", "CreateDXGIFactory1", App::Config::Acquire()->Runtime.ChainLoadPath_dxgi.Value(), [&](auto pfn, auto discardImmediately) { const auto res = pfn(riid, reinterpret_cast<void**>(ppFactory)); if (res == S_OK && discardImmediately) { if (ppFactory) (*ppFactory)->Release(); } return res; }); } HRESULT WINAPI FORWARDER_CreateDXGIFactory2( UINT Flags, REFIID riid, IDXGIFactory2** ppFactory ) { return ChainCall<decltype(&CreateDXGIFactory2), HRESULT>("dxgi.dll", "CreateDXGIFactory1", App::Config::Acquire()->Runtime.ChainLoadPath_dxgi.Value(), [&](auto pfn, auto discardImmediately) { const auto res = pfn(Flags, riid, reinterpret_cast<void**>(ppFactory)); if (res == S_OK && discardImmediately) { if (ppFactory) (*ppFactory)->Release(); } return res; }); } #elif INTPTR_MAX == INT32_MAX #include <d3d9.h> void WINAPI FORWARDER_D3DPERF_SetOptions(DWORD dwOptions) { return ChainCall<decltype(&D3DPERF_SetOptions), void>("d3d9.dll", "D3DPERF_SetOptions", App::Config::Acquire()->Runtime.ChainLoadPath_d3d9.Value(), [&](auto pfn, auto discardImmediately) { pfn(dwOptions); }); } IDirect3D9* WINAPI FORWARDER_Direct3DCreate9(UINT SDKVersion) { return ChainCall<decltype(&Direct3DCreate9), IDirect3D9*>("d3d9.dll", "Direct3DCreate9", App::Config::Acquire()->Runtime.ChainLoadPath_d3d9.Value(), [&](auto pfn, auto discardImmediately) { const auto res = pfn(SDKVersion); if (res && discardImmediately) res->Release(); return res; }); } #endif HRESULT WINAPI FORWARDER_DirectInput8Create( HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, IUnknown** ppvOut, LPUNKNOWN punkOuter ) { return ChainCall<decltype(&DirectInput8Create), HRESULT>("dinput8.dll", "DirectInput8Create", App::Config::Acquire()->Runtime.ChainLoadPath_dinput8.Value(), [&](auto pfn, auto discardImmediately) { const auto res = pfn(hinst, dwVersion, riidltf, reinterpret_cast<void**>(ppvOut), punkOuter); if (res == S_OK && discardImmediately) { if (ppvOut) (*ppvOut)->Release(); } return res; }); } static Utils::Win32::LoadedModule EnsureOriginalDependencyModule(const char* szDllName, std::filesystem::path originalDllPath) { static std::mutex preventDuplicateLoad; std::lock_guard lock(preventDuplicateLoad); if (originalDllPath.empty()) originalDllPath = Utils::Win32::GetSystem32Path() / szDllName; auto mod = Utils::Win32::LoadedModule(originalDllPath); mod.SetPinned(); return mod; }
32.419811
198
0.729521
retaker
704ec269c666e188c069d16a14b832138f56ff3c
21,254
cpp
C++
tests/ami_test/no_module/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tests/ami_test/no_module/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tests/ami_test/no_module/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file client.cpp * @author Marijke Hengstmengel * * @brief CORBA C++11 client ami test * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "ace/Get_Opt.h" #include "ace/Task.h" #include "ami_testAmiC.h" #include <thread> #include "testlib/taox11_testlog.h" const ACE_TCHAR *ior = ACE_TEXT("file://server.ior"); int16_t result = 0; int16_t callback_attrib = 0; int16_t callback_operation = 0; int16_t callback_attrib_der = 0; int16_t callback_operation_der = 0; int16_t callback_excep = 0; // Flag indicates that all replies have been received static int16_t received_all_replies = 0; bool parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'k': ior = get_opts.opt_arg (); break; case '?': default: TAOX11_TEST_ERROR << "usage: -k <ior>" << std::endl; return false; } // Indicates successful parsing of the command line return true; } class Handler : public virtual CORBA::amic_traits<MyFoo>::replyhandler_base_type { public: /// Constructor. Handler () = default; /// Destructor. ~Handler () = default; void foo (int32_t ami_return_val, int32_t out_l) override { TAOX11_TEST_INFO << "Callback method <Handler::foo> called: result <" << ami_return_val << ">, out_arg <" << out_l << ">"<< std::endl; callback_operation++; // Last reply flips the flag. if (out_l == 931235) { received_all_replies = 1; } else if (out_l != 931233) { TAOX11_TEST_ERROR <<"ERROR: method <Handler::foo> out_l not 931233: " << out_l << std::endl; result = 1; } if (ami_return_val != 931234) { TAOX11_TEST_ERROR << "ERROR: method <Handler::foo> ami_return_val not 931234: " << ami_return_val << std::endl; result = 1; } } void foo_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override { TAOX11_TEST_INFO << "Callback method <foo_excep> called:" << " Testing proper exception handling."<< std::endl; callback_excep++; try { excep_holder->raise_exception (); } catch (const DidTheRightThing& ex) { TAOX11_TEST_INFO << "Callback method <Handler::foo_excep> received successfully <" << ex.id() << "> and <" << ex.whatDidTheRightThing() << ">." << std::endl; if (ex.id() != 42) { TAOX11_TEST_ERROR << "ERROR: method <Handler::foo_excep> ex.id not 42 but " << ex.id() << std::endl; result = 1; } if (ex.whatDidTheRightThing () != "Hello world") { TAOX11_TEST_ERROR << "ERROR: method <Handler::foo_excep> ex.whatDidTheRightThing not ok: " << ex.whatDidTheRightThing() << std::endl; result = 1; } } catch (const CORBA::Exception&) { TAOX11_TEST_ERROR << "Callback method <Handler::foo_excep> " << "caught the wrong exception -> ERROR" << std::endl; result = 1; } } void get_yadda (int32_t ret) override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <Handler::get_yadda> called: ret " << ret << std::endl; }; void get_yadda_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override { callback_excep++; TAOX11_TEST_INFO << "Callback method <Handler::get_yadda_excep> called:" << std::endl; try { excep_holder->raise_exception (); } catch (const CORBA::Exception& ex) { TAOX11_TEST_INFO << "... caught expected exception -> " << ex << std::endl; std::stringstream excep_c; excep_c << ex; std::string excep_cstr = excep_c.str(); if (excep_cstr.find ("NO_IMPLEMENT") == std::string::npos) { TAOX11_TEST_ERROR << "ERROR: Callback method <Handler::get_yadda_excep>" << " returned wrong CORBA::exception! -" << excep_cstr << std::endl; result = 1; } } } void set_yadda () override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <Handler::set_yadda> called:"<< std::endl; } void set_yadda_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override { TAOX11_TEST_INFO << "Callback method <Handler::set_yadda_excep> called:" << std::endl; callback_excep++; try { excep_holder->raise_exception (); } catch (const CORBA::Exception& ex) { TAOX11_TEST_INFO << "... caught expected exception -> " << ex << std::endl; std::stringstream excep_s; excep_s << ex; std::string excep_str = excep_s.str(); if (excep_str.find ("NO_IMPLEMENT") == std::string::npos) { TAOX11_TEST_ERROR << "ERROR: Callback method <Handler::set_yadda_excep> " << "returned wrong std::exception info! -" << excep_str << std::endl; result = 1; } } } void get_bool_attr (bool result) override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <Handler::get_bool_attr> called:" << result << std::endl; }; void get_bool_attr_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override { TAOX11_TEST_INFO << "Callback method <Handler::get_bool_attr_excep> called:" << std::endl; callback_excep++; try { excep_holder->raise_exception (); } catch (const DidTheRightThing& ex) { TAOX11_TEST_INFO << "Callback method <Handler::get_bool_attr_excep> exception" << "received successfully <" << ex.id() << "> and <" << ex.whatDidTheRightThing() << ">."<< std::endl; if (ex.id() != 42) { TAOX11_TEST_ERROR << "ERROR: ex.id not 42 but "<< ex.id() << std::endl; result = 1; } if (ex.whatDidTheRightThing () != "Hello world") { TAOX11_TEST_ERROR << "ERROR: method <Handler::get_bool_attr_excep> " << "ex.whatDidTheRightThing not ok: " << ex.whatDidTheRightThing() << std::endl; result = 1; } } catch (const CORBA::Exception&) { TAOX11_TEST_ERROR << "Callback method <Handler::get_bool_attr_excep> " << "caught the wrong exception -> ERROR" << std::endl; } } void set_bool_attr () override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <Handler::set_bool_attr> called:" << std::endl; } void set_bool_attr_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override { callback_excep++; TAOX11_TEST_INFO << "Callback method <Handler::set_bool_attr_excep> called:" << std::endl; } void foo_struct ( const std::string& ami_return_val, const structType& t) override { callback_operation++; TAOX11_TEST_INFO << "Callback method <fHandler::oo_struct> called: t.as = " << t.as() << " return = <" << ami_return_val << ">" << std::endl; if ((t.as() != 5) || (ami_return_val != "bye from foo_struct")) { TAOX11_TEST_ERROR << "ERROR: ami_return_val not 'bye from foo_struct' but '" << ami_return_val << "' or t.as not <5> but <" << t.as() << ">" << std::endl; result = 1; } } void foo_struct_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override { } }; class DerivedHandler : public virtual CORBA::amic_traits<A::MyDerived>::replyhandler_base_type { public: /// Constructor. DerivedHandler () = default; /// Destructor. ~DerivedHandler () = default; void do_something (int32_t ami_return_val) override { callback_operation_der++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::do_something> called." << std::endl; if (ami_return_val != 4) { TAOX11_TEST_ERROR << "ERROR: method <DerivedHandler::do_something> ami_return_val not 4: " << ami_return_val << std::endl; result = 1; } } void do_something_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::do_someting_excep> called." << std::endl; } void get_my_derived_attrib (int32_t ret) override { callback_attrib_der++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_my_derived_attrib> called: ret " << ret << std::endl; if (ret != 5) { TAOX11_TEST_ERROR << "ERROR: method <DerivedHandler::get_my_derived_attrib ret not 5: " << ret << std::endl; result = 1; } } void get_my_derived_attrib_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_my_derived_attrib_excep> called." << std::endl; } void set_my_derived_attrib () override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_my_derived_attrib> called." << std::endl; } void set_my_derived_attrib_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_my_derived_attrib_excep> called:" << std::endl; } void foo (int32_t ami_return_val,int32_t out_l) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::foo> called: result <" << ami_return_val << ">, out_arg <" << out_l << ">"<< std::endl; } void foo_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::foo_excep> called:" << " Testing proper exception handling."<< std::endl; } void get_yadda (int32_t ret) override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_yadda> called: ret " << ret << std::endl; }; void get_yadda_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override { callback_excep++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_yadda_excep> called:"<< std::endl; } void set_yadda () override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_yadda> called:"<< std::endl; } void set_yadda_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_yadda_excep> called:" << std::endl; callback_excep++; } void get_bool_attr (bool result) override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_bool_attr> called:" << result << std::endl; }; void get_bool_attr_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override { TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_bool_attr_excep> called:" << std::endl; callback_excep++; } void set_bool_attr () override { callback_attrib++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_bool_attr> called:" << std::endl; } void set_bool_attr_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override { callback_excep++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_bool_attr_excep> called:" << std::endl; } void foo_struct ( const std::string& ami_return_val, const structType& t) override { callback_operation++; TAOX11_TEST_INFO << "Callback method <DerivedHandler::foo_struct> called: t.as = " << t.as() << " return = <" << ami_return_val << ">" << std::endl; } void foo_struct_excep ( IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override { } }; int main(int argc, char* argv[]) { try { IDL::traits<CORBA::ORB>::ref_type _orb = CORBA::ORB_init (argc, argv); if (_orb == nullptr) { TAOX11_TEST_ERROR << "ERROR: CORBA::ORB_init (argc, argv) returned null ORB." << std::endl; return 1; } if (parse_args (argc, argv) == false) return 1; IDL::traits<CORBA::Object>::ref_type obj = _orb->string_to_object (ior); if (!obj) { TAOX11_TEST_ERROR << "ERROR: string_to_object(<ior>) returned null reference." << std::endl; return 1; } IDL::traits<Hello>::ref_type ami_test_var = IDL::traits<Hello>::narrow (obj); if (!ami_test_var) { TAOX11_TEST_ERROR << "ERROR: IDL::traits<Hello>::narrow (obj) returned null object." << std::endl; return 1; } TAOX11_TEST_INFO << "narrowed Hello interface" << std::endl; // Instantiate the ReplyHandler and register that with the POA. IDL::traits<CORBA::Object>::ref_type poa_obj = _orb->resolve_initial_references ("RootPOA"); if (!poa_obj) { TAOX11_TEST_ERROR << "ERROR: resolve_initial_references (\"RootPOA\") returned null reference." << std::endl; return 1; } TAOX11_TEST_INFO << "retrieved RootPOA object reference" << std::endl; IDL::traits<PortableServer::POA>::ref_type root_poa = IDL::traits<PortableServer::POA>::narrow (poa_obj); if (!root_poa) { TAOX11_TEST_ERROR << "ERROR: IDL::traits<PortableServer::POA>::narrow (obj)" <<" returned null object." << std::endl; return 1; } TAOX11_TEST_INFO << "narrowed POA interface" << std::endl; IDL::traits<PortableServer::POAManager>::ref_type poaman = root_poa->the_POAManager (); if (!poaman) { TAOX11_TEST_ERROR << "ERROR: root_poa->the_POAManager () returned null object." << std::endl; return 1; } CORBA::amic_traits<MyFoo>::replyhandler_servant_ref_type test_handler_impl = CORBA::make_reference<Handler> (); TAOX11_TEST_INFO << "created MyFoo replyhandler servant" << std::endl; PortableServer::ObjectId id = root_poa->activate_object (test_handler_impl); TAOX11_TEST_INFO << "activated MyFoo replyhandler servant" << std::endl; IDL::traits<CORBA::Object>::ref_type test_handler_obj = root_poa->id_to_reference (id); if (test_handler_obj == nullptr) { TAOX11_TEST_ERROR << "ERROR: root_poa->id_to_reference (id) returned null reference." << std::endl; return 1; } CORBA::amic_traits<MyFoo>::replyhandler_ref_type test_handler = CORBA::amic_traits<MyFoo>::replyhandler_traits::narrow (test_handler_obj); if (test_handler == nullptr) { TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<MyFoo>::replyhandler_traits::narrow" << " (test_handler_obj) returned null reference." << std::endl; return 1; } CORBA::amic_traits<A::MyDerived>::replyhandler_servant_ref_type test_handler_der_impl = CORBA::make_reference<DerivedHandler> (); TAOX11_TEST_INFO << "created MyDerived replyhandler servant" << std::endl; PortableServer::ObjectId id_der = root_poa->activate_object (test_handler_der_impl); TAOX11_TEST_INFO << "activated MyDerived replyhandler servant" << std::endl; IDL::traits<CORBA::Object>::ref_type test_handler_der_obj = root_poa->id_to_reference (id_der); if (test_handler_der_obj == nullptr) { TAOX11_TEST_ERROR << "ERROR: root_poa->id_to_reference (id_der) returned null reference." << std::endl; return 1; } CORBA::amic_traits<A::MyDerived>::replyhandler_ref_type test_handler_der = CORBA::amic_traits<A::MyDerived>::replyhandler_traits::narrow (test_handler_der_obj); if (test_handler_der == nullptr) { TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<A::MyDerived>::replyhandler_traits::narrow" << " (test_handler_obj) returned null reference." << std::endl; return 1; } poaman->activate (); A::MyDerived::_ref_type i_der_ref = ami_test_var->get_iMyDerived(); if (!i_der_ref) { TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyDerived returned null object." << std::endl; return 1; } CORBA::amic_traits<A::MyDerived>::ref_type i_der = CORBA::amic_traits<A::MyDerived>::narrow (i_der_ref); if (!i_der) { TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<A::MyDerived>::narrow (i_der) " << "returned null object." << std::endl; return 1; } MyFoo::_ref_type i_foo_ref = ami_test_var->get_iMyFoo(); if (!i_foo_ref) { TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyFoo returned null object." << std::endl; return 1; } CORBA::amic_traits<MyFoo>::ref_type i_foo = CORBA::amic_traits<MyFoo>::narrow (i_foo_ref); if (!i_foo) { TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<MyFoo>::narrow (i_foo) " << " returned null object." << std::endl; return 1; } // Trigger the DidTheRightThing exception on the server side // by sending 0 to it. TAOX11_TEST_INFO << "Client: Sending asynch message sendc_foo to trigger an exception" << std::endl; i_foo->sendc_foo (test_handler, 0, "Let's talk AMI."); int32_t l = 931247; TAOX11_TEST_INFO << "Client: Sending asynch message foo." << std::endl; i_foo->sendc_foo (test_handler, l, "Let's talk AMI."); i_der->sendc_do_something(test_handler_der, "Hello"); // Begin test of attributes TAOX11_TEST_INFO << "Client: Sending asynch message sendc_get_yadda to trigger " << "an exception" << std::endl; i_foo->sendc_get_yadda (test_handler); TAOX11_TEST_INFO << "Client: Sending asynch attributes yadda." << std::endl; i_foo->sendc_set_yadda (test_handler, 4711); i_foo->sendc_get_yadda (test_handler); TAOX11_TEST_INFO << "Client: Sending asynch message sendc_set_yadda to trigger " << "an exception" << std::endl; i_foo->sendc_set_yadda (test_handler, 0); TAOX11_TEST_INFO << "Client: Sending asynch message sendc_get_bool_attr to trigger " << "an exception" << std::endl; i_foo->sendc_get_bool_attr (test_handler); TAOX11_TEST_INFO << "Client: Sending asynch attributes bool_attr." << std::endl; i_foo->sendc_set_bool_attr (test_handler, false); i_foo->sendc_get_bool_attr (test_handler); TAOX11_TEST_INFO << "Client: Sending asynch message sendc_set_yadda to trigger " << "an exception" << std::endl; i_foo->sendc_set_bool_attr (test_handler, true); i_der->sendc_get_my_derived_attrib (test_handler_der); // End test of attributes i_foo->sendc_foo_struct (test_handler); TAOX11_TEST_INFO << "Client: Sending another asynch message foo." << std::endl; i_foo->sendc_foo (test_handler, l, "Let's talk AMI."); TAOX11_TEST_INFO << "Client: Sending the last asynch message foo." << std::endl; i_foo->sendc_foo (test_handler, 931235, "Let's talk AMI the last time."); TAOX11_TEST_INFO << "Client: Do something else before coming back for the replies." << std::endl; for (int i = 0; i < 10; i ++) { TAOX11_TEST_INFO << " ..."; std::this_thread::sleep_for (std::chrono::milliseconds (10)); } TAOX11_TEST_INFO << std::endl << "Client: Now let's look for the replies." << std::endl; std::this_thread::sleep_for (std::chrono::seconds (2)); while (!received_all_replies) { std::chrono::seconds tv (1); _orb->perform_work (tv); } if ((callback_operation != 4) || (callback_excep != 5 ) || (callback_attrib != 4 ) || (callback_attrib_der != 1 ) || (callback_operation_der != 1 )) { TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected callbacks." << " Foo : expected -4- , received -" << callback_operation << "-" << " do_something : expected -1- , received -" << callback_operation_der << "-" << " Attrib : expected -4-, received -" << callback_attrib << "-" << " Attrib derived : expected -1-, received -" << callback_attrib_der << "-" << " Exceptions: expected -5-, received -" << callback_excep << "-." << std::endl; result = 1; } ami_test_var->shutdown (); _orb->destroy (); } catch (const std::exception& e) { TAOX11_TEST_ERROR << "exception caught: " << e << std::endl; return 1; } return result; }
30.362857
100
0.605063
ClausKlein
7050f2e5980ace3eb9362d575e23d51924b74e39
598
cc
C++
core/src/counter.cc
avidbots/prometheus-cpp
e7b542c3bd5e68d5377641dd7a90b1a4a9146b0b
[ "MIT" ]
null
null
null
core/src/counter.cc
avidbots/prometheus-cpp
e7b542c3bd5e68d5377641dd7a90b1a4a9146b0b
[ "MIT" ]
2
2020-09-29T14:55:30.000Z
2021-06-08T16:40:42.000Z
core/src/counter.cc
avidbots/prometheus-cpp
e7b542c3bd5e68d5377641dd7a90b1a4a9146b0b
[ "MIT" ]
null
null
null
#include "prometheus/counter.h" namespace prometheus { Counter::Counter(const bool alert_if_no_family) : MetricBase(alert_if_no_family) {}; void Counter::Reset() { value_ = 0; last_update_ = std::time(nullptr); AlertIfNoFamily(); } void Counter::Increment(const double value) { if (value < 0.0) return; value_ = value_ + value; last_update_ = std::time(nullptr); AlertIfNoFamily(); } double Counter::Value() const { return value_; } ClientMetric Counter::Collect() const { ClientMetric metric; metric.counter.value = Value(); return metric; } } // namespace prometheus
19.933333
84
0.70903
avidbots
7056d48b5554f5390c94686c59484a028f902958
705
hpp
C++
food.hpp
cwink87/wsnake
6d4f3a42d83f6b54312316302dd52cbd80370dd5
[ "MIT" ]
null
null
null
food.hpp
cwink87/wsnake
6d4f3a42d83f6b54312316302dd52cbd80370dd5
[ "MIT" ]
null
null
null
food.hpp
cwink87/wsnake
6d4f3a42d83f6b54312316302dd52cbd80370dd5
[ "MIT" ]
null
null
null
#ifndef FOOD_HPP #define FOOD_HPP #include "grid.hpp" class Food final { public: explicit Food(const Grid &grid) noexcept; ~Food() noexcept = default; Food(const Food &) noexcept = default; Food(Food &&) noexcept = default; Food &operator=(const Food &) noexcept = default; Food &operator=(Food &&) noexcept = default; auto x() const noexcept -> std::int32_t; auto y() const noexcept -> std::int32_t; private: struct Impl; std::shared_ptr<Impl> impl; }; auto draw(const Food &food, const Grid &grid, const Display &display, const std::uint8_t red, const std::uint8_t green, const std::uint8_t blue, const std::uint8_t alpha = 255) noexcept -> void; #endif // FOOD_HPP
25.178571
119
0.686525
cwink87
7058bd21523d751bcda72d9809aa839f0e9cca5f
18,574
cpp
C++
src/Details/xbmp_tools_atlas.cpp
LIONant-depot/xbmp_tools
670320ec35470b0204af8413bf34d017aa6e2868
[ "MIT" ]
null
null
null
src/Details/xbmp_tools_atlas.cpp
LIONant-depot/xbmp_tools
670320ec35470b0204af8413bf34d017aa6e2868
[ "MIT" ]
null
null
null
src/Details/xbmp_tools_atlas.cpp
LIONant-depot/xbmp_tools
670320ec35470b0204af8413bf34d017aa6e2868
[ "MIT" ]
null
null
null
namespace xbmp::tools{ //------------------------------------------------------------------------------------------------- static int Area( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB ) { int b1 = (*pA)->getArea(); int a1 = (*pB)->getArea(); if( a1 < b1 ) return -1; return a1>b1; } //------------------------------------------------------------------------------------------------- static int Perimeter( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB ) { int b1 = (*pA)->getPerimeter(); int a1 = (*pB)->getPerimeter(); if( a1 < b1 ) return -1; return a1>b1; } //------------------------------------------------------------------------------------------------- static int MaxSide( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB ) { int b1 = std::max( (*pA)->m_W, (*pA)->m_H ); int a1 = std::max( (*pB)->m_W, (*pB)->m_H ); if( a1 < b1 ) return -1; return a1>b1; } //------------------------------------------------------------------------------------------------- static int MaxWidth( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB ) { int b1 = (*pA)->m_W; int a1 = (*pB)->m_W; if( a1 < b1 ) return -1; return a1>b1; } //------------------------------------------------------------------------------------------------- static int MaxHeight( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB ) { int b1 = (*pA)->m_H; int a1 = (*pB)->m_H; if( a1 < b1 ) return -1; return a1>b1; } // just add another comparing function name to cmpf to perform another packing attempt // more functions == slower but probably more efficient cases covered and hence less area wasted constexpr static auto comparison_fn_v = std::array { Area, Perimeter, MaxSide, MaxWidth, MaxHeight }; // if you find the algorithm running too slow you may double this factor to increase speed but also decrease efficiency // 1 == most efficient, slowest // efficiency may be still satisfying at 64 or even 256 with nice speedup constexpr static int s_discard_step_v = 16; // For every sorting function, algorithm will perform packing attempts beginning with a bin with width // and height equal to max_side, and decreasing its dimensions if it finds out that rectangles did // actually fit, increasing otherwise. Although, it's doing that in sort of binary search manner, so // for every comparing function it will perform at most log2(max_side) packing attempts looking for // the smallest possible bin size. discard_step means that if the algorithm will break of the searching // loop if the rectangles fit but "it may be possible to fit them in a bin smaller by discard_step" // // may be pretty slow in debug mode anyway (std::vector and stuff like that in debug mode is always slow) // // the algorithm was based on http://www.blackpawn.com/texts/lightmaps/default.html // the algorithm reuses the node tree so it doesn't reallocate them between searching attempts // // // please let me know about bugs at <---- // [email protected] | // | // | // ps. I'm 16 so take this --------------- more than seriously, though I made some realtime tests // with packing several hundreds of rectangles every frame, no crashes, no memory leaks, good results // Thank you. struct node { struct pnode { node* m_pNode; bool m_Fill; pnode() : m_Fill(false), m_pNode( nullptr ) {} void setup( int L, int T, int R, int B ) { if( m_pNode ) { m_pNode->m_RC = atlas::rect_ltrb( L, T, R, B ); m_pNode->m_pID = nullptr; } else { m_pNode = new node(); m_pNode->setup( atlas::rect_ltrb( L, T, R, B ) ); } m_Fill = true; } }; pnode m_C[2]; atlas::rect_ltrb m_RC; atlas::rect_xywhf* m_pID; ~node() { if( m_C[0].m_pNode ) delete m_C[0].m_pNode; if( m_C[1].m_pNode ) delete m_C[1].m_pNode; } node( void ) { setup( atlas::rect_ltrb(0,0,0,0) ); } void setup( const atlas::rect_ltrb& RC ) { m_pID = nullptr; m_RC = RC; } void Reset( const atlas::rect_wh& R ) { m_pID = nullptr; m_RC = atlas::rect_ltrb( 0, 0, R.m_W, R.m_H ); DelCheck(); } void DelCheck( void ) { if( m_C[0].m_pNode ) { m_C[0].m_Fill = false; m_C[0].m_pNode->DelCheck(); } if( m_C[1].m_pNode ) { m_C[1].m_Fill = false; m_C[1].m_pNode->DelCheck(); } } node* Insert( atlas::rect_xywhf& ImageRect ) { if( m_C[0].m_pNode && m_C[0].m_Fill ) { node* pNewNode = m_C[0].m_pNode->Insert( ImageRect ); if( pNewNode ) return pNewNode; pNewNode = m_C[1].m_pNode->Insert( ImageRect ); return pNewNode; } if( m_pID ) return nullptr; int f = ImageRect.Fits( atlas::rect_xywh(m_RC) ); switch( f ) { case 0: return 0; case 1: ImageRect.m_bFlipped = false; break; case 2: ImageRect.m_bFlipped = true; break; case 3: m_pID = &ImageRect; ImageRect.m_bFlipped = false; return this; case 4: m_pID = &ImageRect; ImageRect.m_bFlipped = true; return this; } int iW = (ImageRect.m_bFlipped ? ImageRect.m_H : ImageRect.m_W); int iH = (ImageRect.m_bFlipped ? ImageRect.m_W : ImageRect.m_H); if( ( m_RC.getWidth() - iW) > ( m_RC.getHeight() - iH) ) { m_C[0].setup( m_RC.m_Left, m_RC.m_Top, m_RC.m_Left + iW, m_RC.m_Bottom ); m_C[1].setup( m_RC.m_Left + iW, m_RC.m_Top, m_RC.m_Right, m_RC.m_Bottom ); } else { m_C[0].setup( m_RC.m_Left, m_RC.m_Top, m_RC.m_Right, m_RC.m_Top + iH ); m_C[1].setup( m_RC.m_Left, m_RC.m_Top + iH, m_RC.m_Right, m_RC.m_Bottom ); } return m_C[0].m_pNode->Insert( ImageRect ); } }; //------------------------------------------------------------------------------------------------- static atlas::rect_wh TheRect2D( atlas::rect_xywhf* const* pV , atlas::pack_mode Mode , int n , int MaxS , xcore::vector<atlas::rect_xywhf*>& Succ , xcore::vector<atlas::rect_xywhf*>& UnSucc ) { node Root; const int nFuncs = 5; atlas::rect_xywhf** Order[ nFuncs ]; const int Multiple = (Mode == atlas::pack_mode::MULTIPLE_OF_4)?4:8; for( int f = 0; f < nFuncs; ++f ) { Order[f] = new atlas::rect_xywhf*[n]{}; std::memcpy( Order[f], pV, sizeof(atlas::rect_xywhf*) * n); std::qsort( (void*)Order[f], n, sizeof(atlas::rect_xywhf*), (int(*)(const void*, const void*))comparison_fn_v[f] ); } atlas::rect_wh MinBin = atlas::rect_wh( MaxS, MaxS ); int MinFunc = -1; int BestFunc = 0; int BestArea = 0; int TheArea = 0; bool bFail = false; int Step, Fit; for( int f = 0; f < nFuncs; ++f ) { pV = Order[f]; Step = MinBin.m_W / 2; Root.Reset( MinBin ); while(1) { if( Root.m_RC.getWidth() > MinBin.m_W ) { if( MinFunc > -1 ) break; TheArea = 0; Root.Reset( MinBin ); for( int i = 0; i < n; ++i ) { if( Root.Insert( *pV[i]) ) TheArea += pV[i]->getArea(); } bFail = true; break; } Fit = -1; for( int i = 0; i < n; ++i ) { if( !Root.Insert( *pV[i]) ) { Fit = 1; break; } } if( Fit == -1 && Step <= s_discard_step_v ) break; int OldW = Root.m_RC.getWidth(); int OldH = Root.m_RC.getHeight(); int NewW = OldW + Fit*Step; int NewH = OldH + Fit*Step; if( Mode == atlas::pack_mode::MULTIPLE_OF_4 || Mode == atlas::pack_mode::MULTIPLE_OF_8 ) { NewW = xcore::bits::Align( NewW, Multiple ); NewH = xcore::bits::Align( NewH, Multiple ); xassert( xcore::bits::Align( OldW, Multiple) == OldW ); xassert( xcore::bits::Align( OldH, Multiple) == OldH ); } else if( Mode == atlas::pack_mode::POWER_OF_TWO || Mode == atlas::pack_mode::POWER_OF_TWO_SQUARE ) { NewW = xcore::bits::RoundToNextPowOfTwo( NewW ); NewH = xcore::bits::RoundToNextPowOfTwo( NewH ); xassert( xcore::bits::RoundToNextPowOfTwo( OldW ) == OldW ); xassert( xcore::bits::RoundToNextPowOfTwo( OldH ) == OldH ); } // // Try to choose the search in the right dimension // if( Mode != atlas::pack_mode::ANY_SIZE ) { if( Fit == 1 ) { if( OldW < OldH ) NewH = OldH; else NewW = OldW; } else { if( OldW < OldH ) NewW = OldW; else NewH = OldH; } } // // For square sizes we need to pick the best dimension for all // if( Mode == atlas::pack_mode::POWER_OF_TWO_SQUARE ) { if( Fit == 1 ) { NewH = NewW = std::max( NewW, NewH ); } else { NewH = NewW = std::min( NewW, NewH ); } } // // Ok now we can change the size // Root.Reset( atlas::rect_wh( NewW, NewH ) ); // // Keep searching // Step /= 2; if( !Step ) Step = 1; } if( !bFail && ( MinBin.getArea() >= Root.m_RC.getArea()) ) { MinBin = atlas::rect_wh( Root.m_RC ); MinFunc = f; } else if( bFail && ( TheArea > BestArea) ) { BestArea = TheArea; BestFunc = f; } bFail = false; } pV = Order[ MinFunc == -1 ? BestFunc : MinFunc ]; int ClipX = 0, ClipY = 0; node* pRet; Root.Reset( MinBin ); for( int i = 0; i < n; ++i ) { pRet = Root.Insert( *pV[i]); if( pRet ) { pV[i]->m_X = pRet->m_RC.m_Left; pV[i]->m_Y = pRet->m_RC.m_Top; if( pV[i]->m_bFlipped ) { pV[i]->m_bFlipped = false; pV[i]->Flip(); } ClipX = std::max( ClipX, pRet->m_RC.m_Right ); ClipY = std::max( ClipY, pRet->m_RC.m_Bottom ); Succ.append() = pV[i]; } else { UnSucc.append() = pV[i]; pV[i]->m_bFlipped = false; } } for( int f = 0; f < nFuncs; ++f ) { delete Order[f]; } // Make sure that we do return a power of two texture if( Mode == atlas::pack_mode::POWER_OF_TWO || Mode == atlas::pack_mode::POWER_OF_TWO_SQUARE ) { return atlas::rect_wh( xcore::bits::RoundToNextPowOfTwo(ClipX), xcore::bits::RoundToNextPowOfTwo(ClipY) ); } else if( Mode == atlas::pack_mode::MULTIPLE_OF_4 || Mode == atlas::pack_mode::MULTIPLE_OF_8 ) { const int Multiple = (Mode == atlas::pack_mode::MULTIPLE_OF_4)?4:8; return atlas::rect_wh( xcore::bits::Align(ClipX, Multiple), xcore::bits::Align(ClipY,Multiple) ); } return atlas::rect_wh( (ClipX), (ClipY) ); } //------------------------------------------------------------------------------------------------- bool atlas::Pack( rect_xywhf* const* pV, int nRects, int MaxSize, xcore::vector<bin>& Bins, pack_mode Mode ) { rect_wh TheRect( MaxSize, MaxSize ); // make sure that all the rectangles fit in the given MaxSize for( int i = 0; i < nRects; ++i ) { if( !pV[i]->Fits(TheRect) ) return false; } // Create a double buffer array of pointers xcore::vector<rect_xywhf*> Vec[2]; xcore::vector<rect_xywhf*>* pVec[2] = { &Vec[0], &Vec[1] }; // Set one pointer per rectangle past by the user Vec[0].appendList( nRects ); // Initialize the firt array to zero std::memcpy( &Vec[0][0], pV, sizeof(rect_xywhf*) * nRects ); while(1) { bin& NewBin = Bins.append(); NewBin.m_Size = TheRect2D( &((*pVec[0])[0]), Mode, static_cast<int>(pVec[0]->size()), MaxSize, NewBin.m_Rects, *pVec[1] ); pVec[0]->clear(); if( pVec[1]->size() == 0 ) break; std::swap( pVec[0], pVec[1] ); } return true; } //------------------------------------------------------------------------------------------------- atlas::rect_wh::rect_wh(const rect_ltrb& rr) : m_W(rr.getWidth()), m_H(rr.getHeight()) {} atlas::rect_wh::rect_wh(const rect_xywh& rr) : m_W(rr.getWidth()), m_H(rr.getHeight()) {} atlas::rect_wh::rect_wh(int w, int h) : m_W(w), m_H(h) {} //------------------------------------------------------------------------------------------------- int atlas::rect_wh::Fits( const rect_wh& r ) const { if( m_W == r.m_W && m_H == r.m_H ) return 3; if( m_H == r.m_W && m_W == r.m_H ) return 4; if( m_W <= r.m_W && m_H <= r.m_H ) return 1; if( m_H <= r.m_W && m_W <= r.m_H ) return 2; return 0; } //------------------------------------------------------------------------------------------------- atlas::rect_ltrb::rect_ltrb( void ) : m_Left(0), m_Top(0), m_Right(0), m_Bottom(0) {} atlas::rect_ltrb::rect_ltrb( int l, int t, int r, int b) : m_Left(l), m_Top(t), m_Right(r), m_Bottom(b) {} //------------------------------------------------------------------------------------------------- int atlas::rect_ltrb::getWidth( void ) const { return m_Right - m_Left; } //------------------------------------------------------------------------------------------------- int atlas::rect_ltrb::getHeight( void ) const { return m_Bottom - m_Top; } //------------------------------------------------------------------------------------------------- int atlas::rect_ltrb::getArea( void ) const { return getWidth() * getHeight(); } //------------------------------------------------------------------------------------------------- int atlas::rect_ltrb::getPerimeter( void ) const { return 2*getWidth() + 2*getHeight(); } //------------------------------------------------------------------------------------------------- void atlas::rect_ltrb::setWidth( int Width ) { m_Right = m_Left + Width; } //------------------------------------------------------------------------------------------------- void atlas::rect_ltrb::setHeight( int Height ) { m_Bottom = m_Top + Height; } //------------------------------------------------------------------------------------------------- atlas::rect_xywh::rect_xywh( void ) : m_X(0), m_Y(0) {} atlas::rect_xywh::rect_xywh( const rect_ltrb& rc ) : m_X( rc.m_Left ), m_Y( rc.m_Top ) { m_H = rc.m_Bottom - rc.m_Top; m_W = rc.m_Right - rc.m_Left; } //------------------------------------------------------------------------------------------------- atlas::rect_xywh::rect_xywh( int x, int y, int w, int h ) : m_X(x), m_Y(y), rect_wh( w, h ) {} //------------------------------------------------------------------------------------------------- atlas::rect_xywh::operator atlas::rect_ltrb( void ) { rect_ltrb rr( m_X, m_Y, 0, 0 ); rr.setWidth ( m_W ); rr.setHeight( m_H ); return rr; } //------------------------------------------------------------------------------------------------- int atlas::rect_xywh::getRight( void ) const { return m_X + m_W; }; //------------------------------------------------------------------------------------------------- int atlas::rect_xywh::getBottom( void ) const { return m_Y + m_H; } //------------------------------------------------------------------------------------------------- void atlas::rect_xywh::setWidth( int Right ) { m_W = Right - m_X; } //------------------------------------------------------------------------------------------------- void atlas::rect_xywh::setHeight( int Bottom ) { m_H = Bottom - m_Y; } //------------------------------------------------------------------------------------------------- int atlas::rect_wh::getArea( void ) const { return m_W * m_H; } //------------------------------------------------------------------------------------------------- int atlas::rect_wh::getPerimeter( void ) const { return 2 * m_W + 2 * m_H; } //------------------------------------------------------------------------------------------------- atlas::rect_xywhf::rect_xywhf( const rect_ltrb& rr ) : rect_xywh(rr), m_bFlipped( false ) {} atlas::rect_xywhf::rect_xywhf( int x, int y, int width, int height ) : rect_xywh( x, y, width, height ), m_bFlipped( false ) {} atlas::rect_xywhf::rect_xywhf() : m_bFlipped( false ) {} //------------------------------------------------------------------------------------------------- void atlas::rect_xywhf::Flip( void ) { m_bFlipped = !m_bFlipped; std::swap( m_W, m_H ); } } // end of namespace xbmp::tools
31.750427
130
0.428233
LIONant-depot
705b97c5b3556c629ef061ce743bb0f610a7d684
33,769
cpp
C++
tcpclientcom/TCPClient.cpp
lasellers/IntrafoundationTCPClient
4e9b9666b914d229335ef534972a94594e93be2b
[ "Intel", "DOC", "NTP", "Unlicense" ]
null
null
null
tcpclientcom/TCPClient.cpp
lasellers/IntrafoundationTCPClient
4e9b9666b914d229335ef534972a94594e93be2b
[ "Intel", "DOC", "NTP", "Unlicense" ]
null
null
null
tcpclientcom/TCPClient.cpp
lasellers/IntrafoundationTCPClient
4e9b9666b914d229335ef534972a94594e93be2b
[ "Intel", "DOC", "NTP", "Unlicense" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // // Intrafoundation.Tcpclient.3 // // Copyright 1999, 200, 2001, 2003, 2004 by Lewis A. Sellers (AKA Min) // http://www.intrafoundation.com // [email protected] // // Software Homepage: http://www.intrafoundation.com/software/tcpclient.htm // // ///////////////////////////////////////////////////////////////////////////// // TCPClient.cpp : Implementation of CTcpclientcomApp and DLL registration. /* ORIGINAL 2.X: send stats secs kbps x 1 3636 277.56 x 2 1983 508.945 x 4 1202 839.63 x 8 741 1361.995 x 16 24755 40.76 x 64 2587 ----- x 128 318 x 256 704 x 512 1229 x 1024 969 recv stats secs kbps x 1 82909 12.17 x 2 42070 23.98 x 4 20449 48.19 x 8 10786 93.56 x 16 5548 181.91 x 32 349 x 64 618 (32768) ----------------- 32708 x 128 847 x 256 1185 x 512 1975 x 1024 2242 recv blocksize 30mb blocksize kbps 32768 639 22 262144 562 159 1048576 642 611 */ #if !defined(_MT) #error This software requires a multithreaded C run-time library. #endif // #include "stdafx.h" #include "tcpclientcom.h" #include "TCPClient.h" ///////////////////////////////////////////////////////////////////////////// // // _open file handling #include "io.h" #include <fcntl.h> //bstr #include <comdef.h> // _stat #include "sys\stat.h" // #define MAX_DWORDEXPANSION 32 #define MAX_IPEXPANSION (26+60) #define MAX_PORTEXPANSION (5+16) #define MAX_URLEXPANSION (26+60+1+5) // #include "Mutex.h" #include "Log.h" #include "BSTR.h" #include "ErrorStringWSA.h" #include "MD5.h" ///////////////////////////////////////////////////////////////////////////// // // const char *description="Intrafoundation.TCPClient.3"; const char *copyright="Copyright (c) 2000, 20001, 2003, 2004, 2012 by Lewis Sellers. <a href=\"http://www.intrafoundation.com\">http://intrafoundation.com</a>"; const char *version="3.2, August 30th 2012"; // TRUE and FALSE defined as ints to support old version of CF that don't understand boolean types. // Annoying. //const int TRUE=1; //const int FALSE=0; ///////////////////////////////////////////////////////////////////////////// // // /* statics */ int CTCPClient::m_last_instance=0; CMutex CTCPClient::mutex; /* */ unsigned _int64 CTCPClient::bitmask[64]={ 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff, 0x1ffff, 0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff, 0x1ffffffff, 0x3ffffffff, 0x7ffffffff, 0xfffffffff, 0x1fffffffff, 0x3fffffffff, 0x7fffffffff, 0xffffffffff, 0x1ffffffffff, 0x3ffffffffff, 0x7ffffffffff, 0xfffffffffff, 0x1fffffffffff, 0x3fffffffffff, 0x7fffffffffff, 0xffffffffffff, 0x1ffffffffffff, 0x3ffffffffffff, 0x7ffffffffffff, 0xfffffffffffff, 0x1fffffffffffff, 0x3fffffffffffff, 0x7fffffffffffff, 0xffffffffffffff, 0x1ffffffffffffff, 0x3ffffffffffffff, 0x7ffffffffffffff, 0xfffffffffffffff, 0x1fffffffffffffff, 0x3fffffffffffffff, 0x7fffffffffffffff, 0xffffffffffffffff }; ///////////////////////////////////////////////////////////////////////////// // // /* */ CTCPClient::CTCPClient() { m_instance=++m_last_instance; // if(mutex.Try()) { w=NULL; } } /* */ CTCPClient::~CTCPClient() { Close(); } ///////////////////////////////////////////////////////////////////////////// // // /* Returns: a boolean in the form of a long (because old versions of CF4 are too stupid to use a true boolean.) */ STDMETHODIMP CTCPClient::Open( BSTR strhost, BSTR strport, long *pconnected ) { #ifdef _DEBUG printf("CTCPClient::Open strhost=%S strport=%S (thread %lu)\n",strhost,strport,GetCurrentThreadId()); #endif // *pconnected=TRUE; // mutex.Lock(); // if(mutex.Try()) { // if(!w) { // char ip[MAX_IPEXPANSION+1]; char port[MAX_PORTEXPANSION+1]; wcstombs(ip,strhost,min(wcslen(strhost)+1,MAX_IPEXPANSION)); wcstombs(port,strport,min(wcslen(strport)+1,MAX_PORTEXPANSION)); w=new tcp( (char* const)ip, (char* const)port ); if(w) { if(w->is_connected()) *pconnected=TRUE; else { *pconnected=FALSE; log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Open", L"Low-level tcp class is_connected (%s) failed on host %S:%S.", w->is_connected()?L"true":L"false",ip,port); delete w; w=NULL; } } } // mutex.Untry(); } return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::Close() { #ifdef _DEBUG printf("CTCPClient::Close (thread %lu)\n",GetCurrentThreadId()); #endif // mutex.Unlock(); // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Close", L"Socket not open."); } else { delete w; w=NULL; } return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::Send(BSTR inText) { #ifdef _DEBUG CBSTR bstr_fns; printf("CTCPClient::Send inText=%S inText_length=%d\n",inText,bstr_fns.character_length(inText)); #endif // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Send", L"Socket not open."); } else { if(inText!=NULL) { CBSTR bstr; const int inText_length=bstr.character_length(inText); char *pszstr=new char[inText_length+1]; if(pszstr) { wcstombs(pszstr,inText,inText_length); #ifdef _DEBUG printf("inText_length=%d\n",inText_length); printf("pszstr=%s\n",pszstr); #endif w->Send(pszstr,inText_length); delete[] pszstr; pszstr=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Send", L"Memory allocation failure (%d bytes).",inText_length); retval=E_OUTOFMEMORY; } } else retval=E_POINTER; } // mutex.Untry(); } return retval; } /* */ STDMETHODIMP CTCPClient::Recv(BSTR *poutText) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Recv", L"Socket not open."); *poutText=SysAllocString(L""); } else { char *buf=NULL; const int buf_length=w->Recv(buf); if(buf_length<=0) *poutText=SysAllocString(L""); else { BSTR bstr=new wchar_t[buf_length+1]; //new bstr section to get around iis5's 256kb stack limit if(bstr) { const size_t w_buf_length=mbstowcs(bstr,buf,buf_length+1); *poutText=SysAllocStringLen(bstr,(unsigned int)w_buf_length); delete[] bstr; bstr=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Recv", L"Memory allocation failure (%d bytes).", buf_length); retval=E_OUTOFMEMORY; } } delete[] buf; buf=NULL; } // mutex.Untry(); } else *poutText=SysAllocString(L""); return retval; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::SendRN(BSTR inText) { #ifdef _DEBUG CBSTR bstr_fns; printf("CTCPClient::SendRN inText=%S inText_length=%d\n",inText,bstr_fns.sz_length(inText)); printf(" sz_length=%d\n",bstr_fns.sz_length(inText)); printf(" character_length=%d\n",bstr_fns.character_length(inText)); printf(" bytes=%d\n",bstr_fns.bytes(inText)); #endif // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::SendRN", L"Socket not open."); } else { if(inText!=NULL) { CBSTR bstr; const int inText_length=bstr.sz_length(inText); char *pszstr=new char[inText_length+1]; if(pszstr) { wcstombs(pszstr,inText,inText_length+1); #ifdef _DEBUG printf("inText_length=%d\n",inText_length); printf("pszstr=%s\n",pszstr); #endif w->SendCRLF(pszstr,inText_length); delete[] pszstr; pszstr=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::SendRN", L"Memory allocation failure (%d bytes).", inText_length); retval=E_OUTOFMEMORY; } } else w->SendCRLF(NULL,0); } // mutex.Untry(); } // return retval; } /* */ STDMETHODIMP CTCPClient::RecvRN(BSTR * poutText) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvRN", L"Socket not open."); *poutText=SysAllocString(L""); } else { char *buf=NULL; const int buf_length=w->RecvCRLF(buf); if(buf_length<=0) *poutText=SysAllocString(L""); else { BSTR bstr=new wchar_t[buf_length+1]; //new bstr section to get around iis5's 256kb stack limit if(bstr) { const size_t w_buf_length=mbstowcs(bstr,buf,buf_length+1); *poutText=SysAllocStringLen(bstr,(unsigned int)w_buf_length); delete[] bstr; bstr=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvRN", L"Memory allocation failure (%d bytes).", buf_length); retval=E_OUTOFMEMORY; } } delete[] buf; buf=NULL; } // mutex.Untry(); } else *poutText=SysAllocString(L""); return retval; } /* */ STDMETHODIMP CTCPClient::FlushRN() { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::FlushRN", L"Socket not open."); } else w->EmptyRecvBuffer(); } return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::SendFile(BSTR strFilename) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::SendFile", L"Socket not open."); } else { //get filename contents char filename[MAX_PATH+1]; wcstombs(filename,strFilename,wcslen(strFilename)+1); // call optimized network file send function. w->SendFile(filename); } // mutex.Untry(); } return retval; } /* */ STDMETHODIMP CTCPClient::RecvFile(BSTR strFilename) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvFile", L"Socket not open."); } else { //get filename contents char filename[MAX_PATH+1]; wcstombs(filename,strFilename,wcslen(strFilename)+1); // call optimized network file recv function. no append. w->RecvFile(filename,false); } // mutex.Untry(); } return retval; } /* */ STDMETHODIMP CTCPClient::RecvFileAppend(BSTR strFilename) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvFileAppend", L"Socket not open."); } else { //get filename contents char filename[MAX_PATH+1]; wcstombs(filename,strFilename,wcslen(strFilename)+1); // call optimized network file revc function. append file. w->RecvFile(filename,true); } // mutex.Untry(); } return retval; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::SendCSV(BSTR inText) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::SendCSV", L"Socket not open."); } else { if(inText!=NULL) { // const size_t inText_length=wcslen(inText)+1; char *csv=new char[inText_length]; if(csv) { wcstombs(csv,inText,inText_length); // char *decsv=new char[inText_length]; if(decsv==NULL) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::SendCSV", L"Memory allocation failure (%d bytes).", inText_length); retval=E_OUTOFMEMORY; } else { // char *s=csv; char *d=decsv; int count=0; char *c=NULL; do { const int i=atoi(s); *d=(BYTE)i; d++; c=strchr(s,','); if(c) s=c+1; count++; } while(c!=NULL); // w->Send( decsv, count); // delete[] decsv; decsv=NULL; } // delete[] csv; csv=NULL; } } else retval=E_POINTER; } // mutex.Untry(); } return retval; } /* */ STDMETHODIMP CTCPClient::RecvCSV(BSTR * poutText) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvCSV", L"Socket not open."); *poutText=SysAllocString(L""); } else { int buflength=0; // get data char *buf=NULL; buflength=w->Recv(buf); // decode raw data to csv if(buflength<=0) *poutText=SysAllocString(L""); else { // const int newbuflength=buflength*4; char *newbuf=new char[newbuflength]; if(newbuf) { newbuf[0]='\0'; char *s=buf; for(int i=0;i<buflength;i++) { char tmp[MAX_DWORDEXPANSION]; _itoa((BYTE)*s,tmp,10); if(i!=0) strcat(newbuf,","); strcat(newbuf,tmp); s++; } //new bstr section to get around iis5's 256kb stack limit BSTR wbuf=new wchar_t[newbuflength+1]; if(wbuf) { mbstowcs(wbuf,newbuf,newbuflength+1); *poutText=SysAllocString(wbuf); delete[] wbuf; wbuf=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvCSV", L"Memory allocation failure (%d bytes).", newbuflength); retval=E_OUTOFMEMORY; } // delete[] newbuf; newbuf=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvCSV", L"Memory allocation failure (%d bytes).", newbuflength); retval=E_OUTOFMEMORY; } } // delete[] buf; buf=NULL; } // mutex.Untry(); } else *poutText=SysAllocString(L""); return retval; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::put_timeout(double secs) { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::put_timeout", L"Socket not open."); } else { int s,ms; s=(int)secs; ms=(int)((secs-(double)s)*1000); w->timeout(s,ms); } // mutex.Untry(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::put_cutoff(long bytes) { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::put_cutoff", L"Socket not open."); } else w->cutoff(bytes); // mutex.Untry(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::put_blocksize(long bytes) { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::put_blocksize", L"Socket not open."); } else w->blocksize(bytes); // mutex.Untry(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::put_packetsize(long bytes) { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::put_packetsize", L"Socket not open."); } else w->packetsize(bytes); // mutex.Untry(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::put_keepalives(long flag) { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::put_keepalives", L"Socket not open."); } else w->keepalives(flag!=0); // mutex.Untry(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::put_nagledelay(long flag) { // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::put_nagledelay", L"Socket not open."); } else w->nagledelay(flag!=0); // mutex.Untry(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::put_set_timeout(double secs) { return put_timeout(secs); } /* */ STDMETHODIMP CTCPClient::put_set_cutoff(long bytes) { return put_cutoff(bytes); } /* */ STDMETHODIMP CTCPClient::put_set_blocksize(long bytes) { return put_blocksize(bytes); } /* */ STDMETHODIMP CTCPClient::put_set_packetsize(long bytes) { return put_packetsize(bytes); } /* */ STDMETHODIMP CTCPClient::put_set_keepalives(long flag) { return put_keepalives(flag); } /* */ STDMETHODIMP CTCPClient::put_set_nagledelay(long flag) { return put_nagledelay(flag); } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_timeout(double *psecs) { if(w) *psecs=(double)w->timeout(); else *psecs=0.0; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_last_timeout(double *psecs) { if(w) *psecs=(double)w->last_timeout(); else *psecs=0.0; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_cutoff(long *pstatus) { if(w) *pstatus=(long)w->cutoff(); else *pstatus=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_blocksize(long *pbytes) { if(w) *pbytes=(long)w->blocksize(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_packetsize(long *pbytes) { if(w) *pbytes=(long)w->packetsize(); else *pbytes=0L; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_description(BSTR* pstr) { CComBSTR bstrtmp(description); if(!bstrtmp) return E_POINTER; else { *pstr=bstrtmp.Detach(); return S_OK; } } /* */ STDMETHODIMP CTCPClient::get_copyright(BSTR* pstr) { CComBSTR bstrtmp(copyright); if(!bstrtmp) return E_POINTER; else { *pstr=bstrtmp.Detach(); return S_OK; } } /* */ STDMETHODIMP CTCPClient::get_version(BSTR* pstr) { CComBSTR bstrtmp(version); if(!bstrtmp) return E_POINTER; else { *pstr=bstrtmp.Detach(); return S_OK; } } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_thread(long* pthread) { DWORD tid=GetCurrentThreadId(); *pthread=(long)tid; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_local(BSTR* pstr) { HRESULT retval=S_OK; char tmp[MAX_URLEXPANSION+1]; if(w) { char ip[MAX_IPEXPANSION+1]; int port; w->localName(ip,port); _snprintf(tmp,MAX_URLEXPANSION,"%S:%d",ip,port); } else tmp[0]='\0'; CComBSTR bstrtmp(tmp); if(!bstrtmp) retval=E_OUTOFMEMORY; else *pstr=bstrtmp.Detach(); return retval; } /* */ STDMETHODIMP CTCPClient::get_remote(BSTR* pstr) { HRESULT retval=S_OK; char tmp[MAX_URLEXPANSION+1]; if(w) { char ip[MAX_IPEXPANSION+1]; int port; w->peerName(ip,port); _snprintf(tmp,MAX_URLEXPANSION,"%S:%d",ip,port); } else tmp[0]='\0'; CComBSTR bstrtmp(tmp); if(!bstrtmp) retval=E_OUTOFMEMORY; else *pstr=bstrtmp.Detach(); return retval; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_is_completed(long* pstatus) { if(w) *pstatus=(long)w->is_completed(); else *pstatus=FALSE; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_is_connected(long* pstatus) { if(w) *pstatus=(long)w->is_connected(); else *pstatus=FALSE; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_is_cutoff(long* pstatus) { if(w) *pstatus=(long)w->is_cutoff(); else *pstatus=FALSE; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_is_keepalives(long* pstatus) { if(w) *pstatus=(long)w->is_keepalives(); else *pstatus=FALSE; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_is_nagledelay(long* pstatus) { if(w) *pstatus=(long)w->is_nagledelay(); else *pstatus=FALSE; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_socket(long* psock) { if(w) *psock=(long)w->socket(); else *psock=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_bytessent(long* pbytes) { if(w) *pbytes=(long)w->bytes_sent(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_bytesreceived(long* pbytes) { if(w) *pbytes=(long)w->bytes_received(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_byteslastreceived(long* pbytes) { if(w) *pbytes=(long)w->last_bytes_received(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_byteslastsent(long* pbytes) { if(w) *pbytes=(long)w->last_bytes_sent(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_stack_recv_buffer(long* pbytes) { if(w) *pbytes=(long)w->stack_recv_buffer(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_stack_send_buffer(long* pbytes) { if(w) *pbytes=(long)w->stack_send_buffer(); else *pbytes=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_send_packets(long* pcount) { if(w) *pcount=(long)w->send_packets(); else *pcount=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_recv_packets(long* pcount) { if(w) *pcount=(long)w->recv_packets(); else *pcount=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_recv_faults(long* pcount) { if(w) *pcount=(long)w->recv_faults(); else *pcount=0L; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_recvbuffer_faults(long* pcount) { if(w) *pcount=(long)w->recvbuffer_faults(); else *pcount=0L; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_kbpssent(double* pkbps) { if(w) *pkbps=(double)w->kbps_sent(); else *pkbps=0.0; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_kbpsreceived(double* pkbps) { if(w) *pkbps=(double)w->kbps_received(); else *pkbps=0.0; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_kbpslastsent(double* pkbps) { if(w) *pkbps=(double)w->last_kbps_sent(); else *pkbps=0.0; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_kbpslastreceived(double* pkbps) { if(w) *pkbps=(double)w->last_kbps_received(); else *pkbps=0.0; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_ping(long* pVal) { if(w) *pVal=(long)w->ping(); else *pVal=0L; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::get_Log(BSTR* pstr) { CComBSTR bstrtmp(log.Logs()); if(!bstrtmp) return E_OUTOFMEMORY; else { *pstr=bstrtmp.Detach(); return S_OK; } } /* */ STDMETHODIMP CTCPClient::ClearLog() { // if(mutex.Try()) { log.Clear(); } return S_OK; } /* */ STDMETHODIMP CTCPClient::get_instance(long* pVal) { *pVal=(long)m_instance; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_instances(long* pVal) { *pVal=(long)m_last_instance; return S_OK; } /* */ STDMETHODIMP CTCPClient::get_mutex_locks(long* pVal) { *pVal=(long)mutex.get_lock_count(); return S_OK; } /* */ STDMETHODIMP CTCPClient::get_mutex_sleep(long* pVal) { *pVal=(long)mutex.get_sleep_milliseconds(); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::SendFrame( BSTR strFrame, long FrameSize ) { #ifdef _DEBUG CBSTR bstr_fns; printf("CTCPClient::SendFrame strFrame=%S FrameSize=%d (szlen strFrame=%d)\n", strFrame,FrameSize,bstr_fns.character_length(strFrame)); #endif // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::SendFrame", L"Socket not open."); } else { if(strFrame!=NULL) { CBSTR bstr; int const strFrame_length=bstr.character_length(strFrame); int const frame_length=(FrameSize<strFrame_length)?FrameSize:strFrame_length; #ifdef _DEBUG printf("strFrame_length=%d\n",strFrame_length); #endif w->Send((char *)strFrame,frame_length); } else retval=E_POINTER; } // mutex.Untry(); } return retval; } /* */ STDMETHODIMP CTCPClient::RecvFrame( long FrameSize, BSTR* pstrFrame ) { // HRESULT retval=S_OK; // if(mutex.Try()) { // if(!w) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvFrame", L"Socket not open."); *pstrFrame=SysAllocString(L""); } else { char *buf=NULL; int const buf_length=w->RecvFrame(buf,FrameSize); if(buf_length<=0) *pstrFrame=SysAllocString(L""); else { BSTR bstr=new wchar_t[buf_length+1]; if(bstr) { const size_t w_buf_length=mbstowcs(bstr,buf,buf_length+1); *pstrFrame=SysAllocStringLen(bstr,(unsigned int)w_buf_length); delete[] bstr; bstr=NULL; } else { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::RecvFrame", L"Memory allocation failure (%d bytes).", buf_length); retval=E_OUTOFMEMORY; } } delete[] buf; buf=NULL; } // mutex.Untry(); } else *pstrFrame=SysAllocString(L""); return retval; } /* */ // 8 16 24 32 40 48 56 64 _int64 CTCPClient::changeEndian( _int64 d, short bits ) { if((bits&7)==0) { int const bytes=(int)(bits>>3); BYTE b[8]; int i; BYTE *p=(BYTE *)&d; for(i=0;i<bytes;i++) { b[i]=*(p+bytes-i-1); } for(;i<8;i++) { b[i]=0; } return *(_int64 *)b; } else { return d; } } /* */ STDMETHODIMP CTCPClient::FrameSize( BSTR strFrameDefinition, long* pFrameSize ) { // if(strFrameDefinition==NULL) { if(pFrameSize==NULL) return S_OK; else { *pFrameSize=0; return S_OK; } } // CBSTR bstr; const int length=bstr.sz_length(strFrameDefinition); wchar_t *p=strFrameDefinition; wchar_t *pend=strFrameDefinition+length; long sum=0; if(strFrameDefinition!=NULL) { while(p<pend) { wchar_t *next; wchar_t c=*p++; int num=_wtoi(p); next=wcschr(p,' '); if(next==NULL) break; p=next+1; next=wcschr(p,','); if(next==NULL) p=pend; else p=next+1; switch(c) { case '+': sum+=num; break; case 's': sum+=8*num; break; case 'u': sum+=16*num; break; case ' ': case '-': sum+=num; break; default: p=pend; } } } // *pFrameSize=(long)sum; return S_OK; } /* */ STDMETHODIMP CTCPClient::DecodeFrame( BSTR strFrameDefinition, BSTR strFieldName, BSTR strFrame, BSTR* pstrValue ) { // if(strFrameDefinition==NULL || strFrame==NULL || strFieldName==NULL || pstrValue==NULL) { if(pstrValue==NULL) return S_OK; else { *pstrValue=SysAllocString(L""); return S_OK; } } // CBSTR bstr; int const length=bstr.sz_length(strFrameDefinition); wchar_t *p=strFrameDefinition; wchar_t *pend=strFrameDefinition+length; // long sum=0; while(p<pend) { wchar_t *next; wchar_t c=*p++; int num=_wtoi(p); next=wcschr(p,' '); if(next==NULL) break; p=next+1; wchar_t *fieldname=p; next=wcschr(p,','); int fieldname_length; if(next==NULL) { p=pend; fieldname_length=(int)(p-fieldname); } else { p=next+1; fieldname_length=(int)(p-fieldname-1); } if(wcsncmp(strFieldName,fieldname,fieldname_length)==0) { const int byte_offset=(sum>>3); const bool aligned=((sum&7)==0); const int shift=sum&7; const int index=(num-1)&63; BYTE *source=(BYTE *)strFrame; _int64 dd; _int64 d; wchar_t wbuffer[22]; switch(c) { case ' ': case '-': dd=*(_int64 *)(source+byte_offset); d=(_int64)((dd>>shift)&bitmask[index]); _i64tow(d,wbuffer,10); *pstrValue=SysAllocString(wbuffer); return S_OK; case '+': dd=*(_int64 *)(source+byte_offset); d=(_int64)((dd>>shift)&bitmask[index]); d=changeEndian(d,num); _i64tow(d,wbuffer,10); *pstrValue=SysAllocString(wbuffer); return S_OK; case 's': { wchar_t *tmp=new wchar_t[num+1]; if(tmp) { const size_t wlength=mbstowcs(tmp,(const char *)(source+byte_offset),num); *(tmp+num)=L'\0'; *pstrValue=SysAllocString(tmp); delete[] tmp; } } return S_OK; case 'u': { wchar_t *tmp=new wchar_t[num+1]; if(tmp) { wcsncpy(tmp,(const wchar_t*)(source+byte_offset),num); *(tmp+num)=L'\0'; *pstrValue=SysAllocString(tmp); delete[] tmp; } } return S_OK; default: *pstrValue=SysAllocString(L""); return S_OK; } break; } switch(c) { case '+': sum+=num; break; case 's': sum+=8*num; break; case 'u': sum+=16*num; break; case ' ': case '-': sum+=num; break; default: p=pend; } } // if(pstrValue) *pstrValue=SysAllocString(L""); return S_OK; } /* */ STDMETHODIMP CTCPClient::EncodeFrame( BSTR strFrameDefinition, BSTR strFieldName, BSTR strFieldValue, BSTR strFrame, BSTR* pstrFrame ) { // if(strFrameDefinition==NULL || strFieldName==NULL || strFieldValue==NULL || strFrame==NULL || pstrFrame==NULL) { if(pstrFrame==NULL) return S_OK; else { *pstrFrame=SysAllocString(L""); return S_OK; } } // CBSTR bstr; const int length=bstr.sz_length(strFrameDefinition); wchar_t *p=strFrameDefinition; wchar_t *pend=strFrameDefinition+length; // long framesize; FrameSize(strFrameDefinition,&framesize); const int framebytes=(framesize>>3)+(((framesize&7)==0)?0:1); BYTE *Frame=new BYTE[framebytes+2+sizeof(_int64)]; if(Frame==NULL) { //memory allocation error log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::EncodeFrame", L"Memory allocation failure (%d bytes)",framebytes+2+sizeof(_int64)); return E_OUTOFMEMORY; } else { // memset(Frame,0,framebytes+2+sizeof(_int64)); // CBSTR bstr; const int strFrame_bytes=bstr.bytes(strFrame); if(strFrame) memcpy(Frame,strFrame,(strFrame_bytes<=framebytes)?strFrame_bytes:framebytes); // long sum=0; while(p<pend) { wchar_t *next; wchar_t c=*p++; int num=_wtoi(p); next=wcschr(p,' '); if(next==NULL) break; p=next+1; wchar_t *fieldname=p; next=wcschr(p,','); int fieldname_length; if(next==NULL) { p=pend; fieldname_length=(int)(p-fieldname); } else { p=next+1; fieldname_length=(int)(p-fieldname-1); } // if(wcsncmp(strFieldName,fieldname,fieldname_length)==0) { const int byte_offset=(sum>>3); const bool aligned=((sum&7)==0); const int shift=sum&7; const int index=(num-1)&63; BYTE *destination=(BYTE *)Frame; _int64 dd; _int64 dd_stream; _int64 d; _int64 inverse_bitmask; switch(c) { case ' ': case '-': d=_wtoi(strFieldValue); dd_stream=*(_int64 *)(destination+byte_offset); inverse_bitmask=~(bitmask[index]<<shift); dd=(dd_stream&inverse_bitmask)|(d<<shift); *(_int64 *)(destination+byte_offset)=dd; p=pend; break; case '+': d=changeEndian(_wtoi(strFieldValue),num); dd_stream=*(_int64 *)(destination+byte_offset); inverse_bitmask=~(bitmask[index]<<shift); dd=(dd_stream&inverse_bitmask)|(d<<shift); *(_int64 *)(destination+byte_offset)=dd; p=pend; break; case 's': { char *tmp=new char[num]; if(tmp) { const size_t wlength=wcstombs(tmp,strFieldValue,num); memset((char*)(destination+byte_offset),0,num); strncpy((char*)(destination+byte_offset),tmp,num); delete[] tmp; } p=pend; } break; case 'u': memset((char*)(destination+byte_offset),0,num*2); wcsncpy((wchar_t *)(destination+byte_offset),strFieldValue,num); p=pend; break; } } switch(c) { case '+': sum+=num; break; case 's': sum+=8*num; break; case 'u': sum+=16*num; break; case ' ': case '-': sum+=num; break; default: p=pend; } } if(pstrFrame) SysFreeString(*pstrFrame); *pstrFrame=::SysAllocStringByteLen((const char*)Frame,framebytes); delete[] Frame; Frame=NULL; } return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // /* */ STDMETHODIMP CTCPClient::Hash( BSTR strHashType, BSTR strInput, BSTR* pstrHash ) { // HRESULT retval=S_OK; CMD5 md5; if(strInput!=NULL) { // const size_t strInput_length=wcslen(strInput)+1; char *szInput=new char[strInput_length]; if(szInput==NULL) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Hash", L"Memory allocation failure (%d bytes).", strInput_length); retval=E_OUTOFMEMORY; } else { // wcstombs(szInput,strInput,strInput_length); char md5hash[32+1]; md5.Hash(szInput,md5hash); BSTR bstr=new wchar_t[32+1]; if(bstr==NULL) { log.AddLog( _T(__FILE__), __LINE__, L"CTCPClient::Hash", L"Memory allocation failure (%d bytes).",32+1); retval=E_OUTOFMEMORY; } else { const size_t w_length=mbstowcs(bstr,md5hash,32+1); *pstrHash=SysAllocString(bstr); delete[] bstr; } delete[] szInput; szInput=NULL; } } return retval; } /* */ STDMETHODIMP CTCPClient::HashFile( BSTR strHashType, BSTR strFilename, BSTR *pstrHash ) { // HRESULT retval=S_OK; CMD5 md5; CBSTR bstr; // char szFilename[_MAX_PATH+1]; const int strFilename_length=bstr.sz_length(strFilename); wcstombs(szFilename,strFilename,strFilename_length+1); // char hash[32+1]; const int blocksize=65536; md5.HashFile(szFilename,hash,blocksize); wchar_t bstr_hash[32+1]; mbstowcs(bstr_hash,hash,32+1); *pstrHash=SysAllocString(bstr_hash); // return retval; }
14.772091
160
0.585922
lasellers
7062009380ad83bfeb972203adf99dd8426568ff
11,107
cpp
C++
modules/core/sensor/src/PinholeCamera.cpp
MobilePerceptionLab/EventCameraCalibration
debd774ac989674b500caf27641b7ad4e94681e9
[ "Apache-2.0" ]
22
2021-08-06T03:21:03.000Z
2022-02-25T03:40:54.000Z
modules/core/sensor/src/PinholeCamera.cpp
MobilePerceptionLab/MultiCamCalib
2f0e94228c2c4aea7f20c26e3e8daa6321ce8022
[ "Apache-2.0" ]
1
2022-02-25T02:55:13.000Z
2022-02-25T15:18:45.000Z
modules/core/sensor/src/PinholeCamera.cpp
MobilePerceptionLab/MultiCamCalib
2f0e94228c2c4aea7f20c26e3e8daa6321ce8022
[ "Apache-2.0" ]
7
2021-08-11T12:29:35.000Z
2022-02-25T03:41:01.000Z
// // Created by huangkun on 2020/8/11. // #include <Eigen/Eigen> #include <opencv2/core/eigen.hpp> #include <opencv2/opencv.hpp> #include <nanoflann.hpp> #include <KDTreeVectorOfVectorsAdaptor.h> #include <opengv2/sensor/PinholeCamera.hpp> #include <opengv2/utility/utility.hpp> opengv2::PinholeCamera::PinholeCamera(const Eigen::Ref<const Eigen::Vector2d> &size, const Eigen::Ref<const Eigen::Matrix3d> &K, const Eigen::Ref<const Eigen::VectorXd> &distCoeffs, cv::Mat mask) : CameraBase(size, mask), K_(K), invK_(K.inverse()), distCoeffs_(distCoeffs), inverseRadialPoly_(Eigen::VectorXd()) {} inline Eigen::Vector2d opengv2::PinholeCamera::project(const Eigen::Ref<const Eigen::Vector3d> &Xc) const { if (distCoeffs_.size() == 0) { Eigen::Vector3d p = K_ * Xc; p /= p(2); return p.block<2, 1>(0, 0); } else { // TODO: implement using Eigen std::vector<cv::Point3f> objectPoints(1, cv::Point3f(Xc[0], Xc[1], Xc[2])); cv::Mat tvec = cv::Mat::zeros(3, 1, CV_32F), rvec, distCoeffs, cameraMatrix; cv::Rodrigues(cv::Mat::eye(3, 3, CV_32F), rvec); cv::eigen2cv(distCoeffs_, distCoeffs); cv::eigen2cv(K_, cameraMatrix); std::vector<cv::Point2f> imagePoints; cv::projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints); return Eigen::Vector2d(imagePoints[0].x, imagePoints[0].y); } } inline Eigen::Vector3d opengv2::PinholeCamera::invProject(const Eigen::Ref<const Eigen::Vector2d> &p) const { Eigen::Vector3d Xc; if (inverseRadialPoly_.size() != 0) { Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1); Xc /= Xc[2]; Eigen::VectorXd r_coeff(inverseRadialPoly_.size()); r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1]; for (int i = 1; i < inverseRadialPoly_.size(); ++i) { r_coeff[i] = r_coeff[i - 1] * r_coeff[0]; } Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly_; Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly_; } else if (distCoeffs_.size() != 0) { // TODO: implement using Eigen std::vector<cv::Point2f> src, dst; src.emplace_back(p[0], p[1]); cv::Mat cameraMatrix, distCoeffs; cv::eigen2cv(K_, cameraMatrix); cv::eigen2cv(distCoeffs_, distCoeffs); cv::undistortPoints(src, dst, cameraMatrix, distCoeffs); Xc = Eigen::Vector3d(dst[0].x, dst[0].y, 1); } else { Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1); } Xc.normalize(); return Xc; } Eigen::VectorXd opengv2::PinholeCamera::inverseRadialDistortion(const Eigen::Ref<const Eigen::Vector4d> &radialDistortion) { const Eigen::Ref<const Eigen::VectorXd> &k = radialDistortion; Eigen::VectorXd b(5); double k00 = k[0] * k[0]; double k000 = k[0] * k00; double k0000 = k[0] * k000; double k00000 = k[0] * k0000; double k01 = k[0] * k[1]; double k001 = k[0] * k01; double k0001 = k[0] * k001; double k11 = k[1] * k[1]; double k011 = k[0] * k11; double k02 = k[0] * k[2]; double k002 = k[0] * k02; double k12 = k[1] * k[2]; double k03 = k[0] * k[3]; b[0] = -k[0]; b[1] = 3 * k00 - k[1]; b[2] = -12 * k000 + 8 * k01 - k[2]; b[3] = 55 * k0000 - 55 * k001 + 5 * k11 + 10 * k02 - k[3]; b[4] = -273 * k00000 + 364 * k0001 - 78 * k011 - 78 * k002 + 12 * k12 + 12 * k03; return b; } Eigen::Vector2d opengv2::PinholeCamera::undistortPoint(const Eigen::Ref<const Eigen::Vector2d> &p) const { Eigen::Vector3d Xc; if (inverseRadialPoly_.size() != 0) { Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1); Xc /= Xc[2]; Eigen::VectorXd r_coeff(inverseRadialPoly_.size()); r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1]; for (int i = 1; i < inverseRadialPoly_.size(); ++i) { r_coeff[i] = r_coeff[i - 1] * r_coeff[0]; } Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly_; Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly_; } else if (distCoeffs_.size() != 0) { // TODO: implement using Eigen std::vector<cv::Point2f> src, dst; src.emplace_back(p[0], p[1]); cv::Mat cameraMatrix, distCoeffs; cv::eigen2cv(K_, cameraMatrix); cv::eigen2cv(distCoeffs_, distCoeffs); cv::undistortPoints(src, dst, cameraMatrix, distCoeffs); Xc = Eigen::Vector3d(dst[0].x, dst[0].y, 1); } else { return p; } Eigen::Vector3d p_c = K_ * Xc; p_c /= p_c[2]; return p_c.block<2, 1>(0, 0); } cv::Mat opengv2::PinholeCamera::undistortImage(cv::Mat src) { if (inverseRadialPoly_.size() != 0) { if (undistortMap_.empty()) { // Initialization int dstRows = std::round(size_[1] * 1.2); int dstCols = std::round(size_[0] * 1.2); int emptyEdge_r = std::round(size_[1] * 0.1); int emptyEdge_c = std::round(size_[0] * 0.1); undistortMap_.assign(dstRows, std::vector(dstCols, std::pair(std::vector<std::pair<int, int>>(), std::vector<double>()))); vectorofEigenMatrix<Eigen::Vector2d> correctedSet; correctedSet.reserve(size_[0] * size_[1]); const int step = size_[0]; // width for (int idx = 0; idx < size_[0] * size_[1]; ++idx) { // index of cv::Mat, row major int row = idx / step; // y int col = idx % step; // x correctedSet.push_back( undistortPoint(Eigen::Vector2d(col, row)) + Eigen::Vector2d(emptyEdge_c, emptyEdge_r)); } KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2, nanoflann::metric_L2_Simple> kdTree(2, correctedSet, 10); std::vector<std::pair<size_t, double>> indicesDists; for (int i = 0; i < dstRows; ++i) { // y, height for (int j = 0; j < dstCols; ++j) { // x, width Eigen::Vector2d p(j, i); kdTree.index->radiusSearch(p.data(), 2 * 2 /*square pixel unit*/, indicesDists, nanoflann::SearchParams(32, 0, false)); for (const auto &pair: indicesDists) { int idx = pair.first; double d = pair.second; int row = idx / step; int col = idx % step; if (d < 100 * std::numeric_limits<double>::epsilon()) { d = 100 * std::numeric_limits<double>::epsilon(); } undistortMap_[i][j].first.emplace_back(row, col); undistortMap_[i][j].second.push_back(1 / d); } } } } if (src.type() != CV_8UC3) { throw std::logic_error("only support CV_8UC3 for now."); } cv::Mat dst(undistortMap_.size(), undistortMap_[0].size(), CV_32FC3, cv::Vec3f(0, 0, 0)); for (int i = 0; i < dst.rows; ++i) { for (int j = 0; j < dst.cols; ++j) { int len = undistortMap_[i][j].first.size(); double w_sum = 0; for (int k = 0; k < len; ++k) { int row = undistortMap_[i][j].first[k].first; int col = undistortMap_[i][j].first[k].second; double w = undistortMap_[i][j].second[k]; // convert to float, since opencv didn't do that(uchar * double, return uchar). cv::Vec3f temp = src.at<cv::Vec3b>(row, col); dst.at<cv::Vec3f>(i, j) += w * temp; w_sum += w; } if (len != 0) { dst.at<cv::Vec3f>(i, j) /= w_sum; } } } cv::normalize(dst, dst, 0, 255, cv::NORM_MINMAX, CV_8UC3); return dst; } else if (distCoeffs_.size() != 0) { if (map1_.empty()) { cv::Size imageSize(size_[0], size_[1]); cv::Mat cameraMatrix, distCoeffs; cv::eigen2cv(K_, cameraMatrix); cv::eigen2cv(distCoeffs_, distCoeffs); cv::initUndistortRectifyMap( cameraMatrix, distCoeffs, cv::Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_32FC1, map1_, map2_); } cv::Mat dst; remap(src, dst, map1_, map2_, cv::INTER_LINEAR); return dst; } else { return src; } } opengv2::PinholeCamera::PinholeCamera(const cv::FileNode &sensorNode) : CameraBase(sensorNode) { std::vector<double> v; cv::FileNode data; data = sensorNode["principal_point"]; if (!data.isSeq()) throw std::invalid_argument(sensorNode.name() + ": principal_point"); for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) { v.push_back(*dataItr); } if (v.size() != 2) throw std::invalid_argument(sensorNode.name() + ": principal_point"); Eigen::Vector2d principal_point(v.data()); std::cout << "principal_point: " << principal_point.transpose() << std::endl; v.clear(); data = sensorNode["distortion_type"]; if (!data.isString()) throw std::invalid_argument(sensorNode.name() + ": distortion_type"); std::string distortion_type = data.string(); std::cout << "distortion_type: " << distortion_type << std::endl; v.clear(); data = sensorNode["distortion"]; if (!data.isSeq()) throw std::invalid_argument(sensorNode.name() + ": distortion"); for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) { v.push_back(*dataItr); } Eigen::Map<Eigen::VectorXd, Eigen::Unaligned> distortion_tmp(v.data(), v.size()); Eigen::VectorXd distortion(distortion_tmp); std::cout << "distortion: " << distortion.transpose() << std::endl; v.clear(); data = sensorNode["focal_length"]; if (!data.isSeq()) throw std::invalid_argument(sensorNode.name() + ": focal_length"); for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) { v.push_back(*dataItr); } if (v.size() != 2) throw std::invalid_argument(sensorNode.name() + ": focal_length"); Eigen::Vector2d focal_length(v.data()); std::cout << "focal_length: " << focal_length.transpose() << std::endl; K_ << focal_length[0], 0, principal_point[0], 0, focal_length[1], principal_point[1], 0, 0, 1; invK_ = K_.inverse(); if (distortion_type == "OpenCV") { distCoeffs_ = distortion; inverseRadialPoly_ = Eigen::VectorXd(); } else { distCoeffs_ = Eigen::VectorXd(); inverseRadialPoly_ = distortion; } }
41.137037
118
0.544431
MobilePerceptionLab
7067790723a609a8a5c5bfac60cf9bd9229aee21
3,491
cpp
C++
LambdaEngine/Source/Game/ECS/Components/Rendering/CameraComponent.cpp
IbexOmega/CrazyCanvas
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
18
2020-09-04T08:00:54.000Z
2021-08-29T23:04:45.000Z
LambdaEngine/Source/Game/ECS/Components/Rendering/CameraComponent.cpp
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
32
2020-09-12T19:24:50.000Z
2020-12-11T14:29:44.000Z
LambdaEngine/Source/Game/ECS/Components/Rendering/CameraComponent.cpp
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
2
2020-12-15T15:36:13.000Z
2021-03-27T14:27:02.000Z
#include "Audio/AudioAPI.h" #include "Audio/FMOD/AudioDeviceFMOD.h" #include "Audio/FMOD/SoundInstance3DFMOD.h" #include "Game/ECS/Components/Rendering/CameraComponent.h" #include "Game/ECS/Components/Audio/AudibleComponent.h" #include "Game/ECS/Components/Audio/ListenerComponent.h" #include "Game/ECS/Components/Physics/Transform.h" #include "Game/ECS/Components/Physics/Collision.h" #include "Game/ECS/Components/Misc/Components.h" #include "Game/ECS/Systems/Physics/PhysicsSystem.h" #include "Resources/ResourceManager.h" namespace LambdaEngine { Entity CreateFreeCameraEntity(const CameraDesc& cameraDesc) { Entity entity = CreateCameraEntity(cameraDesc); FreeCameraComponent freeCamComp; ECSCore::GetInstance()->AddComponent<FreeCameraComponent>(entity, freeCamComp); return entity; } Entity CreateFPSCameraEntity(const CameraDesc& cameraDesc) { ECSCore* pECS = ECSCore::GetInstance(); Entity entity = CreateCameraEntity(cameraDesc); FPSControllerComponent FPSCamComp; FPSCamComp.SpeedFactor = 2.4f; pECS->AddComponent<FPSControllerComponent>(entity, FPSCamComp); const CharacterColliderCreateInfo colliderInfo = { .Entity = entity, .Position = pECS->GetComponent<PositionComponent>(entity), .Rotation = pECS->GetComponent<RotationComponent>(entity), .CollisionGroup = FCollisionGroup::COLLISION_GROUP_DYNAMIC, .CollisionMask = UINT32_MAX, // The player collides with everything .EntityID = entity }; constexpr const float capsuleHeight = 1.8f; constexpr const float capsuleRadius = 0.2f; CharacterColliderComponent characterColliderComponent = PhysicsSystem::GetInstance()->CreateCharacterCapsule(colliderInfo, std::max(0.0f, capsuleHeight - 2.0f * capsuleRadius), capsuleRadius); pECS->AddComponent<CharacterColliderComponent>(entity, characterColliderComponent); // Listener pECS->AddComponent<ListenerComponent>(entity, { AudioAPI::GetDevice()->GetAudioListener(false) }); return entity; } Entity CreateCameraTrackEntity(const LambdaEngine::CameraDesc& cameraDesc, const TArray<glm::vec3>& track) { ECSCore* pECS = ECSCore::GetInstance(); Entity entity = CreateCameraEntity(cameraDesc); TrackComponent camTrackComp; camTrackComp.Track = track; pECS->AddComponent<TrackComponent>(entity, camTrackComp); return entity; } Entity CreateCameraEntity(const CameraDesc& cameraDesc) { ECSCore* pECS = ECSCore::GetInstance(); const Entity entity = pECS->CreateEntity(); const ViewProjectionMatricesComponent viewProjComp = { .Projection = glm::perspective(glm::radians(cameraDesc.FOVDegrees), cameraDesc.Width / cameraDesc.Height, cameraDesc.NearPlane, cameraDesc.FarPlane), .View = glm::lookAt(cameraDesc.Position, cameraDesc.Position + cameraDesc.Direction, g_DefaultUp) }; pECS->AddComponent<ViewProjectionMatricesComponent>(entity, viewProjComp); const CameraComponent camComp = { .NearPlane = cameraDesc.NearPlane, .FarPlane = cameraDesc.FarPlane, .FOV = cameraDesc.FOVDegrees }; pECS->AddComponent<CameraComponent>(entity, camComp); pECS->AddComponent<PositionComponent>(entity, PositionComponent{ .Position = cameraDesc.Position }); pECS->AddComponent<RotationComponent>(entity, RotationComponent{ .Quaternion = glm::quatLookAt(cameraDesc.Direction, g_DefaultUp) }); pECS->AddComponent<ScaleComponent>(entity, ScaleComponent{ .Scale = {1.f, 1.f, 1.f} }); pECS->AddComponent<VelocityComponent>(entity, VelocityComponent()); return entity; } }
37.138298
194
0.776282
IbexOmega
0adb4715fed4338c2bc04fc8b68daba3dd0520c4
3,003
hh
C++
AssocTools/AstSTLMap2.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
AssocTools/AstSTLMap2.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
AssocTools/AstSTLMap2.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------- // File and Version Information: // $Id: AstSTLMap2.hh 436 2010-01-13 16:51:56Z stroili $ // // Description: // two -directional association map between two data types. // // // Author List: // Luca Lista 27 Mar 97 // //------------------------------------------------------------------- #ifndef ASTSTLMAP2_HH #define ASTSTLMAP2_HH //------------- // C Headers -- //------------- //--------------- // C++ Headers -- //--------------- #include <iostream> #include <vector> using std::vector; #include <map> using std::map; #include "BbrStdUtils/CollectionUtils.hh" //---------------------- // Base Class Headers -- //---------------------- #include "AbsEvent/AbsEvtObj.hh" //------------------------------- // Collaborating Class Headers -- //------------------------------- // --------------------- // -- Class Interface -- // --------------------- template<class T1, class T2> class AstSTLMap2 : public AbsEvtObj { //-------------------- // Declarations -- //-------------------- // Typedefs, consts, and enums public: typedef std::map< T1*, vector<T2*>, BbrPtrLess > Map1; typedef std::map< T2*, vector<T1*>, BbrPtrLess > Map2; //-------------------- // Instance Members -- //-------------------- public: // Constructors AstSTLMap2(); AstSTLMap2(unsigned (*)(T1 *const&), unsigned (*)(T2 *const&)); // Detsructor virtual ~AstSTLMap2(); // Selectors (const) inline const Map1& map1() const { return _map1; } inline const Map2& map2() const { return _map2; } bool findValue1(T1*, vector<T2*>& retval) const; bool findValue2(T2*, vector<T1*>& retval) const; // Return the associated list T2* findFirstValue1(const T1*) const; T1* findFirstValue2(const T2*) const; // Return the first item in the associated list, or 0 if there is no match. int members1() const {return _map1.size();} int members2() const {return _map2.size();} int entries1(T1* ) const; int entries2(T2*) const; size_t removeMatchesForKey1(const T1 *); size_t removeMatchesForKey2(const T2 *); // Return the number of matches removed, 0 if the key was not found. // Helpers (const) bool contains(T1*, T2*) const ; // Note that the search for T2 is linear. bool containsT1(T1*) const ; bool containsT2(T2*) const ; // Modifiers void append(T1*, T2*); size_t remove(T1*, T2*); // Returns 0 if either T1 or T2 cannot be found. // Note that the search for T2 is linear. void clear(); // Clear map of entries. Does not delete contents. protected: private: static unsigned hashFunction1(T1 *const & p); static unsigned hashFunction2(T2 *const & p); Map1 _map1; Map2 _map2; Map1& notConstMap1() const; Map2& notConstMap2() const; }; #ifdef BABAR_COMP_INST #include "AssocTools/AstSTLMap2.icc" #endif // BABAR_COMP_INST #endif // TEMPLATE_HH
21.604317
77
0.549784
brownd1978
0ade3fa514c18931177c702ef1f57baefe1c50c9
835
cpp
C++
Atum/Support/MetaData/ColorWidget.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
23
2017-11-01T14:47:26.000Z
2021-12-30T08:04:31.000Z
Atum/Support/MetaData/ColorWidget.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
1
2018-12-06T14:19:55.000Z
2018-12-07T04:06:35.000Z
Atum/Support/MetaData/ColorWidget.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
4
2017-11-30T10:25:58.000Z
2019-04-21T14:11:40.000Z
#include "ColorWidget.h" void ColorWidget::Init(EUICategories* parent, const char* catName, const char* labelName) { ProperyWidget::Init(parent, catName, labelName); ecolor = new EUILabel(panel, "", 90, 5, 95, 20); ecolor->SetListener(-1, this, 0); } void ColorWidget::SetData(void* owner, void* set_data) { data = (Color*)set_data; int clr[3]; clr[0] = (int)(data->r * 255.0f); clr[1] = (int)(data->g * 255.0f); clr[2] = (int)(data->b * 255.0f); ecolor->SetBackgroundColor(true, clr); } void ColorWidget::OnLeftDoubliClick(EUIWidget* sender, int mx, int my) { if (EUI::OpenColorDialog(ecolor->GetRoot()->GetNative(), &data->r)) { int clr[3]; clr[0] = (int)(data->r * 255.0f); clr[1] = (int)(data->g * 255.0f); clr[2] = (int)(data->b * 255.0f); ecolor->SetBackgroundColor(true, clr); changed = true; } }
23.194444
89
0.640719
ENgineE777
0ae0f6253de6e035a276845c24110d086db66b27
2,267
cpp
C++
TDEngine2/source/graphics/UI/CImageComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-15T01:14:15.000Z
2019-07-15T01:14:15.000Z
TDEngine2/source/graphics/UI/CImageComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
76
2018-10-27T16:59:36.000Z
2022-03-30T17:40:39.000Z
TDEngine2/source/graphics/UI/CImageComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-29T02:02:08.000Z
2019-07-29T02:02:08.000Z
#include "../../../include/graphics/UI/CImageComponent.h" namespace TDEngine2 { struct TImageArchiveKeys { }; CImage::CImage() : CBaseComponent() { } E_RESULT_CODE CImage::Init() { if (mIsInitialized) { return RC_FAIL; } mImageResourceId = TResourceId::Invalid; mImageSpriteId = Wrench::StringUtils::GetEmptyStr(); mIsInitialized = true; return RC_OK; } E_RESULT_CODE CImage::Load(IArchiveReader* pReader) { if (!pReader) { return RC_FAIL; } return RC_OK; } E_RESULT_CODE CImage::Save(IArchiveWriter* pWriter) { if (!pWriter) { return RC_FAIL; } return RC_OK; } E_RESULT_CODE CImage::SetImageId(const std::string& id) { if (id.empty()) { return RC_INVALID_ARGS; } mImageSpriteId = id; return RC_OK; } E_RESULT_CODE CImage::SetImageResourceId(TResourceId resourceId) { if (TResourceId::Invalid == resourceId) { return RC_INVALID_ARGS; } mImageResourceId = resourceId; return RC_OK; } const std::string& CImage::GetImageId() const { return mImageSpriteId; } TResourceId CImage::GetImageResourceId() const { return mImageResourceId; } IComponent* CreateImage(E_RESULT_CODE& result) { return CREATE_IMPL(IComponent, CImage, result); } CImageFactory::CImageFactory() : CBaseObject() { } E_RESULT_CODE CImageFactory::Init() { if (mIsInitialized) { return RC_FAIL; } mIsInitialized = true; return RC_OK; } E_RESULT_CODE CImageFactory::Free() { if (!mIsInitialized) { return RC_FAIL; } mIsInitialized = false; delete this; return RC_OK; } IComponent* CImageFactory::Create(const TBaseComponentParameters* pParams) const { if (!pParams) { return nullptr; } const TImageParameters* params = static_cast<const TImageParameters*>(pParams); E_RESULT_CODE result = RC_OK; return CreateImage(result); } IComponent* CImageFactory::CreateDefault(const TBaseComponentParameters& params) const { E_RESULT_CODE result = RC_OK; return CreateImage(result); } TypeId CImageFactory::GetComponentTypeId() const { return CImage::GetTypeId(); } IComponentFactory* CreateImageFactory(E_RESULT_CODE& result) { return CREATE_IMPL(IComponentFactory, CImageFactory, result); } }
14.720779
87
0.698721
bnoazx005
0ae1e5cb12c6d0b8f7e0165ff950ad9198842ba4
2,087
hpp
C++
include/termox/widget/widgets/horizontal_slider.hpp
skvl/TermOx
35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934
[ "MIT" ]
null
null
null
include/termox/widget/widgets/horizontal_slider.hpp
skvl/TermOx
35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934
[ "MIT" ]
null
null
null
include/termox/widget/widgets/horizontal_slider.hpp
skvl/TermOx
35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934
[ "MIT" ]
1
2021-08-06T10:17:28.000Z
2021-08-06T10:17:28.000Z
#ifndef TERMOX_WIDGET_WIDGETS_HORIZONTAL_SLIDER_HPP #define TERMOX_WIDGET_WIDGETS_HORIZONTAL_SLIDER_HPP #include <cstddef> #include <signals_light/signal.hpp> #include <termox/painter/color.hpp> #include <termox/painter/glyph.hpp> #include <termox/painter/painter.hpp> #include <termox/system/key.hpp> #include <termox/system/mouse.hpp> #include <termox/widget/focus_policy.hpp> #include <termox/widget/pipe.hpp> #include <termox/widget/widget.hpp> namespace ox { // TODO this can probably be removed, scroll bar replaces it. class Horizontal_slider : public Widget { public: sl::Signal<void(float)> percent_changed; sl::Signal<void()> scrolled_up; sl::Signal<void()> scrolled_down; public: Horizontal_slider() { using namespace pipe; *this | fixed_height(1) | strong_focus() | wallpaper(L' ' | bg(Color::Light_gray)); } void set_percent(float percent); auto percent() const -> float { return percent_progress_; } protected: auto paint_event() -> bool override { auto const x = percent_to_position(percent_progress_); Painter{*this}.put(indicator_, x, 0); return Widget::paint_event(); } auto mouse_press_event(Mouse const& m) -> bool override; auto mouse_wheel_event(Mouse const& m) -> bool override; auto key_press_event(Key k) -> bool override; private: Glyph indicator_ = L'░'; float percent_progress_ = 0.0; private: auto position_to_percent(std::size_t position) -> float; auto percent_to_position(float percent) -> std::size_t; }; /// Helper function to create an instance. template <typename... Args> auto horizontal_slider(Args&&... args) -> std::unique_ptr<Horizontal_slider> { return std::make_unique<Horizontal_slider>(std::forward<Args>(args)...); } namespace slot { auto set_percent(Horizontal_slider& s) -> sl::Slot<void(float)>; auto set_percent(Horizontal_slider& s, float percent) -> sl::Slot<void(void)>; } // namespace slot } // namespace ox #endif // TERMOX_WIDGET_WIDGETS_HORIZONTAL_SLIDER_HPP
27.460526
78
0.703402
skvl
0ae24cf263f367d8460b5612c853eeda781029c5
70
cpp
C++
sprint00/t06/main.cpp
Hvvang/CppTrack
3e1854d626d153f5597459200f715a91f6a03107
[ "MIT" ]
1
2020-08-27T23:41:48.000Z
2020-08-27T23:41:48.000Z
sprint00/t06/main.cpp
Hvvang/CppTrack
3e1854d626d153f5597459200f715a91f6a03107
[ "MIT" ]
null
null
null
sprint00/t06/main.cpp
Hvvang/CppTrack
3e1854d626d153f5597459200f715a91f6a03107
[ "MIT" ]
null
null
null
#include "meadSong.h" int main(void) { showLyrics(); return 0; }
10
21
0.628571
Hvvang
0ae69f1eeb6ed74a8c946c9194f0d558aaf1f9bf
13,299
hpp
C++
include/xul/net/http/http_client.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/net/http/http_client.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/net/http/http_client.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <xul/net/http/http_connection.hpp> #include <xul/net/url_request.hpp> #include <xul/net/uri.hpp> #include <xul/util/timer_holder.hpp> #include <xul/util/runnable_callback.hpp> #include <xul/net/http/http_content_type.hpp> #include <xul/net/http/http_method.hpp> #include <xul/net/url_messages.hpp> #include <xul/net/url_response.hpp> #include <xul/data/printables.hpp> #include <xul/data/buffer.hpp> #include <xul/util/log.hpp> #include <xul/lang/object_ptr.hpp> #include <xul/lang/object_impl.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/asio/error.hpp> #include <string> namespace xul { class http_client : public object_impl<object> { public: typedef boost::function<void (http_client*, uri*, int, url_response*, uint8_t*, int)> download_data_callback_type; typedef boost::function<void (http_client*, uri*, int, url_response*, int64_t)> query_head_callback_type; enum error_code { error_general = -1, error_timeout = -2, }; class http_handler : private boost::noncopyable, public timer_listener, public http_connection_listener_adapter { public: explicit http_handler(http_client& owner) : m_owner(owner) { m_xul_logger = owner.m_xul_logger; m_content_length = 0; } virtual ~http_handler() { } void set_extra_header(const string_table* extra_headers) { m_extra_headers = extra_headers; } void request(uri* u) { m_url = u; m_owner.m_connection->request(m_method.c_str(), m_url->get_original_string(), m_extra_headers.get()); } virtual void on_timer_elapsed(timer* sender) { handle_error(error_timeout); } virtual void do_handle_response() = 0; virtual bool on_http_response(http_connection* sender, url_response* resp, const char* real_url) { m_response = resp; m_content_length = url_messages::get_content_length(*resp); XUL_DEBUG("on_http_response content_length=" << m_content_length << " " << *resp); do_handle_response(); return true; } virtual bool on_http_data(http_connection* sender, const uint8_t* data, int size) { return false; } virtual void on_http_complete(http_connection* sender, int64_t size) { } virtual void on_http_error(http_connection* sender, int errcode) { handle_error(errcode); } virtual void handle_error(int errcode) = 0; protected: XUL_LOGGER_DEFINE(); http_client& m_owner; boost::intrusive_ptr<uri> m_url; boost::intrusive_ptr<url_response> m_response; int64_t m_content_length; boost::intrusive_ptr<const string_table> m_extra_headers; std::string m_method; //timer_ptr m_timeout_timer; }; class http_download_data_handler : public http_handler { public: explicit http_download_data_handler(http_client& owner, int maxSize, download_data_callback_type callback) : http_handler(owner), m_callback(callback) { m_method = http_method::get(); m_max_size = maxSize; m_recv_size = 0; } virtual void do_handle_response() { m_data.resize(0); if (m_content_length < 0) { XUL_WARN("http_client do_handle_response no content-length from " << m_url->get_original_string()); } if (m_content_length > m_max_size) { XUL_WARN("content_length is too large " << xul::make_tuple(m_content_length, m_max_size)); handle_error(-1); return; } if (m_content_length > 0) m_data.reserve(m_content_length); } virtual bool on_http_data(http_connection* sender, const uint8_t* data, int size) { m_data.append(data, size); if (m_data.size() > m_max_size) { XUL_REL_ERROR("recv_size is too large " << xul::make_tuple(m_data.size(), m_max_size)); handle_error(-1); return false; } return true; } virtual void on_http_complete(http_connection* sender, int64_t size) { invoke_callback(0); } virtual void handle_error(int errcode) { m_owner.close_connection(); if (boost::asio::error::eof == errcode && m_content_length < 0) { invoke_callback(0); return; } invoke_callback(errcode); } protected: void invoke_callback(int errcode) { m_owner.handle_complete(); m_callback(&m_owner, m_url.get(), errcode, m_response.get(), m_data.data(), m_data.size()); } private: download_data_callback_type m_callback; byte_buffer m_data; int m_max_size; int m_recv_size; }; class http_query_head_handler : public http_handler { public: explicit http_query_head_handler(http_client& owner, query_head_callback_type callback) : http_handler(owner), m_callback(callback) { m_method = http_method::head(); } virtual void do_handle_response() { m_owner.handle_complete(); m_callback(&m_owner, m_url.get(), 0, m_response.get(), m_content_length); } virtual void handle_error(int errcode) { m_owner.handle_complete(); m_callback(&m_owner, m_url.get(), errcode, m_response.get(), 0); } private: query_head_callback_type m_callback; }; class http_post_data_handler : public http_download_data_handler { public: explicit http_post_data_handler(http_client& owner, int maxSize, download_data_callback_type callback , const std::string& bodyData, const std::string& contentType = std::string()) : http_download_data_handler(owner, maxSize, callback) , m_post_body_data(bodyData) , m_content_type(contentType) { m_method = http_method::post(); if (m_content_type.empty()) { m_content_type = http_content_type::octet_stream(); } } virtual void on_http_put_content(http_connection* sender) { sender->send_data(reinterpret_cast<const uint8_t*>(m_post_body_data.data()), m_post_body_data.size()); } private: std::string m_post_body_data; std::string m_content_type; }; explicit http_client(io_service* ios, bool http11 = false, bool gzip_enabled = false) : m_ios(ios) , m_connection(create_http_connection(ios)) , m_keepalive(false) { XUL_LOGGER_INIT("http_client"); m_receive_buffer_size = 32 * 1024; set_keepalive(false); m_connection->ref_options()->set("gzip", gzip_enabled ? "on" : "off"); m_connection->ref_options()->set_protocol_version(http11 ? "1.1" : "1.0"); m_connection->set_receive_buffer_size(m_receive_buffer_size); m_connection->set_decoder_buffer_size(m_receive_buffer_size + 1000); } virtual ~http_client() { if (m_connection) { m_connection->set_listener(NULL); } this->clear(); } void set_keepalive(bool keepalive) { set_keep_alive(keepalive); } void set_keep_alive(bool keepalive) { m_keepalive = keepalive; if (m_connection) m_connection->ref_options()->set_keep_alive(m_keepalive); } void clear() { m_http_handler.reset(); this->close(); } bool is_started() const { return m_connection && m_connection->is_started(); } void set_receive_buffer_size(size_t bufsize) { if (bufsize < 1024 || bufsize > 2 * 1024 * 1024) return; m_receive_buffer_size = bufsize; if (m_connection) m_connection->set_receive_buffer_size(m_receive_buffer_size); } void handle_complete() { XUL_DEBUG("handle_complete"); if (!m_keepalive) { close_connection(); } } void close_connection() { if (m_connection) { m_connection->set_listener(NULL); m_connection->close(); } } void close() { XUL_DEBUG("close"); close_connection(); //m_http_handler.reset(); } //void async_download_data(const char* host, int port, const url_request* req, int maxSize, download_data_callback_type callback) //{ // close(); // m_http_handler.reset(new http_download_data_handler(*this, maxSize, callback)); // async_execute(host, port, req); //} void async_download_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback, const string_table* extra_header = NULL) { download_data(urlstr, maxSize, callback, extra_header); } void download_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback, const string_table* extra_header = NULL) { boost::intrusive_ptr<uri> u = create_uri(); if (false == u->parse(urlstr.c_str())) { uint8_t* buf = NULL; boost::intrusive_ptr<runnable> r = make_runnable(boost::bind(callback, this, u.get(), -1, (xul::url_response*)NULL, buf, 0)); m_ios->post(r.get()); return; } async_download_uri_data(u.get(), maxSize, callback, extra_header); } void async_download_uri_data(uri* u, size_t maxSize, download_data_callback_type callback, const string_table* extra_header = NULL) { XUL_DEBUG("async_download_uri_data " << u->get_original_string()); //close(); m_http_handler.reset(new http_download_data_handler(*this, maxSize, callback)); if (extra_header) { m_http_handler->set_extra_header(extra_header); } async_download(u); } void async_query_head(uri* u, query_head_callback_type callback) { //close(); m_http_handler.reset(new http_query_head_handler(*this, callback)); async_download(u); } void async_post_data(uri* u, size_t maxSize, download_data_callback_type callback, const std::string& body, const std::string& contentType = std::string(), const string_table* extra_header = NULL) { post_data(u->get_original_string(), maxSize, callback, body, contentType, extra_header); } void async_post_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback, const std::string& body, const std::string& contentType = std::string(), const string_table* extra_header = NULL) { post_data(urlstr, maxSize, callback, body, contentType, extra_header); } void post_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback, const std::string& body, const std::string& contentType = std::string(), const string_table* extra_header = NULL) { boost::intrusive_ptr<uri> u = create_uri(); u->parse(urlstr.c_str()); //close(); m_http_handler.reset(new http_post_data_handler(*this, maxSize, callback, body, contentType)); boost::intrusive_ptr<string_table> headers; if (extra_header) headers = extra_header->clone(); else headers = create_associative_istring_array(); headers->set("Content-Length", numerics::format<int>(body.size()).c_str()); m_http_handler->set_extra_header(headers.get()); async_download(u.get()); } const http_connection* get_connection() const { return m_connection.get(); } protected: void async_download(uri* u) { XUL_DEBUG("async_download " << u->get_original_string()); if (!m_http_handler) { assert(false); return; } m_connection->set_listener(m_http_handler.get()); m_http_handler->request(u); } //void async_execute(const char* host, int port, const url_request* req) //{ // XUL_DEBUG("async_execute " << xul::make_tuple(host, port, req->get_url())); // if (!m_http_handler) // { // assert(false); // return; // } // m_connection->set_listener(m_http_handler.get()); // m_connection->execute(host, port, req); //} private: XUL_LOGGER_DEFINE(); boost::intrusive_ptr<io_service> m_ios; size_t m_receive_buffer_size; boost::intrusive_ptr<http_connection> m_connection; boost::shared_ptr<http_handler> m_http_handler; bool m_keepalive; }; }
33.498741
137
0.609219
hindsights
0aee68ed3261bbc11f994664754f9d0544f656e5
6,803
cpp
C++
lv_demos/src/lv_demo_graphing/lv_demo_graphing.cpp
mov-rax/Smart_Symbolic_Graphing_Calculator
2ebd2e1cb12da1a826a9aa650027c11e239bfe4a
[ "MIT" ]
null
null
null
lv_demos/src/lv_demo_graphing/lv_demo_graphing.cpp
mov-rax/Smart_Symbolic_Graphing_Calculator
2ebd2e1cb12da1a826a9aa650027c11e239bfe4a
[ "MIT" ]
null
null
null
lv_demos/src/lv_demo_graphing/lv_demo_graphing.cpp
mov-rax/Smart_Symbolic_Graphing_Calculator
2ebd2e1cb12da1a826a9aa650027c11e239bfe4a
[ "MIT" ]
null
null
null
#include "lv_demo_graphing.hxx" #include "graph.hxx" #include <math.h> static mpf_class plot_sin(mpf_class x) { return mpf_class(sin(x.get_d()*0.1) * 50.0); } static void zoom_btnmatrix_cb(lv_event_t* event){ uint32_t id = lv_btnmatrix_get_selected_btn(event->target); if (id == 0) { static_cast<graphing::Graph*>(event->user_data)->scale_delta(mpf_class(-0.1)); } else { static_cast<graphing::Graph*>(event->user_data)->scale_delta(mpf_class(+0.1)); } } static void dropdown_button_cb(lv_event_t* event){ char buf[10]; std::cout << "DROPDOWN_BUTTON_CB\n"; //std::stringstream ss; int id = lv_dropdown_get_selected(event->target); lv_dropdown_get_selected_str(event->target, buf, sizeof(buf)); // C function, so no std::string //ss << buf; auto graph = static_cast<graphing::Graph*>(event->user_data); // Check if user selected to add a function to the graph. if (buf[0]=='+'){ graph->add_function(""); lv_dropdown_set_selected(event->target, id); graph->set_function_textarea_str(""); return; } graph->switch_to_bold(id); // Finds user-selected plot. graphing::Plot* plot = graph->get_plot(id); if (plot == nullptr) graph->set_function_textarea_str("NULL"); else { // std::cout << "ID: " << id << "\n"; // std::cout << "EXPR: " << plot->function_expression << "\n"; graph->set_function_textarea_str(plot->function_expression); } //graph->update(); //std::cout << buf << "\n"; } static void textarea_cb(lv_event_t* event){ auto graph = static_cast<graphing::Graph*>(event->user_data); auto func_str = graph->get_function_button_selected_str(); auto func_id = graph->get_function_button_selected_id(); auto func_expression = std::string(lv_textarea_get_text(event->target)); auto plot = graph->get_plot(func_id); std::cout << "TEXTAREA_CB: " << func_str << " " << func_expression << " " << func_id << "\n"; graph->update_function(func_str + "(x):=" + func_expression); plot->name = std::move(func_str); plot->function_expression = std::move(func_expression); graph->update(); } DEFINE_GRAPH { #if ENABLE_GIAC == 1 static graphing::Graph graph(lv_scr_act(), ctx); #else static graphing::Graph graph(lv_scr_act()); #endif static lv_style_t zoom_style_bg; static lv_style_t zoom_style; static lv_style_t textarea_style; static lv_style_t function_button_style; static const char* map[] = {"+", "-"}; static lv_obj_t* zoom_buttons = lv_btnmatrix_create(graph.get_canvas()); static lv_obj_t* function_text_area = lv_textarea_create(graph.get_canvas()); static lv_obj_t* function_button = lv_dropdown_create(graph.get_canvas()); // zoom button setup lv_style_init(&zoom_style_bg); lv_style_set_pad_all(&zoom_style_bg, 10); //lv_style_set_pad_gap(&zoom_style_bg, 0); //lv_style_set_clip_corner(&zoom_style_bg, true); //lv_style_set_radius(&zoom_style_bg, LV_RADIUS_CIRCLE); lv_style_set_border_width(&zoom_style_bg, 0); lv_style_set_bg_opa(&zoom_style_bg, LV_OPA_0); //lv_style_set_size(&zoom_style_bg, 50); lv_style_init(&zoom_style); //lv_style_set_radius(&zoom_style, 0); //lv_style_set_border_width(&zoom_style, 1); lv_style_set_border_opa(&zoom_style, LV_OPA_50); lv_style_set_shadow_color(&zoom_style, lv_color_black()); lv_style_set_shadow_spread(&zoom_style, 1); lv_style_set_shadow_width(&zoom_style, 20); lv_style_set_shadow_ofs_y(&zoom_style, 0); lv_style_set_shadow_opa(&zoom_style, LV_OPA_70); lv_style_set_text_font(&zoom_style, &lv_font_dejavu_16_persian_hebrew); //lv_style_set_border_color(&zoom_style, lv_palette_main(LV_PALETTE_GREY)); //lv_style_set_border_side(&zoom_style, LV_BORDER_SIDE_INTERNAL); //lv_style_set_radius(&zoom_style, 0); lv_btnmatrix_set_map(zoom_buttons, map); lv_btnmatrix_set_btn_ctrl_all(zoom_buttons, LV_BTNMATRIX_CTRL_CLICK_TRIG); lv_obj_add_style(zoom_buttons, &zoom_style_bg, 0); lv_obj_add_style(zoom_buttons, &zoom_style, LV_PART_ITEMS); lv_obj_set_size(zoom_buttons, 80, 50); lv_obj_align(zoom_buttons, LV_ALIGN_TOP_RIGHT, 0, 0); lv_obj_add_event_cb(zoom_buttons, zoom_btnmatrix_cb, LV_EVENT_VALUE_CHANGED, &graph); // function text area setup lv_style_init(&textarea_style); lv_style_set_text_font(&textarea_style, &lv_font_montserrat_12_subpx); lv_style_set_border_width(&textarea_style, 1); lv_style_set_border_opa(&textarea_style, LV_OPA_50); lv_style_set_shadow_color(&textarea_style, lv_color_black()); lv_style_set_shadow_spread(&textarea_style, 1); lv_style_set_shadow_width(&textarea_style, 20); lv_style_set_shadow_ofs_y(&textarea_style, 0); lv_style_set_shadow_opa(&textarea_style, LV_OPA_70); lv_style_set_pad_top(&textarea_style, 5); lv_style_set_pad_right(&textarea_style, 40); //lv_style_set_pad_left(&textarea_style, 3); lv_style_set_text_align(&textarea_style, LV_ALIGN_LEFT_MID); //lv_style_set_text_color(&textarea_style, lv_color_make(255, 0, 0)); lv_textarea_set_one_line(function_text_area, true); lv_obj_add_style(function_text_area, &textarea_style, 0); lv_obj_set_size(function_text_area, 180, 30); lv_obj_align(function_text_area, LV_ALIGN_TOP_MID, -20, 10); lv_obj_add_event_cb(function_text_area, textarea_cb, LV_EVENT_VALUE_CHANGED, &graph); // function button setup lv_style_init(&function_button_style); lv_style_set_text_font(&function_button_style, &lv_font_montserrat_12_subpx); lv_style_set_text_align(&function_button_style, LV_ALIGN_CENTER); lv_style_set_pad_all(&function_button_style, 6); //lv_style_set_align(&function_button_style, LV_ALIGN_TOP_MID); //lv_dropdown_add_option(function_button, "f(x)", 0); //lv_dropdown_set_options(function_button, "f(x)\ng(x)\nh(x)"); lv_dropdown_set_symbol(function_button , NULL); lv_obj_add_style(function_button, &function_button_style, 0); lv_obj_add_style(function_button, &function_button_style, LV_PART_ITEMS); lv_obj_set_size(function_button, 40, 30); lv_obj_align(function_button, LV_ALIGN_TOP_MID, 50, 10); lv_obj_add_event_cb(function_button, dropdown_button_cb, LV_EVENT_VALUE_CHANGED, &graph); // graph setup graph.set_function_button(function_button); graph.set_function_textarea(function_text_area); graph.set_scale(mpf_class("0.5")); graph.add_function(""); // graph.add_function(plot_sin, LV_COLOR_MAKE16(255, 0, 0), "sin(x)"); // graph.add_function([](mpf_class x){return x;}, LV_COLOR_MAKE16(0, 255, 0), "x"); std::cout <<"EVERYTHING ADDED\n"; graph.update(); }
41.993827
99
0.721446
mov-rax
0af0040150be21d39134aa89a76ca7b88410cc2b
358
cpp
C++
02_code/20_sdl_show_bmp_change_target/mainwindow.cpp
okFancy/audio-video-dev-tutorial
2cee9e530b402d13a3b84acac6d25bc3b5bd4dc2
[ "MIT" ]
null
null
null
02_code/20_sdl_show_bmp_change_target/mainwindow.cpp
okFancy/audio-video-dev-tutorial
2cee9e530b402d13a3b84acac6d25bc3b5bd4dc2
[ "MIT" ]
null
null
null
02_code/20_sdl_show_bmp_change_target/mainwindow.cpp
okFancy/audio-video-dev-tutorial
2cee9e530b402d13a3b84acac6d25bc3b5bd4dc2
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "playthread.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_playButton_clicked() { PlayThread *thread = new PlayThread(this); thread->start(); }
18.842105
46
0.681564
okFancy
0af2a24c515740fceb1225d3bc42fa245c8d3e41
29,148
cc
C++
tests/math/gtest_matrix_svd.cc
lemony-fresh/mve
d90cc2c813fef026f7732c5a26f6c15973a36042
[ "BSD-3-Clause" ]
1
2019-05-30T13:19:21.000Z
2019-05-30T13:19:21.000Z
tests/math/gtest_matrix_svd.cc
MasterShockwave/mve
7a96751db098bb6f5c0b4075921b0e8e43a69bb6
[ "BSD-3-Clause" ]
null
null
null
tests/math/gtest_matrix_svd.cc
MasterShockwave/mve
7a96751db098bb6f5c0b4075921b0e8e43a69bb6
[ "BSD-3-Clause" ]
null
null
null
/* * Test cases for matrix singular value decomposition (SVD). * Written by Simon Fuhrmann and Daniel Thuerck. */ #include <limits> #include <gtest/gtest.h> #include "math/matrix_svd.h" TEST(MatrixSVDTest, MatrixSimpleTest1) { math::Matrix<double, 3, 2> A; A(0, 0) = 1.0; A(0, 1) = 4.0; A(1, 0) = 2.0; A(1, 1) = 5.0; A(2, 0) = 3.0; A(2, 1) = 6.0; math::Matrix<double, 3, 2> U; math::Matrix<double, 2, 2> S; math::Matrix<double, 2, 2> V; math::matrix_svd(A, &U, &S, &V, 1e-10); math::Matrix<double, 3, 2> A_svd = U * S * V.transposed(); for (int i = 0; i < 6; ++i) EXPECT_NEAR(A_svd[i], A[i], 1e-13); } TEST(MatrixSVDTest, MatrixSimpleTest2) { math::Matrix<double, 2, 3> A; A(0, 0) = 1.0; A(0, 1) = 2.0; A(0, 2) = 3.0; A(1, 0) = 4.0; A(1, 1) = 5.0; A(1, 2) = 6.0; math::Matrix<double, 2, 3> U; math::Matrix<double, 3, 3> S; math::Matrix<double, 3, 3> V; math::matrix_svd(A, &U, &S, &V, 1e-10); math::Matrix<double, 2, 3> A_svd = U * S * V.transposed(); for (int i = 0; i < 6; ++i) EXPECT_NEAR(A_svd[i], A[i], 1e-13); } TEST(MatrixSVDTest, MatrixIsDiagonalTest) { float mat[3 * 10]; std::fill(mat, mat + 3 * 10, 0.0f); EXPECT_TRUE(math::matrix_is_diagonal(mat, 3, 10, 0.0f)); EXPECT_TRUE(math::matrix_is_diagonal(mat, 10, 3, 0.0f)); // Interpret as 3x10 matrix (3 rows, 10 columns). mat[0 * 10 + 0] = 10.0f; mat[1 * 10 + 1] = 20.0f; mat[2 * 10 + 2] = 30.0f; EXPECT_TRUE(math::matrix_is_diagonal(mat, 3, 10, 0.0f)); mat[2 * 10 + 3] = 40.0f; EXPECT_FALSE(math::matrix_is_diagonal(mat, 3, 10, 0.0f)); } TEST(MatrixSVDTest, MatrixIsSubmatrixZeroEnclosed) { float mat[4 * 4]; std::fill(mat, mat + 4 * 4, 0.0f); // Everything is zero. EXPECT_TRUE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f)); // Doesn't check diagonally. mat[1 * 4 + 1] = 1.0f; EXPECT_TRUE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f)); // Damage the upper row. mat[1 * 4 + 2] = 2.0f; EXPECT_FALSE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f)); mat[1 * 4 + 2] = 0.0f; // Damage the left column. mat[2 * 4 + 1] = 3.0f; EXPECT_FALSE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f)); mat[2 * 4 + 1] = 0.0f; // Check with submatrix as large as full matrix. EXPECT_TRUE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 4, 0.0f)); } TEST(MatrixSVDTest, MatrixIsSuperdiagonalNonzero) { float mat[3 * 10]; std::fill(mat, mat + 3 * 10, 1.0f); EXPECT_TRUE(math::internal::matrix_is_superdiagonal_nonzero(mat, 3, 10, 0.0f)); EXPECT_TRUE(math::internal::matrix_is_superdiagonal_nonzero(mat, 10, 3, 0.0f)); // Interpret as 3x10. Inject a zero. mat[1 * 10 + 2] = 0.0f; EXPECT_FALSE(math::internal::matrix_is_superdiagonal_nonzero(mat, 3, 10, 0.0f)); } TEST(MatrixSVDTest, Matrix2x2Eigenvalues) { math::Matrix2d mat; mat(0,0) = 0.318765239858981; mat(0,1) = -0.433592022305684; mat(1,0) = -1.307688296305273; mat(1,1) = 0.342624466538650; double smaller_ev, larger_ev; math::internal::matrix_2x2_eigenvalues(mat.begin(), &smaller_ev, &larger_ev); EXPECT_NEAR(-0.422395797795416, smaller_ev, 1e-14); EXPECT_NEAR(1.083785504193047, larger_ev, 1e-14); } TEST(MatrixSVDTest, MatrixHouseholderOnZeroTest) { double vec_zero[2]; vec_zero[0] = 0; vec_zero[1] = 0; double house_vector[2]; double house_beta; math::internal::matrix_householder_vector(vec_zero, 2, house_vector, &house_beta, 1e-14, 1.0); EXPECT_NEAR(1.0, house_vector[0], 1e-14); EXPECT_NEAR(0.0, house_vector[1], 1e-14); EXPECT_NEAR(0.0, house_beta, 1e-14); } TEST(MatrixSVDTest, MatrixHouseholderNormalTest) { double vec[3]; vec[0] = 1; vec[1] = 4; vec[2] = 7; double house_vector[3]; double house_beta; math::internal::matrix_householder_vector(vec, 3, house_vector, &house_beta, 1e-14, 1.0); EXPECT_NEAR(1.0, house_vector[0], 1e-14); EXPECT_NEAR(-0.561479286439136, house_vector[1], 1e-14); EXPECT_NEAR(-0.982588751268488, house_vector[2], 1e-14); EXPECT_NEAR(0.876908509020667, house_beta, 1e-14); } TEST(MatrixSVDTest, MatrixHouseholderMatrixTest) { double house_vector[3]; house_vector[0] = 1.000000000000000; house_vector[1] = -0.561479286439136; house_vector[2] = -0.982588751268488; double house_beta; house_beta = 0.876908509020667; double groundtruth_house_matrix[9]; groundtruth_house_matrix[0] = 0.123091490979333; groundtruth_house_matrix[1] = 0.492365963917331; groundtruth_house_matrix[2] = 0.861640436855329; groundtruth_house_matrix[3] = 0.492365963917331; groundtruth_house_matrix[4] = 0.723546709912780; groundtruth_house_matrix[5] = -0.483793257652636; groundtruth_house_matrix[6] = 0.861640436855329; groundtruth_house_matrix[7] = -0.483793257652636; groundtruth_house_matrix[8] = 0.153361799107888; double house_matrix[9]; math::internal::matrix_householder_matrix(house_vector, 3, house_beta, house_matrix); for (int i = 0; i < 9; ++i) { EXPECT_NEAR(groundtruth_house_matrix[i], house_matrix[i], 1e-14); } } TEST(MatrixSVDTest, MatrixHouseholderApplicationTest) { double house_matrix[9]; house_matrix[0] = 0.123091490979333; house_matrix[1] = 0.492365963917331; house_matrix[2] = 0.861640436855329; house_matrix[3] = 0.492365963917331; house_matrix[4] = 0.723546709912780; house_matrix[5] = -0.483793257652636; house_matrix[6] = 0.861640436855329; house_matrix[7] = -0.483793257652636; house_matrix[8] = 0.153361799107888; double groundtruth_mat[9]; groundtruth_mat[0] = 8.124038404635961; groundtruth_mat[1] = 9.601136296387953; groundtruth_mat[2] = 11.078234188139946; groundtruth_mat[3] = 0; groundtruth_mat[4] = 0.732119416177475; groundtruth_mat[5] = 1.464238832354949; groundtruth_mat[6] = 0; groundtruth_mat[7] = 0.531208978310581; groundtruth_mat[8] = 1.062417956621162; double mat[9]; for (int i =0; i < 9; ++i) { mat[i] = static_cast<double>(i + 1); } math::internal::matrix_apply_householder_matrix(mat, 3, 3, house_matrix, 3, 0, 0); for (int i = 0; i < 9; ++i) { EXPECT_NEAR(groundtruth_mat[i], mat[i], 1e-14); } } TEST(MatrixSVDTest, MatrixBidiagonalizationStandardTest) { const int M = 5; const int N = 4; double test_matrix[M * N]; for (int i = 0; i < M*N; ++i) { test_matrix[i] = static_cast<double>(i + 1); } double mat_u[M * M]; double mat_b[M * N]; double mat_v[N * N]; math::internal::matrix_bidiagonalize(test_matrix, M, N, mat_u, mat_b, mat_v, 1e-14); double groundtruth_mat_u[M * M]; groundtruth_mat_u[0] = 0.042070316191167; groundtruth_mat_u[1] = 0.773453352501348; groundtruth_mat_u[2] = -0.565028398052320; groundtruth_mat_u[3] = -0.167888229103364; groundtruth_mat_u[4] = 0.229251939845590; groundtruth_mat_u[5] = 0.210351580955836; groundtruth_mat_u[6] = 0.505719499712420; groundtruth_mat_u[7] = 0.667776546677112; groundtruth_mat_u[8] = 0.448708735648741; groundtruth_mat_u[9] = 0.229640924620372; groundtruth_mat_u[10] = 0.378632845720504; groundtruth_mat_u[11] = 0.237985646923492; groundtruth_mat_u[12] = 0.312183334193103; groundtruth_mat_u[13] = -0.623816560842154; groundtruth_mat_u[14] = -0.559816455877411; groundtruth_mat_u[15] = 0.546914110485173; groundtruth_mat_u[16] = -0.029748205865437; groundtruth_mat_u[17] = -0.367582716208264; groundtruth_mat_u[18] = 0.573059831151541; groundtruth_mat_u[19] = -0.486297621488654; groundtruth_mat_u[20] = 0.715195375249841; groundtruth_mat_u[21] = -0.297482058654365; groundtruth_mat_u[22] = -0.047348766609631; groundtruth_mat_u[23] = -0.230063776854764; groundtruth_mat_u[24] = 0.587221212900103; double groundtruth_mat_b[M * N]; std::fill(groundtruth_mat_b, groundtruth_mat_b + M * N, 0); groundtruth_mat_b[0] = 23.769728648009426; groundtruth_mat_b[1] = 47.80352488206745; groundtruth_mat_b[5] = 4.209811764688732; groundtruth_mat_b[6] = 1.449308026420137; groundtruth_mat_b[10] = -0.000000000000001; groundtruth_mat_b[16] = 0.000000000000002; double groundtruth_mat_v[N * N]; groundtruth_mat_v[0] = 1; groundtruth_mat_v[1] = 0; groundtruth_mat_v[2] = 0; groundtruth_mat_v[3] = 0; groundtruth_mat_v[4] = 0; groundtruth_mat_v[5] = 0.536841016220519; groundtruth_mat_v[6] = -0.738332619241934; groundtruth_mat_v[7] = 0.408248290463862; groundtruth_mat_v[8] = 0; groundtruth_mat_v[9] = 0.576444042007278; groundtruth_mat_v[10] = -0.032335735149281; groundtruth_mat_v[11] = -0.816496580927726; groundtruth_mat_v[12] = 0; groundtruth_mat_v[13] = 0.616047067794038; groundtruth_mat_v[14] = 0.673661148943370; groundtruth_mat_v[15] = 0.408248290463864; } TEST(MatrixSVDTest, MatrixBidiagonalizationQuadraticTest) { const int M = 3; double test_matrix[M * M]; for (int i = 0; i < M*M; ++i) { test_matrix[i] = static_cast<double>(i + 1); } double mat_u[M * M]; double mat_b[M * M]; double mat_v[M * M]; math::internal::matrix_bidiagonalize(test_matrix, M, M, mat_u, mat_b, mat_v, 1e-14); double groundtruth_mat_u[M * M]; groundtruth_mat_u[0] = 0.123091490979333; groundtruth_mat_u[1] = 0.904534033733291; groundtruth_mat_u[2] = -0.408248290463863; groundtruth_mat_u[3] = 0.492365963917331; groundtruth_mat_u[4] = 0.301511344577764; groundtruth_mat_u[5] = 0.816496580927726; groundtruth_mat_u[6] = 0.861640436855329; groundtruth_mat_u[7] = -0.301511344577764; groundtruth_mat_u[8] = -0.408248290463863; double groundtruth_mat_b[M * M]; groundtruth_mat_b[0] = 8.124038404635961; groundtruth_mat_b[1] = 14.659777996582722; groundtruth_mat_b[2] = 0; groundtruth_mat_b[3] = 0; groundtruth_mat_b[4] = 1.959499950338375; groundtruth_mat_b[5] = -0.501267429156329; groundtruth_mat_b[6] = 0; groundtruth_mat_b[7] = 0; groundtruth_mat_b[8] = 0; double groundtruth_mat_v[M * M]; groundtruth_mat_v[0] = 1; groundtruth_mat_v[1] = 0; groundtruth_mat_v[2] = 0; groundtruth_mat_v[3] = 0; groundtruth_mat_v[4] = 0.654930538417842; groundtruth_mat_v[5] = 0.755689082789818; groundtruth_mat_v[6] = 0; groundtruth_mat_v[7] = 0.755689082789818; groundtruth_mat_v[8] = -0.654930538417842; for (int i = 0; i < M * M; ++i) { EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-14); EXPECT_NEAR(groundtruth_mat_b[i], mat_b[i], 1e-14); EXPECT_NEAR(groundtruth_mat_v[i], mat_v[i], 1e-14); } } TEST(MatrixSVDTest, MatrixBidiagonalizationScalarTest) { double mat_a = 2; double mat_u, mat_b, mat_v; math::internal::matrix_bidiagonalize(&mat_a, 1, 1, &mat_u, &mat_b, &mat_v, 1e-14); EXPECT_NEAR(1, mat_u, 1e-14); EXPECT_NEAR(2, mat_b, 1e-14); EXPECT_NEAR(1, mat_v, 1e-14); } TEST(MatrixSVDTest, MatrixSVDQuadraticSTest) { double mat_a[9]; for (int i = 0; i < 9; ++i) { mat_a[i] = static_cast<double>(i + 1); } double mat_u[9]; double mat_s[3]; double mat_v[9]; math::internal::matrix_gk_svd(mat_a, 3, 3, mat_u, mat_s, mat_v, 1e-6); double groundtruth_mat_s[3]; groundtruth_mat_s[0] = 16.848103352614210; groundtruth_mat_s[1] = 1.068369514554709; groundtruth_mat_s[2] = 0; EXPECT_NEAR(groundtruth_mat_s[0], mat_s[0], 1e-14); EXPECT_NEAR(groundtruth_mat_s[1], mat_s[1], 1e-14); EXPECT_NEAR(groundtruth_mat_s[2], mat_s[2], 1e-14); } TEST(MatrixSVDTest, MatrixSVDQuadraticUVTest) { double mat_a[9]; for (int i = 0; i < 9; ++i) { mat_a[i] = static_cast<double>(i + 1); } double mat_u[9]; double mat_s[3]; double mat_v[9]; math::internal::matrix_gk_svd(mat_a, 3, 3, mat_u, mat_s, mat_v, 1e-14); double groundtruth_mat_u[9]; groundtruth_mat_u[0] = -0.214837238368396; groundtruth_mat_u[1] = -0.887230688346370; groundtruth_mat_u[2] = 0.408248290463863; groundtruth_mat_u[3] = -0.520587389464737; groundtruth_mat_u[4] = -0.249643952988298; groundtruth_mat_u[5] = -0.816496580927726; groundtruth_mat_u[6] = -0.826337540561078; groundtruth_mat_u[7] = 0.387942782369775; groundtruth_mat_u[8] = 0.408248290463863; double groundtruth_mat_v[9]; groundtruth_mat_v[0] = -0.479671177877772; groundtruth_mat_v[1] = 0.776690990321559; groundtruth_mat_v[2] = -0.408248290463863; groundtruth_mat_v[3] = -0.572367793972062; groundtruth_mat_v[4] = 0.075686470104559; groundtruth_mat_v[5] = 0.816496580927726; groundtruth_mat_v[6] = -0.665064410066353; groundtruth_mat_v[7] = -0.625318050112443; groundtruth_mat_v[8] = -0.408248290463863; for (int i = 0; i < 9; ++i) { EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-14); EXPECT_NEAR(groundtruth_mat_v[i], mat_v[i], 1e-14); } } TEST(MatrixSVDTest, MatrixSVDNonQuadraticFullTest) { double mat_a[20]; for (int i = 0; i < 20; ++i) { mat_a[i] = static_cast<double>(i + 1); } double mat_u[20]; double mat_s[4]; double mat_v[20]; math::internal::matrix_gk_svd(mat_a, 5, 4, mat_u, mat_s, mat_v, 1e-14); double groundtruth_mat_s[4]; groundtruth_mat_s[0] = 53.520222492850067; groundtruth_mat_s[1] = 2.363426393147627; groundtruth_mat_s[2] = 0; groundtruth_mat_s[3] = 0; double groundtruth_mat_u[20]; groundtruth_mat_u[0] = -0.096547843444803; groundtruth_mat_u[1] = -0.768556122821332; groundtruth_mat_u[2] = 0.565028398052320; groundtruth_mat_u[3] = 0.167888229103364; groundtruth_mat_u[4] = -0.245515644353003; groundtruth_mat_u[5] = -0.489614203611302; groundtruth_mat_u[6] = -0.667776546677112; groundtruth_mat_u[7] = -0.448708735648741; groundtruth_mat_u[8] = -0.394483445261204; groundtruth_mat_u[9] = -0.210672284401273; groundtruth_mat_u[10] = -0.312183334193103; groundtruth_mat_u[11] = 0.623816560842154; groundtruth_mat_u[12] = -0.543451246169405; groundtruth_mat_u[13] = 0.068269634808757; groundtruth_mat_u[14] = 0.367582716208264; groundtruth_mat_u[15] = -0.573059831151541; groundtruth_mat_u[16] = -0.692419047077605; groundtruth_mat_u[17] = 0.347211554018787; groundtruth_mat_u[18] = 0.047348766609631; groundtruth_mat_u[19] = 0.230063776854764; double groundtruth_mat_v[20]; groundtruth_mat_v[0] = -0.443018843508167; groundtruth_mat_v[1] = 0.709742421091395; groundtruth_mat_v[2] = 0.547722557505176; groundtruth_mat_v[3] = 0; groundtruth_mat_v[4] = -0.479872524872618; groundtruth_mat_v[5] = 0.264049919281154; groundtruth_mat_v[6] = -0.730296743340218; groundtruth_mat_v[7] = 0.408248290463862; groundtruth_mat_v[8] = -0.516726206237069; groundtruth_mat_v[9] = -0.181642582529112; groundtruth_mat_v[10] = -0.182574185835057; groundtruth_mat_v[11] = -0.816496580927726; groundtruth_mat_v[12] = -0.553579887601520; groundtruth_mat_v[13] = -0.627335084339378; groundtruth_mat_v[14] = 0.365148371670102; groundtruth_mat_v[15] = 0.408248290463864; for (int i = 0; i < 4; ++i) { EXPECT_NEAR(groundtruth_mat_s[i], mat_s[i], 1e-13); } for (int i = 0; i < 20; ++i) { EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-13); } for (int i = 0; i < 16; ++i) { EXPECT_NEAR(std::abs(groundtruth_mat_v[i]), std::abs(mat_v[i]), 1e-13); } } TEST(MatrixSVDTest, MatrixSVDNonQuadraticEconomyTest) { double mat_a[20]; for (int i = 0; i < 20; ++i) { mat_a[i] = static_cast<double>(i + 1); } double mat_u[20]; double mat_s[4]; double mat_v[20]; math::internal::matrix_r_svd(mat_a, 5, 4, mat_u, mat_s, mat_v, 1e-10); double groundtruth_mat_s[4]; groundtruth_mat_s[0] = 53.520222492850067; groundtruth_mat_s[1] = 2.363426393147627; groundtruth_mat_s[2] = 0; groundtruth_mat_s[3] = 0; double groundtruth_mat_u[20]; groundtruth_mat_u[0] = -0.096547843444803; groundtruth_mat_u[1] = -0.768556122821332; groundtruth_mat_u[2] = 0.632455532033676; groundtruth_mat_u[3] = 0; groundtruth_mat_u[4] = -0.245515644353003; groundtruth_mat_u[5] = -0.489614203611302; groundtruth_mat_u[6] = -0.632455532033676; groundtruth_mat_u[7] = 0.547722557505167; groundtruth_mat_u[8] = -0.394483445261204; groundtruth_mat_u[9] = -0.210672284401272; groundtruth_mat_u[10] = -0.316227766016837; groundtruth_mat_u[11] = -0.730296743340219; groundtruth_mat_u[12] = -0.543451246169405; groundtruth_mat_u[13] = 0.068269634808755; groundtruth_mat_u[14] = -0.000000000000002; groundtruth_mat_u[15] = -0.182574185835059; groundtruth_mat_u[16] = -0.692419047077606; groundtruth_mat_u[17] = 0.347211554018788; groundtruth_mat_u[18] = 0.316227766016839; groundtruth_mat_u[19] = 0.365148371670112; double groundtruth_mat_v[16]; groundtruth_mat_v[0] = -0.443018843508167; groundtruth_mat_v[1] = 0.709742421091395; groundtruth_mat_v[2] = 0.547722557505176; groundtruth_mat_v[3] = 0; groundtruth_mat_v[4] = -0.479872524872618; groundtruth_mat_v[5] = 0.264049919281154; groundtruth_mat_v[6] = -0.730296743340218; groundtruth_mat_v[7] = 0.408248290463862; groundtruth_mat_v[8] = -0.516726206237069; groundtruth_mat_v[9] = -0.181642582529112; groundtruth_mat_v[10] = -0.182574185835057; groundtruth_mat_v[11] = -0.816496580927726; groundtruth_mat_v[12] = -0.553579887601520; groundtruth_mat_v[13] = -0.627335084339378; groundtruth_mat_v[14] = 0.365148371670102; groundtruth_mat_v[15] = 0.408248290463864; for (int i = 0; i < 4; ++i) { EXPECT_NEAR(groundtruth_mat_s[i], mat_s[i], 1e-10); } for (int i = 0; i < 20; ++i) { EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-10); } for (int i = 0; i < 16; ++i) { EXPECT_NEAR(std::abs(groundtruth_mat_v[i]), std::abs(mat_v[i]), 1e-10); } } TEST(MatrixSVDTest, MatrixTransposeTest) { int mat_a[6]; mat_a[0] = 1; mat_a[1] = 3; mat_a[2] = 5; mat_a[3] = 2; mat_a[4] = 4; mat_a[5] = 6; math::matrix_transpose(mat_a, 2, 3); int groundtruth_mat_a_t[6]; groundtruth_mat_a_t[0] = 1; groundtruth_mat_a_t[1] = 2; groundtruth_mat_a_t[2] = 3; groundtruth_mat_a_t[3] = 4; groundtruth_mat_a_t[4] = 5; groundtruth_mat_a_t[5] = 6; for (int i = 0; i < 6; ++i) { EXPECT_NEAR(groundtruth_mat_a_t[i], mat_a[i], 1e-14); } } TEST(MatrixSVDTest, MatrixSVDUnderdeterminedTest) { double mat_a[2 * 3]; mat_a[0] = 1.0; mat_a[1] = 3.0; mat_a[2] = 5.0; mat_a[3] = 2.0; mat_a[4] = 4.0; mat_a[5] = 6.0; double mat_u[2 * 3]; double mat_s[3]; double mat_v[3 * 3]; math::matrix_svd(mat_a, 2, 3, mat_u, mat_s, mat_v, 1e-14); double groundtruth_mat_u[2 * 3]; groundtruth_mat_u[0] = -0.619629483829340; groundtruth_mat_u[1] = -0.784894453267053; groundtruth_mat_u[2] = 0.0; groundtruth_mat_u[3] = -0.784894453267052; groundtruth_mat_u[4] = 0.619629483829340; groundtruth_mat_u[5] = 0.0; double groundtruth_mat_s[3]; groundtruth_mat_s[0] = 9.525518091565104; groundtruth_mat_s[1] = 0.514300580658644; groundtruth_mat_s[2] = 0.0; double groundtruth_mat_v[3 * 3]; groundtruth_mat_v[0] = -0.229847696400071; groundtruth_mat_v[1] = 0.883461017698525; groundtruth_mat_v[2] = -0.408248290463863; groundtruth_mat_v[3] = -0.524744818760294; groundtruth_mat_v[4] = 0.240782492132546; groundtruth_mat_v[5] = 0.816496580927726; groundtruth_mat_v[6] = -0.819641941120516; groundtruth_mat_v[7] = -0.401896033433432; groundtruth_mat_v[8] = -0.408248290463863; for (int i = 0; i < 6; ++i) EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-13); for (int i = 0; i < 3; ++i) EXPECT_NEAR(groundtruth_mat_s[i], mat_s[i], 1e-13); for (int i = 0; i < 9; ++i) EXPECT_NEAR(groundtruth_mat_v[i], mat_v[i], 1e-13); } TEST(MatrixSVDTest, TestLargeBeforeAfter) { const int rows = 100; const int cols = 50; double mat_a[rows * cols]; for (int i = 0; i < rows * cols; ++i) mat_a[i] = static_cast<double>(i + 1); /* Allocate results on heap to allow SVD of very big matrices. */ double* mat_u = new double[rows * rows]; double* vec_s = new double[cols]; double* mat_s = new double[cols * cols]; double* mat_v = new double[cols * cols]; math::matrix_svd(mat_a, rows, cols, mat_u, vec_s, mat_v, 1e-8); math::matrix_transpose(mat_v, cols, cols); std::fill(mat_s, mat_s + cols * cols, 0.0); for (int i = 0; i < cols; ++i) mat_s[i * cols + i] = vec_s[i]; double* multiply_temp = new double[cols * cols]; double* multiply_result = new double[rows * cols]; math::matrix_multiply(mat_s, cols, cols, mat_v, cols, multiply_temp); math::matrix_multiply(mat_u, rows, cols, multiply_temp, cols, multiply_result); for (int i = 0; i < rows * cols; ++i) EXPECT_NEAR(mat_a[i], multiply_result[i], 1e-7); delete[] mat_u; delete[] vec_s; delete[] mat_s; delete[] mat_v; delete[] multiply_temp; delete[] multiply_result; } TEST(MatrixSVDTest, BeforeAfter1) { math::Matrix<double, 2, 2> A; A(0,0) = 1.0f; A(0,1) = 2.0f; A(1,0) = 3.0f; A(1,1) = 4.0f; math::Matrix<double, 2, 2> U; math::Matrix<double, 2, 2> S; math::Matrix<double, 2, 2> V; math::matrix_svd(A, &U, &S, &V, 1e-12); EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12)); EXPECT_GT(S(0,0), S(1,1)); } TEST(MatrixSVDTest, BeforeAfter2) { double values[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }; math::Matrix<double, 3, 2> A(values); math::Matrix<double, 3, 2> U; math::Matrix<double, 2, 2> S; math::Matrix<double, 2, 2> V; math::matrix_svd(A, &U, &S, &V, 1e-12); EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12)); EXPECT_GT(S(0,0), S(1,1)); } TEST(MatrixSVDTest, BeforeAfter3) { double values[] = {1.0, 2.0, 3.0, 4.0 }; math::Matrix<double, 2, 2> A(values); math::Matrix<double, 2, 2> U; math::Matrix<double, 2, 2> S(0.0); math::Matrix<double, 2, 2> V; math::matrix_svd<double>(*A, 2, 2, *U, *S, *V, 1e-12); std::swap(S(0,1), S(1,1)); // Swap the eigenvalues into place. EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12)); EXPECT_GT(S(0,0), S(1,1)); } TEST(MatrixSVDTest, BeforeAfter4) { double values[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }; math::Matrix<double, 3, 2> A(values); math::Matrix<double, 3, 2> U; math::Matrix<double, 2, 2> S(0.0); math::Matrix<double, 2, 2> V; math::matrix_svd(*A, 3, 2, *U, *S, *V, 1e-12); std::swap(S(0,1), S(1,1)); // Swap the eigenvalues into place. EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12)); EXPECT_GT(S(0,0), S(1,1)); } TEST(MatrixSVDTest, BeforeAfter5) { math::Matrix<double, 3, 3> A; A[0] = 1.0; A[1] = 0.0; A[2] = 1.0; A[3] = 1.0; A[4] = 0.0; A[5] = 1.0; A[6] = 1.0; A[7] = 0.0; A[8] = 1.0; math::Matrix<double, 3, 3> U, S, V; math::matrix_svd<double>(A, &U, &S, &V); math::Matrix<double, 3, 3> X = U * S * V.transposed(); for (int i = 0; i < 9; ++i) EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i; } TEST(MatrixSVDTest, BeforeAfter6) { math::Matrix<double, 3, 3> A; A[0] = 1.0; A[1] = 1.0; A[2] = 0.0; A[3] = 1.0; A[4] = 1.0; A[5] = 0.0; A[6] = 1.0; A[7] = 1.0; A[8] = 0.0; math::Matrix<double, 3, 3> U, S, V; math::matrix_svd<double>(A, &U, &S, &V); math::Matrix<double, 3, 3> X = U * S * V.transposed(); for (int i = 0; i < 9; ++i) EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i; } TEST(MatrixSVDTest, BeforeAfter7) { math::Matrix<double, 3, 3> A; A[0] = 0.0; A[1] = 1.0; A[2] = 1.0; A[3] = 0.0; A[4] = 1.0; A[5] = 1.0; A[6] = 0.0; A[7] = 1.0; A[8] = 1.0; math::Matrix<double, 3, 3> U, S, V; math::matrix_svd<double>(A, &U, &S, &V); math::Matrix<double, 3, 3> X = U * S * V.transposed(); for (int i = 0; i < 9; ++i) EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i; } TEST(MatrixSVDTest, BeforeAfter8) { math::Matrix<double, 3, 3> A; A[0] = 0.0; A[1] = 0.0; A[2] = 0.0; A[3] = 1.0; A[4] = 1.0; A[5] = 1.0; A[6] = 1.0; A[7] = 1.0; A[8] = 1.0; math::Matrix<double, 3, 3> U, S, V; math::matrix_svd<double>(A, &U, &S, &V); math::Matrix<double, 3, 3> X = U * S * V.transposed(); for (int i = 0; i < 9; ++i) EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i; } TEST(MatrixSVDTest, BeforeAfter9) { math::Matrix<double, 3, 3> A; A[0] = 1.0; A[1] = 1.0; A[2] = 1.0; A[3] = 0.0; A[4] = 0.0; A[5] = 0.0; A[6] = 1.0; A[7] = 1.0; A[8] = 1.0; math::Matrix<double, 3, 3> U, S, V; math::matrix_svd<double>(A, &U, &S, &V); math::Matrix<double, 3, 3> X = U * S * V.transposed(); for (int i = 0; i < 9; ++i) EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i; } TEST(MatrixSVDTest, BeforeAfter10) { math::Matrix<double, 3, 3> A; A[0] = 1.0; A[1] = 1.0; A[2] = 1.0; A[3] = 1.0; A[4] = 1.0; A[5] = 1.0; A[6] = 0.0; A[7] = 0.0; A[8] = 0.0; math::Matrix<double, 3, 3> U, S, V; math::matrix_svd<double>(A, &U, &S, &V); math::Matrix<double, 3, 3> X = U * S * V.transposed(); for (int i = 0; i < 9; ++i) EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i; } TEST(MatrixSVDTest, SortedEigenvalues) { double values[] = { 0.0697553, 0.949327, 0.525995, 0.0860558, 0.192214, 0.663227 }; math::Matrix<double, 3, 2> U, mat(values); math::Matrix<double, 2, 2> S, V; math::matrix_svd<double, 3, 2>(mat, &U, &S, &V, 1e-12); EXPECT_GT(S(0,0), S(1,1)); } #if 0 namespace { double getrand (void) { return std::rand() / static_cast<double>(RAND_MAX); } } // namespace TEST(MatrixSVDTest, ForbiddenRandomTestLargeMatrix) { #define TEST_ROWS 10000 #define TEST_COLS 10 std::srand(0); math::Matrix<double, TEST_ROWS, TEST_COLS> A; for (int i = 0; i < TEST_ROWS * TEST_COLS; ++i) A[i] = getrand(); math::Matrix<double, TEST_ROWS, TEST_COLS> U; math::Matrix<double, TEST_COLS, TEST_COLS> S; math::Matrix<double, TEST_COLS, TEST_COLS> V; math::matrix_svd(A, &U, &S, &V, 1e-10); math::Matrix<double, TEST_ROWS, TEST_COLS> X = U * S * V.transposed(); for (int i = 0; i < TEST_ROWS * TEST_COLS; ++i) EXPECT_NEAR(A[i], X[i], 1e-10); } // Note: Random is a bad thing in test cases! Don't do it! TEST(MatrixSVDTest, ForbiddenRandomTest) { std::srand(0); math::Matrix<double, 3, 2> A; for (int i = 0; i < 10; ++i) { A(0,0) = getrand(); A(0,1) = getrand(); A(1,0) = getrand(); A(1,1) = getrand(); A(2,0) = getrand(); A(2,1) = getrand(); math::Matrix<double, 3, 2> U; math::Matrix<double, 2, 2> S; math::Matrix<double, 2, 2> V; math::matrix_svd(A, &U, &S, &V, 1e-12); EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12)); EXPECT_GT(S(0,0), S(1,1)); } } #endif TEST(MatrixSVDTest, TestPseudoInverse) { math::Matrix<double, 3, 2> mat; mat[0] = 1.0; mat[1] = 2.0; mat[2] = 3.0; mat[3] = 4.0; mat[4] = 5.0; mat[5] = 6.0; math::Matrix<double, 2, 3> pinv; math::matrix_pseudo_inverse(mat, &pinv, 1e-10); math::Matrix<double, 3, 2> mat2 = mat * pinv * mat; for (int i = 0; i < 6; ++i) EXPECT_NEAR(mat2[i], mat[i], 1e-14); math::Matrix<double, 2, 3> pinv2 = pinv * mat * pinv; for (int i = 0; i < 6; ++i) EXPECT_NEAR(pinv2[i], pinv[i], 1e-14); } TEST(MatrixSVDTest, TestPseudoInverseGoldenData1) { double a_values[] = { 2, -4, 5, 6, 0, 3, 2, -4, 5, 6, 0, 3 }; double a_inv_values[] = { -2, 6, -2, 6, -5, 3, -5, 3, 4, 0, 4, 0 }; math::Matrix<double, 4, 3> A(a_values); math::Matrix<double, 3, 4> Ainv(a_inv_values); Ainv /= 72.0; math::Matrix<double, 3, 4> result; math::matrix_pseudo_inverse(A, &result, 1e-10); for (int r = 0; r < 3; ++r) for (int c = 0; c < 4; ++c) EXPECT_NEAR(Ainv(r, c), result(r, c), 1e-16); } TEST(MatrixSVDTest, TestPseudoInverseGoldenData2) { double a_values[] = { 1, 1, 1, 1, 5, 7, 7, 9 }; double a_inv_values[] = { 2, -0.25, 0.25, 0, 0.25, 0, -1.5, 0.25 }; math::Matrix<double, 2, 4> A(a_values); math::Matrix<double, 4, 2> Ainv(a_inv_values); math::Matrix<double, 4, 2> result; math::matrix_pseudo_inverse(A, &result, 1e-10); for (int r = 0; r < 4; ++r) for (int c = 0; c < 2; ++c) EXPECT_NEAR(Ainv(r, c), result(r, c), 1e-13); }
31.207709
88
0.625257
lemony-fresh
0af32920c4b1e61f869a61a1c3ad5ad66e4e69e9
2,272
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/client/remote/channels.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/client/remote/channels.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/client/remote/channels.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <functional> #include <msw/std/memory.hpp> #include <rubetek/remote_link/channel.hpp> #include <rubetek/remote_link/channel_set.hpp> namespace rubetek { namespace client { struct remote_channels : remote_channel_set<unique_client_id::type> { typedef std::function<void(unique_channel_id_type, std::string const& ip, unique_client_id::const_reference, remote_link_interface<>*)> channel_open; remote_channels ( channel_open channel_open , channel_close channel_close , send_payload send_payload ) : remote_channel_set<unique_client_id::type> ( channel_close, send_payload ) , channel_open_ ( channel_open ) {} void on_open(unique_channel_id_type channel_id, unique_client_id::const_reference rem_id, std::string const& ip) { if (channel_by_remote_id_list_.find(rem_id) != channel_by_remote_id_list_.end()) { logger_.error("channel to ", rem_id, " already exists"); } else { logger_.info("insert new channel to ", rem_id, ", channel id: ", channel_id); channel_by_remote_id_list_.insert(std::make_pair(rem_id, channel_id)); auto res = channels_.insert ( std::make_pair ( channel_id , msw::make_unique<remote_channel<remote_id>> ( rem_id , [this, channel_id](msw::range<msw::byte const> payload) { send_payload_(channel_id, payload); } ) ) ); if (!res.second) throw std::runtime_error("adding channel fail"); if (!res.first->second) throw std::runtime_error("remote channel fail ptr"); channel_open_(channel_id, ip, rem_id, res.first->second.get()); } } private: channel_open channel_open_; }; }}
34.424242
157
0.524648
yklishevich
0af46217160d042fa5933256ae741fc7571b84fc
3,008
cpp
C++
jlp_x11plot/jlp_x11_utils.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
null
null
null
jlp_x11plot/jlp_x11_utils.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
null
null
null
jlp_x11plot/jlp_x11_utils.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
1
2020-07-09T00:20:49.000Z
2020-07-09T00:20:49.000Z
/************************************************************************* * jlp_x11_utils.cpp * Set of programs useful for the JLP_X11 and JLP_Dlg_X11 Classes * * JLP * Version 17/11/2006 **************************************************************************/ #if JLP_USE_X11 /* New flag to disable X11 if necessary */ #include "jlp_x11_utils.h" /************************************************************* * Load fonts * (You can check which fonts are available with the program "xfontsel") * * OUTPUT: * **font_struct ************************************************************/ int JLP_LoadFonts(Display *display, XFontStruct **font_struct) { /* Fonts: look for courier-18, if not present use simply 9x15*/ *font_struct = XLoadQueryFont(display,"-*-courier-medium-r-*-*-14-*"); if(*font_struct == NULL) { printf("LoadFonts/Error loading fonts: courier-medium 14 not found\n"); *font_struct = XLoadQueryFont(display,"9x15"); if(*font_struct == NULL) { #ifdef DEBUG printf("LoadFonts/Error loading fonts: courier and 9x15 not found\n"); #endif *font_struct = XLoadQueryFont(display,"fixed"); if(*font_struct == NULL) { printf("setup/Fatal error loading fonts: 'fixed' not found\n"); exit(-1); } } } return(0); } /************************************************************** * Get value of the cell in the colormap corresponding * to (r,g,b) value * * INPUT: * r,g,b between 0 and 255 * * OUTPUT: * xcolor.pixel: full XColor structure of xcolor is initialized ***************************************************************/ int JLP_Xcolor_pixel(Display *display, Colormap& cmap, unsigned long int &pixel, int r, int g, int b) { int status = 0; XColor xcolor; pixel = 0; status = JLP_Xcolor(display, cmap, xcolor, r, g, b); if(!status) pixel = xcolor.pixel; return(status); } /************************************************************** * Get value of the cell in the colormap corresponding * to (r,g,b) value * * INPUT: * r,g,b between 0 and 255 * * OUTPUT: * xcolor.pixel: full XColor structure of xcolor is initialized ***************************************************************/ int JLP_Xcolor(Display *display, Colormap& cmap, XColor &xcolor, int r, int g, int b) { int status = 0; int white_pixel; white_pixel = WhitePixel(display,DefaultScreen(display)); xcolor.red = (white_pixel * r) / 255; xcolor.green = (white_pixel * g) / 255; xcolor.blue = (white_pixel * b) / 255; xcolor.flags = DoRed | DoGreen | DoBlue; /* XAllocColor returns the index of the (readonly) colorcell that contains the * RGB value closest to the one required from the ASCII color data base * (loaded in xcolor.pixel) */ if (XAllocColor(display, cmap, &xcolor) == 0) { fprintf(stderr," JLP_Xcolor_pixel/Error: can't find color (%d,%d,%d)\n", r, g, b); status = -1; } return(status); } #endif /* End of JLP_USE_X11 */
30.383838
78
0.541888
jlprieur
0af9479f817433d44d160f75ed399bbbfa17f9ad
2,822
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionProductResourceTypeEnum.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionProductResourceTypeEnum.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionProductResourceTypeEnum.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcConstructionProductResourceTypeEnum.h" // TYPE IfcConstructionProductResourceTypeEnum = ENUMERATION OF (ASSEMBLY ,FORMWORK ,USERDEFINED ,NOTDEFINED); IfcConstructionProductResourceTypeEnum::IfcConstructionProductResourceTypeEnum() {} IfcConstructionProductResourceTypeEnum::~IfcConstructionProductResourceTypeEnum() {} shared_ptr<BuildingObject> IfcConstructionProductResourceTypeEnum::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcConstructionProductResourceTypeEnum> copy_self( new IfcConstructionProductResourceTypeEnum() ); copy_self->m_enum = m_enum; return copy_self; } void IfcConstructionProductResourceTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCCONSTRUCTIONPRODUCTRESOURCETYPEENUM("; } switch( m_enum ) { case ENUM_ASSEMBLY: stream << ".ASSEMBLY."; break; case ENUM_FORMWORK: stream << ".FORMWORK."; break; case ENUM_USERDEFINED: stream << ".USERDEFINED."; break; case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break; } if( is_select_type ) { stream << ")"; } } const std::wstring IfcConstructionProductResourceTypeEnum::toString() const { switch( m_enum ) { case ENUM_ASSEMBLY: return L"ASSEMBLY"; case ENUM_FORMWORK: return L"FORMWORK"; case ENUM_USERDEFINED: return L"USERDEFINED"; case ENUM_NOTDEFINED: return L"NOTDEFINED"; } return L""; } shared_ptr<IfcConstructionProductResourceTypeEnum> IfcConstructionProductResourceTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcConstructionProductResourceTypeEnum>(); } else if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcConstructionProductResourceTypeEnum>(); } shared_ptr<IfcConstructionProductResourceTypeEnum> type_object( new IfcConstructionProductResourceTypeEnum() ); if( boost::iequals( arg, L".ASSEMBLY." ) ) { type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_ASSEMBLY; } else if( boost::iequals( arg, L".FORMWORK." ) ) { type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_FORMWORK; } else if( boost::iequals( arg, L".USERDEFINED." ) ) { type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_USERDEFINED; } else if( boost::iequals( arg, L".NOTDEFINED." ) ) { type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_NOTDEFINED; } return type_object; }
42.119403
193
0.759391
promethe42
0afb5cf0b93d741a5fc9006a69257006ef471105
13,025
hpp
C++
packages/utility/core/src/Utility_Measurement.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/utility/core/src/Utility_Measurement.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/utility/core/src/Utility_Measurement.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file Utility_Measurement.hpp //! \author Alex Robinson //! \brief The measurement class declaration. This object is based of of the //! measurement class in the boost::units examples //! //---------------------------------------------------------------------------// #ifndef UTILITY_MEASUREMENT_HPP #define UTILITY_MEASUREMENT_HPP // Boost Includes #include <boost/units/config.hpp> #include <boost/units/operators.hpp> #include <boost/typeof/typeof.hpp> // Trilinos Includes #include <Teuchos_ScalarTraits.hpp> // FRENSIE Includes #include "Utility_PrintableObject.hpp" #include "Utility_ContractException.hpp" namespace Utility{ /*! The measurement class * * This class wraps is meant to be used as any typical scalar type * (e.g. double). It is designed to keep track of and propagate the * uncertainty of a value (like one would with a measured quantity). */ template<typename T> class Measurement : public PrintableObject { private: // The scalar traits typedef typedef Teuchos::ScalarTraits<T> ST; public: //! The typedef for this type typedef Measurement<T> ThisType; //! The typedef for the value type typedef T ValueType; //! Constructor Measurement( const ValueType& value = ValueType(), const ValueType& uncertainty = ValueType() ); //! Copy constructor Measurement( const ThisType& other_measurement ); //! Destructor ~Measurement() { /* ... */ } //! Print method void print( std::ostream& os ) const; //! Return the value of the measurement const ValueType& getValue() const; //! Return the uncertainty of the measurement const ValueType& getUncertainty() const; //! Return the relative uncertainty of the measurement const ValueType getRelativeUncertainty() const; //! Return the lower bound of the measurement const ValueType getLowerBound() const; //! Return the upper bound of the measurement const ValueType getUpperBound() const; //! Implicit conversion to value type operator ValueType() const; //! In-place addition operator ThisType& operator+=( const ValueType& value ); //! In-place addition operator ThisType& operator+=( const ThisType& other_measurement ); //! In-place subtraction operator ThisType& operator-=( const ValueType& value ); //! In-place subtraction operator ThisType& operator-=( const ThisType& other_measurement ); //! In-place multiplication operator ThisType& operator*=( const ValueType& value ); //! In-place multiplication operator ThisType& operator*=( const ThisType& other_measurement ); //! In-place division operator ThisType& operator/=( const ValueType& value ); //! In-place division operator ThisType& operator/=( const ThisType& other_measurement ); private: // The measurement value ValueType d_value; // The measurement uncertainty ValueType d_uncertainty; }; //! Addition operator template<typename T> inline Measurement<T> operator+( T lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs, T(0) ) += rhs); testNestedConditionsEnd(1); } //! Addition operator template<typename T> inline Measurement<T> operator+( const Measurement<T>& lhs, T rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) += Measurement<T>( rhs, T(0) )); testNestedConditionsEnd(1); } //! Addition operator template<typename T> inline Measurement<T> operator+( const Measurement<T>& lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) += rhs ); testNestedConditionsEnd(1); } //! Subtraction operator template<typename T> inline Measurement<T> operator-( T lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs, T(0) ) -= rhs); testNestedConditionsEnd(1); } //! Subtraction operator template<typename T> inline Measurement<T> operator-( const Measurement<T>& lhs, T rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) -= Measurement<T>( rhs, T(0) )); testNestedConditionsEnd(1); } //! Subtraction operator template<typename T> inline Measurement<T> operator-( const Measurement<T>& lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) -= rhs ); testNestedConditionsEnd(1); } //! Multiplication operator template<typename T> inline Measurement<T> operator*( T lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs, T(0) ) *= rhs); testNestedConditionsEnd(1); } //! Multiplication operator template<typename T> inline Measurement<T> operator*( const Measurement<T>& lhs, T rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) *= Measurement<T>( rhs, T(0) )); testNestedConditionsEnd(1); } //! Multiplication operator template<typename T> inline Measurement<T> operator*( const Measurement<T>& lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) *= rhs ); testNestedConditionsEnd(1); } //! Division operator template<typename T> inline Measurement<T> operator/( T lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); // Make sure nested conditions are met return (Measurement<T>( lhs, T(0) ) /= rhs); testNestedConditionsEnd(1); } //! Division operator template<typename T> inline Measurement<T> operator/( const Measurement<T>& lhs, T rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) /= Measurement<T>( rhs, T(0) )); testNestedConditionsEnd(1); } //! Division operator template<typename T> inline Measurement<T> operator/( const Measurement<T>& lhs, const Measurement<T>& rhs ) { // Make sure nested conditions are met testNestedConditionsBegin(1); return (Measurement<T>( lhs ) /= rhs ); testNestedConditionsEnd(1); } //! Overload of sqrt for a measurement template<typename T> inline Measurement<T> sqrt( const Measurement<T>& x ) { // Make sure the measurement is valid testPrecondition( x.getValue() >= 0.0 ); const T new_value = std::sqrt( x.getValue() ); const T propagated_uncertainty = 0.5*(new_value/x.getValue())* x.getUncertainty(); // Make sure reasonable values have been calculated testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) ); testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( propagated_uncertainty ) ); return Measurement<T>( new_value, propagated_uncertainty ); } //! Overload of pow for a measurement template<typename T, typename ExponentType> inline Measurement<T> pow( const Measurement<T>& x, const ExponentType exponent ) { const T new_value = std::pow( x.getValue(), exponent ); const T propagated_uncertainty = fabs(exponent*(new_value/x.getValue()))* x.getUncertainty(); // Make sure reasonable values have been calculated testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) ); testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( propagated_uncertainty ) ); testPostcondition( propagated_uncertainty >= 0.0 ); return Measurement<T>( new_value, propagated_uncertainty ); } } // end Utility namespace namespace boost{ namespace units{ //! Specialization of the boost::units::power_typeof_helper template<typename Y, long N, long D> struct power_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> > { typedef Utility::Measurement<typename power_typeof_helper<Y,static_rational<N,D> >::type> type; static type value( const Utility::Measurement<Y>& x) { const static_rational<N,D> rational; const Y rational_power = Y(rational.numerator())/Y(rational.denominator()); return Utility::pow( x, rational_power ); } }; //! Specialization of the boost::units::root_typeof_helper template<typename Y, long N, long D> struct root_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> > { typedef Utility::Measurement<typename root_typeof_helper<Y,static_rational<N,D> >::type> type; static type value( const Utility::Measurement<Y>& x ) { const static_rational<N,D> rational; // Compute D/N instead of N/D since we're interested in the root const Y rational_power = Y(rational.denominator())/Y(rational.numerator()); return Utility::pow( x, rational_power ); } }; } // end units namespace } // end boost namespace namespace Teuchos{ //! Partial specialization of Teuchos::ScalarTraits for the Measurement class template<typename T> struct ScalarTraits<Utility::Measurement<T> > { typedef Utility::Measurement<T> Measurement; typedef T magnitudeType; typedef typename Teuchos::ScalarTraits<T>::halfPrecision halfPrecision; typedef typename Teuchos::ScalarTraits<T>::doublePrecision doublePrecision; static const bool isComplex = Teuchos::ScalarTraits<T>::isComplex; static const bool isOrdinal = Teuchos::ScalarTraits<T>::isOrdinal; static const bool isComparable = Teuchos::ScalarTraits<T>::isComparable; static const bool hasMachineParameters = Teuchos::ScalarTraits<T>::hasMachineParameters; static inline magnitudeType eps() { return ScalarTraits<magnitudeType>::eps(); } static inline magnitudeType sfmin() { return ScalarTraits<magnitudeType>::sfmin(); } static inline magnitudeType base() { return ScalarTraits<magnitudeType>::base(); } static inline magnitudeType prec() { return ScalarTraits<magnitudeType>::prec(); } static inline magnitudeType t() { return ScalarTraits<magnitudeType>::t(); } static inline magnitudeType rnd() { return ScalarTraits<magnitudeType>::rnd(); } static inline magnitudeType emin() { return ScalarTraits<magnitudeType>::emin(); } static inline magnitudeType rmin() { return ScalarTraits<magnitudeType>::rmin(); } static inline magnitudeType emax() { return ScalarTraits<magnitudeType>::emax(); } static inline magnitudeType rmax() { return ScalarTraits<magnitudeType>::rmax(); } static inline magnitudeType magnitude(Measurement a) { return ScalarTraits<magnitudeType>::magnitude( a.getValue() ); } static inline Measurement zero() { return Measurement( ScalarTraits<magnitudeType>::zero(), 0.0 ); } static inline Measurement one() { return Measurement( ScalarTraits<magnitudeType>::zero(), 1.0 ); } static inline Measurement conjugate(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::conjugate(a.getValue()), ScalarTraits<magnitudeType>::conjugate(a.getUncertainty()) ); } static inline Measurement real(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::real(a.getValue()), ScalarTraits<magnitudeType>::real(a.getUncertainty()) ); } static inline Measurement imag(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::imag(a.getValue()), ScalarTraits<magnitudeType>::imag(a.getUncertainty()) ); } static inline Measurement nan() { return Measurement( ScalarTraits<magnitudeType>::nan(), ScalarTraits<magnitudeType>::nan() ); } static inline bool isnaninf(Measurement a){ return ScalarTraits<magnitudeType>::isnaninf(a.getValue()) || ScalarTraits<magnitudeType>::isnaninf(a.getUncertainty()); } static inline void seedrandom(unsigned int s) { ScalarTraits<magnitudeType>::seedrandom(s); } static inline Measurement random() { return Measurement( ScalarTraits<magnitudeType>::random(), 0.0 ); } static inline std::string name() { return std::string("Measurement<")+std::string(ScalarTraits<magnitudeType>::name())+std::string(">"); } static inline Measurement squareroot(Measurement a) { return Utility::sqrt(a); } static inline Measurement pow(Measurement a, Measurement b) { return Utility::pow( a, b.getValue() ); } }; } // end Teuchos namespace // Register the Measurement class with boost typeof for auto-like type // deduction when used with the boost::units library #if BOOST_UNITS_HAS_BOOST_TYPEOF BOOST_TYPEOF_REGISTER_TEMPLATE(Utility::Measurement, 1) #endif // end BOOST_UNITS_HAS_BOOST_TYPEOF //---------------------------------------------------------------------------// // Template Includes //---------------------------------------------------------------------------// #include "Utility_Measurement_def.hpp" //---------------------------------------------------------------------------// #endif // end UTILITY_MEASUREMENT_HPP //---------------------------------------------------------------------------// // end Utility_Measurement.hpp //---------------------------------------------------------------------------//
31.614078
191
0.697889
lkersting
e403bc0dedff958ba0ef76ea4b67175bd370fe3c
8,887
cpp
C++
QuantExt/test/discountratiomodifiedcurve.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/test/discountratiomodifiedcurve.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/test/discountratiomodifiedcurve.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
1
2022-02-07T02:04:10.000Z
2022-02-07T02:04:10.000Z
/* Copyright (C) 2018 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "toplevelfixture.hpp" #include <boost/assign/list_of.hpp> #include <boost/make_shared.hpp> #include <boost/test/unit_test.hpp> #include <ql/math/comparison.hpp> #include <ql/settings.hpp> #include <ql/termstructures/yield/discountcurve.hpp> #include <ql/termstructures/yield/flatforward.hpp> #include <ql/termstructures/yield/zerocurve.hpp> #include <ql/time/calendars/nullcalendar.hpp> #include <qle/termstructures/discountratiomodifiedcurve.hpp> using QuantExt::DiscountRatioModifiedCurve; using namespace QuantLib; using namespace boost::unit_test_framework; using namespace boost::assign; using std::vector; BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture) BOOST_AUTO_TEST_SUITE(DiscountingRatioModifiedCurveTest) BOOST_AUTO_TEST_CASE(testStandardCurves) { BOOST_TEST_MESSAGE("Testing discount ratio modified curve with some standard curves"); SavedSettings backup; Date today(15, Aug, 2018); Settings::instance().evaluationDate() = today; Actual365Fixed dc; // Base curve with fixed reference date of 15th Aug 2018 vector<Date> baseDates = list_of(today)(today + 1 * Years); vector<Real> baseDfs = list_of(1.0)(0.98); Handle<YieldTermStructure> baseCurve(boost::make_shared<DiscountCurve>(baseDates, baseDfs, dc)); baseCurve->enableExtrapolation(); // Numerator curve with fixed reference date of 15th Aug 2018 vector<Date> numDates = list_of(today)(today + 1 * Years)(today + 2 * Years); vector<Real> numZeroes = list_of(0.025)(0.025)(0.026); Handle<YieldTermStructure> numCurve(boost::make_shared<ZeroCurve>(numDates, numZeroes, dc)); numCurve->enableExtrapolation(); // Denominator curve with floating reference date Handle<YieldTermStructure> denCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, dc)); DiscountRatioModifiedCurve curve(baseCurve, numCurve, denCurve); Date discountDate = today + 18 * Months; BOOST_CHECK( close(curve.discount(discountDate), baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(discountDate))); discountDate = today + 3 * Years; BOOST_CHECK( close(curve.discount(discountDate), baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(discountDate))); // When we change evaluation date, we may not get what we expect here because reference date is taken from the // base curve which has been set up here with a fixed reference date. However, the denominator curve has been // set up here with a floating reference date. See the warning in the ctor of DiscountRatioModifiedCurve Settings::instance().evaluationDate() = today + 3 * Months; BOOST_TEST_MESSAGE("Changed evaluation date to " << Settings::instance().evaluationDate()); BOOST_CHECK(!close(curve.discount(discountDate), baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(discountDate))); Time t = dc.yearFraction(curve.referenceDate(), discountDate); BOOST_CHECK(close(curve.discount(discountDate), baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(t))); } BOOST_AUTO_TEST_CASE(testExtrapolationSettings) { BOOST_TEST_MESSAGE("Testing extrapolation settings for discount ratio modified curve"); SavedSettings backup; Date today(15, Aug, 2018); Settings::instance().evaluationDate() = today; Actual365Fixed dc; // Base curve with fixed reference date of 15th Aug 2018 vector<Date> baseDates = list_of(today)(Date(15, Aug, 2019)); vector<Real> baseDfs = list_of(1.0)(0.98); Handle<YieldTermStructure> baseCurve(boost::make_shared<DiscountCurve>(baseDates, baseDfs, dc)); // Numerator curve with fixed reference date of 15th Aug 2018 vector<Date> numDates = list_of(today)(Date(15, Aug, 2019))(Date(15, Aug, 2020)); vector<Real> numZeroes = list_of(0.025)(0.025)(0.026); Handle<YieldTermStructure> numCurve(boost::make_shared<ZeroCurve>(numDates, numZeroes, dc)); // Denominator curve with floating reference date Handle<YieldTermStructure> denCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, dc)); // Create the discount ratio curve DiscountRatioModifiedCurve curve(baseCurve, numCurve, denCurve); // Extrapolation is always true BOOST_CHECK(curve.allowsExtrapolation()); // Max date is maximum possible date BOOST_CHECK_EQUAL(curve.maxDate(), Date::maxDate()); // Extrapolation is determined by underlying curves BOOST_CHECK_NO_THROW(curve.discount(Date(15, Aug, 2019))); BOOST_CHECK_THROW(curve.discount(Date(15, Aug, 2019) + 1 * Days), QuantLib::Error); baseCurve->enableExtrapolation(); BOOST_CHECK_NO_THROW(curve.discount(Date(15, Aug, 2019) + 1 * Days)); BOOST_CHECK_THROW(curve.discount(Date(15, Aug, 2020) + 1 * Days), QuantLib::Error); numCurve->enableExtrapolation(); BOOST_CHECK_NO_THROW(curve.discount(Date(15, Aug, 2020) + 1 * Days)); } BOOST_AUTO_TEST_CASE(testConstructionNullUnderlyingCurvesThrow) { BOOST_TEST_MESSAGE("Testing construction with null underlying curves throw"); boost::shared_ptr<DiscountRatioModifiedCurve> curve; // All empty handles throw Handle<YieldTermStructure> baseCurve; Handle<YieldTermStructure> numCurve; Handle<YieldTermStructure> denCurve; BOOST_CHECK_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve, numCurve, denCurve), QuantLib::Error); // Numerator and denominator empty handles throw Handle<YieldTermStructure> baseCurve_1( boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed())); BOOST_CHECK_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve_1, numCurve, denCurve), QuantLib::Error); // Denominator empty handles throw Handle<YieldTermStructure> numCurve_1(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed())); BOOST_CHECK_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve_1, numCurve_1, denCurve), QuantLib::Error); // No empty handles succeeds Handle<YieldTermStructure> denCurve_1(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed())); BOOST_CHECK_NO_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve_1, numCurve_1, denCurve_1)); } BOOST_AUTO_TEST_CASE(testLinkingNullUnderlyingCurvesThrow) { BOOST_TEST_MESSAGE("Testing that linking with null underlying curves throw"); boost::shared_ptr<DiscountRatioModifiedCurve> curve; // All empty handles throw RelinkableHandle<YieldTermStructure> baseCurve( boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed())); RelinkableHandle<YieldTermStructure> numCurve( boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed())); RelinkableHandle<YieldTermStructure> denCurve( boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed())); // Curve building succeeds since no empty handles BOOST_CHECK_NO_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve, numCurve, denCurve)); // Switching base curve to empty handle should give a failure BOOST_CHECK_THROW(baseCurve.linkTo(boost::shared_ptr<YieldTermStructure>()), QuantLib::Error); BOOST_CHECK_NO_THROW(baseCurve.linkTo(*numCurve)); // Switching numerator curve to empty handle should give a failure BOOST_CHECK_THROW(numCurve.linkTo(boost::shared_ptr<YieldTermStructure>()), QuantLib::Error); BOOST_CHECK_NO_THROW(numCurve.linkTo(*denCurve)); // Switching denominator curve to empty handle should give a failure BOOST_CHECK_THROW(denCurve.linkTo(boost::shared_ptr<YieldTermStructure>()), QuantLib::Error); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
45.341837
120
0.738382
PiotrSiejda
e4043fd358a98ab0d838f1acaa68aea2e815df92
951
hpp
C++
microptp/config.hpp
decimad/microptp
bc7e10ddafc9015d480425f3f462ae086bf48c3b
[ "BSL-1.0" ]
3
2015-07-14T19:22:18.000Z
2015-12-03T01:15:15.000Z
microptp/config.hpp
decimad/microptp
bc7e10ddafc9015d480425f3f462ae086bf48c3b
[ "BSL-1.0" ]
1
2015-12-02T23:46:25.000Z
2015-12-04T14:17:43.000Z
microptp/config.hpp
decimad/microptp
bc7e10ddafc9015d480425f3f462ae086bf48c3b
[ "BSL-1.0" ]
null
null
null
// Copyright Michael Steinberg 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 SYSTEM_MICROPTP_MICROPTP_CONFIG_HPP_ #define SYSTEM_MICROPTP_MICROPTP_CONFIG_HPP_ #include <microptp_config.hpp> #include <microptp/ptpdatatypes.hpp> #include <fixed/fixed.hpp> #ifndef PRINT #define PRINT(...) #endif #ifndef TRACE #define TRACE(...) #endif #ifndef UPTP_SLAVE_ONLY #define UPTP_SLAVE_ONLY 1 #endif namespace uptp { struct Config { #if !UPTP_SLAVE_ONLY ClockQuality clock_quality; #endif static const bool two_step = true; static const bool any_domain = false; static const uint8 preferred_domain = 0; static constexpr auto kp_ = FIXED_RANGE(0, 0.1, 32)::from(0.005); static constexpr auto kn_ = FIXED_RANGE(0, 0.01, 32)::from(0.0005); }; } #endif /* SYSTEM_MICROPTP_MICROPTP_CONFIG_HPP_ */
22.642857
69
0.741325
decimad
e4070845458d6f19ddf0c15ea52dc80f8366e609
5,201
cpp
C++
Sail/src/API/DX11/shader/DX11InputLayout.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
1
2020-09-03T09:53:45.000Z
2020-09-03T09:53:45.000Z
Sail/src/API/DX11/shader/DX11InputLayout.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
null
null
null
Sail/src/API/DX11/shader/DX11InputLayout.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
1
2021-01-31T05:27:36.000Z
2021-01-31T05:27:36.000Z
#include "pch.h" #include "../DX11API.h" #include "DX11InputLayout.h" #include "Sail/Application.h" InputLayout* InputLayout::Create() { return SAIL_NEW DX11InputLayout(); } DX11InputLayout::DX11InputLayout() : InputLayout() { } DX11InputLayout::~DX11InputLayout() { Memory::SafeRelease(m_inputLayout); } void DX11InputLayout::pushFloat(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) { if (m_ied.size() == m_ied.capacity()) { m_ied.reserve(m_ied.size() + 1); InputOrder.reserve(InputOrder.size() + 1); } UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT; DXGI_FORMAT format = DXGI_FORMAT_R32_FLOAT;; /*if (typeid(T) == typeid(glm::vec4)) { format = DXGI_FORMAT_R32G32B32A32_FLOAT; } if (typeid(T) == typeid(glm::vec3)) { format = DXGI_FORMAT_R32G32B32_FLOAT; } if (typeid(T) == typeid(glm::vec2)) { format = DXGI_FORMAT_R32G32_FLOAT; } if (typeid(T) == typeid(float)) { format = DXGI_FORMAT_R32_FLOAT; }*/ auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass); m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate }); UINT typeSize = sizeof(float); if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA) InstanceSize += typeSize; else VertexSize += typeSize; InputLayout::pushFloat(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate); } void DX11InputLayout::pushVec2(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) { if (m_ied.size() == m_ied.capacity()) { m_ied.reserve(m_ied.size() + 1); InputOrder.reserve(InputOrder.size() + 1); } UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT; DXGI_FORMAT format = DXGI_FORMAT_R32G32_FLOAT;; auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass); m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate }); UINT typeSize = sizeof(glm::vec2); if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA) InstanceSize += typeSize; else VertexSize += typeSize; InputLayout::pushVec2(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate); } void DX11InputLayout::pushVec3(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) { if (m_ied.size() == m_ied.capacity()) { m_ied.reserve(m_ied.size() + 1); InputOrder.reserve(InputOrder.size() + 1); } UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT; DXGI_FORMAT format = DXGI_FORMAT_R32G32B32_FLOAT;; auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass); m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate }); UINT typeSize = sizeof(glm::vec3); if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA) InstanceSize += typeSize; else VertexSize += typeSize; InputLayout::pushVec3(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate); } void DX11InputLayout::pushVec4(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) { if (m_ied.size() == m_ied.capacity()) { m_ied.reserve(m_ied.size() + 1); InputOrder.reserve(InputOrder.size() + 1); } UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT; DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT;; auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass); m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate }); UINT typeSize = sizeof(glm::vec4); if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA) InstanceSize += typeSize; else VertexSize += typeSize; InputLayout::pushVec4(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate); } void DX11InputLayout::create(void* vertexShaderBlob) { if (!vertexShaderBlob) { Logger::Error("Failed to set up input layout, the ShaderSet does not have a vertex shader!"); return; } auto shaderBlob = static_cast<ID3D10Blob*>(vertexShaderBlob); Application::getInstance()->getAPI<DX11API>()->getDevice()->CreateInputLayout(&m_ied[0], m_ied.size(), shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), &m_inputLayout); } void DX11InputLayout::bind() const { Application::getInstance()->getAPI<DX11API>()->getDeviceContext()->IASetInputLayout(m_inputLayout); } int DX11InputLayout::convertInputClassification(InputClassification inputSlotClass) { switch (inputSlotClass) { case InputLayout::PER_VERTEX_DATA: return D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_VERTEX_DATA; case InputLayout::PER_INSTANCE_DATA: return D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_INSTANCE_DATA; default: Logger::Error("Invalid input classifier specified"); return 0; } }
43.705882
181
0.781388
h3nx
e40747c211e8941c3a1bb4f766431e17b5477028
1,243
cpp
C++
BZOJ/3875/brute.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3875/brute.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3875/brute.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<queue> #define pli pair<LL,int> #define mp make_pair #define fi first #define se second #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; typedef long long LL; const int N=2e5+10,M=1e6+10; int n; struct Heap{ priority_queue<pli,vector<pli>,greater<pli> >A,B; int size(){return A.size()-B.size();} void update(){while(B.size()&&A.top()==B.top())A.pop(),B.pop();} void push(pli x){A.push(x);} void del(pli x){B.push(x);} pli top(){update();return A.top();} void pop(){update();A.pop();} }heap; struct Graph{ int tot,head[N],to[M],next[M]; LL dis[N],mag[N],com[N],tmp[N]; void ins(int a,int b){to[++tot]=b;next[tot]=head[a];head[a]=tot;} void update(){ rep(i,1,n)tmp[i]=com[i]; rep(i,1,n)for(int p=head[i];p;p=next[p])tmp[to[p]]+=dis[i]; rep(i,1,n)dis[i]=min(dis[i],tmp[i]); } }G; int main(){ freopen("code.in","r",stdin);freopen("brute.out","w",stdout); scanf("%d",&n); rep(i,1,n){ LL s,k,r;scanf("%lld%lld%lld",&s,&k,&r); G.mag[i]=k;G.com[i]=s; rep(j,1,r){int x;scanf("%d",&x);G.ins(x,i);} } rep(i,1,n)G.dis[i]=G.mag[i]; rep(i,1,n)G.update(); printf("%lld",G.dis[1]); return 0; }
26.446809
66
0.602574
sjj118
e40a2bf75023cdeec08958fc8fabc796a873f0b1
11,743
hxx
C++
resip/stack/TransactionUser.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
resip/stack/TransactionUser.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
resip/stack/TransactionUser.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#if !defined(RESIP_TU_HXX) #define RESIP_TU_HXX #include <iosfwd> #include <set> #include "rutil/TimeLimitFifo.hxx" #include "rutil/Data.hxx" #include "rutil/CongestionManager.hxx" #include "resip/stack/Message.hxx" #include "resip/stack/MessageFilterRule.hxx" namespace resip { class SipMessage; /** @brief The base-class for an RFC 3261 Transaction User. This is the "app-layer". Subclasses of TransactionUser are expected to do the following things: - Register itself by using SipStack::registerTransactionUser(). - Regularly pull messages out of mFifo, and process them. - Particularly, every received SIP request MUST be responded to, or the stack will leak transactions. - Before the TransactionUser is destroyed, it should ensure that it has been unregistered from the stack using SipStack::unregisterTransactionUser(), and gotten a confirmation in the form of a TransactionUserMessage. There is also a collection of things you can do to customize how the stack interacts with your TransactionUser: - If you wish to restrict the types of SIP traffic your TransactionUser will receive from the stack, you can do so by setting the MessageFilterRuleList, either in the constructor, or with setMessageFilterRuleList() (see MessageFilterRule for more) - If you need more fine-grained control over what SIP messages your TransactionUser is willing/able to handle, you can override TransactionUser::isForMe(). - If you wish your TransactionUser to be notified whenever a transaction ends, just pass RegisterForTransactionTermination in the constructor. - If you wish your TransactionUser to be notified when Connections are closed, pass RegisterForConnectionTermination in the constructor. @ingroup resip_crit */ class TransactionUser { public: /** @brief Posts a Message to this TransactionUser's fifo. Ownership of msg is taken. @param msg The Message to add to mFifo. (This takes ownership of msg) */ void post(Message* msg); /** @brief Returns true iff domain matches one of the domains that this TransactionUser is responsible for. (added with addDomain). @param domain The domain name to check. @return True iff this TransactionUser is responsible for domain. @note The comparison performed is case-sensitive; make sure you lower-case everything you put in here. */ bool isMyDomain(const Data& domain) const; /** @brief Adds a domain to the set of domains that this TransactionUser is responsible for. @note The comparison performed is case-sensitive; make sure you lower-case everything you put in here. @todo Make this case-insensitive. */ void addDomain(const Data& domain); /** @brief Return the name of this TransactionUser. Used in encode(). @return The name of this TransactionUser, as a Data. */ virtual const Data& name() const=0; /** @brief Encodes the name of this TransactionUser (as specified by name()), and the current depth of its fifo. @param strm The ostream to encode to. @return strm */ virtual EncodeStream& encode(EncodeStream& strm) const; /** @brief Sets this TransactionUser's MessageFilterRuleList. This tells the stack which SIP messages this TransactionUser is interested in, and which ones it is not. This allows multiple TransactionUsers to run on top of the same SipStack. @param rules The MessageFilterRuleList to use. @see MessageFilterRule */ void setMessageFilterRuleList(MessageFilterRuleList &rules); /** @internal @brief Returns true iff this TransactionUser should be notified when transactions end. */ bool isRegisteredForTransactionTermination() const; /** @internal @brief Returns true iff this TransactionUser should be notified when connections close. */ bool isRegisteredForConnectionTermination() const; bool isRegisteredForKeepAlivePongs() const; inline CongestionManager::RejectionBehavior getRejectionBehavior() const { if(mCongestionManager) { return mCongestionManager->getRejectionBehavior(&mFifo); } return CongestionManager::NORMAL; } virtual void setCongestionManager(CongestionManager* manager) { if(mCongestionManager) { mCongestionManager->unregisterFifo(&mFifo); } mCongestionManager=manager; if(mCongestionManager) { mCongestionManager->registerFifo(&mFifo); } } virtual UInt16 getExpectedWait() const { return (UInt16)mFifo.expectedWaitTimeMilliSec(); } // .bwc. This specifies whether the TU can cope with dropped responses // (due to congestion). Some TUs may need responses to clean up state, // while others may rely on TransactionTerminated messages. Those that // rely on TransactionTerminated messages will be able to return false // here, meaning that in dire congestion situations, the stack will drop // responses bound for the TU. virtual bool responsesMandatory() const {return true;} protected: enum TransactionTermination { RegisterForTransactionTermination, DoNotRegisterForTransactionTermination }; enum ConnectionTermination { RegisterForConnectionTermination, DoNotRegisterForConnectionTermination }; enum KeepAlivePongs { RegisterForKeepAlivePongs, DoNotRegisterForKeepAlivePongs }; /** @brief Constructor that specifies whether this TransactionUser needs to hear about the completion of transactions, and the closing of connections. @param t Whether or not the TransactionUser should be informed when transactions end (disabled by default). @param c Whether or not the TransactionUser should be informed when connections close (disabled by default). @note The default MessageFilterRuleList used will accept all SIP requests with either sip: or sips: in the Request-Uri. @note This is protected to ensure than no-one constructs the base-class. (Subclasses call this in their constructor) */ TransactionUser(TransactionTermination t=DoNotRegisterForTransactionTermination, ConnectionTermination c=DoNotRegisterForConnectionTermination, KeepAlivePongs k=DoNotRegisterForKeepAlivePongs); /** @brief Constructor that specifies the MessageFilterRuleList, whether this TransactionUser needs to hear about the completion of transactions, and the closing of connections. @param rules The MessageFilterRuleList to use. (A copy is made) @param t Whether or not the TransactionUser should be informed when transactions end (disabled by default). @param c Whether or not the TransactionUser should be informed when connections close (disabled by default). @note This is protected to ensure than no-one constructs the base-class. (Subclasses call this in their constructor) */ TransactionUser(MessageFilterRuleList &rules, TransactionTermination t=DoNotRegisterForTransactionTermination, ConnectionTermination c=DoNotRegisterForConnectionTermination, KeepAlivePongs k=DoNotRegisterForKeepAlivePongs); virtual ~TransactionUser()=0; /** @brief Returns true iff this TransactionUser should process msg. @param msg The SipMessage we received. @return True iff this TransactionUser should process msg. @note By default, this uses the MessageFilterRuleList. It can be overridden for more flexibility. */ virtual bool isForMe(const SipMessage& msg) const; /** @brief This TransactionUser's fifo. All communication with the TransactionUser goes through here. */ TimeLimitFifo<Message> mFifo; CongestionManager* mCongestionManager; private: void postToTransactionUser(Message* msg, TimeLimitFifo<Message>::DepthUsage usage); unsigned int size() const; bool wouldAccept(TimeLimitFifo<Message>::DepthUsage usage) const; private: MessageFilterRuleList mRuleList; typedef std::set<Data> DomainList; DomainList mDomainList; bool mRegisteredForTransactionTermination; bool mRegisteredForConnectionTermination; bool mRegisteredForKeepAlivePongs; friend class TuSelector; }; EncodeStream& operator<<(EncodeStream& strm, const TransactionUser& tu); } #endif /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */
39.80678
89
0.668909
dulton
e40bf78aee0b38be1168a99cf5ff5e2f690c0040
2,192
cpp
C++
src/PhotonComponent/NetworkSystem.cpp
mak1a/SivComponent
1043cde67a5dc14f2d4e0128aecfee7f54ed7002
[ "MIT" ]
1
2021-01-24T08:55:59.000Z
2021-01-24T08:55:59.000Z
src/PhotonComponent/NetworkSystem.cpp
mak1a/SivComponent
1043cde67a5dc14f2d4e0128aecfee7f54ed7002
[ "MIT" ]
2
2021-01-24T06:12:12.000Z
2021-01-24T14:37:10.000Z
src/PhotonComponent/NetworkSystem.cpp
mak1a/SivComponent
1043cde67a5dc14f2d4e0128aecfee7f54ed7002
[ "MIT" ]
null
null
null
#define NO_S3D_USING #include "NetworkSystem.hpp" namespace ComponentEngine::Photon { NetworkSystem* NetworkSystem::instance = nullptr; std::string NetworkObjectName() { return "PhotonSystem"; } [[nodiscard]] s3d::String ConvertJStringToString(const ExitGames::Common::JString& str) { return s3d::Unicode::FromWString(std::wstring(str)); } [[nodiscard]] ExitGames::Common::JString ConvertStringToJString(const s3d::String& str) { return ExitGames::Common::JString(str.toWstr().c_str()); } NetworkSystem::NetworkSystem() : mLoadBalancingClient(*this, ChangeAppIDString(), appVersion, ExitGames::Photon::ConnectionProtocol::UDP) { SetPlayerName(L"null player"); mLogger.setDebugOutputLevel(ExitGames::Common::DebugLevel::ALL); mLogger.setListener(*this); //しっかりとしたシングルトンにしたい instance = this; } NetworkSystem::~NetworkSystem() { Disconnect(); instance = nullptr; } void NetworkSystem::Connect(void) { mLoadBalancingClient.setAutoJoinLobby(true); // connect() is asynchronous - the actual result arrives in the Listener::connectReturn() or the Listener::connectionErrorReturn() callback if (!mLoadBalancingClient.connect(ExitGames::LoadBalancing::AuthenticationValues().setUserID(ExitGames::Common::JString() + GETTIMEMS()), playerName)) EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"Could not connect."); } void NetworkSystem::Update() { mLoadBalancingClient.service(); // needs to be called regularly! } void NetworkSystem::OnDestroy() { Disconnect(); } void NetworkSystem::Disconnect(void) { mLoadBalancingClient.disconnect(); // disconnect() is asynchronous - the actual result arrives in the Listener::disconnectReturn() callback } //シーン変更するだけのクラス class SceneChanger : public ComponentEngine::AttachableComponent { void Update() override { GetGameObject().lock()->GetScene().lock()->GetSceneManager()->ChangeScene("Title"); } }; } // namespace ComponentEngine::Photon
30.444444
158
0.663777
mak1a
e40d1bd6f22363279ad1910e69bb856c7eff6349
4,113
cpp
C++
Samples/Win7Samples/winui/shell/appplatform/UsingImageFactory/ImageFactorySample.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/winui/shell/appplatform/UsingImageFactory/ImageFactorySample.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/winui/shell/appplatform/UsingImageFactory/ImageFactorySample.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
////////////////////////////////////////////////////////////////////////////// // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // ////////////////////////////////////////////////////////////////////////////// #include <windows.h> #include <shobjidl.h> //For IShellItemImageFactory #include <stdio.h> #include "resource.h" #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") int LookUp(PCWSTR pwszArg) { int nSize = 0; // The possbile sizes for the image that is requested struct { PCWSTR pwszSize; int nSize; } const sizeTable[] = { {L"small", 16}, {L"medium", 48}, {L"large", 96}, {L"extralarge", 256} }; for (int i = 0; i < ARRAYSIZE(sizeTable); i++) { if (CSTR_EQUAL == CompareStringOrdinal(pwszArg, -1, sizeTable[i].pwszSize, -1, TRUE)) { nSize = sizeTable[i].nSize; break; } } return nSize; } void DisplayUsage() { wprintf(L"Usage:\n"); wprintf(L"IShellItemImageFactory.exe <size> <Absolute Path to file>\n"); wprintf(L"size - small, medium, large, extralarge\n"); wprintf(L"e.g. ImageFactorySample.exe medium c:\\HelloWorld.jpg \n"); } INT_PTR CALLBACK DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { INT_PTR nReturn = FALSE; switch (message) { case WM_INITDIALOG: SendDlgItemMessage(hDlg, IDC_STATIC1, STM_SETIMAGE , IMAGE_BITMAP, (LPARAM)lParam); nReturn = TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); nReturn = TRUE; } break; } return nReturn; } int wmain(int argc, wchar_t *argv[]) { if (argc != 3) { DisplayUsage(); } else { int nSize = LookUp(argv[1]); if (!nSize) { DisplayUsage(); } else { PCWSTR pwszError = NULL; HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (SUCCEEDED(hr)) { // Getting the IShellItemImageFactory interface pointer for the file. IShellItemImageFactory *pImageFactory; hr = SHCreateItemFromParsingName(argv[2], NULL, IID_PPV_ARGS(&pImageFactory)); if (SUCCEEDED(hr)) { SIZE size = { nSize, nSize }; //sz - Size of the image, SIIGBF_BIGGERSIZEOK - GetImage will stretch down the bitmap (preserving aspect ratio) HBITMAP hbmp; hr = pImageFactory->GetImage(size, SIIGBF_BIGGERSIZEOK, &hbmp); if (SUCCEEDED(hr)) { DialogBoxParamW(NULL, MAKEINTRESOURCEW(IDD_DIALOG1), NULL, DialogProc, (LPARAM)hbmp); DeleteObject(hbmp); } else { pwszError = L"IShellItemImageFactory::GetImage failed with error code %x"; } pImageFactory->Release(); } else { pwszError = L"SHCreateItemFromParsingName failed with error %x"; } CoUninitialize(); } else { pwszError = L"CoInitializeEx failed with error code %x"; } if (FAILED(hr)) { wprintf(pwszError, hr); } } } return 0; }
30.924812
195
0.508145
windows-development
e40d874a80a9001fb4d44742f76cb84c3fd81d85
13,816
cpp
C++
src/backends/miniaudio/AudioDevice_Miniaudio.cpp
xioxin/LabSound
3e2568fcee9d0b07a91750380daec6305c20855e
[ "BSD-2-Clause" ]
43
2015-02-11T15:52:38.000Z
2020-01-08T18:19:27.000Z
src/backends/miniaudio/AudioDevice_Miniaudio.cpp
xioxin/LabSound
3e2568fcee9d0b07a91750380daec6305c20855e
[ "BSD-2-Clause" ]
2
2015-04-05T18:33:13.000Z
2015-06-11T05:16:19.000Z
src/backends/miniaudio/AudioDevice_Miniaudio.cpp
xioxin/LabSound
3e2568fcee9d0b07a91750380daec6305c20855e
[ "BSD-2-Clause" ]
3
2015-02-22T09:10:51.000Z
2015-08-09T22:49:22.000Z
// SPDX-License-Identifier: BSD-2-Clause // Copyright (C) 2020, The LabSound Authors. All rights reserved. #define LABSOUND_ENABLE_LOGGING #include "AudioDevice_Miniaudio.h" #include "internal/Assertions.h" #include "internal/VectorMath.h" #include "LabSound/core/AudioDevice.h" #include "LabSound/core/AudioHardwareDeviceNode.h" #include "LabSound/core/AudioNode.h" #include "LabSound/extended/Logging.h" //#define MA_DEBUG_OUTPUT #define MINIAUDIO_IMPLEMENTATION #include "miniaudio.h" namespace lab { //////////////////////////////////////////////////// // Platform/backend specific static functions // //////////////////////////////////////////////////// const float kLowThreshold = -1.0f; const float kHighThreshold = 1.0f; const int kRenderQuantum = AudioNode::ProcessingSizeInFrames; /// @TODO - the AudioDeviceInfo wants to support specific sample rates, but miniaudio only tells min and max /// miniaudio also has a concept of minChannels, which LabSound ignores namespace { ma_context g_context; static std::vector<AudioDeviceInfo> g_devices; static bool g_must_init = true; void init_context() { if (g_must_init) { LOG_TRACE("[LabSound] init_context() must_init"); if (ma_context_init(NULL, 0, NULL, &g_context) != MA_SUCCESS) { LOG_ERROR("[LabSound] init_context(): Failed to initialize miniaudio context"); return; } LOG_TRACE("[LabSound] init_context() succeeded"); g_must_init = false; } } } void PrintAudioDeviceList() { if (!g_devices.size()) LOG_INFO("No devices detected"); else for (auto & device : g_devices) { LOG_INFO("[%d] %s\n----------------------\n", device.index, device.identifier.c_str()); LOG_INFO(" ins:%d outs:%d default_in:%s default:out:%s\n", device.num_input_channels, device.num_output_channels, device.is_default_input?"yes":"no", device.is_default_output?"yes":"no"); LOG_INFO(" nominal samplerate: %f\n", device.nominal_samplerate); for (float f : device.supported_samplerates) LOG_INFO(" %f\n", f); } } std::vector<AudioDeviceInfo> AudioDevice::MakeAudioDeviceList() { init_context(); static bool probed = false; if (probed) return g_devices; probed = true; ma_result result; ma_device_info * pPlaybackDeviceInfos; ma_uint32 playbackDeviceCount; ma_device_info * pCaptureDeviceInfos; ma_uint32 captureDeviceCount; ma_uint32 iDevice; result = ma_context_get_devices(&g_context, &pPlaybackDeviceInfos, &playbackDeviceCount, &pCaptureDeviceInfos, &captureDeviceCount); if (result != MA_SUCCESS) { LOG_ERROR("Failed to retrieve audio device information.\n"); return {}; } for (iDevice = 0; iDevice < playbackDeviceCount; ++iDevice) { AudioDeviceInfo lab_device_info; lab_device_info.index = (int32_t) g_devices.size(); lab_device_info.identifier = pPlaybackDeviceInfos[iDevice].name; if (ma_context_get_device_info(&g_context, ma_device_type_playback, &pPlaybackDeviceInfos[iDevice].id, ma_share_mode_shared, &pPlaybackDeviceInfos[iDevice]) != MA_SUCCESS) continue; lab_device_info.num_output_channels = pPlaybackDeviceInfos[iDevice].maxChannels; lab_device_info.num_input_channels = 0; lab_device_info.supported_samplerates.push_back(static_cast<float>(pPlaybackDeviceInfos[iDevice].minSampleRate)); lab_device_info.supported_samplerates.push_back(static_cast<float>(pPlaybackDeviceInfos[iDevice].maxSampleRate)); lab_device_info.nominal_samplerate = static_cast<float>(pPlaybackDeviceInfos[iDevice].maxSampleRate); lab_device_info.is_default_output = iDevice == 0; lab_device_info.is_default_input = false; g_devices.push_back(lab_device_info); } for (iDevice = 0; iDevice < captureDeviceCount; ++iDevice) { AudioDeviceInfo lab_device_info; lab_device_info.index = (int32_t) g_devices.size(); lab_device_info.identifier = pCaptureDeviceInfos[iDevice].name; if (ma_context_get_device_info(&g_context, ma_device_type_capture, &pPlaybackDeviceInfos[iDevice].id, ma_share_mode_exclusive, &pPlaybackDeviceInfos[iDevice]) != MA_SUCCESS) continue; lab_device_info.num_output_channels = 0; lab_device_info.num_input_channels = 2; // pCaptureDeviceInfos[iDevice].maxChannels; lab_device_info.supported_samplerates.push_back(static_cast<float>(pCaptureDeviceInfos[iDevice].minSampleRate)); lab_device_info.supported_samplerates.push_back(static_cast<float>(pCaptureDeviceInfos[iDevice].maxSampleRate)); lab_device_info.nominal_samplerate = 48000.f; // static_cast<float>(pCaptureDeviceInfos[iDevice].maxSampleRate); lab_device_info.is_default_output = false; lab_device_info.is_default_input = iDevice == 0; g_devices.push_back(lab_device_info); } return g_devices; } AudioDeviceIndex AudioDevice::GetDefaultOutputAudioDeviceIndex() noexcept { auto devices = MakeAudioDeviceList(); size_t c = devices.size(); for (uint32_t i = 0; i < c; ++i) if (devices[i].is_default_output) return {i, true}; return {0, false}; } AudioDeviceIndex AudioDevice::GetDefaultInputAudioDeviceIndex() noexcept { auto devices = MakeAudioDeviceList(); size_t c = devices.size(); for (uint32_t i = 0; i < c; ++i) if (devices[i].is_default_input) return {i, true}; return {0, false}; } namespace { void outputCallback(ma_device * pDevice, void * pOutput, const void * pInput, ma_uint32 frameCount) { // Buffer is nBufferFrames * channels, interleaved float * fBufOut = (float *) pOutput; AudioDevice_Miniaudio * ad = reinterpret_cast<AudioDevice_Miniaudio *>(pDevice->pUserData); memset(fBufOut, 0, sizeof(float) * frameCount * ad->outputConfig.desired_channels); ad->render(frameCount, pOutput, const_cast<void *>(pInput)); } } AudioDevice * AudioDevice::MakePlatformSpecificDevice(AudioDeviceRenderCallback & callback, const AudioStreamConfig outputConfig, const AudioStreamConfig inputConfig) { return new AudioDevice_Miniaudio(callback, outputConfig, inputConfig); } AudioDevice_Miniaudio::AudioDevice_Miniaudio(AudioDeviceRenderCallback & callback, const AudioStreamConfig _outputConfig, const AudioStreamConfig _inputConfig) : _callback(callback) , outputConfig(_outputConfig) , inputConfig(_inputConfig) { auto device_list = AudioDevice::MakeAudioDeviceList(); PrintAudioDeviceList(); //ma_device_config deviceConfig = ma_device_config_init(ma_device_type_duplex); ma_device_config deviceConfig = ma_device_config_init(ma_device_type_playback); deviceConfig.playback.format = ma_format_f32; deviceConfig.playback.channels = outputConfig.desired_channels; deviceConfig.sampleRate = static_cast<int>(outputConfig.desired_samplerate); deviceConfig.capture.format = ma_format_f32; deviceConfig.capture.channels = inputConfig.desired_channels; deviceConfig.dataCallback = outputCallback; deviceConfig.performanceProfile = ma_performance_profile_low_latency; deviceConfig.pUserData = this; #ifdef __WINDOWS_WASAPI__ deviceConfig.wasapi.noAutoConvertSRC = true; #endif if (ma_device_init(&g_context, &deviceConfig, &_device) != MA_SUCCESS) { LOG_ERROR("Unable to open audio playback device"); return; } authoritativeDeviceSampleRateAtRuntime = outputConfig.desired_samplerate; samplingInfo.epoch[0] = samplingInfo.epoch[1] = std::chrono::high_resolution_clock::now(); _ring = new cinder::RingBufferT<float>(); _ring->resize(static_cast<int>(authoritativeDeviceSampleRateAtRuntime)); // ad hoc. hold one second _scratch = reinterpret_cast<float *>(malloc(sizeof(float) * kRenderQuantum * inputConfig.desired_channels)); } AudioDevice_Miniaudio::~AudioDevice_Miniaudio() { stop(); ma_device_uninit(&_device); ma_context_uninit(&g_context); g_must_init = true; delete _renderBus; delete _inputBus; delete _ring; if (_scratch) free(_scratch); } void AudioDevice_Miniaudio::backendReinitialize() { auto device_list = AudioDevice::MakeAudioDeviceList(); PrintAudioDeviceList(); //ma_device_config deviceConfig = ma_device_config_init(ma_device_type_duplex); ma_device_config deviceConfig = ma_device_config_init(ma_device_type_playback); deviceConfig.playback.format = ma_format_f32; deviceConfig.playback.channels = outputConfig.desired_channels; deviceConfig.sampleRate = static_cast<int>(outputConfig.desired_samplerate); deviceConfig.capture.format = ma_format_f32; deviceConfig.capture.channels = inputConfig.desired_channels; deviceConfig.dataCallback = outputCallback; deviceConfig.performanceProfile = ma_performance_profile_low_latency; deviceConfig.pUserData = this; #ifdef __WINDOWS_WASAPI__ deviceConfig.wasapi.noAutoConvertSRC = true; #endif if (ma_device_init(&g_context, &deviceConfig, &_device) != MA_SUCCESS) { LOG_ERROR("Unable to open audio playback device"); return; } } void AudioDevice_Miniaudio::start() { ASSERT(authoritativeDeviceSampleRateAtRuntime != 0.f); // something went very wrong if (ma_device_start(&_device) != MA_SUCCESS) { LOG_ERROR("Unable to start audio device"); } } void AudioDevice_Miniaudio::stop() { if (ma_device_stop(&_device) != MA_SUCCESS) { LOG_ERROR("Unable to stop audio device"); } } bool AudioDevice_Miniaudio::isRunning() const { return ma_device_is_started(&_device); } // Pulls on our provider to get rendered audio stream. void AudioDevice_Miniaudio::render(int numberOfFrames_, void * outputBuffer, void * inputBuffer) { int numberOfFrames = numberOfFrames_; if (!_renderBus) { _renderBus = new AudioBus(outputConfig.desired_channels, kRenderQuantum, true); _renderBus->setSampleRate(authoritativeDeviceSampleRateAtRuntime); } if (!_inputBus && inputConfig.desired_channels) { _inputBus = new AudioBus(inputConfig.desired_channels, kRenderQuantum, true); _inputBus->setSampleRate(authoritativeDeviceSampleRateAtRuntime); } float * pIn = static_cast<float *>(inputBuffer); float * pOut = static_cast<float *>(outputBuffer); int in_channels = inputConfig.desired_channels; int out_channels = outputConfig.desired_channels; if (pIn && numberOfFrames * in_channels) _ring->write(pIn, numberOfFrames * in_channels); while (numberOfFrames > 0) { if (_remainder > 0) { // copy samples to output buffer. There might have been some rendered frames // left over from the previous numberOfFrames, so start by moving those into // the output buffer. // miniaudio expects interleaved data, this loop leverages the vclip operation // to copy, interleave, and clip in one pass. int samples = _remainder < numberOfFrames ? _remainder : numberOfFrames; for (int i = 0; i < out_channels; ++i) { int src_stride = 1; // de-interleaved int dst_stride = out_channels; // interleaved AudioChannel * channel = _renderBus->channel(i); VectorMath::vclip(channel->data() + kRenderQuantum - _remainder, src_stride, &kLowThreshold, &kHighThreshold, pOut + i, dst_stride, samples); } pOut += out_channels * samples; numberOfFrames -= samples; // deduct samples actually copied to output _remainder -= samples; // deduct samples remaining from last render() invocation } else { if (in_channels) { // miniaudio provides the input data in interleaved form, vclip is used here to de-interleave _ring->read(_scratch, in_channels * kRenderQuantum); for (int i = 0; i < in_channels; ++i) { int src_stride = in_channels; // interleaved int dst_stride = 1; // de-interleaved AudioChannel * channel = _inputBus->channel(i); VectorMath::vclip(_scratch + i, src_stride, &kLowThreshold, &kHighThreshold, channel->mutableData(), dst_stride, kRenderQuantum); } } // Update sampling info for use by the render graph const int32_t index = 1 - (samplingInfo.current_sample_frame & 1); const uint64_t t = samplingInfo.current_sample_frame & ~1; samplingInfo.sampling_rate = authoritativeDeviceSampleRateAtRuntime; samplingInfo.current_sample_frame = t + kRenderQuantum + index; samplingInfo.current_time = samplingInfo.current_sample_frame / static_cast<double>(samplingInfo.sampling_rate); samplingInfo.epoch[index] = std::chrono::high_resolution_clock::now(); // generate new data _callback.render(_inputBus, _renderBus, kRenderQuantum, samplingInfo); _remainder = kRenderQuantum; } } } } // namespace lab
37.441734
201
0.672192
xioxin
e415f963b78d16ab5d2fe0e7607b8bb0e4cfa703
77
cpp
C++
engine/plyMaker.cpp
heyday665/symmetrical-pancake
4e3bb710923dc7162d0562185ee9ba76b0c46bf5
[ "MIT" ]
null
null
null
engine/plyMaker.cpp
heyday665/symmetrical-pancake
4e3bb710923dc7162d0562185ee9ba76b0c46bf5
[ "MIT" ]
null
null
null
engine/plyMaker.cpp
heyday665/symmetrical-pancake
4e3bb710923dc7162d0562185ee9ba76b0c46bf5
[ "MIT" ]
null
null
null
#include "plyMaker.h" PLYMAKER::PLYMAKER() { } PLYMAKER::~PLYMAKER() { }
6.416667
21
0.623377
heyday665
e41c20061d618e55c21ad1e8605c6c1b03dedfb9
12,355
cpp
C++
source/utility_parse.cpp
DynasticSponge/Frederick2
410ad4a3ca43547d645248e13d27497e6c5b5f26
[ "MIT" ]
null
null
null
source/utility_parse.cpp
DynasticSponge/Frederick2
410ad4a3ca43547d645248e13d27497e6c5b5f26
[ "MIT" ]
null
null
null
source/utility_parse.cpp
DynasticSponge/Frederick2
410ad4a3ca43547d645248e13d27497e6c5b5f26
[ "MIT" ]
null
null
null
// // utility_parse.cpp // ~~~~~~~~~~~~~~~~~ // // Author: Joseph Adomatis // Copyright (c) 2020 Joseph R Adomatis (joseph dot adomatis at gmail dot com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <exception> #include <sstream> #include <string> #include "../headers/frederick2_namespace.hpp" #include "../headers/utility_parse.hpp" namespace utility = frederick2::utility; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // global variable definitions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // global function definitions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities member definitions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////// utility::parseUtilities::parseUtilities() { } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::dqExtract /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::dqExtract(const std::string& original, std::string& revised, bool escape) { size_t dqueFoundS{original.find_first_of('\"')}; if(dqueFoundS != std::string::npos) { /////////////////////////////////////////////////////////////////////////////// // double quoted string should have DQUOTE as first and last char /////////////////////////////////////////////////////////////////////////////// size_t dqueFoundE{original.find_last_of('\"')}; if(dqueFoundS != 0 || dqueFoundE != (original.size() - 1)) { return(false); } else { /////////////////////////////////////////////////////////////////////////////// // DQUOTE are first and last char // extract out the string between them // if escape = true then run the escapeReplace on the extracted string /////////////////////////////////////////////////////////////////////////////// std::string extractInit{original.substr(1, original.size() - 2)}; if(escape) { std::string extractFinal; this->escapeReplace(extractInit, extractFinal); revised = std::move(extractFinal); } else { revised = std::move(extractInit); } } } else { /////////////////////////////////////////////////////////////////////////////// // no DQUOTE found in string.. just set revised = original /////////////////////////////////////////////////////////////////////////////// revised = original; } return(true); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::escapeReplace /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::escapeReplace(const std::string& original, std::string& revised) { std::string bldStr; size_t maxBound{original.size()}; size_t maxSlashBound{(original.size() - 1)}; for(size_t i = 0; i < maxBound; i++) { char c0{original[i]}; if (c0 == '\\') { if(i < maxSlashBound) { /////////////////////////////////////////////////////////////////////////////// // '\' not the last char // get next char /////////////////////////////////////////////////////////////////////////////// char c1{original[i+1]}; bldStr.append(1, c1); i += 1; } else { /////////////////////////////////////////////////////////////////////////////// // '\' is last char.. // return false /////////////////////////////////////////////////////////////////////////////// return(false); } } else { /////////////////////////////////////////////////////////////////////////////// // target char isnt a '\' // just append it to bldStr /////////////////////////////////////////////////////////////////////////////// bldStr.append(1, c0); } } /////////////////////////////////////////////////////////////////////////////// // move contents of bldStr back into supplied string ref /////////////////////////////////////////////////////////////////////////////// revised = std::move(bldStr); return(true); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::isHex /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::isHex(char c) { return((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::pctDecode /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::pctDecode(const std::string& original, std::string& revised) { bool returnValue{true}; std::string bldStr; size_t maxBound{original.size()}; size_t maxHexBound{(original.size() - 2)}; for(size_t i = 0; i < maxBound; i++) { char c0{original[i]}; if(c0 == '+') { /////////////////////////////////////////////////////////////////////////////// // '+' decodes to space /////////////////////////////////////////////////////////////////////////////// bldStr.append(1, ' '); } else if (c0 == '%') { if(i < maxHexBound) { /////////////////////////////////////////////////////////////////////////////// // '%' not one of the last two chars // check next 2 chars to ensure they are potential hex values /////////////////////////////////////////////////////////////////////////////// char c1{original[i+1]}; char c2{original[i+2]}; if(this->isHex(c1) && this->isHex(c2)) { /////////////////////////////////////////////////////////////////////////////// // next 2 chars are hex, use stoi base 16 to convert them to int // then static cast into to unsigned char /////////////////////////////////////////////////////////////////////////////// unsigned int numVal = std::stoi(original.substr(i+1, 2), 0, 16); unsigned char outChar{(unsigned char)numVal}; /////////////////////////////////////////////////////////////////////////////// // add decoded char to bldStr // because the next 2 chars were part of this single encoded char // manual increment i 2 more spaces to skip evaluating them individually /////////////////////////////////////////////////////////////////////////////// bldStr.append(1, outChar); i += 2; } else { /////////////////////////////////////////////////////////////////////////////// // 1 or both of the chars after '%' was not a hex val // go ahead and add '%' to bldStr and report invalid URI /////////////////////////////////////////////////////////////////////////////// returnValue = false; bldStr.append(1, c0); } } else { /////////////////////////////////////////////////////////////////////////////// // '%' is one of the last 2 chars.. // go ahead and add to bldStr and report invalid URI /////////////////////////////////////////////////////////////////////////////// returnValue = false; bldStr.append(1, c0); } } else { /////////////////////////////////////////////////////////////////////////////// // target char isnt a special character... // just append it to bldStr /////////////////////////////////////////////////////////////////////////////// bldStr.append(1, c0); } } /////////////////////////////////////////////////////////////////////////////// // move contents of bldStr back into supplied string ref /////////////////////////////////////////////////////////////////////////////// revised = std::move(bldStr); return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::pctEncode /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::pctEncode(const std::string& original, std::string& revised) { bool returnValue{true}; return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::replace /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::replace(std::string& src, const std::string& sPre, const std::string& sPost) { bool returnValue{true}; size_t sPreSize = sPre.size(); size_t sPreFound{src.find(sPre)}; while(sPreFound != std::string::npos) { src.replace(sPreFound, sPreSize, sPost); sPreFound = src.find(sPre); } return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::toHex /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::toHex(const size_t& original, std::string& revised) { bool opSuccess{true}; revised.clear(); std::stringstream ss; ss << std::hex << original; ss >> revised; return(opSuccess); } /////////////////////////////////////////////////////////////////////////////// // frederick2::utility::parseUtilities::toLower /////////////////////////////////////////////////////////////////////////////// bool utility::parseUtilities::toLower(const std::string& original, std::string& revised) { bool opSuccess{true}; std::string str{original}; try { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){return(std::tolower(c));}); } catch(const std::exception& e) { opSuccess = false; } if(opSuccess) { revised = std::move(str); } else { revised = original; } return(opSuccess); } /////////////////////////////////////////////////////////////////////////////// // Deconstructor /////////////////////////////////////////////////////////////////////////////// utility::parseUtilities::~parseUtilities() { }
38.132716
119
0.299555
DynasticSponge
e4219840a75fd304bcd009ff8726b4b73a3bb05c
14,312
cpp
C++
TVTest_0.7.23_Src/NetworkRemocon.cpp
mark10als/TVTest_0.7.23_fix_Sources
313c295ab67a39bb285303ad814ee4f5aa15d921
[ "libpng-2.0" ]
null
null
null
TVTest_0.7.23_Src/NetworkRemocon.cpp
mark10als/TVTest_0.7.23_fix_Sources
313c295ab67a39bb285303ad814ee4f5aa15d921
[ "libpng-2.0" ]
null
null
null
TVTest_0.7.23_Src/NetworkRemocon.cpp
mark10als/TVTest_0.7.23_fix_Sources
313c295ab67a39bb285303ad814ee4f5aa15d921
[ "libpng-2.0" ]
null
null
null
#include "stdafx.h" #include "TVTest.h" #include "AppMain.h" #include "NetworkRemocon.h" #include "resource.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #pragma comment(lib,"Ws2_32.lib") class CSendStringInfo { public: CNetworkRemocon *m_pRemocon; char *m_pBuffer; int m_Length; CNetworkRemoconReceiver *m_pReceiver; CSendStringInfo(CNetworkRemocon *pRemocon,const char *pBuffer,int Length, CNetworkRemoconReceiver *pReceiver) { m_pRemocon=pRemocon; m_pBuffer=new char[Length+1]; CopyMemory(m_pBuffer,pBuffer,Length); m_pBuffer[Length]='\0'; m_Length=Length; m_pReceiver=pReceiver; } ~CSendStringInfo() { delete [] m_pBuffer; } }; CNetworkRemocon::CNetworkRemocon() { m_fInitialized=false; m_Address=INADDR_NONE; m_Port=0; m_hThread=NULL; m_Socket=INVALID_SOCKET; m_fConnected=false; } CNetworkRemocon::~CNetworkRemocon() { if (m_fInitialized) { Shutdown(); WSACleanup(); } } bool CNetworkRemocon::Init(LPCSTR pszAddress,WORD Port) { int Err; if (!m_fInitialized) { Err=WSAStartup(MAKEWORD(2,0),&m_WSAData); if (Err!=0) return false; m_fInitialized=true; } else { if (m_Address==inet_addr(pszAddress) && m_Port==Port) return true; Shutdown(); } m_Address=inet_addr(pszAddress); if (m_Address==INADDR_NONE) return false; m_Port=Port; return true; } bool CNetworkRemocon::Shutdown() { if (m_fInitialized) { if (m_hThread!=NULL) { if (WaitForSingleObject(m_hThread,5000)==WAIT_TIMEOUT) TerminateThread(m_hThread,FALSE); CloseHandle(m_hThread); m_hThread=NULL; } if (m_Socket!=INVALID_SOCKET) { shutdown(m_Socket,1); closesocket(m_Socket); m_Socket=INVALID_SOCKET; } } return true; } DWORD CNetworkRemocon::SendProc(LPVOID pParam) { CSendStringInfo *pInfo=(CSendStringInfo*)pParam; int Result; char Buffer[4096]; if (pInfo->m_pRemocon->m_Socket==INVALID_SOCKET) { pInfo->m_pRemocon->m_Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (pInfo->m_pRemocon->m_Socket==INVALID_SOCKET) return FALSE; } if (!pInfo->m_pRemocon->m_fConnected) { struct sockaddr_in sockaddri; sockaddri.sin_family=AF_INET; sockaddri.sin_port=htons(pInfo->m_pRemocon->m_Port); sockaddri.sin_addr.S_un.S_addr=pInfo->m_pRemocon->m_Address; ZeroMemory(sockaddri.sin_zero,sizeof(sockaddri.sin_zero)); Result=connect(pInfo->m_pRemocon->m_Socket, (struct sockaddr*)&sockaddri,sizeof(sockaddr_in)); if (Result!=0) { delete pInfo; return FALSE; } pInfo->m_pRemocon->m_fConnected=true; } Result=send(pInfo->m_pRemocon->m_Socket,pInfo->m_pBuffer,pInfo->m_Length,0); if (Result==SOCKET_ERROR) { closesocket(pInfo->m_pRemocon->m_Socket); pInfo->m_pRemocon->m_Socket=INVALID_SOCKET; pInfo->m_pRemocon->m_fConnected=false; return FALSE; } Result=recv(pInfo->m_pRemocon->m_Socket,Buffer,sizeof(Buffer)-1,0); if (Result!=SOCKET_ERROR && pInfo->m_pReceiver!=NULL) { Buffer[Result]='\0'; pInfo->m_pReceiver->OnReceive(Buffer); } if (Result==SOCKET_ERROR || Result==0) { closesocket(pInfo->m_pRemocon->m_Socket); pInfo->m_pRemocon->m_Socket=INVALID_SOCKET; pInfo->m_pRemocon->m_fConnected=false; delete pInfo; return Result==SOCKET_ERROR; } delete pInfo; return TRUE; } bool CNetworkRemocon::Send(const char *pBuffer,int Length, CNetworkRemoconReceiver *pReceiver) { DWORD ThreadID; CSendStringInfo *pInfo; if (!m_fInitialized) return false; if (m_hThread!=NULL) { if (WaitForSingleObject(m_hThread,0)==WAIT_TIMEOUT) return false; CloseHandle(m_hThread); } pInfo=new CSendStringInfo(this,pBuffer,Length,pReceiver); m_hThread=CreateThread(NULL,0,SendProc,pInfo,0,&ThreadID); if (m_hThread==NULL) { delete pInfo; return false; } return true; } bool CNetworkRemocon::SetChannel(int ChannelNo) { char szText[16]; int Length; if (m_ChannelList.NumChannels()>0) { int i; for (i=0;i<m_ChannelList.NumChannels();i++) { if (m_ChannelList.GetChannelNo(i)==ChannelNo+1) { Length=wsprintfA(szText,"SetCh:%d",i); return Send(szText,Length); } } } else { Length=wsprintfA(szText,"SetCh:%d",ChannelNo); return Send(szText,Length); } return false; } class CGetChannelReceiver : public CNetworkRemoconReceiver { public: CNetworkRemoconReceiver *m_pReceiver; void OnReceive(LPCSTR pszText); }; void CGetChannelReceiver::OnReceive(LPCSTR pszText) { LPCSTR p; char szChannel[16]; int i; p=pszText; while (*p!='\t') { if (*p=='\0') return; p++; } p++; for (i=0;*p>='0' && *p<='9';i++) { if (i==sizeof(szChannel)) return; szChannel[i]=*p++; } if (i==0) return; szChannel[i]='\0'; m_pReceiver->OnReceive(szChannel); } bool CNetworkRemocon::GetChannel(CNetworkRemoconReceiver *pReceiver) { static CGetChannelReceiver Receiver; Receiver.m_pReceiver=pReceiver; return Send("GetChList",9,&Receiver); } bool CNetworkRemocon::SetService(int Service) { char szText[16]; int Length; Length=wsprintfA(szText,"SetService:%d",Service); return Send(szText,Length); } bool CNetworkRemocon::GetDriverList(CNetworkRemoconReceiver *pReceiver) { return Send("GetBonList",10,pReceiver); } bool CNetworkRemocon::LoadChannelText(LPCTSTR pszFileName, const CChannelList *pChannelList) { HANDLE hFile; DWORD FileSize,Read; char *pszText,*p; hFile=CreateFile(pszFileName,GENERIC_READ,FILE_SHARE_READ,NULL, OPEN_EXISTING,0,NULL); if (hFile==INVALID_HANDLE_VALUE) return false; FileSize=GetFileSize(hFile,NULL); if (FileSize==INVALID_FILE_SIZE || FileSize==0) { CloseHandle(hFile); return false; } pszText=new char[FileSize+1]; if (!ReadFile(hFile,pszText,FileSize,&Read,NULL) || Read!=FileSize) { CloseHandle(hFile); return false; } pszText[FileSize]='\0'; CloseHandle(hFile); m_ChannelList.Clear(); p=pszText; while (*p!='\0') { char *pszName; int Space,Channel; while (*p=='\r' || *p=='\n') p++; if (*p==';') { // Comment while (*p!='\r' && *p!='\n' && *p!='\0') p++; continue; } pszName=p; while (*p!='\t' && *p!='\0') p++; if (*p=='\0') break; *p++='\0'; Space=0; while (*p>='0' && *p<='9') { Space=Space*10+(*p-'0'); p++; } if (*p!='\t') break; p++; Channel=0; while (*p>='0' && *p<='9') { Channel=Channel*10+(*p-'0'); p++; } int i; for (i=0;i<pChannelList->NumChannels();i++) { const CChannelInfo *pChInfo=pChannelList->GetChannelInfo(i); if (pChInfo->GetSpace()==Space && pChInfo->GetChannelIndex()==Channel) { m_ChannelList.AddChannel(*pChInfo); break; } } if (i==pChannelList->NumChannels()) { TCHAR szName[MAX_CHANNEL_NAME]; MultiByteToWideChar(CP_ACP,0,pszName,-1,szName,MAX_CHANNEL_NAME); m_ChannelList.AddChannel( CChannelInfo(Space,Channel, pChannelList->NumChannels()==0?m_ChannelList.NumChannels()+1:Channel+1, szName)); } while (*p!='\r' && *p!='\n' && *p!='\0') p++; } delete [] pszText; return true; } CNetworkRemoconOptions::CNetworkRemoconOptions() { m_fUseNetworkRemocon=false; ::lstrcpyA(m_szAddress,"127.0.0.1"); m_Port=1334; m_szChannelFileName[0]='\0'; m_szDefaultChannelFileName[0]='\0'; m_fTempEnable=false; m_TempPort=0; } CNetworkRemoconOptions::~CNetworkRemoconOptions() { Destroy(); } bool CNetworkRemoconOptions::ReadSettings(CSettings &Settings) { TCHAR szText[16]; Settings.Read(TEXT("UseNetworkRemocon"),&m_fUseNetworkRemocon); if (Settings.Read(TEXT("NetworkRemoconAddress"),szText,lengthof(szText))) ::WideCharToMultiByte(CP_ACP,0,szText,-1, m_szAddress,lengthof(m_szAddress),NULL,NULL); Settings.Read(TEXT("NetworkRemoconPort"),&m_Port); Settings.Read(TEXT("NetworkRemoconChFile"), m_szChannelFileName,lengthof(m_szChannelFileName)); return true; } bool CNetworkRemoconOptions::WriteSettings(CSettings &Settings) { Settings.Write(TEXT("UseNetworkRemocon"),m_fUseNetworkRemocon); WCHAR szAddress[16]; ::MultiByteToWideChar(CP_ACP,0,m_szAddress,-1,szAddress,lengthof(szAddress)); Settings.Write(TEXT("NetworkRemoconAddress"),szAddress); Settings.Write(TEXT("NetworkRemoconPort"),m_Port); Settings.Write(TEXT("NetworkRemoconChFile"),m_szChannelFileName); return true; } bool CNetworkRemoconOptions::Create(HWND hwndOwner) { return CreateDialogWindow(hwndOwner, GetAppClass().GetResourceInstance(),MAKEINTRESOURCE(IDD_OPTIONS_NETWORKREMOCON)); } bool CNetworkRemoconOptions::SetTempEnable(bool fEnable) { m_fTempEnable=fEnable; return true; } bool CNetworkRemoconOptions::SetTempPort(unsigned int Port) { if (m_fUseNetworkRemocon || m_fTempEnable) m_TempPort=Port; return true; } bool CNetworkRemoconOptions::SetDefaultChannelFileName(LPCTSTR pszFileName) { ::lstrcpy(m_szDefaultChannelFileName,pszFileName); return true; } bool CNetworkRemoconOptions::IsEnable() const { return m_fUseNetworkRemocon || m_fTempEnable; } bool CNetworkRemoconOptions::IsSettingValid() const { return m_Port>0; } bool CNetworkRemoconOptions::CreateNetworkRemocon(CNetworkRemocon **ppNetworkRemocon) { *ppNetworkRemocon=new CNetworkRemocon; if (!(*ppNetworkRemocon)->Init(m_szAddress,m_TempPort>0?m_TempPort:m_Port)) { delete *ppNetworkRemocon; *ppNetworkRemocon=NULL; } return true; } bool CNetworkRemoconOptions::InitNetworkRemocon(CNetworkRemocon **ppNetworkRemocon, const CCoreEngine *pCoreEngine,CChannelManager *pChannelManager) const { if ((m_fUseNetworkRemocon || m_fTempEnable) && pCoreEngine->IsNetworkDriver()) { TCHAR szChannelFile[MAX_PATH]; if (!GetChannelFilePath(szChannelFile)) return false; if (*ppNetworkRemocon==NULL) *ppNetworkRemocon=new CNetworkRemocon; if ((*ppNetworkRemocon)->LoadChannelText(szChannelFile, pChannelManager->GetFileAllChannelList())) { pChannelManager->SetNetworkRemoconMode(true, &(*ppNetworkRemocon)->GetChannelList()); pChannelManager->SetNetworkRemoconCurrentChannel(-1); } (*ppNetworkRemocon)->Init(m_szAddress,m_TempPort>0?m_TempPort:m_Port); } else { if (*ppNetworkRemocon!=NULL) { delete *ppNetworkRemocon; *ppNetworkRemocon=NULL; } } return true; } bool CNetworkRemoconOptions::FindChannelFile(LPCTSTR pszDriverName,LPTSTR pszFileName) const { TCHAR szMask[MAX_PATH]; HANDLE hFind; WIN32_FIND_DATA wfd; ::SHGetSpecialFolderPath(NULL,szMask,CSIDL_PERSONAL,FALSE); ::PathAppend(szMask,TEXT("EpgTimerBon\\*(*).ChSet.txt")); hFind=::FindFirstFile(szMask,&wfd); if (hFind==INVALID_HANDLE_VALUE) return false; bool fFound=false; do { LPCTSTR p; TCHAR szName[MAX_PATH]; int i; p=wfd.cFileName; while (*p!='(') p++; p++; for (i=0;*p!=')';i++) szName[i]=*p++; szName[i]='\0'; if (::lstrcmpi(szName,pszDriverName)==0) { ::lstrcpy(pszFileName,wfd.cFileName); fFound=true; break; } } while (::FindNextFile(hFind,&wfd)); ::FindClose(hFind); return fFound; } bool CNetworkRemoconOptions::GetChannelFilePath(LPTSTR pszPath) const { if (m_szChannelFileName[0]=='\0' || ::PathIsFileSpec(m_szChannelFileName)) { ::SHGetSpecialFolderPath(NULL,pszPath,CSIDL_PERSONAL,FALSE); ::PathAppend(pszPath,TEXT("EpgTimerBon")); if (m_szChannelFileName[0]!='\0') { ::PathAppend(pszPath,m_szChannelFileName); } else if (m_szDefaultChannelFileName[0]!='\0') { ::PathAppend(pszPath,m_szDefaultChannelFileName); } else { TCHAR szMask[MAX_PATH]; HANDLE hFind; WIN32_FIND_DATA fd; ::lstrcpy(szMask,pszPath); ::PathAppend(szMask,TEXT("BonDriver_*(*).ChSet.txt")); hFind=::FindFirstFile(szMask,&fd); if (hFind==INVALID_HANDLE_VALUE) return false; ::FindClose(hFind); ::PathAppend(pszPath,fd.cFileName); } } else { ::lstrcpy(pszPath,m_szChannelFileName); } return true; } INT_PTR CNetworkRemoconOptions::DlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { ::CheckDlgButton(hDlg,IDC_NETWORKREMOCON_USE, m_fUseNetworkRemocon?BST_CHECKED: m_fTempEnable?BST_INDETERMINATE:BST_UNCHECKED); ::SetDlgItemTextA(hDlg,IDC_NETWORKREMOCON_ADDRESS,m_szAddress); ::SetDlgItemInt(hDlg,IDC_NETWORKREMOCON_PORT,m_Port,FALSE); { TCHAR szFileMask[MAX_PATH]; HANDLE hFind; WIN32_FIND_DATA wfd; ::SendDlgItemMessage(hDlg,IDC_NETWORKREMOCON_CHANNELFILE,CB_LIMITTEXT,MAX_PATH-1,0); ::SHGetSpecialFolderPath(NULL,szFileMask,CSIDL_PERSONAL,FALSE); ::PathAppend(szFileMask,TEXT("EpgTimerBon\\*(*).ChSet.txt")); hFind=::FindFirstFile(szFileMask,&wfd); if (hFind!=INVALID_HANDLE_VALUE) { do { ::SendDlgItemMessage(hDlg,IDC_NETWORKREMOCON_CHANNELFILE, CB_ADDSTRING,0, reinterpret_cast<LPARAM>(wfd.cFileName)); } while (::FindNextFile(hFind,&wfd)); ::FindClose(hFind); } ::SetDlgItemText(hDlg,IDC_NETWORKREMOCON_CHANNELFILE,m_szChannelFileName); } } return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_NETWORKREMOCON_USE: ::CheckDlgButton(hDlg,IDC_NETWORKREMOCON_USE, ::IsDlgButtonChecked(hDlg,IDC_NETWORKREMOCON_USE)==BST_CHECKED? BST_UNCHECKED:BST_CHECKED); return TRUE; } return TRUE; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case PSN_APPLY: { int State; char szAddress[16]; unsigned int Port; TCHAR szChannelFile[MAX_PATH]; State=::IsDlgButtonChecked(hDlg,IDC_NETWORKREMOCON_USE); ::GetDlgItemTextA(hDlg,IDC_NETWORKREMOCON_ADDRESS,szAddress, lengthof(szAddress)); Port=::GetDlgItemInt(hDlg,IDC_NETWORKREMOCON_PORT,NULL,FALSE); ::GetDlgItemText(hDlg,IDC_NETWORKREMOCON_CHANNELFILE, szChannelFile,lengthof(szChannelFile)); bool fUpdate=false; if (State!=BST_INDETERMINATE && (State==BST_CHECKED)!=(m_fUseNetworkRemocon || m_fTempEnable)) { m_fUseNetworkRemocon=State==BST_CHECKED; m_fTempEnable=false; fUpdate=true; } else if (m_fUseNetworkRemocon || m_fTempEnable) { if (m_Port!=Port || ::lstrcmpiA(m_szAddress,szAddress)!=0 || ::lstrcmpi(m_szChannelFileName,szChannelFile)!=0) { fUpdate=true; } } m_Port=Port; ::lstrcpyA(m_szAddress,szAddress); ::lstrcpy(m_szChannelFileName,szChannelFile); if (fUpdate) SetUpdateFlag(UPDATE_NETWORKREMOCON); m_fChanged=true; } return TRUE; } break; } return FALSE; }
23.462295
92
0.712759
mark10als
e424c4bbe7e1da7cd4fc349e2cca6f7099b9ad70
11,594
cpp
C++
src/proposal.cpp
OpenIKEv2/libopenikev2
9d91225e5917cbc9afc83db37dfe4905c5501d01
[ "Apache-2.0" ]
7
2017-02-27T17:52:26.000Z
2021-12-15T06:03:26.000Z
src/proposal.cpp
David-WL/libopenikev2
9d91225e5917cbc9afc83db37dfe4905c5501d01
[ "Apache-2.0" ]
5
2017-03-02T20:16:41.000Z
2017-11-04T08:23:13.000Z
src/proposal.cpp
David-WL/libopenikev2
9d91225e5917cbc9afc83db37dfe4905c5501d01
[ "Apache-2.0" ]
3
2017-04-12T00:25:25.000Z
2021-09-23T09:13:27.000Z
/*************************************************************************** * Copyright (C) 2005 by * * Pedro J. Fernandez Ruiz [email protected] * * Alejandro Perez Mendez [email protected] * * * * This software may be modified and distributed under the terms * * of the Apache license. See the LICENSE file for details. * ***************************************************************************/ #include "proposal.h" #include "utils.h" #include "exception.h" #include <string.h> namespace openikev2 { Proposal::Proposal( Enums::PROTOCOL_ID protocol_id ) { // assigns the proposal number this->proposal_number = 0; // Assigns protocol id this->protocol_id = protocol_id; // The SPI value is 0-length until it was assigned using setIkeSpi() or setIpsecSpi() if ( protocol_id == Enums::PROTO_IKE ) { this->spi.reset ( new ByteArray( 8 ) ); } else if ( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP ) { this->spi.reset ( new ByteArray( 4 ) ); } else assert( 0 ); } Proposal::Proposal( Enums::PROTOCOL_ID protocol_id, auto_ptr<ByteArray> spi ) { // Checks if spi size agrees with protocol id if ( protocol_id == Enums::PROTO_IKE && spi->size() != 8 && spi->size() != 0 ) throw ParsingException( "Proposal and SPI size don't match." ); else if ( ( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP ) && spi->size() != 4 ) throw ParsingException( "Proposal and SPI size don't match." ); this->protocol_id = protocol_id; this->spi = spi; this->proposal_number = 0; } auto_ptr<Proposal> Proposal::parse( ByteBuffer& byte_buffer ) { // Pointer to the begin of the Proposal uint8_t * proposal_begin = byte_buffer.getReadPosition() - 2; // reads the proposal length uint32_t proposal_length = byte_buffer.readInt16(); // Size must be at least size of fixed header if ( proposal_length < 8 ) throw ParsingException( "Proposal length cannot be < 8 bytes. len=[" + intToString( proposal_length ) + "]" ); // reads the proposal number uint8_t proposal_number = byte_buffer.readInt8(); if ( proposal_number == 0 ) throw ParsingException( "Proposal number cannot be 0" ); // Reads protocol id from buffer Enums::PROTOCOL_ID protocol_id = ( Enums::PROTOCOL_ID ) byte_buffer.readInt8(); // Reads spi size from buffer uint8_t spi_size = byte_buffer.readInt8(); // Reads transform count uint8_t transform_count = byte_buffer.readInt8(); // Reads spi value and stores it in the internal variable auto_ptr<ByteArray> spi = byte_buffer.readByteArray( spi_size ); // Creates the Proposal auto_ptr<Proposal> result ( new Proposal( protocol_id, spi ) ); result->proposal_number = proposal_number; // Reads transforms from buffer for ( int i = 0; i < transform_count; i++ ) { // reads has more transforms byte uint8_t has_more_transforms = byte_buffer.readInt8(); // Checks if this is the last transform if ( i == transform_count - 1 && has_more_transforms ) throw ParsingException( "Transform count field is lower than real transform number." ); if ( i < transform_count - 1 && !has_more_transforms ) throw ParsingException( "Transform count field is higher than real transform number." ); // reads RESERVED byte byte_buffer.readInt8(); // Reads Transform and adds to the collection (without fixed header of size 4) auto_ptr<Transform> transform = Transform::parse( byte_buffer ); // adds this transform the the transform collection result->addTransform( transform ); } // checks the size if ( byte_buffer.getReadPosition() != proposal_begin + proposal_length ) throw ParsingException( "Proposal has different length than indicated in the header" ); return result; } Proposal::~Proposal() {} auto_ptr<Proposal> Proposal::clone() const { auto_ptr<Proposal> result ( new Proposal( this->protocol_id ) ); result->spi = this->spi->clone(); for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) result->addTransform( ( *it ) ->clone() ); return result; } void Proposal::addTransform( auto_ptr<Transform> transform ) { assert ( transform.get() != NULL ); switch ( this->protocol_id ) { case Enums::PROTO_AH: if ( transform->type == Enums::ENCR ) throw ProposalException( "AH protocol has ENCR transform" ); if ( transform->type == Enums::PRF ) throw ProposalException( "AH protocol has PRF transform" ); break; case Enums::PROTO_ESP: if ( transform->type == Enums::PRF ) throw ProposalException( "ESP protocol has PRF transform" ); break; case Enums::PROTO_IKE: if ( transform->type == Enums::ESN ) throw ProposalException( "IKE protocol has ESN transform" ); break; } this->transforms->push_back( transform.release() ); } void Proposal::getBinaryRepresentation( ByteBuffer& byte_buffer ) const { // ASSERT: transform count must fits in uint8_t (octet) assert( this->transforms->size() > 0 && this->transforms->size() < 256 ); // pointer to the beginning of the proposal uint8_t* proposal_begin = byte_buffer.getWritePosition(); // writes a dummy value for the proposal length byte_buffer.writeInt16( 0 ); // writes the proposal number byte_buffer.writeInt8( this->proposal_number ); // Writes protocol id byte_buffer.writeInt8( this->protocol_id ); // Writes spi size byte_buffer.writeInt8( this->spi->size() ); // Writes transform count byte_buffer.writeInt8( this->transforms->size() ); // Writes spi value byte_buffer.writeByteArray( *this->spi ); // Writes each transform in the collection for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) { // Writes last transform flags (0=last, 3=more) if ( *it == this->transforms->back() ) byte_buffer.writeInt8( 0 ); else byte_buffer.writeInt8( 3 ); // Fills RESERVED field with 0s byte_buffer.writeInt8( 0 ); // Writes transform ( *it ) ->getBinaryRepresentation( byte_buffer ); } // pointer to the end of the proposal uint8_t* proposal_end = byte_buffer.getWritePosition(); // writes the real proposal length value byte_buffer.setWritePosition( proposal_begin ); byte_buffer.writeInt16( proposal_end - proposal_begin + 2 ); byte_buffer.setWritePosition( proposal_end ); } Transform * Proposal::getFirstTransformByType( Enums::TRANSFORM_TYPE type ) const { for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) if ( ( *it ) ->type == type ) return ( *it ); return NULL; } string Proposal::toStringTab( uint8_t tabs ) const { ostringstream oss; oss << Printable::generateTabs( tabs ) << "<PROPOSAL> {\n"; oss << Printable::generateTabs( tabs + 1 ) << "proposal_number=" << ( int ) proposal_number << "\n"; oss << Printable::generateTabs( tabs + 1 ) << "protocol_id=" << Enums::PROTOCOL_ID_STR( this->protocol_id ) << "\n"; oss << Printable::generateTabs( tabs + 1 ) << "spi=" << this->spi->toStringTab( tabs + 1 ) + "\n"; for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) oss << ( *it ) ->toStringTab( tabs + 1 ); oss << Printable::generateTabs( tabs ) << "}\n"; return oss.str(); } void Proposal::deleteTransformsByType( Enums::TRANSFORM_TYPE type ) { vector<Transform*>::iterator it = this->transforms->begin(); while ( it != this->transforms->end() ) { if ( ( *it ) ->type == type ) { delete ( *it ); it = this->transforms->erase( it ); } else { it++; } } } bool Proposal::hasTransform( const Transform & transform ) const { for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) { Transform* current_transform = ( *it ); if ( *current_transform == transform ) return true; } return false; } auto_ptr< Proposal > Proposal::intersection( const Proposal & proposal1, const Proposal & proposal2 ) { assert ( proposal1.protocol_id == proposal2.protocol_id ); auto_ptr<Proposal> result ( new Proposal( proposal1.protocol_id ) ); result->spi = proposal1.spi->clone(); // for all the transform in the proposal1 for ( vector<Transform*>::const_iterator it = proposal1.transforms->begin(); it != proposal1.transforms->end(); it++ ) { Transform* current_transform = ( *it ); // if the proposal2 has the same transform type and id, then adds it to the result if ( proposal2.hasTransform( *current_transform ) ) result->addTransform( current_transform->clone() ); } return result; } bool Proposal::hasTheSameTransformTypes( const Proposal & other ) const { for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) { Transform* current_transform = ( *it ); if ( other.getFirstTransformByType( current_transform->type ) == NULL ) return false; } return true; } void Proposal::setIkeSpi( uint64_t spi ) { assert ( protocol_id == Enums::PROTO_IKE ); this->spi.reset ( new ByteArray( &spi, 8 ) ); } void Proposal::setIpsecSpi( uint32_t spi ) { assert( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP ); auto_ptr<ByteBuffer> spi_value ( new ByteBuffer( 4 ) ); spi_value->writeInt32( spi ); this->spi = spi_value; } uint64_t Proposal::getIkeSpi( ) { assert ( protocol_id == Enums::PROTO_IKE ); assert ( this->spi->size() == 8 ); uint64_t spi = 0; memcpy( &spi, this->spi->getRawPointer(), 8 ); return spi; } uint32_t Proposal::getIpsecSpi( ) { assert( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP ); assert ( this->spi->size() == 4 ); uint32_t spi = 0; ByteBuffer spi_value ( *this->spi ); return spi_value.readInt32(); } }
36.574132
128
0.568829
OpenIKEv2
e4255dbc4c4cc6663e965218e9e9126f37c2c60c
13,319
cpp
C++
PongCommon/PlayerSlot.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
16
2018-12-22T02:09:05.000Z
2022-03-09T20:38:59.000Z
PongCommon/PlayerSlot.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
46
2018-04-02T11:06:01.000Z
2019-12-14T11:16:04.000Z
PongCommon/PlayerSlot.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
14
2018-04-09T02:26:15.000Z
2021-09-11T03:12:15.000Z
// ------------------------------------ // #ifndef PONG_PLAYERSLOT #include "PlayerSlot.h" #endif #include "Iterators/StringIterator.h" #include "Networking/NetworkServerInterface.h" #include "Utility/ComplainOnce.h" #include "Entities/Components.h" #include "CommonPong.h" #ifdef PONG_VERSION #include "PongGame.h" #include "PongNetHandler.h" #endif //PONG_VERSION #include "GameInputController.h" using namespace Pong; using namespace Leviathan; // ------------------------------------ // Pong::PlayerSlot::PlayerSlot(int slotnumber, PlayerList* owner) : Slot(slotnumber), PlayerType(PLAYERTYPE_CLOSED), PlayerNumber(0), ControlType(PLAYERCONTROLS_NONE), ControlIdentifier(0), PlayerControllerID(0), Colour(Float4::GetColourWhite()), Score(0), MoveState(0), PaddleObject(0), GoalAreaObject(0), TrackObject(0), SplitSlot(nullptr), ParentSlot(nullptr), InputObj(nullptr), SlotsPlayer(NULL), PlayerID(-1), NetworkedInputID(-1), Parent(owner) { } Pong::PlayerSlot::~PlayerSlot(){ _ResetNetworkInput(); SAFE_DELETE(SplitSlot); } // ------------------------------------ // void Pong::PlayerSlot::Init(PLAYERTYPE type /*= PLAYERTYPE_EMPTY*/, int PlayerNumber /*= 0*/, PLAYERCONTROLS controltype /*= PLAYERCONTROLS_NONE*/, int ctrlidentifier /*= 0*/, int playercontrollerid /*= -1*/, const Float4 &playercolour /*= Float4::GetColourWhite()*/) { PlayerType = type; PlayerNumber = PlayerNumber; ControlType = controltype; ControlIdentifier = ctrlidentifier; Colour = playercolour; PlayerControllerID = playercontrollerid; } // ------------------------------------ // void Pong::PlayerSlot::SetPlayer(PLAYERTYPE type, int identifier){ PlayerType = type; PlayerNumber = identifier; } Pong::PLAYERTYPE Pong::PlayerSlot::GetPlayerType(){ return PlayerType; } int Pong::PlayerSlot::GetPlayerNumber(){ return PlayerNumber; } // ------------------------------------ // void Pong::PlayerSlot::SetControls(PLAYERCONTROLS type, int identifier){ ControlType = type; ControlIdentifier = identifier; } Pong::PLAYERCONTROLS Pong::PlayerSlot::GetControlType(){ return ControlType; } int Pong::PlayerSlot::GetControlIdentifier(){ return ControlIdentifier; } // ------------------------------------ // int Pong::PlayerSlot::GetSlotNumber(){ return Slot; } // ------------------------------------ // int Pong::PlayerSlot::GetSplitCount(){ return SplitSlot != NULL ? 1+SplitSlot->GetSplitCount(): 0; } void Pong::PlayerSlot::PassInputAction(CONTROLKEYACTION actiontoperform, bool active){ GUARD_LOCK(); // if this is player 0 or 3 flip inputs // if(Slot == 0 || Slot == 2){ switch(actiontoperform){ case CONTROLKEYACTION_LEFT: actiontoperform = CONTROLKEYACTION_POWERUPUP; break; case CONTROLKEYACTION_POWERUPDOWN: actiontoperform = CONTROLKEYACTION_RIGHT; break; case CONTROLKEYACTION_RIGHT: actiontoperform = CONTROLKEYACTION_POWERUPDOWN; break; case CONTROLKEYACTION_POWERUPUP: actiontoperform = CONTROLKEYACTION_LEFT; break; } } // set control state // if(active){ if(actiontoperform == CONTROLKEYACTION_LEFT){ MoveState = 1; } else if(actiontoperform == CONTROLKEYACTION_RIGHT){ MoveState = -1; } } else { if(actiontoperform == CONTROLKEYACTION_LEFT && MoveState == 1){ MoveState = 0; } else if(actiontoperform == CONTROLKEYACTION_RIGHT && MoveState == -1){ MoveState = 0; } } try{ DEBUG_BREAK; //auto& track = BasePongParts::Get()->GetGameWorld()->GetComponent<TrackController>( // TrackObject); //// Set the track speed based on move direction // //track.ChangeSpeed = MoveState*INPUT_TRACK_ADVANCESPEED; //track.Marked = true; } catch(const NotFound&){ Logger::Get()->Warning("PlayerSlot has a TrackObject that has no TrackController " "component, object: "+Convert::ToString(TrackObject)); } } void Pong::PlayerSlot::InputDisabled(){ // Reset control state // MoveState = 0; if(TrackObject == 0) return; // Set apply force to zero // try{ DEBUG_BREAK; //auto& track = BasePongParts::Get()->GetGameWorld()->GetComponent<TrackController>( // TrackObject); //// Set the track speed based on move direction // //track.ChangeSpeed = 0; //track.Marked = true; } catch(const NotFound&){ } } int Pong::PlayerSlot::GetScore(){ return Score; } // ------------------------------------ // void Pong::PlayerSlot::AddEmptySubSlot(){ SplitSlot = new PlayerSlot(this->Slot, Parent); // Set this as the parent // SplitSlot->ParentSlot = this; } bool Pong::PlayerSlot::IsVerticalSlot(){ return Slot == 0 || Slot == 2; } float Pong::PlayerSlot::GetTrackProgress(){ try{ DEBUG_BREAK; //auto& track = BasePongParts::Get()->GetGameWorld()->GetComponent<TrackController>( // TrackObject); //return track.NodeProgress; } catch(const NotFound&){ } return 0.f; } bool Pong::PlayerSlot::DoesPlayerNumberMatchThisOrParent(int number){ if(number == PlayerNumber) return true; // Recurse to parent, if one exists // if(ParentSlot) return ParentSlot->DoesPlayerNumberMatchThisOrParent(number); return false; } // ------------------------------------ // void Pong::PlayerSlot::AddDataToPacket(sf::Packet &packet){ GUARD_LOCK(); // Write all our data to the packet // packet << Slot << (int)PlayerType << PlayerNumber << NetworkedInputID << ControlIdentifier << (int)ControlType << PlayerControllerID << Colour; packet << PaddleObject << GoalAreaObject << TrackObject; packet << PlayerID << Score << (bool)(SplitSlot != NULL); if(SplitSlot){ // Add our sub slot data // SplitSlot->AddDataToPacket(packet); } } void Pong::PlayerSlot::UpdateDataFromPacket(sf::Packet &packet, Lock &listlock){ GUARD_LOCK(); int tmpival; // Get our data from it // packet >> Slot >> tmpival; PlayerType = static_cast<PLAYERTYPE>(tmpival); packet >> PlayerNumber >> NetworkedInputID >> ControlIdentifier >> tmpival; ControlType = static_cast<PLAYERCONTROLS>(tmpival); packet >> PlayerControllerID; packet >> Colour; packet >> PaddleObject >> GoalAreaObject >> TrackObject; packet >> PlayerID >> Score; bool wantedsplit; packet >> wantedsplit; if(!packet) throw InvalidArgument("packet format for PlayerSlot is invalid"); // Check do we need to change split // if(wantedsplit && !SplitSlot){ AddEmptySubSlot(); } else if(!wantedsplit && SplitSlot){ SAFE_DELETE(SplitSlot); } // Update split value // if(wantedsplit){ SplitSlot->UpdateDataFromPacket(packet, listlock); } #ifdef PONG_VERSION // Update everything related to input // if(PlayerID == PongGame::Get()->GetInterface().GetOurID()){ // Create new one only if there isn't one already created // if(!InputObj){ // Skip if it is an AI slot // if(ControlType != PLAYERCONTROLS_AI){ Logger::Get()->Info("Creating input for our player id, NetworkedInputID: "+Convert::ToString( NetworkedInputID)); // Hook a networked input receiver to the server // DEBUG_BREAK; //PongGame::Get()->GetInputController()->RegisterNewLocalGlobalReflectingInputSource( // PongGame::GetInputFactory()->CreateNewInstanceForLocalStart(guard, // NetworkedInputID, true)); } } else { if(ControlType == PLAYERCONTROLS_AI){ // Destroy out input if there is an AI // _ResetNetworkInput(guard); } else { // Update the existing one // InputObj->UpdateSettings(ControlType); Logger::Get()->Info("Updated our control type: "+Convert::ToString(ControlType)); } } } #endif //PONG_VERSION } int Pong::PlayerSlot::GetPlayerControllerID(){ return PlayerControllerID; } void Pong::PlayerSlot::SlotJoinPlayer(Leviathan::ConnectedPlayer* ply, int uniqnumber){ SlotsPlayer = ply; PlayerID = SlotsPlayer->GetID(); PlayerNumber = uniqnumber; PlayerType = PLAYERTYPE_HUMAN; } void Pong::PlayerSlot::AddServerAI(int uniquenumber, int aitype /*= 2*/){ // TODO: properly kick // SlotsPlayer = NULL; PlayerNumber = uniquenumber; PlayerType = PLAYERTYPE_COMPUTER; ControlType = PLAYERCONTROLS_AI; ControlIdentifier = aitype; } void Pong::PlayerSlot::SlotLeavePlayer(){ SlotsPlayer = NULL; ControlType = PLAYERCONTROLS_NONE; PlayerType = PLAYERTYPE_EMPTY; } void Pong::PlayerSlot::SetInputThatSendsControls(Lock &guard, PongNInputter* input){ if(InputObj && input != InputObj){ Logger::Get()->Info("PlayerSlot: destroying old networked input"); _ResetNetworkInput(guard); } InputObj = input; } void PlayerSlot::InputDeleted(Lock &guard){ InputObj = nullptr; } void Pong::PlayerSlot::_ResetNetworkInput(Lock &guard){ if(InputObj){ InputObj->StopSendingInput(this); } InputObj = NULL; } // ------------------ PlayerList ------------------ // Pong::PlayerList::PlayerList(std::function<void (PlayerList*)> callback, size_t playercount /*= 4*/) : SyncedResource("PlayerList"), GamePlayers(4), CallbackFunc(callback) { // Fill default player data // for(int i = 0; i < 4; i++){ GamePlayers[i] = new PlayerSlot(i, this); } } Pong::PlayerList::~PlayerList(){ SAFE_DELETE_VECTOR(GamePlayers); } // ------------------------------------ // void Pong::PlayerList::UpdateCustomDataFromPacket(Lock &guard, sf::Packet &packet){ sf::Int32 vecsize; if(!(packet >> vecsize)){ throw InvalidArgument("packet format for PlayerSlot is invalid"); } if(vecsize != static_cast<int>(GamePlayers.size())){ // We need to resize // int difference = vecsize-GamePlayers.size(); if(difference < 0){ // Loop and delete items // int deleted = 0; while(deleted < difference){ SAFE_DELETE(GamePlayers[GamePlayers.size()-1]); GamePlayers.pop_back(); deleted++; } } else { // We need to add items // for(int i = 0; i < difference; i++){ GamePlayers.push_back(new PlayerSlot(GamePlayers.size(), this)); } } } // Update the data // auto end = GamePlayers.end(); for(auto iter = GamePlayers.begin(); iter != end; ++iter){ (*iter)->UpdateDataFromPacket(packet, guard); } } void Pong::PlayerList::SerializeCustomDataToPacket(Lock &guard, sf::Packet &packet){ // First put the size // packet << static_cast<sf::Int32>(GamePlayers.size()); // Loop through them and add them // for(auto iter = GamePlayers.begin(); iter != GamePlayers.end(); ++iter){ // Serialize it // (*iter)->AddDataToPacket(packet); } } void Pong::PlayerList::OnValueUpdated(Lock &guard){ // Call our callback // CallbackFunc(this); } PlayerSlot* Pong::PlayerList::GetSlot(size_t index){ if(index >= GamePlayers.size()) throw InvalidArgument("player index is out of range"); return GamePlayers[index]; } // ------------------------------------ // void Pong::PlayerList::ReportPlayerInfoToLog() const{ GUARD_LOCK(); Logger::Get()->Write("PlayerList:::: size "+Convert::ToString(GamePlayers.size())); for(auto iter = GamePlayers.begin(); iter != GamePlayers.end(); ++iter){ (*iter)->WriteInfoToLog(1); } } void Pong::PlayerSlot::WriteInfoToLog(int depth /*= 0*/) const{ string prefix; if(depth >= 0) prefix.reserve(depth*4); for(int i = 0; i < depth; i++) prefix += " "; Logger::Get()->Write(prefix+"----PlayerSlot "+Convert::ToString(Slot)); #define PUT_FIELD(x) Logger::Get()->Write(prefix+ #x +" "+Convert::ToString(x)); PUT_FIELD(PlayerType); PUT_FIELD(PlayerNumber); PUT_FIELD(ControlType); PUT_FIELD(ControlIdentifier); PUT_FIELD(PlayerControllerID); PUT_FIELD(Colour); PUT_FIELD(Score); PUT_FIELD(MoveState); Logger::Get()->Write(prefix+"PaddleObject "+Convert::ToString(PaddleObject)); Logger::Get()->Write(prefix + "GoalAreaObject "+Convert::ToString(GoalAreaObject)); Logger::Get()->Write(prefix+"TrackObject "+Convert::ToString(TrackObject)); Logger::Get()->Write(prefix+"InputObj "+Convert::ToString(InputObj)); Logger::Get()->Write(prefix+"SlotsPlayer "+Convert::ToString(SlotsPlayer)); PUT_FIELD(PlayerID); PUT_FIELD(NetworkedInputID); if(SplitSlot){ Logger::Get()->Write(prefix+"====Split:"); SplitSlot->WriteInfoToLog(depth+1); } Logger::Get()->Write(prefix+"----"); }
26.426587
118
0.611908
Higami69
e4293959199c064d4c22a04c770f3ba6c842728f
654
hh
C++
seed/include/ActionInitialization.hh
MeighenBergerS/fennel
c2e4640ef34e0ed88c0c50e5dde36c7d9fa39db6
[ "MIT" ]
null
null
null
seed/include/ActionInitialization.hh
MeighenBergerS/fennel
c2e4640ef34e0ed88c0c50e5dde36c7d9fa39db6
[ "MIT" ]
null
null
null
seed/include/ActionInitialization.hh
MeighenBergerS/fennel
c2e4640ef34e0ed88c0c50e5dde36c7d9fa39db6
[ "MIT" ]
null
null
null
/// \file ActionInitialization.hh /// \brief Definition of the ActionInitialization class #ifndef ActionInitialization_h #define ActionInitialization_h 1 #include "G4VUserActionInitialization.hh" class DetectorConstruction; /// Action initialization class. class ActionInitialization : public G4VUserActionInitialization { public: ActionInitialization(DetectorConstruction*); virtual ~ActionInitialization(); virtual void BuildForMaster() const; virtual void Build() const; private: DetectorConstruction* fDetConstruction; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif
20.4375
80
0.746177
MeighenBergerS
e42af3e405ca379249fb4f38ca9ca44c78dbe1e5
7,373
cxx
C++
GPU/GPUTracking/Base/opencl2/GPUReconstructionOCL2.cxx
chengtt0406/AliRoot
c1d89b133b433f608b2373112d3608d8cec26095
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
GPU/GPUTracking/Base/opencl2/GPUReconstructionOCL2.cxx
chengtt0406/AliRoot
c1d89b133b433f608b2373112d3608d8cec26095
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
GPU/GPUTracking/Base/opencl2/GPUReconstructionOCL2.cxx
chengtt0406/AliRoot
c1d89b133b433f608b2373112d3608d8cec26095
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <[email protected]> *\ //* for The ALICE HLT Project. *\ //* *\ //* 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. *\ //************************************************************************** /// \file GPUReconstructionOCL2.cxx /// \author David Rohr #define GPUCA_GPUTYPE_OPENCL #define __OPENCL_HOST__ #include "GPUReconstructionOCL2.h" #include "GPUReconstructionOCL2Internals.h" #include "GPUReconstructionIncludes.h" using namespace GPUCA_NAMESPACE::gpu; #include <cstring> #include <unistd.h> #include <typeinfo> #include <cstdlib> #ifdef OPENCL2_ENABLED_AMD extern "C" char _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd[]; extern "C" unsigned int _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd_size; #endif #ifdef OPENCL2_ENABLED_SPIRV extern "C" char _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv[]; extern "C" unsigned int _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv_size; #endif extern "C" char _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src[]; extern "C" unsigned int _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src_size; GPUReconstruction* GPUReconstruction_Create_OCL2(const GPUSettingsDeviceBackend& cfg) { return new GPUReconstructionOCL2(cfg); } GPUReconstructionOCL2Backend::GPUReconstructionOCL2Backend(const GPUSettingsDeviceBackend& cfg) : GPUReconstructionOCL(cfg) { } template <class T, int I, typename... Args> int GPUReconstructionOCL2Backend::runKernelBackend(krnlSetup& _xyz, const Args&... args) { cl_kernel k = _xyz.y.num > 1 ? getKernelObject<cl_kernel, T, I, true>() : getKernelObject<cl_kernel, T, I, false>(); return runKernelBackendCommon(_xyz, k, args...); } template <class S, class T, int I, bool MULTI> S& GPUReconstructionOCL2Backend::getKernelObject() { static unsigned int krnl = FindKernel<T, I>(MULTI ? 2 : 1); return mInternals->kernels[krnl].first; } int GPUReconstructionOCL2Backend::GetOCLPrograms() { char platform_version[64] = {}, platform_vendor[64] = {}; clGetPlatformInfo(mInternals->platform, CL_PLATFORM_VERSION, sizeof(platform_version), platform_version, nullptr); clGetPlatformInfo(mInternals->platform, CL_PLATFORM_VENDOR, sizeof(platform_vendor), platform_vendor, nullptr); float ver = 0; sscanf(platform_version, "OpenCL %f", &ver); cl_int return_status[1] = {CL_SUCCESS}; cl_int ocl_error; #ifdef OPENCL2_ENABLED_AMD if (strcmp(platform_vendor, "Advanced Micro Devices, Inc.") == 0) { size_t program_sizes[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd_size}; char* program_binaries[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd}; mInternals->program = clCreateProgramWithBinary(mInternals->context, 1, &mInternals->device, program_sizes, (const unsigned char**)program_binaries, return_status, &ocl_error); } else #endif #ifdef OPENCL2_ENABLED_SPIRV // clang-format off if (ver >= 2.2) { mInternals->program = clCreateProgramWithIL(mInternals->context, _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv, _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv_size, &ocl_error); } else #endif // clang-format on { size_t program_sizes[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src_size}; char* programs_sources[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src}; mInternals->program = clCreateProgramWithSource(mInternals->context, (cl_uint)1, (const char**)&programs_sources, program_sizes, &ocl_error); } if (GPUFailedMsgI(ocl_error)) { GPUError("Error creating OpenCL program from binary"); return 1; } if (GPUFailedMsgI(return_status[0])) { GPUError("Error creating OpenCL program from binary (device status)"); return 1; } if (GPUFailedMsgI(clBuildProgram(mInternals->program, 1, &mInternals->device, GPUCA_M_STR(OCL_FLAGS), nullptr, nullptr))) { cl_build_status status; if (GPUFailedMsgI(clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_STATUS, sizeof(status), &status, nullptr)) == 0 && status == CL_BUILD_ERROR) { size_t log_size; clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG, 0, nullptr, &log_size); std::unique_ptr<char[]> build_log(new char[log_size + 1]); clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG, log_size, build_log.get(), nullptr); build_log[log_size] = 0; GPUError("Build Log:\n\n%s\n", build_log.get()); } return 1; } #define GPUCA_KRNL(x_class, x_attributes, x_arguments, x_forward) \ GPUCA_KRNL_WRAP(GPUCA_KRNL_LOAD_, x_class, x_attributes, x_arguments, x_forward) #define GPUCA_KRNL_LOAD_single(x_class, x_attributes, x_arguments, x_forward) \ if (AddKernel<GPUCA_M_KRNL_TEMPLATE(x_class)>(false)) { \ return 1; \ } #define GPUCA_KRNL_LOAD_multi(x_class, x_attributes, x_arguments, x_forward) \ if (AddKernel<GPUCA_M_KRNL_TEMPLATE(x_class)>(true)) { \ return 1; \ } #include "GPUReconstructionKernels.h" #undef GPUCA_KRNL #undef GPUCA_KRNL_LOAD_single #undef GPUCA_KRNL_LOAD_multi return 0; } bool GPUReconstructionOCL2Backend::CheckPlatform(unsigned int i) { char platform_version[64] = {}, platform_vendor[64] = {}; clGetPlatformInfo(mInternals->platforms[i], CL_PLATFORM_VERSION, sizeof(platform_version), platform_version, nullptr); clGetPlatformInfo(mInternals->platforms[i], CL_PLATFORM_VENDOR, sizeof(platform_vendor), platform_vendor, nullptr); float ver1 = 0; sscanf(platform_version, "OpenCL %f", &ver1); if (ver1 >= 2.2f) { if (mProcessingSettings.debugLevel >= 2) { GPUInfo("OpenCL 2.2 capable platform found"); } return true; } if (strcmp(platform_vendor, "Advanced Micro Devices, Inc.") == 0 && ver1 >= 2.0f) { float ver2 = 0; const char* pos = strchr(platform_version, '('); if (pos) { sscanf(pos, "(%f)", &ver2); } if ((ver1 >= 2.f && ver2 >= 2000.f) || ver1 >= 2.1f) { if (mProcessingSettings.debugLevel >= 2) { GPUInfo("AMD ROCm OpenCL Platform found"); } return true; } } return false; }
44.957317
224
0.696731
chengtt0406
e42e39811d115bc810ffd4b7f6a704411adc14c2
4,798
cpp
C++
Practice/2019.1.18/BZOJ3159.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2019.1.18/BZOJ3159.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2019.1.18/BZOJ3159.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define Max(x,y) x=max(x,y) #define Min(x,y) x=min(x,y) #define ll long long const int maxN=50500; const int maxM=maxN<<1; class Treap { public: int ls,rs,sz; ll sum,mx,mn,pls,rev,key; }; int n,m,root; int edgecnt=0,Head[maxN],Next[maxM],V[maxM],dep[maxN]; int Sz[maxN],Hs[maxN],Fa[maxN],Top[maxN],Rt[maxN],nodecnt; Treap T[maxN]; void Add_Edge(int u,int v); void dfs1(int u,int fa); void dfs2(int u,int top); void Build(int &x,int l,int r); void Plus(int x,int k); void Reverse(int x); void PushDown(int x); void Update(int x); void Split(int u,int k,int &x,int &y); int Merge(int u,int v); int Split(int x,int y); void Pushback(int rt,int x,int y); int main() { scanf("%d%d%d",&n,&m,&root); mem(Head,-1); for (int i=1; i<n; i++) { int u,v; scanf("%d%d",&u,&v); Add_Edge(u,v); Add_Edge(v,u); } dfs1(root,0); dfs2(root,root); while (m--) { char ipt[10]; int x,y; scanf("%s%d%d",ipt,&x,&y); int rt=Split(x,y); if (ipt[0]=='I'&&ipt[2]=='c') { int w; scanf("%d",&w); Plus(rt,w); } if (ipt[0]=='S') printf("%lld\n",T[rt].sum); if (ipt[0]=='M'&&ipt[1]=='a') printf("%lld\n",T[rt].mx); if (ipt[0]=='M'&&ipt[1]=='i') printf("%lld\n",T[rt].mn); if (ipt[0]=='I'&&ipt[2]=='v') Reverse(rt); Pushback(rt,x,y); } return 0; } void Add_Edge(int u,int v) { Next[++edgecnt]=Head[u]; Head[u]=edgecnt; V[edgecnt]=v; return; } void dfs1(int u,int fa) { dep[u]=dep[fa]+1; Sz[u]=1; Fa[u]=fa; for (int i=Head[u]; i!=-1; i=Next[i]) if (V[i]!=fa) { dfs1(V[i],u); Sz[u]+=Sz[V[i]]; if (Sz[V[i]]>Sz[Hs[u]]) Hs[u]=V[i]; } return; } void dfs2(int u,int top) { Top[u]=top; if (Hs[u]==0) { Build(Rt[top],dep[top],dep[u]); return; } dfs2(Hs[u],top); for (int i=Head[u]; i!=-1; i=Next[i]) if (V[i]!=Fa[u]&&V[i]!=Hs[u]) dfs2(V[i],V[i]); return; } void Build(int &x,int l,int r) { x=++nodecnt; T[x].sz=r-l+1; int mid=(l+r)>>1; if (l<mid) Build(T[x].ls,l,mid-1); if (mid<r) Build(T[x].rs,mid+1,r); return; } void Plus(int x,int k) { T[x].pls+=k; T[x].sum+=k*T[x].sz; T[x].mn+=k; T[x].mx+=k; T[x].key+=k; return; } void Reverse(int x) { T[x].rev^=1; swap(T[x].ls,T[x].rs); return; } void PushDown(int x) { if (T[x].rev) { if (T[x].ls) Reverse(T[x].ls); if (T[x].rs) Reverse(T[x].rs); T[x].rev=0; } if (T[x].pls) { if (T[x].ls) Plus(T[x].ls,T[x].pls); if (T[x].rs) Plus(T[x].rs,T[x].pls); T[x].pls=0; } return; } void Update(int x) { T[x].sz=T[T[x].ls].sz+T[T[x].rs].sz+1; T[x].sum=T[T[x].ls].sum+T[T[x].rs].sum+T[x].key; T[x].mn=T[x].mx=T[x].key; if (T[x].ls) Min(T[x].mn,T[T[x].ls].mn),Max(T[x].mx,T[T[x].ls].mx); if (T[x].rs) Min(T[x].mn,T[T[x].rs].mn),Max(T[x].mx,T[T[x].rs].mx); return; } void Split(int u,int k,int &x,int &y) { if (u==0) { x=y=0; return; } PushDown(u); if (T[T[u].ls].sz>=k) y=u,Split(T[u].ls,k,x,T[y].ls),Update(y); else x=u,Split(T[u].rs,k-T[T[u].ls].sz-1,T[u].rs,y),Update(x); return; } int Merge(int u,int v) { if (!u||!v) return u+v; PushDown(u); PushDown(v); if (rand()%(T[u].sz+T[v].sz)+1<=T[u].sz) { T[u].rs=Merge(T[u].rs,v); Update(u); return u; } else { T[v].ls=Merge(u,T[v].ls); Update(v); return v; } } int Split(int x,int y) { int rt1=0,rt2=0; while (Top[x]!=Top[y]) { if (dep[Top[x]]>=dep[Top[y]]) { int left,right; Split(Rt[Top[x]],dep[x]-dep[Top[x]]+1,left,right); Rt[Top[x]]=right; rt1=Merge(left,rt1); x=Fa[Top[x]]; } else { int left,right; Split(Rt[Top[y]],dep[y]-dep[Top[y]]+1,left,right); Rt[Top[y]]=right; rt2=Merge(left,rt2); y=Fa[Top[y]]; } } if (dep[x]<=dep[y]) { int a,b,c; Split(Rt[Top[x]],dep[y]-dep[Top[x]]+1,a,c); Split(a,dep[x]-dep[Top[x]],a,b); Rt[Top[x]]=Merge(a,c); rt2=Merge(b,rt2); } else { int a,b,c; Split(Rt[Top[x]],dep[x]-dep[Top[x]]+1,a,c); Split(a,dep[y]-dep[Top[x]],a,b); Rt[Top[x]]=Merge(a,c); rt1=Merge(b,rt1); } if (rt1) Reverse(rt1); return Merge(rt1,rt2); } void Pushback(int rt,int x,int y) { while (Top[x]!=Top[y]) { if (dep[Top[x]]>=dep[Top[y]]) { int push; Split(rt,dep[x]-dep[Top[x]]+1,push,rt); Reverse(push); Rt[Top[x]]=Merge(push,Rt[Top[x]]); x=Fa[Top[x]]; } else { int push; Split(rt,T[rt].sz-(dep[y]-dep[Top[y]]+1),rt,push); Rt[Top[y]]=Merge(push,Rt[Top[y]]); y=Fa[Top[y]]; } } if (dep[x]<=dep[y]) { int a,b; Split(Rt[Top[x]],dep[x]-dep[Top[x]],a,b); Rt[Top[x]]=Merge(Merge(a,rt),b); } else { int a,b; Reverse(rt); Split(Rt[Top[x]],dep[y]-dep[Top[x]],a,b); Rt[Top[y]]=Merge(Merge(a,rt),b); } return; } /* 5 8 1 1 2 2 3 3 4 4 5 Sum 2 4 Increase 3 5 3 Minor 1 4 Sum 4 5 Invert 1 3 Major 1 2 Increase 1 5 2 Sum 1 5 //*/
18.964427
68
0.544185
SYCstudio
e42eb46eea87f0a320c6b9b590bce4e6b8df866f
757
hpp
C++
src/estd/memory.hpp
hvellyr/sairy
3b7b797c71384222d58b67bded24ee5b5cc6aa2a
[ "BSD-3-Clause" ]
null
null
null
src/estd/memory.hpp
hvellyr/sairy
3b7b797c71384222d58b67bded24ee5b5cc6aa2a
[ "BSD-3-Clause" ]
null
null
null
src/estd/memory.hpp
hvellyr/sairy
3b7b797c71384222d58b67bded24ee5b5cc6aa2a
[ "BSD-3-Clause" ]
1
2018-01-29T10:57:09.000Z
2018-01-29T10:57:09.000Z
// Copyright (c) 2020 Gregor Klinke #pragma once #include "config.hpp" #include "estd/type_traits.hpp" #include <memory> #include <type_traits> #include <utility> namespace eyestep { namespace estd { #if !defined(TEXTBOOK_HAVE_STD_MAKE_UNIQUE) template <class T, class... Args> auto make_unique(Args&&... args) -> enable_if_t<!std::is_array<T>::value, std::unique_ptr<T>> { return std::unique_ptr<T>{new T(std::forward<Args>(args)...)}; } template <class T> auto make_unique(std::size_t size) -> enable_if_t<std::is_array<T>::value, std::unique_ptr<T>> { return std::unique_ptr<T>{new typename std::remove_extent<T>::type[size]()}; } #else using std::make_unique; #endif } // namespace estd } // namespace eyestep
19.410256
80
0.681638
hvellyr
e433bad26c6094b8709f4fa172a436ad7efdce4d
7,978
cpp
C++
src/SysProcess.cpp
Yhgenomics/maraton-framework
9044321d8c252c635a197a5c32512cb0538688f1
[ "MIT" ]
4
2015-11-12T03:51:46.000Z
2015-11-13T03:29:04.000Z
src/SysProcess.cpp
Yhgenomics/maraton-framework
9044321d8c252c635a197a5c32512cb0538688f1
[ "MIT" ]
null
null
null
src/SysProcess.cpp
Yhgenomics/maraton-framework
9044321d8c252c635a197a5c32512cb0538688f1
[ "MIT" ]
null
null
null
#include "SysProcess.h" #include <thread> #include <string.h> #include <memory> #include <thread> #include "maraton.h" #ifdef _WIN32 #include <direct.h> #else #include <unistd.h> #endif SysProcess::~SysProcess() { if ( this->file_ != NULL ) { delete this->file_; this->file_ = NULL; } if ( this->args_ != NULL ) { delete this->args_; this->args_ = NULL; } if ( this->directory_ != NULL ) { delete this->directory_; this->directory_ = NULL; } } void SysProcess::desctroy( SysProcess ** process ) { if ( process != nullptr && *process != nullptr ) { delete *process; *process = nullptr; } } SysProcess * SysProcess::create( std::string file , std::string args , std::string directry , prceoss_callback_t on_finish ) { auto ret = new SysProcess( file , args , directry , on_finish ); return ret; } SysProcess * SysProcess::create( std::string file , std::string args , prceoss_callback_t on_finish ) { auto ret = new SysProcess( file , args , on_finish ); return ret; } SysProcess * SysProcess::create( std::string file , prceoss_callback_t on_finish ) { auto ret = new SysProcess( file , on_finish ); return ret; } void SysProcess::uv_process_exit_callback( uv_process_t * process , int64_t exit_status , int term_signal ) { SysProcess* instance = static_cast< SysProcess* >( process->data ); uv_close( ( uv_handle_t* )process , SysProcess::uv_process_close_callback ); instance->callback( instance , exit_status ); } void SysProcess::uv_process_close_callback( uv_handle_t * handle ) { SysProcess* instance = static_cast< SysProcess* >( handle->data ); SAFE_DELETE( instance ); } void SysProcess::uv_process_alloc_buffer( uv_handle_t * handle , size_t suggested_size , uv_buf_t * buf ) { *buf = uv_buf_init( ( char* )malloc( suggested_size ) , suggested_size ); } void SysProcess::uv_prcoess_read_stream( uv_stream_t * stream , ssize_t nread , const uv_buf_t * buf ) { SysProcess* inst = static_cast< SysProcess* > ( stream->data ); if ( nread < 0 ) { if ( nread == UV_EOF ) { // end of file uv_close( ( uv_handle_t * )&inst->pipe_ , NULL ); } return; } inst->std_out_ = std::string( buf->base , nread ); if ( buf->base ) delete buf->base; } SysProcess::SysProcess() { //uv_sem_init( &this->sem , 0 ); } SysProcess::SysProcess( std::string file, std::string args, std::string directry, prceoss_callback_t on_finish ) : SysProcess() { std::string newArgs = args; this->file_ = new char[this->STR_LENGTH]; this->args_ = new char[this->STR_LENGTH]; this->directory_ = new char[this->STR_LENGTH]; memset( this->file_, 0, this->STR_LENGTH ); memset( this->args_, 0, this->STR_LENGTH ); memset( this->directory_, 0, this->STR_LENGTH ); memcpy( this->file_, file.c_str() , file.length() ); memcpy( this->args_, newArgs.c_str(), newArgs.length() ); memcpy( this->directory_, directry.c_str(), directry.length() ); this->callback = on_finish; } SysProcess::SysProcess( std::string file, std::string args, prceoss_callback_t on_finish ) : SysProcess() { std::string newArgs = args; this->file_ = new char[this->STR_LENGTH]; this->args_ = new char[this->STR_LENGTH]; memset( this->file_, 0, this->STR_LENGTH ); memset( this->args_, 0, this->STR_LENGTH ); memcpy( this->file_, file.c_str(), file.length() ); memcpy( this->args_, newArgs.c_str(), newArgs.length() ); this->callback = on_finish; } SysProcess::SysProcess( std::string file, prceoss_callback_t on_finish ) : SysProcess() { this->file_ = new char[this->STR_LENGTH]; memset( this->file_, 0, this->STR_LENGTH ); memcpy( this->file_, file.c_str(), file.length() ); this->callback = on_finish; } void SysProcess::invoke() { int r; char** args = NULL; //if ( this->directory_ == nullptr ) //{ // char path[512] = { 0 }; // getcwd( path , 512 ); // int path_len = strlen( path ); // this->directory_ = new char[path_len + 1]; // memset( this->directory_ , 0 , path_len + 1 ); // memcpy( this->directory_ , path , strlen( path ) ); //} printf( "File:%s\r\n" , this->file_ ); if ( args_ == nullptr ) { //char path[512] = { 0 }; //getcwd( path , 512 ); //args = new char*[2]; //args[0] = ' '; //args[1] = NULL; //args[0] = new char[strlen( path ) + 1]; //memset( args[0] , 0 , strlen( path ) + 1 ); //memcpy( args[0] , path , strlen( path ) ); //args[1] = NULL; } else { args = new char*[64]; for ( size_t i = 0; i < 64; i++ ) { args[i] = new char[512]; memset( args[i] , 0 , 512 ); args[i][0] = ' '; } auto raw_args = this->args_; size_t len = strlen( this->args_ ); int start_pos = 0; #ifdef _WIN32 int row = 0; #else int row = 0; #endif int col = 0; bool has_dot = false; for ( int e = start_pos; e < len; e++ ) { if ( raw_args[e] == '\'') { if ( has_dot ) has_dot = false; else has_dot = true; } if ( raw_args[e] == ' ' && !has_dot) { printf( "Args:%s\r\n", args[row] ); col = 0; row++; args[row][col] = ' '; col = 1; } else { args[row][col] = raw_args[e]; col++; } } printf( "Args:%s\r\n" , args[row] ); args[row+1] = NULL; } auto loop = uv_default_loop(); this->pipe_ = { 0 }; r = uv_pipe_init( loop , &this->pipe_ , 0 ); this->pipe_.data = this; this->options.exit_cb = SysProcess::uv_process_exit_callback; this->options.file = this->file_; this->options.args = args; this->options.cwd = this->directory_; this->child_req.data = this; this->options.stdio_count = 3; uv_stdio_container_t child_stdio[3]; // ( uv_stdio_flags )( UV_CREATE_PIPE | UV_READABLE_PIPE ); child_stdio[0].flags = UV_IGNORE; child_stdio[1].flags = ( uv_stdio_flags )( UV_CREATE_PIPE | UV_WRITABLE_PIPE ); child_stdio[1].data.stream = ( uv_stream_t* )&this->pipe_; child_stdio[2].flags = UV_IGNORE; this->options.stdio = child_stdio; r = uv_spawn( loop , &this->child_req , &this->options ); if ( r != 0 ) { printf( "uv_spawn: %s\r\n" , uv_strerror( r ) ); } r = uv_read_start( ( uv_stream_t* )&this->pipe_ , SysProcess::uv_process_alloc_buffer , SysProcess::uv_prcoess_read_stream ); if ( r != 0 ) { printf( "uv_read_start: %s\r\n" , uv_strerror( r ) ); } delete[] args; } size_t SysProcess::wait_for_exit() { // uv_sem_wait( &this->sem ); //uv_sem_destroy( &this->sem ); return this->result; } void SysProcess::start() { this->invoke(); } void SysProcess::kill() { uv_process_kill( &this->child_req , 1 ); #ifdef _WIN32 //TerminateProcess( this->pi_.hProcess, -1 ); #else pclose( p_stream ); #endif // _WIN32 }
25.488818
83
0.526573
Yhgenomics
e43793741d62a54bd63c15b5236573d181bb4bf8
5,325
cpp
C++
lib/Transforms/Loop/PartialAffineLoopTile.cpp
Luke-Jacobs/scalehls
76e3980b9ddd1f8f01606d1bf53ef03eb3a8e502
[ "Apache-2.0" ]
60
2021-07-30T03:30:35.000Z
2022-03-27T20:00:41.000Z
lib/Transforms/Loop/PartialAffineLoopTile.cpp
Luke-Jacobs/scalehls
76e3980b9ddd1f8f01606d1bf53ef03eb3a8e502
[ "Apache-2.0" ]
13
2021-08-02T16:13:04.000Z
2022-03-30T23:43:45.000Z
lib/Transforms/Loop/PartialAffineLoopTile.cpp
Luke-Jacobs/scalehls
76e3980b9ddd1f8f01606d1bf53ef03eb3a8e502
[ "Apache-2.0" ]
14
2021-07-30T12:55:01.000Z
2022-03-04T14:29:39.000Z
//===----------------------------------------------------------------------===// // // Copyright 2020-2021 The ScaleHLS Authors. // //===----------------------------------------------------------------------===// #include "mlir/Analysis/LoopAnalysis.h" #include "mlir/Analysis/Utils.h" #include "mlir/Dialect/Affine/Utils.h" #include "mlir/IR/IntegerSet.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/LoopUtils.h" #include "scalehls/Transforms/Passes.h" #include "scalehls/Transforms/Utils.h" using namespace mlir; using namespace scalehls; static IntegerSet simplify(IntegerSet set) { return simplifyIntegerSet(set); } /// Performs basic affine map simplifications. static AffineMap simplify(AffineMap map) { MutableAffineMap mMap(map); mMap.simplify(); return mMap.getAffineMap(); } /// Utility to simplify an affine attribute and update its entry in the parent /// operation if necessary. template <typename AttrT> static void simplifyAndUpdateAttr(Operation *op, Identifier name, AttrT attr, DenseMap<Attribute, Attribute> &simplifiedAttrs) { auto &simplified = simplifiedAttrs[attr]; if (simplified == attr) return; // This is a newly encountered attribute. if (!simplified) { // Try to simplify the value of the attribute. auto value = attr.getValue(); auto simplifiedValue = simplify(value); if (simplifiedValue == value) { simplified = attr; return; } simplified = AttrT::get(simplifiedValue); } // Simplification was successful, so update the attribute. op->setAttr(name, simplified); } static void simplifyAffineStructures(Block &block) { auto context = block.front().getContext(); DenseMap<Attribute, Attribute> simplifiedAttrs; RewritePatternSet patterns(context); AffineApplyOp::getCanonicalizationPatterns(patterns, context); AffineForOp::getCanonicalizationPatterns(patterns, context); AffineIfOp::getCanonicalizationPatterns(patterns, context); FrozenRewritePatternSet frozenPatterns(std::move(patterns)); // The simplification of affine attributes will likely simplify the op. Try to // fold/apply canonicalization patterns when we have affine dialect ops. SmallVector<Operation *> opsToSimplify; block.walk([&](Operation *op) { for (auto attr : op->getAttrs()) { if (auto mapAttr = attr.second.dyn_cast<AffineMapAttr>()) simplifyAndUpdateAttr(op, attr.first, mapAttr, simplifiedAttrs); else if (auto setAttr = attr.second.dyn_cast<IntegerSetAttr>()) simplifyAndUpdateAttr(op, attr.first, setAttr, simplifiedAttrs); } if (isa<AffineForOp, AffineIfOp, AffineApplyOp>(op)) opsToSimplify.push_back(op); }); applyOpPatternsAndFold(opsToSimplify, frozenPatterns, /*strict=*/true); } /// Apply loop tiling to the input loop band and sink all intra-tile loops to /// the innermost loop with the original loop order. Return the location of the /// innermost tile-space loop. Optional<unsigned> scalehls::applyLoopTiling(AffineLoopBand &band, TileList tileList, bool simplify) { if (!isPerfectlyNested(band)) return Optional<unsigned>(); // Loop tiling. auto bandSize = band.size(); AffineLoopBand tiledBand; if (failed(tilePerfectlyNested(band, tileList, &tiledBand))) return Optional<unsigned>(); if (simplify) { band.clear(); unsigned simplifiedBandSize = 0; for (unsigned i = 0, e = tiledBand.size(); i < e; ++i) { auto loop = tiledBand[i]; normalizeAffineFor(loop); if (loop) { band.push_back(loop); if (i < bandSize) ++simplifiedBandSize; } } simplifyAffineStructures(*band.front().getBody()); return simplifiedBandSize - 1; } else { band = tiledBand; return bandSize - 1; } } namespace { struct PartialAffineLoopTile : public PartialAffineLoopTileBase<PartialAffineLoopTile> { void runOnOperation() override { AffineLoopBands targetBands; getTileableBands(getOperation(), &targetBands); for (auto &band : targetBands) { TileList sizes; unsigned remainTileSize = tileSize; // Calculate the tiling size of each loop level. for (auto loop : band) { if (auto optionalTripCount = getConstantTripCount(loop)) { auto tripCount = optionalTripCount.getValue(); auto size = tripCount; if (remainTileSize >= tripCount) remainTileSize = (remainTileSize + tripCount - 1) / tripCount; else if (remainTileSize > 1) { size = 1; while (size < remainTileSize || tripCount % size != 0) { ++size; } remainTileSize = 1; } else size = 1; sizes.push_back(size); } else sizes.push_back(1); } auto tileLoc = applyLoopTiling(band, sizes).getValue(); band.resize(tileLoc + 1); // TODO: canonicalize here to eliminate affine.apply ops. if (applyOrderOpt) applyAffineLoopOrderOpt(band); if (applyPipeline) applyLoopPipelining(band, tileLoc, (unsigned)1); } } }; } // namespace std::unique_ptr<Pass> scalehls::createPartialAffineLoopTilePass() { return std::make_unique<PartialAffineLoopTile>(); }
31.886228
80
0.659155
Luke-Jacobs
e43b025db5216ecde8d795491dda551f8852a178
666
cpp
C++
src/graphics/gl/buffer.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
src/graphics/gl/buffer.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
src/graphics/gl/buffer.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
#include "buffer.h" #include <algorithm> namespace TankGame { Buffer::Buffer(size_t size, const void* data, GLbitfield flags) { GLuint buffer; glCreateBuffers(1, &buffer); SetID(buffer); glNamedBufferStorage(buffer, size, data, flags); } void DeleteBuffer(GLuint id) { glDeleteBuffers(1, &id); } static size_t uniformBufferOffsetAlignment = 0; size_t GetUniformBufferOffsetAlignment() { if (uniformBufferOffsetAlignment == 0) { GLint value; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &value); uniformBufferOffsetAlignment = static_cast<size_t>(std::max(value, 0)); } return uniformBufferOffsetAlignment; } }
19.028571
74
0.728228
Eae02
e43cff509538b2ed8441f84f7de5a62451e5cde4
6,474
cc
C++
source/jones/cartridge/mapper/mapper_mmc1.cc
JonForShort/nes-emulator
513d00a0f1774a262d8a879367db8d3c2a69fbc1
[ "MIT" ]
2
2018-01-24T01:18:07.000Z
2018-12-29T05:17:32.000Z
source/jones/cartridge/mapper/mapper_mmc1.cc
JonForShort/nes-emulator
513d00a0f1774a262d8a879367db8d3c2a69fbc1
[ "MIT" ]
null
null
null
source/jones/cartridge/mapper/mapper_mmc1.cc
JonForShort/nes-emulator
513d00a0f1774a262d8a879367db8d3c2a69fbc1
[ "MIT" ]
null
null
null
// // MIT License // // Copyright 2019 // // 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 <boost/static_assert.hpp> #include "configuration.hh" #include "mapper_mmc1.hh" using namespace jones; namespace jc = jones::configuration; mapper_mmc1::mapper_mmc1(mapper_view const &mapper_view) : mapper(mapper_view), shift_register_(0x10) { auto const &cartridge = mapper_view.cartridge(); prg_rom_size_ = cartridge.header()->prgrom_size(); if (prg_rom_size_ > 0) { prg_rom_ = cartridge.address() + cartridge.header()->prgrom_offset(); } chr_rom_size_ = cartridge.header()->chrrom_size(); if (chr_rom_size_ > 0) { chr_rom_ = cartridge.address() + cartridge.header()->chrrom_offset(); } else { chr_ram_.resize(8192); chr_rom_size_ = 8192; chr_rom_ = &chr_ram_[0]; } sram_.resize(0x2000); std::fill(sram_.begin(), sram_.end(), 0); prg_offsets_[1] = get_prg_bank_offset(-1); mapper_view.cpu_memory().map(std::make_unique<memory_mappable_component<mapper_mmc1>>(this, "mapper_mmc1", 0x6000, 0xFFFF)); mapper_view.ppu_memory().map(std::make_unique<memory_mappable_component<mapper_mmc1>>(this, "mapper_mmc1", 0x0000, 0x1FFF)); } auto mapper_mmc1::get_prg_bank_offset(int const index) const -> uint16_t { auto adjusted_index = index; if (adjusted_index >= 0x80) { adjusted_index -= 0x100; } adjusted_index %= prg_rom_size_ / 0x4000; auto offset = adjusted_index * 0x4000; if (offset < 0) { offset += prg_rom_size_; } return offset; } auto mapper_mmc1::get_chr_bank_offset(int const index) const -> uint16_t { auto adjusted_index = index; if (adjusted_index >= 0x80) { adjusted_index -= 0x100; } adjusted_index %= chr_rom_size_ / 0x1000; auto offset = adjusted_index * 0x1000; if (offset < 0) { offset += chr_rom_size_; } return offset; } auto mapper_mmc1::update_offsets() -> void { switch (prg_mode_) { case 0: case 1: { prg_offsets_[0] = get_prg_bank_offset(prg_bank_ & 0xFEU); prg_offsets_[1] = get_prg_bank_offset(prg_bank_ | 0x01U); break; } case 2: { prg_offsets_[0] = 0; prg_offsets_[1] = get_prg_bank_offset(prg_bank_); break; } case 3: { prg_offsets_[0] = get_prg_bank_offset(prg_bank_); prg_offsets_[1] = get_prg_bank_offset(-1); break; } } switch (chr_mode_) { case 0: { chr_offsets_[0] = get_chr_bank_offset(chr_bank_[0] & 0xFEU); chr_offsets_[1] = get_chr_bank_offset(chr_bank_[0] | 0x01U); break; } case 1: { chr_offsets_[0] = get_chr_bank_offset(chr_bank_[0]); chr_offsets_[1] = get_chr_bank_offset(chr_bank_[1]); break; } } } auto mapper_mmc1::peek(uint16_t const address) const -> uint8_t { return read(address); } auto mapper_mmc1::read(uint16_t const address) const -> uint8_t { if (address < 0x2000) { auto const bank = address / 0x1000; auto const offset = address % 0x1000; auto const chr_offset = chr_offsets_[bank] + offset; return chr_rom_[chr_offset]; } if (address >= 0x8000) { auto const adjusted_address = address - 0x8000; auto const bank = adjusted_address / 0x4000; auto const offset = adjusted_address % 0x4000; auto const prg_offset = prg_offsets_[bank] + offset; return prg_rom_[prg_offset]; } if (address >= 0x6000) { auto const adjusted_address = address - 0x6000; return sram_[adjusted_address]; } BOOST_STATIC_ASSERT("unexpected read for mmc1 mapper"); return 0; } auto mapper_mmc1::write(uint16_t const address, uint8_t const data) -> void { if (address < 0x2000) { auto const bank = address / 0x1000; auto const offset = address % 0x1000; auto const chr_offset = chr_offsets_[bank] + offset; chr_rom_[chr_offset] = data; } if (address >= 0x8000) { load_register(address, data); } if (address >= 0x6000) { auto const adjusted_address = address - 0x6000; sram_[adjusted_address] = data; } BOOST_STATIC_ASSERT("unexpected read for mmc1 mapper"); } auto mapper_mmc1::load_register(uint16_t const address, uint8_t const data) -> void { if ((data & 0x80U) == 0x80U) { shift_register_ = 0x10U; write_control_register(control_register_ | 0x0CU); } else { auto const is_register_complete = (shift_register_ & 1) == 1; shift_register_ >>= 1U; shift_register_ |= (data & 1U) << 4; if (is_register_complete) { write_register(address, shift_register_); shift_register_ = 0x10; } } } auto mapper_mmc1::write_register(uint16_t const address, uint8_t const data) -> void { if (address <= 0x9FFF) { write_control_register(data); } else if (address <= 0xBFFF) { write_chr_bank_zero(data); } else if (address <= 0xDFFF) { write_chr_bank_one(data); } else { write_prg_bank(data); } } auto mapper_mmc1::write_chr_bank_zero(const uint8_t data) -> void { chr_bank_[0] = data; update_offsets(); } auto mapper_mmc1::write_chr_bank_one(const uint8_t data) -> void { chr_bank_[1] = data; update_offsets(); } auto mapper_mmc1::write_prg_bank(const uint8_t data) -> void { prg_bank_ = data & 0x0FU; } auto mapper_mmc1::write_control_register(const uint8_t data) -> void { control_register_ = data; chr_mode_ = (data >> 4U) & 1U; prg_mode_ = (data >> 2U) & 3U; auto const mirror_mode = jc::get_mirror_mode(data & 3U); jc::configuration::instance().set<uint8_t>(jc::property::PROPERTY_MIRROR_MODE, mirror_mode); update_offsets(); }
30.394366
126
0.700958
JonForShort
e43ee07a179e9a0ecad7a3794d5dd19de8d227e9
859
cpp
C++
SlatebackAppCLI/src/commands/ChangeRoll.cpp
filmbrood/Slateback
b512df3b3f13ba152bcf0801c2ad36676d57d2e2
[ "MIT" ]
null
null
null
SlatebackAppCLI/src/commands/ChangeRoll.cpp
filmbrood/Slateback
b512df3b3f13ba152bcf0801c2ad36676d57d2e2
[ "MIT" ]
2
2020-09-22T09:19:48.000Z
2020-09-22T09:28:57.000Z
SlatebackAppCLI/src/commands/ChangeRoll.cpp
filmbrood/Slateback
b512df3b3f13ba152bcf0801c2ad36676d57d2e2
[ "MIT" ]
1
2020-09-22T09:23:44.000Z
2020-09-22T09:23:44.000Z
#include "sltcli_pch.h" void ChangeRoll::OnInit() { SetInput("changeroll"); SetDesc("Change the active camera roll."); } void ChangeRoll::OnUpdate() { LoadSltProjXML("No projects created"); Camera& activeCamera = Controller::Get().GetActiveCamera(); std::cout << "Change active roll to: " << std::endl; for (unsigned int i = 0; i < activeCamera.GetRollCount(); i++) std::cout << i << " - " << activeCamera.GetRoll(i).GetID() << std::endl; std::string userinput; UserPrompt(userinput, ""); for (unsigned int i = 0; i < activeCamera.GetRollCount(); i++) { if (userinput == std::to_string(i)) { Controller::Get().ChangeActiveRoll(i); std::cout << "Active roll changed to " << Controller::Get().GetActiveRoll().GetID() << std::endl; Serializer::Get().SerializeProjectVector(Controller::Get().GetProjectVector()); break; } } }
26.030303
100
0.66007
filmbrood
e4487fad43edde1a1fe15e3acce8c27d474fe4ba
33,669
cpp
C++
retrace/daemon/glframe_state_override.cpp
devcode1981/apitrace
cf11139d6a05688b55c3ab08844a4c9c3c736ea2
[ "MIT" ]
1
2021-03-05T10:49:37.000Z
2021-03-05T10:49:37.000Z
retrace/daemon/glframe_state_override.cpp
MarcelRaschke/apitrace
cf11139d6a05688b55c3ab08844a4c9c3c736ea2
[ "MIT" ]
null
null
null
retrace/daemon/glframe_state_override.cpp
MarcelRaschke/apitrace
cf11139d6a05688b55c3ab08844a4c9c3c736ea2
[ "MIT" ]
1
2018-10-05T03:09:13.000Z
2018-10-05T03:09:13.000Z
// Copyright (C) Intel Corp. 2017. 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 (including the // next paragraph) shall be included in all copies or substantial // portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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. // **********************************************************************/ // * Authors: // * Mark Janes <[email protected]> // **********************************************************************/ // **********************************************************************/ // Checklist for enabling state overrides: // - in dispatch/glframe_glhelper.hpp // - add entry point for required GL calls in the header // - glframe_glhelper.cpp // - declare static pointer to GL function // - look up function pointer in ::Init // - implement entry point to call GL function at the pointer // - in glframe_state_enums.cpp: // - for overrides with choices, add all possibilities to // state_name_to_choices (including true/false state) // - add all enum values in state_name_to_enum // - add all enum values in state_enum_to_name // - if state item has multiple values (eg ClearColor value is // RGBA), define the indices that should be displayed for each // value in state_name_to_indices. // - in glframe_state_override.cpp // - add entries to ::interpret_value, which converts a string // representation of the items value into the bytes sent to the // GL. Internally, StateOverride holds the data as uint32_t, and // converts them to the appropriate type before calling the GL. // - add entries to ::state_type, which indicates which GL call // retrieves the current state of the item, and converting into // bytes uint32_t. // - add entries to ::enact_state, which calls the GL to set state // according to what is stored in StateOverride. Convert the // bytes from uint32_t to whatever is required by the GL api // before calling the GL entry point. // - add entries to ::onState, which queries current state from the // GL and makes the onState callback to pass data back to the UI. // For each entry, choose a hierarchical path to help organize // the state in the UI. // **********************************************************************/ #include "glframe_state_override.hpp" #include <stdio.h> #include <map> #include <string> #include <vector> #include "glframe_glhelper.hpp" #include "glframe_state_enums.hpp" using glretrace::ExperimentId; using glretrace::OnFrameRetrace; using glretrace::RenderId; using glretrace::SelectionId; using glretrace::StateOverride; using glretrace::StateKey; union IntFloat { uint32_t i; float f; }; void StateOverride::setState(const StateKey &item, int offset, const std::string &value) { auto &i = m_overrides[item]; if (i.empty()) { // save the prior state so we can restore it getState(item, &i); m_saved_state[item] = i; } const uint32_t data_value = interpret_value(item, value); // for GL4, front and back face are latched if (item.name == "GL_POLYGON_MODE") { GlFunctions::PolygonMode(GL_FRONT, m_saved_state[item][0]); // if glPolygonMode reports error, then it only accepts // GL_FRONT_AND_BACK GLenum err = GL::GetError(); if (err != GL_NO_ERROR) { // set all offsets to the new value for (auto &face : i) face = data_value; return; } } i[offset] = data_value; } // The UI uses strings for all state values. The override model // stores all data types in a vector of uint32_t. uint32_t StateOverride::interpret_value(const StateKey &item, const std::string &value) { switch (state_name_to_enum(item.name)) { // enumeration values // true/false values case GL_BLEND: case GL_BLEND_DST: case GL_BLEND_DST_ALPHA: case GL_BLEND_DST_RGB: case GL_BLEND_EQUATION_ALPHA: case GL_BLEND_EQUATION_RGB: case GL_BLEND_SRC: case GL_BLEND_SRC_ALPHA: case GL_BLEND_SRC_RGB: case GL_COLOR_WRITEMASK: case GL_CULL_FACE: case GL_CULL_FACE_MODE: case GL_LINE_SMOOTH: case GL_DEPTH_FUNC: case GL_DEPTH_TEST: case GL_DEPTH_WRITEMASK: case GL_DITHER: case GL_FRONT_FACE: case GL_POLYGON_MODE: case GL_POLYGON_OFFSET_FILL: case GL_SAMPLE_COVERAGE_INVERT: case GL_SCISSOR_TEST: case GL_STENCIL_BACK_FAIL: case GL_STENCIL_BACK_FUNC: case GL_STENCIL_BACK_PASS_DEPTH_FAIL: case GL_STENCIL_BACK_PASS_DEPTH_PASS: case GL_STENCIL_FAIL: case GL_STENCIL_FUNC: case GL_STENCIL_PASS_DEPTH_FAIL: case GL_STENCIL_PASS_DEPTH_PASS: case GL_STENCIL_TEST: return state_name_to_enum(value); // float values case GL_BLEND_COLOR: case GL_COLOR_CLEAR_VALUE: case GL_DEPTH_CLEAR_VALUE: case GL_DEPTH_RANGE: case GL_LINE_WIDTH: case GL_POLYGON_OFFSET_FACTOR: case GL_POLYGON_OFFSET_UNITS: case GL_SAMPLE_COVERAGE_VALUE: { IntFloat i_f; i_f.f = std::stof(value); return i_f.i; } // int values case GL_SCISSOR_BOX: return std::stoi(value); // hex values case GL_STENCIL_BACK_REF: case GL_STENCIL_BACK_VALUE_MASK: case GL_STENCIL_BACK_WRITEMASK: case GL_STENCIL_CLEAR_VALUE: case GL_STENCIL_REF: case GL_STENCIL_VALUE_MASK: case GL_STENCIL_WRITEMASK: return std::stoul(value, 0, 16); default: assert(false); return 0; } } enum StateCategory { kStateEnabled, kStateBoolean, kStateBoolean4, kStateInteger, kStateInteger2, kStateInteger4, kStateFloat, kStateFloat2, kStateFloat4, kStateInvalid }; StateCategory state_type(uint32_t state) { switch (state) { case GL_BLEND: case GL_CULL_FACE: case GL_DEPTH_TEST: case GL_DITHER: case GL_LINE_SMOOTH: case GL_POLYGON_OFFSET_FILL: case GL_SCISSOR_TEST: case GL_STENCIL_TEST: return kStateEnabled; case GL_BLEND_DST: case GL_BLEND_DST_ALPHA: case GL_BLEND_DST_RGB: case GL_BLEND_EQUATION_ALPHA: case GL_BLEND_EQUATION_RGB: case GL_BLEND_SRC: case GL_BLEND_SRC_ALPHA: case GL_BLEND_SRC_RGB: case GL_CULL_FACE_MODE: case GL_DEPTH_FUNC: case GL_FRONT_FACE: case GL_STENCIL_BACK_FAIL: case GL_STENCIL_BACK_FUNC: case GL_STENCIL_BACK_PASS_DEPTH_FAIL: case GL_STENCIL_BACK_PASS_DEPTH_PASS: case GL_STENCIL_BACK_REF: case GL_STENCIL_BACK_VALUE_MASK: case GL_STENCIL_BACK_WRITEMASK: case GL_STENCIL_CLEAR_VALUE: case GL_STENCIL_FAIL: case GL_STENCIL_FUNC: case GL_STENCIL_PASS_DEPTH_FAIL: case GL_STENCIL_PASS_DEPTH_PASS: case GL_STENCIL_REF: case GL_STENCIL_VALUE_MASK: case GL_STENCIL_WRITEMASK: return kStateInteger; case GL_COLOR_WRITEMASK: return kStateBoolean4; case GL_DEPTH_WRITEMASK: case GL_SAMPLE_COVERAGE_INVERT: return kStateBoolean; case GL_BLEND_COLOR: case GL_COLOR_CLEAR_VALUE: return kStateFloat4; case GL_DEPTH_CLEAR_VALUE: case GL_LINE_WIDTH: case GL_POLYGON_OFFSET_FACTOR: case GL_POLYGON_OFFSET_UNITS: case GL_SAMPLE_COVERAGE_VALUE: return kStateFloat; case GL_DEPTH_RANGE: return kStateFloat2; case GL_SCISSOR_BOX: return kStateInteger4; case GL_POLYGON_MODE: return kStateInteger2; } assert(false); return kStateInvalid; } void StateOverride::getState(const StateKey &item, std::vector<uint32_t> *data) { const auto n = state_name_to_enum(item.name); data->clear(); switch (state_type(n)) { case kStateEnabled: { data->resize(1); get_enabled_state(n, data); break; } case kStateInteger: { data->resize(1); get_integer_state(n, data); break; } case kStateBoolean4: { data->resize(4); get_bool_state(n, data); break; } case kStateBoolean: { data->resize(1); get_bool_state(n, data); break; } case kStateFloat4: { data->resize(4); get_float_state(n, data); break; } case kStateFloat: { data->resize(1); get_float_state(n, data); break; } case kStateFloat2: { data->resize(2); get_float_state(n, data); break; } case kStateInteger2: { data->resize(2); get_integer_state(n, data); break; } case kStateInteger4: { data->resize(4); get_integer_state(n, data); break; } case kStateInvalid: assert(false); break; } } void StateOverride::get_enabled_state(GLint k, std::vector<uint32_t> *data) { GL::GetError(); assert(data->size() == 1); (*data)[0] = GlFunctions::IsEnabled(k); assert(!GL::GetError()); } void StateOverride::get_integer_state(GLint k, std::vector<uint32_t> *data) { GL::GetError(); GlFunctions::GetIntegerv(k, reinterpret_cast<GLint*>(data->data())); assert(!GL::GetError()); } void StateOverride::get_bool_state(GLint k, std::vector<uint32_t> *data) { GL::GetError(); std::vector<GLboolean> b(data->size()); GlFunctions::GetBooleanv(k, b.data()); auto d = data->begin(); for (auto v : b) { *d = v ? 1 : 0; ++d; } assert(!GL::GetError()); } void StateOverride::get_float_state(GLint k, std::vector<uint32_t> *data) { GL::GetError(); GlFunctions::GetFloatv(k, reinterpret_cast<GLfloat*>(data->data())); assert(!GL::GetError()); } void StateOverride::overrideState() const { enact_state(m_overrides); } void StateOverride::restoreState() const { enact_state(m_saved_state); } void StateOverride::enact_enabled_state(GLint setting, bool v) const { if (v) GlFunctions::Enable(setting); else GlFunctions::Disable(setting); assert(GL::GetError() == GL_NO_ERROR); } void StateOverride::enact_state(const KeyMap &m) const { GL::GetError(); for (auto i : m) { GL::GetError(); const auto n = state_name_to_enum(i.first.name); switch (n) { case GL_BLEND: case GL_CULL_FACE: case GL_DEPTH_TEST: case GL_DITHER: case GL_LINE_SMOOTH: case GL_POLYGON_OFFSET_FILL: case GL_SCISSOR_TEST: case GL_STENCIL_TEST: { enact_enabled_state(n, i.second[0]); break; } case GL_BLEND_COLOR: { std::vector<float> f(4); IntFloat u; for (int j = 0; j < 4; ++j) { u.i = i.second[j]; f[j] = u.f; } GlFunctions::BlendColor(f[0], f[1], f[2], f[3]); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_BLEND_EQUATION_ALPHA: case GL_BLEND_EQUATION_RGB: { GLint modeRGB, modeAlpha; GlFunctions::GetIntegerv(GL_BLEND_EQUATION_RGB, &modeRGB); GlFunctions::GetIntegerv(GL_BLEND_EQUATION_ALPHA, &modeAlpha); GlFunctions::BlendEquationSeparate( n == GL_BLEND_EQUATION_RGB ? i.second[0] : modeRGB, n == GL_BLEND_EQUATION_ALPHA ? i.second[0] : modeAlpha); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_BLEND_SRC: case GL_BLEND_DST: { GLint src, dst; GlFunctions::GetIntegerv(GL_BLEND_DST, &dst); GlFunctions::GetIntegerv(GL_BLEND_SRC, &src); assert(GL::GetError() == GL_NO_ERROR); GlFunctions::BlendFunc( n == GL_BLEND_SRC ? i.second[0] : src, n == GL_BLEND_DST ? i.second[0] : dst); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_BLEND_DST_ALPHA: case GL_BLEND_DST_RGB: case GL_BLEND_SRC_ALPHA: case GL_BLEND_SRC_RGB: { GLint src_rgb, dst_rgb, src_alpha, dst_alpha; GlFunctions::GetIntegerv(GL_BLEND_SRC_RGB, &src_rgb); GlFunctions::GetIntegerv(GL_BLEND_DST_RGB, &dst_rgb); GlFunctions::GetIntegerv(GL_BLEND_SRC_ALPHA, &src_alpha); GlFunctions::GetIntegerv(GL_BLEND_DST_ALPHA, &dst_alpha); GlFunctions::BlendFuncSeparate( n == GL_BLEND_SRC_RGB ? i.second[0] : src_rgb, n == GL_BLEND_DST_RGB ? i.second[0] : dst_rgb, n == GL_BLEND_SRC_ALPHA ? i.second[0] : src_alpha, n == GL_BLEND_DST_ALPHA ? i.second[0] : dst_alpha); break; } case GL_COLOR_CLEAR_VALUE: { std::vector<float> f(4); IntFloat u; for (int j = 0; j < 4; ++j) { u.i = i.second[j]; f[j] = u.f; } GlFunctions::ClearColor(f[0], f[1], f[2], f[3]); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_COLOR_WRITEMASK: { GlFunctions::ColorMask(i.second[0], i.second[1], i.second[2], i.second[3]); break; } case GL_CULL_FACE_MODE: { GlFunctions::CullFace(i.second[0]); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_DEPTH_CLEAR_VALUE: { IntFloat u; u.i = i.second[0]; GlFunctions::ClearDepthf(u.f); break; } case GL_DEPTH_FUNC: { GlFunctions::DepthFunc(i.second[0]); break; } case GL_LINE_WIDTH: { assert(i.second.size() == 1); IntFloat u; u.i = i.second[0]; GlFunctions::LineWidth(u.f); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_DEPTH_RANGE: { assert(i.second.size() == 2); IntFloat _near, _far; _near.i = i.second[0]; _far.i = i.second[1]; GlFunctions::DepthRangef(_near.f, _far.f); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_DEPTH_WRITEMASK: { GlFunctions::DepthMask(i.second[0]); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_FRONT_FACE: { GlFunctions::FrontFace(i.second[0]); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_POLYGON_MODE: { GlFunctions::PolygonMode(GL_FRONT, i.second[0]); GlFunctions::PolygonMode(GL_BACK, i.second[1]); GLenum err = GL::GetError(); if (err != GL_NO_ERROR) GlFunctions::PolygonMode(GL_FRONT_AND_BACK, i.second[0]); break; } case GL_POLYGON_OFFSET_FACTOR: case GL_POLYGON_OFFSET_UNITS: { GLfloat factor, units; GlFunctions::GetFloatv(GL_POLYGON_OFFSET_FACTOR, &factor); GlFunctions::GetFloatv(GL_POLYGON_OFFSET_UNITS, &units); IntFloat convert; convert.i = i.second[0]; GlFunctions::PolygonOffset( n == GL_POLYGON_OFFSET_FACTOR ? convert.f : factor, n == GL_POLYGON_OFFSET_UNITS ? convert.f : units); assert(GL::GetError() == GL_NO_ERROR); break; } case GL_SAMPLE_COVERAGE_INVERT: case GL_SAMPLE_COVERAGE_VALUE: { GLfloat value; GLboolean invert; GlFunctions::GetFloatv(GL_SAMPLE_COVERAGE_VALUE, &value); GlFunctions::GetBooleanv(GL_SAMPLE_COVERAGE_INVERT, &invert); IntFloat convert; convert.i = i.second[0]; GlFunctions::SampleCoverage( n == GL_SAMPLE_COVERAGE_VALUE ? convert.f : value, n == GL_SAMPLE_COVERAGE_INVERT ? i.second[0] : invert); break; } case GL_SCISSOR_BOX: { GlFunctions::Scissor(i.second[0], i.second[1], i.second[2], i.second[3]); break; } case GL_STENCIL_BACK_FAIL: case GL_STENCIL_BACK_PASS_DEPTH_FAIL: case GL_STENCIL_BACK_PASS_DEPTH_PASS: { GLint sfail = 0, dpfail = 0, dppass = 0; GlFunctions::GetIntegerv(GL_STENCIL_BACK_FAIL, &sfail); GlFunctions::GetIntegerv( GL_STENCIL_BACK_PASS_DEPTH_FAIL, &dpfail); GlFunctions::GetIntegerv( GL_STENCIL_BACK_PASS_DEPTH_PASS, &dppass); GlFunctions::StencilOpSeparate( GL_BACK, n == GL_STENCIL_BACK_FAIL ? i.second[0] : sfail, n == GL_STENCIL_BACK_PASS_DEPTH_FAIL ? i.second[0] : dpfail, n == GL_STENCIL_BACK_PASS_DEPTH_PASS ? i.second[0] : dppass); break; } case GL_STENCIL_BACK_FUNC: case GL_STENCIL_BACK_REF: case GL_STENCIL_BACK_VALUE_MASK: { GLint func = 0, ref = 0, mask = 0; GlFunctions::GetIntegerv(GL_STENCIL_BACK_FUNC, &func); GlFunctions::GetIntegerv(GL_STENCIL_BACK_REF, &ref); GlFunctions::GetIntegerv(GL_STENCIL_BACK_VALUE_MASK, &mask); GlFunctions::StencilFuncSeparate( GL_BACK, n == GL_STENCIL_BACK_FUNC ? i.second[0] : func, n == GL_STENCIL_BACK_REF ? i.second[0] : ref, n == GL_STENCIL_BACK_VALUE_MASK ? i.second[0] : mask); break; } case GL_STENCIL_FAIL: case GL_STENCIL_PASS_DEPTH_FAIL: case GL_STENCIL_PASS_DEPTH_PASS: { GLint sfail, dpfail, dppass; GlFunctions::GetIntegerv(GL_STENCIL_FAIL, &sfail); GlFunctions::GetIntegerv( GL_STENCIL_PASS_DEPTH_FAIL, &dpfail); GlFunctions::GetIntegerv( GL_STENCIL_PASS_DEPTH_PASS, &dppass); GlFunctions::StencilOpSeparate( GL_FRONT, n == GL_STENCIL_FAIL ? i.second[0] : sfail, n == GL_STENCIL_PASS_DEPTH_FAIL ? i.second[0] : dpfail, n == GL_STENCIL_PASS_DEPTH_PASS ? i.second[0] : dppass); break; } case GL_STENCIL_FUNC: case GL_STENCIL_REF: case GL_STENCIL_VALUE_MASK: { GLint func = 0, ref = 0, mask = 0; GlFunctions::GetIntegerv(GL_STENCIL_FUNC, &func); GlFunctions::GetIntegerv(GL_STENCIL_REF, &ref); GlFunctions::GetIntegerv(GL_STENCIL_VALUE_MASK, &mask); GlFunctions::StencilFuncSeparate( GL_FRONT, n == GL_STENCIL_FUNC ? i.second[0] : func, n == GL_STENCIL_REF ? i.second[0] : ref, n == GL_STENCIL_VALUE_MASK ? i.second[0] : mask); break; } case GL_STENCIL_WRITEMASK: case GL_STENCIL_BACK_WRITEMASK: { GlFunctions::StencilMaskSeparate( n == GL_STENCIL_WRITEMASK ? GL_FRONT : GL_BACK, i.second[0]); break; } case GL_STENCIL_CLEAR_VALUE: { GlFunctions::ClearStencil(i.second[0]); break; } case GL_INVALID_ENUM: default: assert(false); break; } } } void floatStrings(const std::vector<uint32_t> &i, std::vector<std::string> *s) { s->clear(); IntFloat u; for (auto d : i) { u.i = d; s->push_back(std::to_string(u.f)); } } void intStrings(const std::vector<uint32_t> &i, std::vector<std::string> *s) { s->clear(); for (auto d : i) { s->push_back(std::to_string(d)); } } void floatString(const uint32_t i, std::string *s) { IntFloat u; u.i = i; *s = std::to_string(u.f); } void hexString(const uint32_t i, std::string *s) { std::vector<char> hexstr(11); snprintf(hexstr.data(), hexstr.size(), "0x%08x", i); *s = hexstr.data(); } bool is_supported(uint32_t state) { glretrace::GL::GetError(); std::vector<uint32_t> data(4); switch (state_type(state)) { case kStateEnabled: glretrace::GL::IsEnabled(state); break; case kStateInteger: case kStateInteger2: case kStateInteger4: glretrace::GL::GetIntegerv(state, reinterpret_cast<GLint*>(data.data())); break; case kStateBoolean: case kStateBoolean4: glretrace::GL::GetBooleanv(state, reinterpret_cast<GLboolean*>(data.data())); break; case kStateFloat: case kStateFloat2: case kStateFloat4: glretrace::GL::GetFloatv(state, reinterpret_cast<GLfloat*>(data.data())); break; case kStateInvalid: assert(false); return false; } return(glretrace::GL::GetError() == false); } void StateOverride::onState(SelectionId selId, ExperimentId experimentCount, RenderId renderId, OnFrameRetrace *callback) { std::vector<uint32_t> data; // these entries are roughly in the order of the items in the glGet // man page: // https://www.khronos.org/registry/OpenGL-Refpages/es3.1/html/glGet.xhtml if (is_supported(GL_CULL_FACE)) { StateKey k("Primitive/Cull", "GL_CULL_FACE"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_CULL_FACE_MODE)) { StateKey k("Primitive/Cull", "GL_CULL_FACE_MODE"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND)) { StateKey k("Fragment/Blend", "GL_BLEND"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_BLEND_SRC)) { StateKey k("Fragment/Blend", "GL_BLEND_SRC"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_SRC_ALPHA)) { StateKey k("Fragment/Blend", "GL_BLEND_SRC_ALPHA"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_SRC_RGB)) { StateKey k("Fragment/Blend", "GL_BLEND_SRC_RGB"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_DST)) { StateKey k("Fragment/Blend", "GL_BLEND_DST"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_DST_ALPHA)) { StateKey k("Fragment/Blend", "GL_BLEND_DST_ALPHA"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_DST_RGB)) { StateKey k("Fragment/Blend", "GL_BLEND_DST_RGB"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_COLOR)) { StateKey k("Fragment/Blend", "GL_BLEND_COLOR"); getState(k, &data); std::vector<std::string> color; floatStrings(data, &color); callback->onState(selId, experimentCount, renderId, k, color); } if (is_supported(GL_LINE_WIDTH)) { StateKey k("Primitive/Line", "GL_LINE_WIDTH"); getState(k, &data); std::string value; floatString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_LINE_SMOOTH)) { StateKey k("Primitive/Line", "GL_LINE_SMOOTH"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_BLEND_EQUATION_RGB)) { StateKey k("Fragment/Blend", "GL_BLEND_EQUATION_RGB"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_BLEND_EQUATION_ALPHA)) { StateKey k("Fragment/Blend", "GL_BLEND_EQUATION_ALPHA"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_COLOR_CLEAR_VALUE)) { StateKey k("Framebuffer", "GL_COLOR_CLEAR_VALUE"); getState(k, &data); std::vector<std::string> color; floatStrings(data, &color); callback->onState(selId, experimentCount, renderId, k, color); } if (is_supported(GL_COLOR_WRITEMASK)) { StateKey k("Framebuffer/Mask", "GL_COLOR_WRITEMASK"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false", data[1] ? "true" : "false", data[2] ? "true" : "false", data[3] ? "true" : "false"}); } if (is_supported(GL_DEPTH_CLEAR_VALUE)) { StateKey k("Fragment/Depth", "GL_DEPTH_CLEAR_VALUE"); getState(k, &data); std::string value; floatString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_DEPTH_FUNC)) { StateKey k("Fragment/Depth", "GL_DEPTH_FUNC"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_DEPTH_RANGE)) { StateKey k("Fragment/Depth", "GL_DEPTH_RANGE"); getState(k, &data); std::vector<std::string> range; floatStrings(data, &range); callback->onState(selId, experimentCount, renderId, k, range); } if (is_supported(GL_DEPTH_TEST)) { StateKey k("Fragment/Depth", "GL_DEPTH_TEST"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_DEPTH_WRITEMASK)) { StateKey k("Framebuffer/Mask", "GL_DEPTH_WRITEMASK"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_DITHER)) { StateKey k("Framebuffer", "GL_DITHER"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_FRONT_FACE)) { StateKey k("Primitive", "GL_FRONT_FACE"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_POLYGON_MODE)) { StateKey k("Primitive/Polygon", "GL_POLYGON_MODE"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0]), state_enum_to_name(data[1])}); } if (is_supported(GL_POLYGON_OFFSET_FACTOR)) { StateKey k("Primitive/Polygon", "GL_POLYGON_OFFSET_FACTOR"); getState(k, &data); std::string value; floatString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_POLYGON_OFFSET_FILL)) { StateKey k("Primitive/Polygon", "GL_POLYGON_OFFSET_FILL"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_POLYGON_OFFSET_UNITS)) { StateKey k("Primitive/Polygon", "GL_POLYGON_OFFSET_UNITS"); getState(k, &data); std::string value; floatString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_SAMPLE_COVERAGE_VALUE)) { StateKey k("Fragment/Multisample", "GL_SAMPLE_COVERAGE_VALUE"); getState(k, &data); std::string value; floatString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_SAMPLE_COVERAGE_INVERT)) { StateKey k("Fragment/Multisample", "GL_SAMPLE_COVERAGE_INVERT"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_SCISSOR_TEST)) { StateKey k("Fragment/Scissor", "GL_SCISSOR_TEST"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_SCISSOR_BOX)) { StateKey k("Fragment/Scissor", "GL_SCISSOR_BOX"); getState(k, &data); std::vector<std::string> box; intStrings(data, &box); callback->onState(selId, experimentCount, renderId, k, box); } if (is_supported(GL_STENCIL_BACK_FAIL)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_FAIL"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_BACK_PASS_DEPTH_FAIL)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_PASS_DEPTH_FAIL"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_BACK_PASS_DEPTH_PASS)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_PASS_DEPTH_PASS"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_BACK_FUNC)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_FUNC"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_BACK_REF)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_REF"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_STENCIL_BACK_VALUE_MASK)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_VALUE_MASK"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_STENCIL_BACK_WRITEMASK)) { StateKey k("Stencil/Back", "GL_STENCIL_BACK_WRITEMASK"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_STENCIL_FAIL)) { StateKey k("Stencil/Front", "GL_STENCIL_FAIL"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_PASS_DEPTH_FAIL)) { StateKey k("Stencil/Front", "GL_STENCIL_PASS_DEPTH_FAIL"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_PASS_DEPTH_PASS)) { StateKey k("Stencil/Front", "GL_STENCIL_PASS_DEPTH_PASS"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_TEST)) { StateKey k("Stencil", "GL_STENCIL_TEST"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {data[0] ? "true" : "false"}); } if (is_supported(GL_STENCIL_FUNC)) { StateKey k("Stencil/Front", "GL_STENCIL_FUNC"); getState(k, &data); callback->onState(selId, experimentCount, renderId, k, {state_enum_to_name(data[0])}); } if (is_supported(GL_STENCIL_REF)) { StateKey k("Stencil/Front", "GL_STENCIL_REF"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_STENCIL_VALUE_MASK)) { StateKey k("Stencil/Front", "GL_STENCIL_VALUE_MASK"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_STENCIL_WRITEMASK)) { StateKey k("Stencil/Front", "GL_STENCIL_WRITEMASK"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } if (is_supported(GL_STENCIL_CLEAR_VALUE)) { StateKey k("Stencil", "GL_STENCIL_CLEAR_VALUE"); getState(k, &data); std::string value; hexString(data[0], &value); callback->onState(selId, experimentCount, renderId, k, {value}); } } void StateOverride::revertExperiments() { m_overrides.clear(); } void StateOverride::revertState(const StateKey &item) { auto i = m_overrides.find(item); if (i != m_overrides.end()) m_overrides.erase(i); }
32.405197
79
0.623719
devcode1981
e44a36b4ed211a2cfc08b5d47c38c4ef1139b106
2,722
cpp
C++
libyangrtc2/src/yangrtp/YangRtpFUAPayload2.cpp
yangxinghai/yangrtc
92cc28ade5af6cbe22c151cd1220ab12816694e7
[ "MIT" ]
23
2021-09-13T06:24:34.000Z
2022-03-24T10:05:12.000Z
libyangrtc2/src/yangrtp/YangRtpFUAPayload2.cpp
yangxinghai/yangrtc
92cc28ade5af6cbe22c151cd1220ab12816694e7
[ "MIT" ]
null
null
null
libyangrtc2/src/yangrtp/YangRtpFUAPayload2.cpp
yangxinghai/yangrtc
92cc28ade5af6cbe22c151cd1220ab12816694e7
[ "MIT" ]
9
2021-09-13T06:27:44.000Z
2022-03-02T00:23:17.000Z
#include <yangrtp/YangRtpFUAPayload2.h> #include <yangrtp/YangRtpConstant.h> #include <yangutil/sys/YangLog.h> int32_t yang_parseFua2(YangBuffer* buf,YangFua2Packet* pkt){ if (!buf->require(2)) { return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 2); } // FU indicator, @see https://tools.ietf.org/html/rfc6184#section-5.8 uint8_t v = buf->read_1bytes(); pkt->nri = YangAvcNaluType(v & (~kNalTypeMask)); // FU header, @see https://tools.ietf.org/html/rfc6184#section-5.8 v = buf->read_1bytes(); pkt->start = v & kStart; pkt->end = v & kEnd; pkt->nalu_type = YangAvcNaluType(v & kNalTypeMask); if (!buf->require(1)) { return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 1); } return Yang_Ok; } YangRtpFUAPayload2::YangRtpFUAPayload2() { m_start = m_end = false; m_nri = m_nalu_type = (YangAvcNaluType) 0; } YangRtpFUAPayload2::~YangRtpFUAPayload2() { } uint64_t YangRtpFUAPayload2::nb_bytes() { return 2 + m_size; } bool YangRtpFUAPayload2::getStart(){ return m_start; } int32_t YangRtpFUAPayload2::encode(YangBuffer *buf) { if (!buf->require(2 + m_size)) { return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 1); } // Fast encoding. char *p = buf->head(); // FU indicator, @see https://tools.ietf.org/html/rfc6184#section-5.8 uint8_t fu_indicate = kFuA; fu_indicate |= (m_nri & (~kNalTypeMask)); *p++ = fu_indicate; // FU header, @see https://tools.ietf.org/html/rfc6184#section-5.8 uint8_t fu_header = m_nalu_type; if (m_start) { fu_header |= kStart; } if (m_end) { fu_header |= kEnd; } *p++ = fu_header; // FU payload, @see https://tools.ietf.org/html/rfc6184#section-5.8 memcpy(p, m_payload, m_size); // Consume bytes. buf->skip(2 + m_size); return Yang_Ok; } int32_t YangRtpFUAPayload2::decode(YangBuffer *buf) { if (!buf->require(2)) { return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 2); } // FU indicator, @see https://tools.ietf.org/html/rfc6184#section-5.8 uint8_t v = buf->read_1bytes(); m_nri = YangAvcNaluType(v & (~kNalTypeMask)); // FU header, @see https://tools.ietf.org/html/rfc6184#section-5.8 v = buf->read_1bytes(); m_start = v & kStart; m_end = v & kEnd; m_nalu_type = YangAvcNaluType(v & kNalTypeMask); if (!buf->require(1)) { return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 1); } m_payload = buf->head(); m_size = buf->left(); buf->skip(m_size); return Yang_Ok; } YangRtpPayloader* YangRtpFUAPayload2::copy() { YangRtpFUAPayload2 *cp = new YangRtpFUAPayload2(); cp->m_nri = m_nri; cp->m_start = m_start; cp->m_end = m_end; cp->m_nalu_type = m_nalu_type; cp->m_payload = m_payload; cp->m_size = m_size; return cp; }
24.522523
71
0.691403
yangxinghai
e44c41c4358c6a96c70c4c55d3437ed39b0675e6
8,978
cpp
C++
source/windows/brwindowsd3d.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/windows/brwindowsd3d.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/windows/brwindowsd3d.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** Shims for d3d9.dll or d3dx9_43.dll Copyright (c) 1995-2017 by Rebecca Ann Heineman <[email protected]> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brwindowstypes.h" #if defined(BURGER_WINDOWS) || defined(DOXYGEN) #if !defined(DOXYGEN) // // Handle some annoying defines that some windows SDKs may or may not have // #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #if !defined(_WIN32_WINNT) #define _WIN32_WINNT 0x0501 // Windows XP #endif #include <Windows.h> #include <d3d9.h> #include <d3dx9math.h> typedef IDirect3D9*(WINAPI* Direct3DCreate9Ptr)(UINT SDKVersion); typedef int(WINAPI* D3DPERF_BeginEventPtr)(D3DCOLOR col, LPCWSTR wszName); typedef int(WINAPI* D3DPERF_EndEventPtr)(void); typedef void(WINAPI* D3DPERF_SetMarkerPtr)(D3DCOLOR col, LPCWSTR wszName); typedef void(WINAPI* D3DPERF_SetRegionPtr)(D3DCOLOR col, LPCWSTR wszName); typedef BOOL(WINAPI* D3DPERF_QueryRepeatFramePtr)(void); typedef void(WINAPI* D3DPERF_SetOptionsPtr)(DWORD dwOptions); typedef DWORD(WINAPI* D3DPERF_GetStatusPtr)(void); typedef HRESULT(WINAPI* D3DXCreateMatrixStackPtr)( DWORD Flags, LPD3DXMATRIXSTACK* ppStack); // Unit tests for pointers // Direct3DCreate9Ptr gDirect3DCreate9 = ::Direct3DCreate9; // D3DPERF_BeginEventPtr gD3DPERF_BeginEvent = ::D3DPERF_BeginEvent; // D3DPERF_EndEventPtr gD3DPERF_EndEvent = ::D3DPERF_EndEvent; // D3DPERF_SetMarkerPtr gD3DPERF_SetMarker = ::D3DPERF_SetMarker; // D3DPERF_SetRegionPtr gD3DPERF_SetRegion = ::D3DPERF_SetRegion; // D3DPERF_QueryRepeatFramePtr gD3DPERF_QueryRepeatFrame = // ::D3DPERF_QueryRepeatFrame; // D3DPERF_SetOptionsPtr gD3DPERF_SetOptions = ::D3DPERF_SetOptions; // D3DPERF_GetStatusPtr gD3DPERF_GetStatus = ::D3DPERF_GetStatus; // D3DXCreateMatrixStackPtr gD3DXCreateMatrixStack = ::D3DXCreateMatrixStack; #endif // // d3d9.dll // /*! ************************************ \brief Load in d3d9.dll and call Direct3DCreate9 To allow maximum compatibility, this function will manually load d3d9.dll and then invoke Direct3DCreate9 if present. \windowsonly \param uSDKVersion Requested version of Direct3D 9 \return \ref NULL if DirectX 9 is not present. A valid Direct3D9 pointer otherwise ***************************************/ IDirect3D9* BURGER_API Burger::Windows::Direct3DCreate9(uint_t uSDKVersion) { // Get the function pointer void* pDirect3DCreate9 = LoadFunctionIndex(CALL_Direct3DCreate9); IDirect3D9* pDirect3D9 = nullptr; if (pDirect3DCreate9) { pDirect3D9 = static_cast<Direct3DCreate9Ptr>(pDirect3DCreate9)(uSDKVersion); } return pDirect3D9; } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_BeginEvent To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_BeginEvent if present. \windowsonly \param col The color of the event \param wszName Pointer to UTF-16 string of the name of the event \return Is the level starting from 0 in the hierarchy to start this event. If an error occurs, the return value is negative. ***************************************/ int BURGER_API Burger::Windows::D3DPERF_BeginEvent( uint32_t col, const uint16_t* wszName) { // Get the function pointer void* pD3DPERF_BeginEvent = LoadFunctionIndex(CALL_D3DPERF_BeginEvent); int iResult = -1; if (pD3DPERF_BeginEvent) { iResult = static_cast<D3DPERF_BeginEventPtr>(pD3DPERF_BeginEvent)( col, static_cast<LPCWSTR>(static_cast<const void*>(wszName))); } return iResult; } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_EndEvent To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_EndEvent if present. \windowsonly \return Is the level starting from 0 in the hierarchy to start this event. If an error occurs, the return value is negative. ***************************************/ int BURGER_API Burger::Windows::D3DPERF_EndEvent(void) { // Get the function pointer void* pD3DPERF_EndEvent = LoadFunctionIndex(CALL_D3DPERF_EndEvent); int iResult = -1; if (pD3DPERF_EndEvent) { iResult = static_cast<D3DPERF_EndEventPtr>(pD3DPERF_EndEvent)(); } return iResult; } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_SetMarker To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_SetMarker if present. \windowsonly \param col The color of the event \param wszName Pointer to UTF-16 string of the name of the marker ***************************************/ void BURGER_API Burger::Windows::D3DPERF_SetMarker( uint32_t col, const uint16_t* wszName) { // Get the function pointer void* pD3DPERF_SetMarker = LoadFunctionIndex(CALL_D3DPERF_SetMarker); if (pD3DPERF_SetMarker) { static_cast<D3DPERF_SetMarkerPtr>(pD3DPERF_SetMarker)( col, static_cast<LPCWSTR>(static_cast<const void*>(wszName))); } } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_SetRegion To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_SetRegion if present. \windowsonly \param col The color of the event \param wszName Pointer to UTF-16 string of the name of the region ***************************************/ void BURGER_API Burger::Windows::D3DPERF_SetRegion( uint32_t col, const uint16_t* wszName) { // Get the function pointer void* pD3DPERF_SetRegion = LoadFunctionIndex(CALL_D3DPERF_SetRegion); if (pD3DPERF_SetRegion) { static_cast<D3DPERF_SetRegionPtr>(pD3DPERF_SetRegion)( col, static_cast<LPCWSTR>(static_cast<const void*>(wszName))); } } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_QueryRepeatFrame To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_QueryRepeatFrame if present. \windowsonly \return When the return value is \ref TRUE, the caller will need to repeat the same sequence of calls. If \ref FALSE, the caller needs to move forward. ***************************************/ int BURGER_API Burger::Windows::D3DPERF_QueryRepeatFrame(void) { // Get the function pointer void* pD3DPERF_QueryRepeatFrame = LoadFunctionIndex(CALL_D3DPERF_QueryRepeatFrame); int iResult = FALSE; if (pD3DPERF_QueryRepeatFrame) { iResult = static_cast<D3DPERF_QueryRepeatFramePtr>( pD3DPERF_QueryRepeatFrame)(); } return iResult; } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_SetOptions To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_SetOptions if present. \windowsonly \param dwOptions Set to 1 if PIX should be turned off ***************************************/ void BURGER_API Burger::Windows::D3DPERF_SetOptions(uint32_t dwOptions) { // Get the function pointer void* pD3DPERF_SetOptions = LoadFunctionIndex(CALL_D3DPERF_SetOptions); if (pD3DPERF_SetOptions) { static_cast<D3DPERF_SetOptionsPtr>(pD3DPERF_SetOptions)(dwOptions); } } /*! ************************************ \brief Load in d3d9.dll and call D3DPERF_GetStatus To allow maximum compatibility, this function will manually load d3d9.dll and then invoke D3DPERF_GetStatus if present. \windowsonly \return Non-zero if profiled by PIX. 0 if PIX is not present. ***************************************/ uint_t BURGER_API Burger::Windows::D3DPERF_GetStatus(void) { // Get the function pointer void* pD3DPERF_GetStatus = LoadFunctionIndex(CALL_D3DPERF_GetStatus); uint_t uResult = 0; if (pD3DPERF_GetStatus) { uResult = static_cast<D3DPERF_GetStatusPtr>(pD3DPERF_GetStatus)(); } return uResult; } // // d3dx9_43.dll // /*! ************************************ \brief Load in d3dx9.dll and call D3DXCreateMatrixStack To allow maximum compatibility, this function will manually load d3dx9.dll if needed and then invoke D3DXCreateMatrixStack. \windowsonly \param uFlags Requested version of Direct3D 9 \param ppStack Pointer to a pointer to receive the created ID3DXMatrixStack \return S_OK if the call succeeded. Windows error if otherwise ***************************************/ uint_t BURGER_API Burger::Windows::D3DXCreateMatrixStack( uint_t uFlags, ID3DXMatrixStack** ppStack) { // Clear in case of error if (ppStack) { ppStack[0] = nullptr; } // Get the function pointer void* pD3DXCreateMatrixStack = LoadFunctionIndex(CALL_D3DXCreateMatrixStack); HRESULT uResult = D3DERR_NOTFOUND; if (pD3DXCreateMatrixStack) { uResult = static_cast<D3DXCreateMatrixStackPtr>(pD3DXCreateMatrixStack)( uFlags, ppStack); } return static_cast<uint_t>(uResult); } #endif
28.683706
77
0.712631
Olde-Skuul
e44c687e571f61f4ae181974bb3198e26edecb8d
36,768
cpp
C++
simulator/mips/t/mips64_test.cpp
M-ximus/mipt-mips
ea0b131e3b70273a58311c6921998b6be4549b9c
[ "MIT" ]
null
null
null
simulator/mips/t/mips64_test.cpp
M-ximus/mipt-mips
ea0b131e3b70273a58311c6921998b6be4549b9c
[ "MIT" ]
null
null
null
simulator/mips/t/mips64_test.cpp
M-ximus/mipt-mips
ea0b131e3b70273a58311c6921998b6be4549b9c
[ "MIT" ]
null
null
null
/* MIPS Instruction unit tests * @author: Pavel Kryukov, Vsevolod Pukhov, Egor Bova * Copyright (C) MIPT-MIPS 2017-2019 */ #include <mips/mips.h> #include <mips/mips_instr.h> #include <catch.hpp> #include <memory/memory.h> class MIPS64Instr : public BaseMIPSInstr<uint64> { public: explicit MIPS64Instr( uint32 bytes) : BaseMIPSInstr<uint64>( MIPSVersion::v64, Endian::little, bytes, 0) { } explicit MIPS64Instr( std::string_view str_opcode) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::little, 0, 0xc000) { } MIPS64Instr( std::string_view str_opcode, uint32 immediate) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::little, immediate, 0xc000) { } }; class MIPS64BEInstr : public BaseMIPSInstr<uint64> { public: explicit MIPS64BEInstr( uint32 bytes) : BaseMIPSInstr<uint64>( MIPSVersion::v64, Endian::big, bytes, 0) { } explicit MIPS64BEInstr( std::string_view str_opcode) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::big, 0, 0xc000) { } MIPS64BEInstr( std::string_view str_opcode, uint32 immediate) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::big, immediate, 0xc000) { } }; static auto get_plain_memory_with_data() { auto memory = FuncMemory::create_plain_memory(15); memory->write<uint32, Endian::little>( 0xABCD'1234, 0x1000); memory->write<uint32, Endian::little>( 0xBADC'5678, 0x1004); return memory; } static_assert( std::is_base_of_v<MIPS64::FuncInstr, MIPS64Instr>); TEST_CASE( "MIPS64_instr: addiu two zeroes") { CHECK(MIPS64Instr(0x253104d2).get_disasm() == "addiu $s1, $t1, 1234"); CHECK(MIPS64Instr(0x2531fb2e).get_disasm() == "addiu $s1, $t1, -1234"); MIPS64Instr instr( "addiu"); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: addiu 0 and 1") { MIPS64Instr instr( "addiu", 1); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: addiu 1 and -1") { MIPS64Instr instr( "addiu", 0xffff); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: addiu overflow") { MIPS64Instr instr( "addiu", 2); instr.set_v_src( 0x7fffffff, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x80000001); CHECK( instr.has_trap() == false); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dclo zero") { CHECK(MIPS64Instr(0x71208825).get_disasm() == "dclo $s1, $t1"); MIPS64Instr instr( "dclo"); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dclo -1") { MIPS64Instr instr( "dclo"); instr.set_v_src( 0xffffffffffffffff, 0); instr.execute(); CHECK( instr.get_v_dst() == 64); } TEST_CASE( "MIPS64_instr: dclo ffe002200011000a") { MIPS64Instr instr( "dclo"); instr.set_v_src( 0xffe002200011000a, 0); instr.execute(); CHECK( instr.get_v_dst() == 11); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dclz zero") { CHECK(MIPS64Instr(0x71208824).get_disasm() == "dclz $s1, $t1"); MIPS64Instr instr( "dclz"); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 64); } TEST_CASE( "MIPS64_instr: dclz -1") { MIPS64Instr instr( "dclz"); instr.set_v_src( 0xffffffffffffffff, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dclz 0x02ffaa00cc720000") { MIPS64Instr instr( "dclz"); instr.set_v_src( 0x02ffaa00cc720000, 0); instr.execute(); CHECK( instr.get_v_dst() == 6); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsllv 0xaaaaaaaafee1dead by 0") { CHECK(MIPS64Instr(0x03298814).get_disasm() == "dsllv $s1, $t1, $t9"); MIPS64Instr instr( "dsllv"); instr.set_v_src( 0xaaaaaaaafee1dead, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xaaaaaaaafee1dead); } TEST_CASE( "MIPS64_instr: dsllv 2 by 1") { MIPS64Instr instr( "dsllv"); instr.set_v_src( 2, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst() == 4); } TEST_CASE( "MIPS64_instr: dsllv 1 by 32") { MIPS64Instr instr( "dsllv"); instr.set_v_src( 1, 0); instr.set_v_src( 32, 1); instr.execute(); CHECK( instr.get_v_dst() == 0x100000000); } TEST_CASE( "MIPS64_instr: dsllv 1 by 64 (shift-variable overflow)") { MIPS64Instr instr( "dsllv"); instr.set_v_src( 1, 0); instr.set_v_src( 64, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dsllv 1 by 128 (shift-variable overflow)") { MIPS64Instr instr( "dsllv"); instr.set_v_src( 1, 0); instr.set_v_src( 128, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dsrav 0xfeedabcd by 0") { CHECK(MIPS64Instr(0x03298817).get_disasm() == "dsrav $s1, $t1, $t9"); MIPS64Instr instr( "dsrav"); instr.set_v_src( 0xfeedabcd, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xfeedabcd); } TEST_CASE( "MIPS64_instr: dsrav 0xab by 0xff") { MIPS64Instr instr( "dsrav"); instr.set_v_src( 0xab, 0); instr.set_v_src( 0xff, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dsrav 0x123400000000 by 4") { MIPS64Instr instr( "dsrav"); instr.set_v_src( 0x123400000000, 0); instr.set_v_src( 4, 1); instr.execute(); CHECK( instr.get_v_dst() == 0x012340000000); } TEST_CASE( "MIPS64_instr: dsrav 0xffab000000000000 by 4") { MIPS64Instr instr( "dsrav"); instr.set_v_src( 0xffab000000000000, 0); instr.set_v_src( 4, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xfffab00000000000); } TEST_CASE( "MIPS64_instr: dsrav 1 by 64 (shift-variable overflow)") { MIPS64Instr instr( "dsrav"); instr.set_v_src( 1, 0); instr.set_v_src( 64, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dsrlv 0xdeadbeef by 0") { CHECK(MIPS64Instr(0x03298816).get_disasm() == "dsrlv $s1, $t1, $t9"); MIPS64Instr instr( "dsrlv"); instr.set_v_src( 0xdeadbeef, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xdeadbeef); } TEST_CASE( "MIPS64_instr: dsrlv 1 by 1") { MIPS64Instr instr( "dsrlv"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dsrlv 0x01a00000 by 8") { MIPS64Instr instr( "dsrlv"); instr.set_v_src( 0x01a00000, 0); instr.set_v_src( 8, 1); instr.execute(); CHECK( instr.get_v_dst() == 0x0001a000); } TEST_CASE( "MIPS64_instr: dsrlv 0x8765432000000011 by 16") { MIPS64Instr instr( "dsrlv"); instr.set_v_src( 0x8765432000000011, 0); instr.set_v_src( 16, 1); instr.execute(); CHECK( instr.get_v_dst() == 0x0000876543200000); } TEST_CASE( "MIPS64_instr: dsrlv 1 by 64 (shift-variable overflow)") { MIPS64Instr instr( "dsrlv"); instr.set_v_src( 1, 0); instr.set_v_src( 64, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: ld") { CHECK(MIPS64Instr(0xdd3104d2).get_disasm() == "ld $s1, 0x4d2($t1)"); CHECK(MIPS64Instr(0xdd31fb2e).get_disasm() == "ld $s1, 0xfb2e($t1)"); MIPS64Instr instr( "ld", 0x0fff); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_mem_addr() == 0x1000); get_plain_memory_with_data()->load_store( &instr); CHECK( instr.get_v_dst() == 0xBADC'5678'ABCD'1234); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: ldl") { CHECK(MIPS64Instr(0x693104d2).get_disasm() == "ldl $s1, 0x4d2($t1)"); CHECK(MIPS64Instr(0x6931fb2e).get_disasm() == "ldl $s1, 0xfb2e($t1)"); MIPS64Instr instr( "ldl", 0x0ffd); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_mem_addr() == 0x0ffe); get_plain_memory_with_data()->load_store( &instr); CHECK( instr.get_v_dst() == 0x5678'ABCD'1234'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: ldr") { CHECK(MIPS64Instr(0x6d3104d2).get_disasm() == "ldr $s1, 0x4d2($t1)"); CHECK(MIPS64Instr(0x6d31fb2e).get_disasm() == "ldr $s1, 0xfb2e($t1)"); MIPS64Instr instr( "ldr", 0x0ffd); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_mem_addr() == 0x0ffe); get_plain_memory_with_data()->load_store( &instr); CHECK( instr.get_v_dst() == 0x5678'ABCD'1234'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: sd 0xdead'beef'fee1'dead") { CHECK(MIPS64Instr(0xfd3104d2).get_disasm() == "sd $s1, 0x4d2($t1)"); CHECK(MIPS64Instr(0xfd31fb2e).get_disasm() == "sd $s1, 0xfb2e($t1)"); MIPS64Instr instr( "sd", 0x1000); instr.set_v_src( 0, 0); instr.set_v_src( 0xdead'beef'fee1'dead, 1); instr.execute(); CHECK( instr.get_mem_addr() == 0x1000); auto memory = get_plain_memory_with_data(); memory->load_store( &instr); auto value = memory->read<uint64, Endian::little>( 0x1000); CHECK( value == 0xdead'beef'fee1'dead); } //////////////////////////////////////////////////////////////////////////////// //Instructions sdl and sdr are not implemented TEST_CASE( "MIPS64_instr: sdl 0xdead'beef'fee1'dead") { CHECK(MIPS64Instr(0xb13104d2).get_disasm() == "sdl $s1, 0x4d2($t1)"); CHECK(MIPS64Instr(0xb131fb2e).get_disasm() == "sdl $s1, 0xfb2e($t1)"); MIPS64Instr instr( "sdl", 0x1000); instr.set_v_src( 0, 0); instr.set_v_src( 0xdead'beef'fee1'dead, 1); instr.execute(); CHECK( instr.get_mem_addr() == 0x1000); auto memory = get_plain_memory_with_data(); memory->load_store( &instr); auto value = memory->read<uint64, Endian::little>( 0x1000); CHECK( value == 0xdead'beef'fee1'dead); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: sdr 0xdead'beef'fee1'dead") { CHECK(MIPS64Instr(0xb53104d2).get_disasm() == "sdr $s1, 0x4d2($t1)"); CHECK(MIPS64Instr(0xb531fb2e).get_disasm() == "sdr $s1, 0xfb2e($t1)"); MIPS64Instr instr( "sdr", 0x1000); instr.set_v_src( 0, 0); instr.set_v_src( 0xdead'beef'fee1'dead, 1); instr.execute(); CHECK( instr.get_mem_addr() == 0x1000); auto memory = get_plain_memory_with_data(); memory->load_store( &instr); auto value = memory->read<uint64, Endian::little>( 0x1000); CHECK( value == 0xdead'beef'fee1'dead); } TEST_CASE( "MIPS64_instr: nor 0 and 0") { CHECK(MIPS64Instr(0x01398827).get_disasm() == "nor $s1, $t1, $t9"); MIPS64Instr instr( "nor"); instr.set_v_src( 0, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xffffffffffffffff); } TEST_CASE( "MIPS64_instr: nor 1 and 1") { MIPS64Instr instr( "nor"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xfffffffffffffffe); } TEST_CASE( "MIPS64_instr: nor 1 and -1") { MIPS64Instr instr( "nor"); instr.set_v_src( 1, 0); instr.set_v_src( 0xffffffffffffffff, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE ( "MIPS64_instr: sll 100 by 0") { CHECK(MIPS64Instr(0x00098cc0).get_disasm() == "sll $s1, $t1, 19"); MIPS64Instr instr( "sll", 0); instr.set_v_src( 100, 0); instr.execute(); CHECK( instr.get_v_dst() == 100); } TEST_CASE ( "MIPS64_instr: sll 3 by 2") { MIPS64Instr instr( "sll", 2); instr.set_v_src( 3, 0); instr.execute(); CHECK( instr.get_v_dst() == 12); } TEST_CASE ( "MIPS64_instr: sll 1 by 16") { MIPS64Instr instr( "sll", 16); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x10000); } TEST_CASE ( "MIPS64_instr: sll 1 by 31") { MIPS64Instr instr( "sll", 31); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'8000'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: sllv by 64 (shift-variable ovreflow)") { MIPS64Instr instr( "sllv"); instr.set_v_src( 1, 0); instr.set_v_src( 64, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: sra 0xdeadc0dde by 0") { CHECK(MIPS64Instr(0x00098cc3).get_disasm() == "sra $s1, $t1, 19"); MIPS64Instr instr( "sra", 0); instr.set_v_src( 0xdeadc0de, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'dead'c0de); } TEST_CASE( "MIPS64_instr: sra 0x0fffffff by 2") { MIPS64Instr instr( "sra", 2); instr.set_v_src( 0x0fffffff, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x03ffffff); } TEST_CASE( "MIPS64_instr: sra 0xdead by 4") { MIPS64Instr instr( "sra", 4); instr.set_v_src( 0xdead, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x0dea); } TEST_CASE( "MIPS64_instr: sra 0xf1234567 by 16") { MIPS64Instr instr( "sra", 16); instr.set_v_src( 0xf1234567, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'f123); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: srav 24 by 0") { CHECK(MIPS64Instr(0x03298807).get_disasm() == "srav $s1, $t1, $t9"); MIPS64Instr instr( "srav"); instr.set_v_src( 24, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 24); } TEST_CASE( "MIPS64_instr: srav 10 by 1") { MIPS64Instr instr( "srav"); instr.set_v_src( 10, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst() == 5); } TEST_CASE( "MIPS64_instr: srav 0x000a by 4") { MIPS64Instr instr( "srav"); instr.set_v_src( 0x000a, 0); instr.set_v_src( 4, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: srav 0xff000000 by 4") { MIPS64Instr instr( "srav"); instr.set_v_src( 0xff000000, 0); instr.set_v_src( 4, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'fff0'0000); } TEST_CASE( "MIPS64_instr: srav 0xffff0000 by 32 (shift-variable overflow)") { MIPS64Instr instr( "srav"); instr.set_v_src( 0xffff0000, 0); instr.set_v_src( 32, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'0000); } TEST_CASE( "MIPS64_instr: srlv 0x11 by 0x00000a00 (shift-variable overflow)") { MIPS64Instr instr( "srlv"); instr.set_v_src( 0x11, 0); instr.set_v_src( 0x00000a00, 1); instr.execute(); CHECK( instr.get_v_dst() == 0x11); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //-------------------------MIPS64Instr unit-tests-----------------------------// static bool not_a_mips32_instruction( std::string_view name) { class MIPS32Instr : public BaseMIPSInstr<uint32> { public: explicit MIPS32Instr( std::string_view str_opcode) : BaseMIPSInstr<uint32>( MIPSVersion::v32, str_opcode, Endian::little, 0, 0xc000) { } }; MIPS32Instr instr( name); instr.execute(); return instr.trap_type() == Trap::UNKNOWN_INSTRUCTION; } TEST_CASE ( "MIPS64_instr: dadd two zeroes") { CHECK(MIPS64Instr(0x0139882C).get_disasm() == "dadd $s1, $t1, $t9"); CHECK( not_a_mips32_instruction("dadd")); MIPS64Instr instr( "dadd"); instr.set_v_src( 0, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE ( "MIPS64_instr: dadd 0 and 1") { MIPS64Instr instr( "dadd"); instr.set_v_src( 0, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE ( "MIPS64_instr: dadd 1 and -1") { MIPS64Instr instr( "dadd"); instr.set_v_src( 1, 0); instr.set_v_src( 0xffffffffffffffff, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE ( "MIPS64_instr: dadd overflow") { MIPS64Instr instr( "dadd"); instr.set_v_src( 0x7fffffffffffffff, 0); instr.set_v_src( 0x7fffffffffffffff, 1); instr.execute(); CHECK( instr.get_v_dst() == NO_VAL32); CHECK( instr.trap_type() != Trap::NO_TRAP); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: daddi two zeroes") { CHECK(MIPS64Instr(0x613104d2).get_disasm() == "daddi $s1, $t1, 1234"); CHECK(MIPS64Instr(0x6131fb2e).get_disasm() == "daddi $s1, $t1, -1234"); CHECK( not_a_mips32_instruction("daddi")); MIPS64Instr instr( "daddi", 0); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: daddi 0 and 1") { MIPS64Instr instr( "daddi", 1); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: daddi 1 and -1") { MIPS64Instr instr( "daddi", 0xffff); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: daddi overflow") { MIPS64Instr instr( "daddi", 1); instr.set_v_src( 0x7fffffffffffffff, 0); instr.execute(); CHECK( instr.get_v_dst() == NO_VAL32); CHECK( instr.trap_type() != Trap::NO_TRAP); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: daddiu two zeroes") { CHECK(MIPS64Instr(0x653104d2).get_disasm() == "daddiu $s1, $t1, 1234"); CHECK(MIPS64Instr(0x6531fb2e).get_disasm() == "daddiu $s1, $t1, -1234"); CHECK( not_a_mips32_instruction("daddiu")); MIPS64Instr instr( "daddiu", 0); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: daddiu 0 and 1") { MIPS64Instr instr( "daddiu", 1); instr.set_v_src( 0, 0); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: daddiu 1 and -1") { MIPS64Instr instr( "daddiu", 0xffff); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: daddiu overflow") { MIPS64Instr instr( "daddiu", 1); instr.set_v_src( 0x7fffffffffffffff, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x8000000000000000); CHECK( instr.trap_type() == Trap::NO_TRAP); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE ( "MIPS64_instr: daddu two zeroes") { CHECK(MIPS64Instr(0x0139882D).get_disasm() == "daddu $s1, $t1, $t9"); CHECK( not_a_mips32_instruction("daddu")); MIPS64Instr instr( "daddu"); instr.set_v_src( 0, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE ( "MIPS64_instr: daddu 0 and 1") { MIPS64Instr instr( "daddu"); instr.set_v_src( 0, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst() == 1); } TEST_CASE ( "MIPS64_instr: daddu 1 and -1") { MIPS64Instr instr( "daddu"); instr.set_v_src( 1, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst() == 0); } TEST_CASE ( "MIPS64_instr: daddu overflow") { MIPS64Instr instr( "daddu"); instr.set_v_src( 0x7fff'ffff'ffff'ffff, 0); instr.set_v_src( 0x7fff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'fffe); CHECK( instr.has_trap() == false); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: ddiv 1 by 1") { CHECK(MIPS64Instr(0x0229001e).get_disasm() == "ddiv $s1, $t1"); CHECK(MIPS64Instr(0x0229001e).is_divmult()); CHECK(MIPS64Instr( "ddiv").is_divmult()); CHECK( not_a_mips32_instruction( "ddiv")); MIPS64Instr instr( "ddiv"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: ddiv -1 by 1") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff); } TEST_CASE( "MIPS64_instr: ddiv -1 by -1") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: ddiv 1 by -1") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 1, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff); } TEST_CASE( "MIPS64_instr: ddiv 0 by 1") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 0, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddiv 1 by 0") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 1, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddiv 0x8000'0000'0000'0000 by -1") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 0x8000'0000'0000'0000, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddiv 0x4c4b'4000'0000'0000 by 0x1dcd'6500'0000'0000") { MIPS64Instr instr( "ddiv"); instr.set_v_src( 0x4c4b'4000'0000'0000, 0); instr.set_v_src( 0x1dcd'6500'0000'0000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0x10b0'7600'0000'0000); CHECK( instr.get_v_dst() == 2); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: ddivu 1 by 1") { CHECK(MIPS64Instr(0x0229001f).get_disasm() == "ddivu $s1, $t1"); CHECK(MIPS64Instr(0x0229001f).is_divmult()); CHECK(MIPS64Instr( "ddivu").is_divmult()); CHECK( not_a_mips32_instruction( "ddivu")); MIPS64Instr instr( "ddivu"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: ddivu -1 by 1") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff); } TEST_CASE( "MIPS64_instr: ddivu -1 by -1") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: ddivu 1 by -1") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 1, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 1); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddivu 0 by 1") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 0, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddivu 1 by 0") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 1, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddivu 0x8000'0000'0000'0000 by -1") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 0x8000'0000'0000'0000, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0x8000'0000'0000'0000); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: ddivu 0x4c4b'4000'0000'0000 by 0x1dcd'6500'0000'0000") { MIPS64Instr instr( "ddivu"); instr.set_v_src( 0x4c4b'4000'0000'0000, 0); instr.set_v_src( 0x1dcd'6500'0000'0000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0x10b0'7600'0000'0000); CHECK( instr.get_v_dst() == 2); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dmult 0 by 0") { CHECK(MIPS64Instr(0x0229001c).get_disasm() == "dmult $s1, $t1"); CHECK(MIPS64Instr(0x0229001c).is_divmult()); CHECK(MIPS64Instr("dmult").is_divmult()); CHECK( not_a_mips32_instruction("dmult")); MIPS64Instr instr( "dmult"); instr.set_v_src( 0, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dmult 1 by 1") { MIPS64Instr instr( "dmult"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dmult -1 by -1") { MIPS64Instr instr( "dmult"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dmult -1 by 1") { MIPS64Instr instr( "dmult"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0xffff'ffff'ffff'ffff); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff); } TEST_CASE( "MIPS64_instr: dmult 0x100000000 by 0x100000000") { MIPS64Instr instr( "dmult"); instr.set_v_src( 0x100000000, 0); instr.set_v_src( 0x100000000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 1); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dmult 0x8000'0000'0000'0000 by 0x8000'0000'0000'0000") { MIPS64Instr instr( "dmult"); instr.set_v_src( 0x8000'0000'0000'0000, 0); instr.set_v_src( 0x8000'0000'0000'0000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0x4000'0000'0000'0000); CHECK( instr.get_v_dst() == 0); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dmultu 0 by 0") { CHECK(MIPS64Instr(0x0229001d).get_disasm() == "dmultu $s1, $t1"); CHECK(MIPS64Instr(0x0229001d).is_divmult()); CHECK(MIPS64Instr("dmultu").is_divmult()); CHECK( not_a_mips32_instruction("dmultu")); MIPS64Instr instr( "dmultu"); instr.set_v_src( 0, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dmultu 1 by 1") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dmultu -1 by -1") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 0xffff'ffff'ffff'ffff, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0xffff'ffff'ffff'fffe); CHECK( instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dmultu -1 by 0") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dmultu -1 by 1") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 0xffff'ffff'ffff'ffff, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff); } TEST_CASE( "MIPS64_instr: dmultu 0x100000000 by 0x100000000") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 0x100000000, 0); instr.set_v_src( 0x100000000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 1); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dmultu 0x8000'0000'0000'0000 by 0x8000'0000'0000'0000") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 0x8000'0000'0000'0000, 0); instr.set_v_src( 0x8000'0000'0000'0000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0x4000'0000'0000'0000); CHECK( instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dmultu 0xcecb'8f27'0000'0000 by 0xfd87'b5f2'0000'0000") { MIPS64Instr instr( "dmultu"); instr.set_v_src( 0xcecb'8f27'0000'0000, 0); instr.set_v_src( 0xfd87'b5f2'0000'0000, 1); instr.execute(); CHECK( instr.get_v_dst2() == 0xcccc'cccb'7134'e5de); CHECK( instr.get_v_dst() == 0); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE ( "MIPS64_instr: dsll 0xaaaa'aaaa'0009'8cc0 by 0") { CHECK(MIPS64Instr(0x00098cf8).get_disasm() == "dsll $s1, $t1, 19"); CHECK( not_a_mips32_instruction("dsll")); MIPS64Instr instr( "dsll", 0); instr.set_v_src( 0xaaaa'aaaa'0009'8cc0, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xaaaa'aaaa'0009'8cc0); } TEST_CASE ( "MIPS64_instr: dsll 51 by 1") { MIPS64Instr instr( "dsll", 1); instr.set_v_src( 51, 0); instr.execute(); CHECK( instr.get_v_dst() == 102); } TEST_CASE ( "MIPS64_instr: dsll 0x8899'aabb'ccdd'eeff by 8") { MIPS64Instr instr( "dsll", 8); instr.set_v_src( 0x8899'aabb'ccdd'eeff, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x99aa'bbcc'ddee'ff00); } TEST_CASE ( "MIPS64_instr: dsll 1 by 63") { MIPS64Instr instr( "dsll", 63); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x8000'0000'0000'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsll32 0xaaaa'aaaa'0009'8ccf by 0") { CHECK(MIPS64Instr(0x00098cfc).get_disasm() == "dsll32 $s1, $t1, 19"); CHECK( not_a_mips32_instruction("dsll32")); MIPS64Instr instr( "dsll32", 0); instr.set_v_src( 0xaaaa'aaaa'0009'8ccf, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x0009'8ccf'0000'0000); } TEST_CASE ( "MIPS64_instr: dsll32 0x8899'aabb'ccdd'eeff by 8") { MIPS64Instr instr( "dsll32", 8); instr.set_v_src( 0x8899'aabb'ccdd'eeff, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xddee'ff00'0000'0000); } TEST_CASE( "MIPS64_instr: dsll32 1 by 31") { MIPS64Instr instr( "dsll32", 31); instr.set_v_src( 1, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x8000'0000'0000'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsra 0xabcd'1234'abcd'1234 by 0") { CHECK(MIPS64Instr(0x00098cfb).get_disasm() == "dsra $s1, $t1, 19"); CHECK( not_a_mips32_instruction("dsra")); MIPS64Instr instr( "dsra", 0); instr.set_v_src( 0xabcd'1234'abcd'1234, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xabcd'1234'abcd'1234); } TEST_CASE( "MIPS64_instr: dsra 49 by 1") { MIPS64Instr instr( "dsra", 1); instr.set_v_src( 49, 0); instr.execute(); CHECK( instr.get_v_dst() == 24); } TEST_CASE( "MIPS64_instr: dsra 0x1000 by 4") { MIPS64Instr instr( "dsra", 4); instr.set_v_src( 0x1000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x100); } TEST_CASE( "MIPS64_instr: dsra 0xffa0'0000'0000'0000 by 16") { MIPS64Instr instr( "dsra", 16); instr.set_v_src( 0xffa0'0000'0000'0000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffa0'0000'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsra32 0xabcd'1234'abcd'1234 by 0") { CHECK(MIPS64Instr(0x00098cff).get_disasm() == "dsra32 $s1, $t1, 19"); CHECK( not_a_mips32_instruction("dsra32")); MIPS64Instr instr( "dsra32", 0); instr.set_v_src( 0xabcd'1234'abcd'1234, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'abcd'1234); } TEST_CASE( "MIPS64_instr: dsra32 0x1000'0000'0000 by 4") { MIPS64Instr instr( "dsra32", 4); instr.set_v_src( 0x1000'0000'0000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x100); } TEST_CASE( "MIPS64_instr: dsra32 0xffa0'0000'0000'0000 by 16") { MIPS64Instr instr( "dsra32", 16); instr.set_v_src( 0xffa0'0000'0000'0000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffa0); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsrl 0xabcd'1234'abcd'1234 by 0") { CHECK(MIPS64Instr(0x00098cfa).get_disasm() == "dsrl $s1, $t1, 19"); CHECK( not_a_mips32_instruction("dsrl")); MIPS64Instr instr( "dsrl", 0); instr.set_v_src( 0xabcd'1234'abcd'1234, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xabcd'1234'abcd'1234); } TEST_CASE( "MIPS64_instr: dsrl 49 by 1") { MIPS64Instr instr( "dsrl", 1); instr.set_v_src( 49, 0); instr.execute(); CHECK( instr.get_v_dst() == 24); } TEST_CASE( "MIPS64_instr: dsrl 0x1000 by 4") { MIPS64Instr instr( "dsrl", 4); instr.set_v_src( 0x1000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x100); } TEST_CASE( "MIPS64_instr: dsrl 0xffa0'0000'0000'0000 by 16") { MIPS64Instr instr( "dsrl", 16); instr.set_v_src( 0xffa0'0000'0000'0000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffa0'0000'0000); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsrl32 0xabcd'1234'abcd'1234 by 0") { CHECK(MIPS64Instr(0x00098cfe).get_disasm() == "dsrl32 $s1, $t1, 19"); CHECK( not_a_mips32_instruction("dsrl32")); MIPS64Instr instr( "dsrl32", 0); instr.set_v_src( 0xabcd'1234'abcd'1234, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xabcd1234); } TEST_CASE( "MIPS64_instr: dsrl32 0x1000'0000'0000 by 4") { MIPS64Instr instr( "dsrl32", 4); instr.set_v_src( 0x1000'0000'0000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0x100); } TEST_CASE( "MIPS64_instr: dsrl32 0xffa0'0000'0000'0000 by 16") { MIPS64Instr instr( "dsrl32", 16); instr.set_v_src( 0xffa0'0000'0000'0000, 0); instr.execute(); CHECK( instr.get_v_dst() == 0xffa0); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsub 1 from 1") { CHECK(MIPS64Instr(0x0139882e).get_disasm() == "dsub $s1, $t1, $t9"); CHECK( not_a_mips32_instruction("dsub")); MIPS64Instr instr( "dsub"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK(instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dsub 1 from 10") { MIPS64Instr instr( "dsub"); instr.set_v_src( 10, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK(instr.get_v_dst() == 9); } TEST_CASE( "MIPS64_instr: dsub 0 from 1") { MIPS64Instr instr( "dsub"); instr.set_v_src( 1, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK(instr.get_v_dst() == 1); } TEST_CASE( "MIPS64_instr: dsub overflow") { MIPS64Instr instr( "dsub"); instr.set_v_src( 0x8000000000000000, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK(instr.get_v_dst() == NO_VAL32); CHECK(instr.trap_type() == Trap::INTEGER_OVERFLOW); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "MIPS64_instr: dsubu 1 from 1") { CHECK(MIPS64Instr(0x0139882f).get_disasm() == "dsubu $s1, $t1, $t9"); CHECK( not_a_mips32_instruction("dsubu")); MIPS64Instr instr( "dsubu"); instr.set_v_src( 1, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK(instr.get_v_dst() == 0); } TEST_CASE( "MIPS64_instr: dsubu 1 from 10") { MIPS64Instr instr( "dsubu"); instr.set_v_src( 10, 0); instr.set_v_src( 1, 1); instr.execute(); CHECK(instr.get_v_dst() == 9); } TEST_CASE( "MIPS64_instr: dsubu 0 from 1") { MIPS64Instr instr( "dsubu"); instr.set_v_src( 1, 0); instr.set_v_src( 0, 1); instr.execute(); CHECK(instr.get_v_dst() == 1); } ////////////////////////////////////////////////////////////////////////////////
28.067176
157
0.597068
M-ximus
e44e4c4347d86fc185952146b58e3a2663aa2efa
641
cpp
C++
demo/main.cpp
Gustafsson88/lr_06
12c4c2651c577478331cd81bb2d07bf7ec133d5b
[ "MIT" ]
null
null
null
demo/main.cpp
Gustafsson88/lr_06
12c4c2651c577478331cd81bb2d07bf7ec133d5b
[ "MIT" ]
null
null
null
demo/main.cpp
Gustafsson88/lr_06
12c4c2651c577478331cd81bb2d07bf7ec133d5b
[ "MIT" ]
null
null
null
#include <header.hpp> #include <mutex> int main(int argc, char *argv[]) { std::mutex mut; Create_HASH::logging(); unsigned int thread_count; if (argc >= 2) { thread_count = boost::lexical_cast<int unsigned>(argv[1]); } else thread_count = std::thread::hardware_concurrency(); std::cout << "Thread count: "<< thread_count << std::endl; std::vector<std::thread> threads; threads.reserve(thread_count); for (unsigned i = 0; i < thread_count; i++) { threads.emplace_back(Create_HASH::create_hash, std::ref(mut)); } for (std::thread &thr : threads) { thr.join(); } Create_HASH::exit_f(); return 0; }
24.653846
66
0.650546
Gustafsson88
e44ff1593cdbb90d2f8be668979fef4b31dded58
4,149
hpp
C++
ZarroKey/UiMainWindow.hpp
MariusOlteanu/ZarroKey
d6bdedaa5ca1c5ffa531cbcc35af0a3b6aa7715d
[ "MIT" ]
null
null
null
ZarroKey/UiMainWindow.hpp
MariusOlteanu/ZarroKey
d6bdedaa5ca1c5ffa531cbcc35af0a3b6aa7715d
[ "MIT" ]
null
null
null
ZarroKey/UiMainWindow.hpp
MariusOlteanu/ZarroKey
d6bdedaa5ca1c5ffa531cbcc35af0a3b6aa7715d
[ "MIT" ]
null
null
null
// // Copyright(c) 2022 Marius Olteanu [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this softwareand 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 noticeand 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. #pragma once #include "Utils.hpp" #include "RegistryData.hpp" class IoSymulator; class UiMainWindow { public: static UiMainWindow* CreateMainWindow(HINSTANCE instance, IoSymulator* _symulator, const wchar_t* registryPath) { static UiMainWindow window; UiMainWindow::mainWindow = &window; UiMainWindow::mainWindow->symulator = _symulator; UiMainWindow::mainWindow->UiRegisterClass(instance); UiMainWindow::mainWindow->registryData.Init(registryPath); UiMainWindow::mainWindow->CreateMainWindow(); return UiMainWindow::mainWindow; } constexpr operator HWND() const noexcept { return this->window; } void Run(); protected: UiMainWindow(); void Update(uint32_t position); void UpdateAll(); void UpdateProfileName(); RegistryData registryData; windows_ptr<HFONT, decltype(&::DeleteObject)> font { ::DeleteObject }; windows_ptr<HFONT, decltype(&::DeleteObject)> fontText { ::DeleteObject }; windows_ptr<HFONT, decltype(&::DeleteObject)> fontSmall { ::DeleteObject }; windows_ptr<HBRUSH, decltype(&::DeleteObject)> backgroundColor { ::DeleteObject }; windows_ptr<HBRUSH, decltype(&::DeleteObject)> backgroundColorList { ::DeleteObject }; windows_ptr<HBRUSH, decltype(&::DeleteObject)> transparentColor { ::DeleteObject }; IoSymulator* symulator; HINSTANCE instance; HWND window; HWND list; HWND editList; HWND edit[RegistryData::maxData]; bool init = false; inline static UiMainWindow* mainWindow = nullptr; private: void UiRegisterClass(HINSTANCE _instance); void CreateMainWindow(); __forceinline LRESULT MainWindow(HWND window, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK MainWindowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam); bool dragWindow = false; POINT clickedPosition; constexpr static uint32_t BUTTON_INFO_ID = 1; constexpr static uint32_t BUTTON_ABOUT_ID = 2; constexpr static uint32_t PICTURE_ID = 5; constexpr static uint32_t COPYRIGHT_ID = 10; constexpr static uint32_t TRANSPARENT_ID = 11; constexpr static uint32_t LISTBOX_ID = 15; constexpr static uint32_t EDITBOX_LIST_ID = 16; constexpr static uint32_t EDITBOX_ID[RegistryData::maxData] = { 21, 22, 23, 24, 25, 26 }; constexpr static uint32_t CHECKBOX_ID[RegistryData::maxData] = { 31, 32, 33, 34, 35, 36 }; constexpr static wchar_t ZarroWindowName[] = L"Zarro Key Symulater"; constexpr static wchar_t ZarroClassName[] = L"ZarroClass"; constexpr static COLORREF TransparentColor = RGB(0x41, 0x51, 0x61); constexpr static int32_t XWindowSize = 575; constexpr static int32_t YWindowSize = 142; };
31.431818
116
0.689082
MariusOlteanu
e4517071e0a1e791d4b33e2844e3b65937a674ad
1,111
hpp
C++
include/polarai/utils/string/String.hpp
alexbatashev/athena
eafbb1e16ed0b273a63a20128ebd4882829aa2db
[ "MIT" ]
2
2020-07-16T06:42:27.000Z
2020-07-16T06:42:28.000Z
include/polarai/utils/string/String.hpp
PolarAI/polarai-framework
c5fd886732afe787a06ebf6fb05fc38069257457
[ "MIT" ]
null
null
null
include/polarai/utils/string/String.hpp
PolarAI/polarai-framework
c5fd886732afe787a06ebf6fb05fc38069257457
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // Copyright (c) 2020 PolarAI. All rights reserved. // // Licensed under MIT license. // // 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. //===----------------------------------------------------------------------===// #pragma once #include <polar_utils_export.h> #include <polarai/utils/allocator/Allocator.hpp> #include <cstddef> namespace polarai::utils { class POLAR_UTILS_EXPORT String { public: String(); String(const char* string, Allocator<byte> allocator = Allocator<byte>()); String(const String&); String(String&&) noexcept; ~String(); [[nodiscard]] const char* getString() const; [[nodiscard]] size_t getSize() const; private: size_t mSize; Allocator<byte> mAllocator; const char* mData; }; } // namespace polarai::utils
30.027027
80
0.629163
alexbatashev
e45b2d1f7bd8756914f85113de8f1d8e07cd547e
2,411
hpp
C++
dev/so_5/disp/prio_one_thread/quoted_round_robin/h/quotes.hpp
eao197/so-5-5
fa0c31c84d2637dce04e13a155040150d505fbbd
[ "BSL-1.0" ]
76
2016-03-25T15:22:03.000Z
2022-02-03T15:11:43.000Z
dev/so_5/disp/prio_one_thread/quoted_round_robin/h/quotes.hpp
eao197/so-5-5
fa0c31c84d2637dce04e13a155040150d505fbbd
[ "BSL-1.0" ]
19
2017-03-09T19:21:53.000Z
2021-02-24T13:02:18.000Z
dev/so_5/disp/prio_one_thread/quoted_round_robin/h/quotes.hpp
eao197/so-5-5
fa0c31c84d2637dce04e13a155040150d505fbbd
[ "BSL-1.0" ]
21
2016-09-23T10:01:09.000Z
2020-08-31T12:01:10.000Z
/* * SObjectizer-5 */ /*! * \since * v.5.5.8 * * \file * \brief A storage of quotes for priorities. */ #pragma once #include <so_5/h/priority.hpp> #include <so_5/h/exception.hpp> #include <so_5/h/ret_code.hpp> #include <algorithm> #include <iterator> namespace so_5 { namespace disp { namespace prio_one_thread { namespace quoted_round_robin { /*! * \since 5.5.8 * \brief A storage of quotes for priorities. * * A usage example: \code using namespace so_5::disp::prio_one_thread::quoted_round_robin; quotes_t quotes{ 150 }; // Default value for all priorities. quotes.set( so_5::prio::p7, 350 ); // New quote for p7. quotes.set( so_5::prio::p6, 250 ); // New quote for p6. // All other quotes will be 150. ... create_private_disp( env, quotes ); \endcode Another example: \code using namespace so_5::disp::prio_one_thread::quoted_round_robin; create_private_disp( env, quotes_t{ 150 } // Default value for all priorites. .set( so_5::prio::p7, 350 ) // New quote for p7. .set( so_5::prio::p6, 250 ) // New quote for p6 ); \endcode * \attention Value of 0 is illegal. An exception will be throw on * attempt of setting 0 as a quote value. */ class quotes_t { public : //! Initializing constructor sets the default value for //! every priority. quotes_t( std::size_t default_value ) { ensure_quote_not_zero( default_value ); std::fill( std::begin(m_quotes), std::end(m_quotes), default_value ); } //! Set a new quote for a priority. quotes_t & set( //! Priority to which a new quote to be set. priority_t prio, //! Quote value. std::size_t quote ) { ensure_quote_not_zero( quote ); m_quotes[ to_size_t( prio ) ] = quote; return *this; } //! Get the quote for a priority. size_t query( priority_t prio ) const { return m_quotes[ to_size_t( prio ) ]; } private : //! Quotes for every priority. std::size_t m_quotes[ so_5::prio::total_priorities_count ]; static void ensure_quote_not_zero( std::size_t value ) { if( !value ) SO_5_THROW_EXCEPTION( rc_priority_quote_illegal_value, "quote for a priority cannot be zero" ); } }; } /* namespace quoted_round_robin */ } /* namespace prio_one_thread */ } /* namespace disp */ } /* namespace so_5 */
21.918182
74
0.636251
eao197
e45cd53c74a73fa804416f878ee5dfd9801baa74
6,047
cpp
C++
apps/LkDemo/LkDemo.cpp
hcl3210/opencv
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
[ "BSD-3-Clause" ]
1
2016-05-09T11:42:00.000Z
2016-05-09T11:42:00.000Z
apps/LkDemo/LkDemo.cpp
hcl3210/opencv
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
[ "BSD-3-Clause" ]
null
null
null
apps/LkDemo/LkDemo.cpp
hcl3210/opencv
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
[ "BSD-3-Clause" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/// LkDemo.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "LkDemo.h" #include "MainFrm.h" #include "LkDemoDoc.h" #include "LkDemoView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CLkDemoApp BEGIN_MESSAGE_MAP(CLkDemoApp, CWinApp) //{{AFX_MSG_MAP(CLkDemoApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CLkDemoApp construction CLkDemoApp::CLkDemoApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CLkDemoApp object CLkDemoApp theApp; ///////////////////////////////////////////////////////////////////////////// // CLkDemoApp initialization BOOL CLkDemoApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CLkDemoDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CLkDemoView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CLkDemoApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CLkDemoApp message handlers
31.494792
90
0.680172
hcl3210
e45ce52bd7a604b9356c17d9b009ceb92cc069bb
1,445
cpp
C++
Userland/Applications/PixelPaint/ProjectLoader.cpp
qeeg/serenity
587048dea7465f387b0ef8bbe439060c448bd996
[ "BSD-2-Clause" ]
6
2021-07-05T15:01:19.000Z
2022-03-24T04:42:43.000Z
Userland/Applications/PixelPaint/ProjectLoader.cpp
qeeg/serenity
587048dea7465f387b0ef8bbe439060c448bd996
[ "BSD-2-Clause" ]
2
2022-01-11T13:08:35.000Z
2022-01-12T19:27:53.000Z
Userland/Applications/PixelPaint/ProjectLoader.cpp
qeeg/serenity
587048dea7465f387b0ef8bbe439060c448bd996
[ "BSD-2-Clause" ]
1
2020-03-16T21:37:46.000Z
2020-03-16T21:37:46.000Z
/* * Copyright (c) 2021, Tobias Christiansen <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include "ProjectLoader.h" #include "Image.h" #include "Layer.h" #include <AK/JsonObject.h> #include <AK/Result.h> #include <AK/String.h> #include <LibCore/File.h> #include <LibCore/MappedFile.h> #include <LibImageDecoderClient/Client.h> namespace PixelPaint { ErrorOr<void> ProjectLoader::try_load_from_fd_and_close(int fd, StringView path) { auto file = Core::File::construct(); file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No); if (file->has_error()) return Error::from_errno(file->error()); auto contents = file->read_all(); auto json_or_error = JsonValue::from_string(contents); if (json_or_error.is_error()) { m_is_raw_image = true; auto mapped_file = TRY(Core::MappedFile::map_from_fd_and_close(fd, path)); // FIXME: Find a way to avoid the memory copy here. auto bitmap = TRY(Image::try_decode_bitmap(mapped_file->bytes())); auto image = TRY(Image::try_create_from_bitmap(move(bitmap))); m_image = image; return {}; } close(fd); auto& json = json_or_error.value().as_object(); auto image = TRY(Image::try_create_from_pixel_paint_json(json)); if (json.has("guides")) m_json_metadata = json.get("guides").as_array(); m_image = image; return {}; } }
26.759259
88
0.672664
qeeg
e46f80ba3cc7d93993b02fc35d12cf51659b828c
2,523
cpp
C++
daemon/SummaryBuffer.cpp
rossburton/gator
9d8d75fa08352470c51abc23fe3b314879bd8b78
[ "BSD-3-Clause" ]
118
2015-03-24T16:09:42.000Z
2022-03-21T09:01:59.000Z
daemon/SummaryBuffer.cpp
rossburton/gator
9d8d75fa08352470c51abc23fe3b314879bd8b78
[ "BSD-3-Clause" ]
26
2016-03-03T23:24:08.000Z
2022-03-21T10:24:43.000Z
daemon/SummaryBuffer.cpp
rossburton/gator
9d8d75fa08352470c51abc23fe3b314879bd8b78
[ "BSD-3-Clause" ]
73
2015-06-09T09:44:06.000Z
2021-12-30T09:49:00.000Z
/* Copyright (C) 2013-2020 by Arm Limited. All rights reserved. */ #define BUFFER_USE_SESSION_DATA #include "SummaryBuffer.h" #include "BufferUtils.h" #include "Logging.h" #include "SessionData.h" #include <cstring> SummaryBuffer::SummaryBuffer(const int size, sem_t & readerSem) : buffer(size, readerSem) { // fresh buffer will always have room for header // so no need to check space buffer.beginFrame(FrameType::SUMMARY); } void SummaryBuffer::write(ISender & sender) { buffer.write(sender); } int SummaryBuffer::bytesAvailable() const { return buffer.bytesAvailable(); } void SummaryBuffer::flush() { buffer.endFrame(); buffer.flush(); buffer.waitForSpace(IRawFrameBuilder::MAX_FRAME_HEADER_SIZE); buffer.beginFrame(FrameType::SUMMARY); } void SummaryBuffer::summary(const int64_t timestamp, const int64_t uptime, const int64_t monotonicDelta, const char * const uname, const long pageSize, const bool nosync, const std::map<std::string, std::string> & additionalAttributes) { // This is only called when buffer is empty so no need to wait for space // we assume the additional attributes won't overflow the buffer?? buffer.packInt(static_cast<int32_t>(MessageType::SUMMARY)); buffer.writeString(NEWLINE_CANARY); buffer.packInt64(timestamp); buffer.packInt64(uptime); buffer.packInt64(monotonicDelta); buffer.writeString("uname"); buffer.writeString(uname); buffer.writeString("PAGESIZE"); char buf[32]; snprintf(buf, sizeof(buf), "%li", pageSize); buffer.writeString(buf); if (nosync) { buffer.writeString("nosync"); buffer.writeString(""); } for (const auto & pair : additionalAttributes) { if (!pair.first.empty()) { buffer.writeString(pair.first.c_str()); buffer.writeString(pair.second.c_str()); } } buffer.writeString(""); } void SummaryBuffer::coreName(const int core, const int cpuid, const char * const name) { waitForSpace(3 * buffer_utils::MAXSIZE_PACK32 + 0x100); buffer.packInt(static_cast<int32_t>(MessageType::CORE_NAME)); buffer.packInt(core); buffer.packInt(cpuid); buffer.writeString(name); } void SummaryBuffer::waitForSpace(int bytes) { if (bytes < buffer.bytesAvailable()) { flush(); } buffer.waitForSpace(bytes); }
29
92
0.650416
rossburton
e470a5bea09fc55a1ad16c9b67faa6cad0f85501
1,882
cpp
C++
EightQueen.cpp
chenshiyang/Algorithm-C-
fc0f6c005b773d07ce03861c0f4f0f5411fc84c5
[ "Apache-2.0" ]
null
null
null
EightQueen.cpp
chenshiyang/Algorithm-C-
fc0f6c005b773d07ce03861c0f4f0f5411fc84c5
[ "Apache-2.0" ]
null
null
null
EightQueen.cpp
chenshiyang/Algorithm-C-
fc0f6c005b773d07ce03861c0f4f0f5411fc84c5
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<vector> using namespace std; const int NUM = 8; void print_table(vector<vector<bool>> &table) { cout << "A valid solution: " << endl; for(int i = 0; i != NUM; ++ i) { for(int j = 0; j != NUM; ++ j) { cout << (table[i][j] ? "Q " : "+ "); } cout << "\n"; } cout << endl; } bool dangerous(vector<bool> &row, vector<bool> &col, vector<bool> &left_slant, vector<bool> &right_slant, int i, int j) { return (row[i] || col[j] || left_slant[i + j] || right_slant[i + NUM - 1 - j]); } void backtrack(vector<vector<bool>> &table, vector<bool> &row, vector<bool> &col, vector<bool> &left_slant, vector<bool> &right_slant, int index) { if(index == NUM) { print_table(table); return; } for(int j = 0; j != NUM; ++ j) { if(!dangerous(row, col, left_slant, right_slant, index, j)) { table[index][j] = true;; row[index] = true; col[j] = true; left_slant[index + j] = true; right_slant[index - j + NUM - 1] = true; backtrack(table, row, col, left_slant, right_slant, index + 1); table[index][j] = false; row[index] = false; col[j] = false; left_slant[index + j] = false; right_slant[index - j + NUM - 1] = false; } } } void solve(vector<vector<bool>> &table) { vector<bool> row(NUM, false); vector<bool> col(NUM, false); vector<bool> left_slant(2 * NUM - 1, false); vector<bool> right_slant(2 * NUM - 1, false); backtrack(table, row, col, left_slant, right_slant, 0); } int main() { vector<vector<bool>> table; vector<bool> line(NUM, false); for(int i = 0; i != NUM; ++ i) { table.push_back(line); } solve(table); }
29.873016
148
0.517003
chenshiyang
e4730746fa0db58c2f1a3ad1f4d248d95224ebba
696
cpp
C++
Topology.cpp
TheHolyBell/Hardware3D
1879c498645dfec874ab25497d1c830482bbf0c7
[ "MIT" ]
null
null
null
Topology.cpp
TheHolyBell/Hardware3D
1879c498645dfec874ab25497d1c830482bbf0c7
[ "MIT" ]
null
null
null
Topology.cpp
TheHolyBell/Hardware3D
1879c498645dfec874ab25497d1c830482bbf0c7
[ "MIT" ]
null
null
null
#include "Topology.h" #include "BindableCodex.h" namespace Bind { Topology::Topology(Graphics& gfx, D3D11_PRIMITIVE_TOPOLOGY topology) : m_Topology(topology) { } void Topology::Bind(Graphics& gfx) noxnd { GetContext(gfx)->IASetPrimitiveTopology(m_Topology); } std::string Topology::GetUID() const noexcept { return GenerateUID(m_Topology); } std::shared_ptr<Topology> Topology::Resolve(Graphics& gfx, D3D11_PRIMITIVE_TOPOLOGY topology) { return Codex::Resolve<Topology>(gfx, topology); } std::string Topology::GenerateUID(D3D11_PRIMITIVE_TOPOLOGY topology) { using namespace std::string_literals; return typeid(Topology).name() + "#"s + std::to_string(topology); } }
24
94
0.747126
TheHolyBell
e4743715c23329c9093f27627c9886744d797f27
661
cc
C++
friend-exceptions.cc
waybeforenow/modular-friend
12e35a49a2a3cd2d6482293788ee5223d981f8cf
[ "MIT" ]
null
null
null
friend-exceptions.cc
waybeforenow/modular-friend
12e35a49a2a3cd2d6482293788ee5223d981f8cf
[ "MIT" ]
null
null
null
friend-exceptions.cc
waybeforenow/modular-friend
12e35a49a2a3cd2d6482293788ee5223d981f8cf
[ "MIT" ]
null
null
null
#include "friend-exceptions.h" #include <exception> namespace Friend { runtime_error::runtime_error(const char* file, const size_t line) : what_str(new std::string(file)) { what_str->push_back(':'); what_str->append(std::to_string(line)); } runtime_error::runtime_error(const char* what, const char* file, const size_t line) : what_str(new std::string(file)) { what_str->push_back(':'); what_str->append(std::to_string(line)); what_str->append(" ("); what_str->append(what); what_str->push_back(')'); } const char* runtime_error::what() const noexcept { return what_str->c_str(); } } // namespace Friend
26.44
78
0.665658
waybeforenow
e4772c060b481e349a963de360f6565102585ce0
7,379
cpp
C++
dynamic_vino_lib/src/inferences/object_segmentation.cpp
pqLee/ros2_openvino_toolkit
6ba38446bf9778567be2df14d1141c3669e7ac92
[ "Apache-2.0" ]
120
2018-09-30T05:36:25.000Z
2022-01-28T17:52:47.000Z
dynamic_vino_lib/src/inferences/object_segmentation.cpp
sammysun0711/ros2_openvino_toolkit
f6ed1d367e452c8672d41d739243bdf59ea6f578
[ "Apache-2.0" ]
151
2018-10-16T17:46:24.000Z
2022-03-11T14:38:54.000Z
dynamic_vino_lib/src/inferences/object_segmentation.cpp
sammysun0711/ros2_openvino_toolkit
f6ed1d367e452c8672d41d739243bdf59ea6f578
[ "Apache-2.0" ]
83
2018-09-30T05:09:35.000Z
2022-01-26T04:56:09.000Z
// Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @brief a header file with declaration of ObjectSegmentation class and * ObjectSegmentationResult class * @file object_segmentation.cpp */ #include <memory> #include <string> #include <vector> #include <algorithm> #include <random> #include "dynamic_vino_lib/inferences/object_segmentation.hpp" #include "dynamic_vino_lib/outputs/base_output.hpp" #include "dynamic_vino_lib/slog.hpp" // ObjectSegmentationResult dynamic_vino_lib::ObjectSegmentationResult::ObjectSegmentationResult(const cv::Rect &location) : Result(location) { } // ObjectSegmentation dynamic_vino_lib::ObjectSegmentation::ObjectSegmentation(double show_output_thresh) : show_output_thresh_(show_output_thresh), dynamic_vino_lib::BaseInference() { } dynamic_vino_lib::ObjectSegmentation::~ObjectSegmentation() = default; void dynamic_vino_lib::ObjectSegmentation::loadNetwork( const std::shared_ptr<Models::ObjectSegmentationModel> network) { slog::info << "Loading Network: " << network->getModelCategory() << slog::endl; valid_model_ = network; setMaxBatchSize(network->getMaxBatchSize()); } /** * Deprecated! * This function only support OpenVINO version <=2018R5 */ bool dynamic_vino_lib::ObjectSegmentation::enqueue_for_one_input( const cv::Mat &frame, const cv::Rect &input_frame_loc) { if (width_ == 0 && height_ == 0) { width_ = frame.cols; height_ = frame.rows; } if (!dynamic_vino_lib::BaseInference::enqueue<u_int8_t>(frame, input_frame_loc, 1, 0, valid_model_->getInputName())) { return false; } Result r(input_frame_loc); results_.clear(); results_.emplace_back(r); return true; } bool dynamic_vino_lib::ObjectSegmentation::enqueue( const cv::Mat &frame, const cv::Rect &input_frame_loc) { if (width_ == 0 && height_ == 0) { width_ = frame.cols; height_ = frame.rows; } if (valid_model_ == nullptr || getEngine() == nullptr) { throw std::logic_error("Model or Engine is not set correctly!"); return false; } if (enqueued_frames_ >= valid_model_->getMaxBatchSize()) { slog::warn << "Number of " << getName() << "input more than maximum(" << max_batch_size_ << ") processed by inference" << slog::endl; return false; } if (!valid_model_->enqueue(getEngine(), frame, input_frame_loc)) { return false; } enqueued_frames_ += 1; return true; } bool dynamic_vino_lib::ObjectSegmentation::submitRequest() { return dynamic_vino_lib::BaseInference::submitRequest(); } bool dynamic_vino_lib::ObjectSegmentation::fetchResults() { bool can_fetch = dynamic_vino_lib::BaseInference::fetchResults(); if (!can_fetch) { return false; } bool found_result = false; results_.clear(); InferenceEngine::InferRequest::Ptr request = getEngine()->getRequest(); slog::debug << "Analyzing Detection results..." << slog::endl; std::string detection_output = valid_model_->getOutputName("detection"); std::string mask_output = valid_model_->getOutputName("masks"); const InferenceEngine::Blob::Ptr do_blob = request->GetBlob(detection_output.c_str()); const auto do_data = do_blob->buffer().as<float *>(); const auto masks_blob = request->GetBlob(mask_output.c_str()); const auto masks_data = masks_blob->buffer().as<float *>(); const size_t output_w = masks_blob->getTensorDesc().getDims().at(3); const size_t output_h = masks_blob->getTensorDesc().getDims().at(2); const size_t output_des = masks_blob-> getTensorDesc().getDims().at(1); const size_t output_extra = masks_blob-> getTensorDesc().getDims().at(0); slog::debug << "output w " << output_w<< slog::endl; slog::debug << "output h " << output_h << slog::endl; slog::debug << "output description " << output_des << slog::endl; slog::debug << "output extra " << output_extra << slog::endl; const float * detections = request->GetBlob(detection_output)->buffer().as<float *>(); std::vector<std::string> &labels = valid_model_->getLabels(); slog::debug << "label size " <<labels.size() << slog::endl; cv::Mat inImg, resImg, maskImg(output_h, output_w, CV_8UC3); cv::Mat colored_mask(output_h, output_w, CV_8UC3); cv::Rect roi = cv::Rect(0, 0, output_w, output_h); for (int rowId = 0; rowId < output_h; ++rowId) { for (int colId = 0; colId < output_w; ++colId) { std::size_t classId = 0; float maxProb = -1.0f; if (output_des < 2) { // assume the output is already ArgMax'ed classId = static_cast<std::size_t>(detections[rowId * output_w + colId]); for (int ch = 0; ch < colored_mask.channels();++ch){ colored_mask.at<cv::Vec3b>(rowId, colId)[ch] = colors_[classId][ch]; } //classId = static_cast<std::size_t>(predictions[rowId * output_w + colId]); } else { for (int chId = 0; chId < output_des; ++chId) { float prob = detections[chId * output_h * output_w + rowId * output_w+ colId]; //float prob = predictions[chId * output_h * output_w + rowId * output_w+ colId]; if (prob > maxProb) { classId = chId; maxProb = prob; } } while (classId >= colors_.size()) { static std::mt19937 rng(classId); std::uniform_int_distribution<int> distr(0, 255); cv::Vec3b color(distr(rng), distr(rng), distr(rng)); colors_.push_back(color); } if(maxProb > 0.5){ for (int ch = 0; ch < colored_mask.channels();++ch){ colored_mask.at<cv::Vec3b>(rowId, colId)[ch] = colors_[classId][ch]; } } } } } const float alpha = 0.7f; Result result(roi); result.mask_ = colored_mask; found_result = true; results_.emplace_back(result); return true; } int dynamic_vino_lib::ObjectSegmentation::getResultsLength() const { return static_cast<int>(results_.size()); } const dynamic_vino_lib::Result * dynamic_vino_lib::ObjectSegmentation::getLocationResult(int idx) const { return &(results_[idx]); } const std::string dynamic_vino_lib::ObjectSegmentation::getName() const { return valid_model_->getModelCategory(); } void dynamic_vino_lib::ObjectSegmentation::observeOutput( const std::shared_ptr<Outputs::BaseOutput> &output) { if (output != nullptr) { output->accept(results_); } } const std::vector<cv::Rect> dynamic_vino_lib::ObjectSegmentation::getFilteredROIs( const std::string filter_conditions) const { if (!filter_conditions.empty()) { slog::err << "Object segmentation does not support filtering now! " << "Filter conditions: " << filter_conditions << slog::endl; } std::vector<cv::Rect> filtered_rois; for (auto res : results_) { filtered_rois.push_back(res.getLocation()); } return filtered_rois; }
31.4
94
0.681122
pqLee
e47b4ca64593f882aaeaca2b7a52de6482a4136f
449
cpp
C++
SGE/src/Platform/Vulkan/VulkanRendererAPI.cpp
Stealthhyy/SGE
e56560a93a4d7c9aac2a525240be6d4d9ba3d4e7
[ "Apache-2.0" ]
1
2021-04-25T05:45:28.000Z
2021-04-25T05:45:28.000Z
SGE/src/Platform/Vulkan/VulkanRendererAPI.cpp
Stealthhyy/SGE
e56560a93a4d7c9aac2a525240be6d4d9ba3d4e7
[ "Apache-2.0" ]
null
null
null
SGE/src/Platform/Vulkan/VulkanRendererAPI.cpp
Stealthhyy/SGE
e56560a93a4d7c9aac2a525240be6d4d9ba3d4e7
[ "Apache-2.0" ]
null
null
null
#include "sgepch.h" #include "VulkanRendererAPI.h" #include <glad/glad.h> namespace SGE { void VulkanRendererAPI::Init() { } void VulkanRendererAPI::SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) { } void VulkanRendererAPI::SetClearColor(const glm::vec4& color) { } void VulkanRendererAPI::Clear() { } void VulkanRendererAPI::DrawIndexed(const Ref<VertexArray>& vertexArray, uint32_t indexCount) { } }
14.966667
94
0.726058
Stealthhyy
e47d069bb3a266c8454fa442b094041188ba2741
2,326
hpp
C++
src/CGPCircuit.hpp
xkraut03/evococo
602461bea72a9f2b81e6e8c289f91030266a08ae
[ "Apache-2.0" ]
null
null
null
src/CGPCircuit.hpp
xkraut03/evococo
602461bea72a9f2b81e6e8c289f91030266a08ae
[ "Apache-2.0" ]
null
null
null
src/CGPCircuit.hpp
xkraut03/evococo
602461bea72a9f2b81e6e8c289f91030266a08ae
[ "Apache-2.0" ]
null
null
null
// CGPCircuit.hpp // author: Daniel Kraut // creation date: 10th of September, 2017 // // Copyright © 2017 Daniel Kraut // // 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. // #pragma once #include <array> #include <vector> // CGP parameters const int circuit_num_rows = 5; const int circuit_num_columns = 9; // const int circuit_lback_value = 1; lback is max for now const int circuit_num_inputs = 25; const int circuit_num_outputs = 1; const int circuit_num_functions = 16; struct CGPComponent { int input1; int input2; int function; uint8_t output; }; class CGPCircuit { private: template<const size_t MatrixRows, const size_t MatrixColumns> using ComponentsMatrix = std::array<std::array<CGPComponent, MatrixColumns>, MatrixRows>; ComponentsMatrix<circuit_num_rows, circuit_num_columns> circuit_matrix_; int output_unit_; int tmp_output_; std::array<uint8_t, circuit_num_inputs> input_; std::vector<int> out_candidates; public: using CGPInputArray = std::array<uint8_t, circuit_num_inputs>; void initRandomly(); void mutateRandomly(); void setInput(const CGPInputArray& input); uint8_t getOutput(); bool saveToFile(std::string_view) const; bool loadFromFile(std::string_view); void printBackwards() const; bool switchToLessPower(); int getCircuitLength() const; private: int column_size = circuit_num_rows; // int row_size = circuit_num_columns; void printBackwards(int) const; uint8_t doSpecificOperation(const uint8_t x, const uint8_t y, const int function) const; uint8_t getComponentOutput(const CGPComponent& unit) const; int indexToRow(const int index) const; int indexToColumn(const int index) const; int setLback1(int target, int curr_column); };
30.605263
76
0.726569
xkraut03
e47f66c6b9df1644d9eaf8c12fa96aa243a0c8c5
19,328
hpp
C++
include/http_frame.hpp
jonathonl/IPSuite
76dfd7913388851c6714645252b2caa3c5596dcc
[ "MIT" ]
1
2016-03-01T15:23:13.000Z
2016-03-01T15:23:13.000Z
include/http_frame.hpp
jonathonl/IPSuite
76dfd7913388851c6714645252b2caa3c5596dcc
[ "MIT" ]
null
null
null
include/http_frame.hpp
jonathonl/IPSuite
76dfd7913388851c6714645252b2caa3c5596dcc
[ "MIT" ]
null
null
null
#pragma once #ifndef MANIFOLD_HTTP_FRAME_HPP #define MANIFOLD_HTTP_FRAME_HPP #include <vector> #include <list> #include <cstdint> #include "socket.hpp" #include "http_error_category.hpp" #ifndef MANIFOLD_DISABLE_HTTP2 namespace manifold { namespace http { //================================================================// // enum class errc : std::uint32_t // TODO: Make error_condition // { // no_error = 0x0, // protocol_error = 0x1, // internal_error = 0x2, // flow_control_error = 0x3, // settings_timeout = 0x4, // stream_closed = 0x5, // frame_size_error = 0x6, // refused_stream = 0x7, // cancel = 0x8, // compression_error = 0x9, // connect_error = 0xa, // enhance_your_calm = 0xb, // inadequate_security = 0xc, // http_1_1_required = 0xd // }; //================================================================// //================================================================// class frame_flag { public: static const std::uint8_t end_stream = 0x01; static const std::uint8_t end_headers = 0x04; static const std::uint8_t padded = 0x08; static const std::uint8_t priority = 0x20; }; //================================================================// //================================================================// class frame_payload_base { protected: std::vector<char> buf_; std::uint8_t flags_; public: frame_payload_base(frame_payload_base&& source) : buf_(std::move(source.buf_)), flags_(source.flags_) {} frame_payload_base(std::uint8_t flags) : flags_(flags) {} virtual ~frame_payload_base() {} frame_payload_base& operator=(frame_payload_base&& source) { if (&source != this) { this->buf_ = std::move(source.buf_); this->flags_ = source.flags_; } return *this; } std::uint8_t flags() const; std::uint32_t serialized_length() const; static void recv_frame_payload(socket& sock, frame_payload_base& destination, std::uint32_t payload_size, std::uint8_t flags, const std::function<void(const std::error_code& ec)>& cb); static void send_frame_payload(socket& sock, const frame_payload_base& source, const std::function<void(const std::error_code& ec)>& cb); }; //================================================================// //================================================================// class data_frame : public frame_payload_base { public: data_frame(const char*const data, std::uint32_t datasz, bool end_stream = false, const char*const padding = nullptr, std::uint8_t paddingsz = 0); data_frame(data_frame&& source) : frame_payload_base(std::move(source)) {} data_frame& operator=(data_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~data_frame() {} data_frame split(std::uint32_t num_bytes); const char*const data() const; std::uint32_t data_length() const; const char*const padding() const; std::uint8_t pad_length() const; bool has_end_stream_flag() const { return this->flags_ & frame_flag::end_stream; } bool has_padded_flag() const { return this->flags_ & frame_flag::padded; } private: data_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// struct priority_options { std::uint32_t stream_dependency_id; std::uint8_t weight; bool exclusive; priority_options(std::uint32_t dependency_id, std::uint8_t priority_weight, bool dependency_is_exclusive) { this->stream_dependency_id = dependency_id; this->weight = priority_weight; this->exclusive = dependency_is_exclusive; } }; //================================================================// //================================================================// class headers_frame : public frame_payload_base { private: std::uint8_t bytes_needed_for_pad_length() const; std::uint8_t bytes_needed_for_dependency_id_and_exclusive_flag() const; std::uint8_t bytes_needed_for_weight() const; public: headers_frame(const char*const header_block, std::uint32_t header_block_sz, bool end_headers, bool end_stream, const char*const padding = nullptr, std::uint8_t paddingsz = 0); headers_frame(const char*const header_block, std::uint32_t header_block_sz, bool end_headers, bool end_stream, priority_options priority_ops, const char*const padding = nullptr, std::uint8_t paddingsz = 0); headers_frame(headers_frame&& source) : frame_payload_base(std::move(source)) {} headers_frame& operator=(headers_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~headers_frame() {} const char*const header_block_fragment() const; std::uint32_t header_block_fragment_length() const; const char*const padding() const; std::uint8_t pad_length() const; std::uint8_t weight() const; std::uint32_t stream_dependency_id() const; bool exclusive_stream_dependency() const; bool has_end_stream_flag() const { return this->flags_ & frame_flag::end_stream; } bool has_end_headers_flag() const { return this->flags_ & frame_flag::end_headers; } bool has_padded_flag() const { return this->flags_ & frame_flag::padded; } bool has_priority_flag() const { return this->flags_ & frame_flag::priority; } private: headers_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class priority_frame : public frame_payload_base { public: priority_frame(priority_options options); priority_frame(priority_frame&& source) : frame_payload_base(std::move(source)) {} priority_frame& operator=(priority_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~priority_frame() {} std::uint8_t weight() const; std::uint32_t stream_dependency_id() const; bool exclusive_stream_dependency() const; private: priority_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class rst_stream_frame : public frame_payload_base { public: rst_stream_frame(http::v2_errc error_code); rst_stream_frame(rst_stream_frame&& source) : frame_payload_base(std::move(source)) {} rst_stream_frame& operator=(rst_stream_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~rst_stream_frame() {} std::uint32_t error_code() const; private: rst_stream_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// class ack_flag { }; //================================================================// class settings_frame : public frame_payload_base { public: settings_frame(ack_flag) : frame_payload_base(0x1) {} settings_frame(std::list<std::pair<std::uint16_t,std::uint32_t>>::const_iterator beg, std::list<std::pair<std::uint16_t,std::uint32_t>>::const_iterator end); settings_frame(settings_frame&& source) : frame_payload_base(std::move(source)) {} settings_frame& operator=(settings_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~settings_frame() {} bool has_ack_flag() const { return (bool)(this->flags_ & 0x1); } std::list<std::pair<std::uint16_t,std::uint32_t>> settings() const; private: settings_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class push_promise_frame : public frame_payload_base // TODO: Impl optional padding. Also flags need to looked at!! { public: push_promise_frame(const char*const header_block, std::uint32_t header_block_sz, std::uint32_t promise_stream_id, bool end_headers, const char*const padding = nullptr, std::uint8_t paddingsz = 0); push_promise_frame(push_promise_frame&& source) : frame_payload_base(std::move(source)) {} push_promise_frame& operator=(push_promise_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~push_promise_frame() {} const char*const header_block_fragment() const; std::uint32_t header_block_fragment_length() const; const char*const padding() const; std::uint8_t pad_length() const; std::uint32_t promised_stream_id() const; bool has_end_headers_flag() const { return this->flags_ & frame_flag::end_headers; } private: push_promise_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class ping_frame : public frame_payload_base { public: ping_frame(std::uint64_t ping_data, bool ack = false); ping_frame(ping_frame&& source) : frame_payload_base(std::move(source)) {} ping_frame& operator=(ping_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~ping_frame() {} bool is_ack() const { return (bool)(this->flags_ & 0x1); } std::uint64_t data() const; private: ping_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class goaway_frame : public frame_payload_base { public: goaway_frame(std::uint32_t last_stream_id, http::v2_errc error_code, const char*const addl_error_data, std::uint32_t addl_error_data_sz); goaway_frame(goaway_frame&& source) : frame_payload_base(std::move(source)) {} goaway_frame& operator=(goaway_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~goaway_frame() {} std::uint32_t last_stream_id() const; http::v2_errc error_code() const; const char*const additional_debug_data() const; std::uint32_t additional_debug_data_length() const; private: goaway_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class window_update_frame : public frame_payload_base { public: window_update_frame(std::uint32_t window_size_increment); window_update_frame(window_update_frame&& source) : frame_payload_base(std::move(source)) {} window_update_frame& operator=(window_update_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~window_update_frame() {} std::uint32_t window_size_increment() const; private: window_update_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// class continuation_frame : public frame_payload_base { public: continuation_frame(const char*const header_data, std::uint32_t header_data_sz, bool end_headers); continuation_frame(continuation_frame&& source) : frame_payload_base(std::move(source)) {} continuation_frame& operator=(continuation_frame&& source) { frame_payload_base::operator=(std::move(source)); return *this; } ~continuation_frame() {} const char*const header_block_fragment() const; std::uint32_t header_block_fragment_length() const; bool has_end_headers_flag() const { return this->flags_ & frame_flag::end_headers; } private: continuation_frame() : frame_payload_base(0) {} friend class frame; }; //================================================================// //================================================================// enum class frame_type : std::uint8_t { data = 0x0, headers, priority, rst_stream, settings, push_promise, ping, goaway, window_update, continuation, invalid_type = 0xFF }; //================================================================// //================================================================// class frame { public: //----------------------------------------------------------------// static const http::data_frame default_data_frame_ ; static const http::headers_frame default_headers_frame_ ; static const http::priority_frame default_priority_frame_ ; static const http::rst_stream_frame default_rst_stream_frame_ ; static const http::settings_frame default_settings_frame_ ; static const http::push_promise_frame default_push_promise_frame_ ; static const http::ping_frame default_ping_frame_ ; static const http::goaway_frame default_goaway_frame_ ; static const http::window_update_frame default_window_update_frame_; static const http::continuation_frame default_continuation_frame_ ; //----------------------------------------------------------------// //----------------------------------------------------------------// static void recv_frame(manifold::socket& sock, frame& destination, const std::function<void(const std::error_code& ec)>& cb); static void send_frame(manifold::socket& sock, const frame& source, const std::function<void(const std::error_code& ec)>& cb); //----------------------------------------------------------------// private: //----------------------------------------------------------------// union payload_union { //----------------------------------------------------------------// http::data_frame data_frame_; http::headers_frame headers_frame_; http::priority_frame priority_frame_; http::rst_stream_frame rst_stream_frame_; http::settings_frame settings_frame_; http::push_promise_frame push_promise_frame_; http::ping_frame ping_frame_; http::goaway_frame goaway_frame_; http::window_update_frame window_update_frame_; http::continuation_frame continuation_frame_; //----------------------------------------------------------------// //----------------------------------------------------------------// payload_union(){} ~payload_union(){} //----------------------------------------------------------------// }; //----------------------------------------------------------------// private: //----------------------------------------------------------------// payload_union payload_; std::array<char, 9> metadata_; //----------------------------------------------------------------// //----------------------------------------------------------------// void destroy_union(); void init_meta(frame_type t, std::uint32_t payload_length, std::uint32_t stream_id, std::uint8_t flags); std::uint8_t flags() const; frame(const frame&) = delete; frame& operator=(const frame&) = delete; //----------------------------------------------------------------// public: //----------------------------------------------------------------// frame(); frame(http::data_frame&& payload, std::uint32_t stream_id); frame(http::headers_frame&& payload, std::uint32_t stream_id); frame(http::priority_frame&& payload, std::uint32_t stream_id); frame(http::rst_stream_frame&& payload, std::uint32_t stream_id); frame(http::settings_frame&& payload, std::uint32_t stream_id); frame(http::push_promise_frame&& payload, std::uint32_t stream_id); frame(http::ping_frame&& payload, std::uint32_t stream_id); frame(http::goaway_frame&& payload, std::uint32_t stream_id); frame(http::window_update_frame&& payload, std::uint32_t stream_id); frame(http::continuation_frame&& payload, std::uint32_t stream_id); frame(frame&& source); ~frame(); frame& operator=(frame&& source); //----------------------------------------------------------------// //----------------------------------------------------------------// template <typename T> bool is() const; std::uint32_t payload_length() const; frame_type type() const; std::uint32_t stream_id() const; //----------------------------------------------------------------// //----------------------------------------------------------------// http::data_frame& data_frame() ; http::headers_frame& headers_frame() ; http::priority_frame& priority_frame() ; http::rst_stream_frame& rst_stream_frame() ; http::settings_frame& settings_frame() ; http::push_promise_frame& push_promise_frame() ; http::ping_frame& ping_frame() ; http::goaway_frame& goaway_frame() ; http::window_update_frame& window_update_frame(); http::continuation_frame& continuation_frame() ; const http::data_frame& data_frame() const; const http::headers_frame& headers_frame() const; const http::priority_frame& priority_frame() const; const http::rst_stream_frame& rst_stream_frame() const; const http::settings_frame& settings_frame() const; const http::push_promise_frame& push_promise_frame() const; const http::ping_frame& ping_frame() const; const http::goaway_frame& goaway_frame() const; const http::window_update_frame& window_update_frame() const; const http::continuation_frame& continuation_frame() const; //----------------------------------------------------------------// }; //================================================================// } } #endif //MANIFOLD_DISABLE_HTTP2 #endif //MANIFOLD_HTTP_FRAME_HPP
41.036093
212
0.527318
jonathonl
6b00c0e9e77f92465f60759944c1f0b4effce707
2,194
hpp
C++
src/polybench/POLYBENCH_FLOYD_WARSHALL.hpp
woodard/RAJAPerf
14a64c4fd124868018735d7bed5ffb5269b519c9
[ "BSD-3-Clause" ]
null
null
null
src/polybench/POLYBENCH_FLOYD_WARSHALL.hpp
woodard/RAJAPerf
14a64c4fd124868018735d7bed5ffb5269b519c9
[ "BSD-3-Clause" ]
null
null
null
src/polybench/POLYBENCH_FLOYD_WARSHALL.hpp
woodard/RAJAPerf
14a64c4fd124868018735d7bed5ffb5269b519c9
[ "BSD-3-Clause" ]
1
2019-06-11T13:43:36.000Z
2019-06-11T13:43:36.000Z
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2017-19, Lawrence Livermore National Security, LLC // and RAJA Performance Suite project contributors. // See the RAJAPerf/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// /// /// POLYBENCH_FLOYD_WARSHALL kernel reference implementation: /// /// Note: kernel is altered to enable parallelism (original did not have /// separate input and output arrays). /// /// for (Index_type k = 0; k < N; k++) { /// for (Index_type i = 0; i < N; i++) { /// for (Index_type j = 0; j < N; j++) { /// pout[i][j] = pin[i][j] < pin[i][k] + pin[k][j] ? /// pin[i][j] : pin[i][k] + pin[k][j]; /// } /// } /// } #ifndef RAJAPerf_POLYBENCH_FLOYD_WARSHALL_HPP #define RAJAPerf_POLYBENCH_FLOYD_WARSHALL_HPP #define POLYBENCH_FLOYD_WARSHALL_BODY \ pout[j + i*N] = pin[j + i*N] < pin[k + i*N] + pin[j + k*N] ? \ pin[j + i*N] : pin[k + i*N] + pin[j + k*N]; #define POLYBENCH_FLOYD_WARSHALL_BODY_RAJA \ poutview(i, j) = pinview(i, j) < pinview(i, k) + pinview(k, j) ? \ pinview(i, j) : pinview(i, k) + pinview(k, j); #define POLYBENCH_FLOYD_WARSHALL_VIEWS_RAJA \ using VIEW_TYPE = RAJA::View<Real_type, \ RAJA::Layout<2, Index_type, 1>>; \ \ VIEW_TYPE pinview(pin, RAJA::Layout<2>(N, N)); \ VIEW_TYPE poutview(pout, RAJA::Layout<2>(N, N)); #include "common/KernelBase.hpp" namespace rajaperf { class RunParams; namespace polybench { class POLYBENCH_FLOYD_WARSHALL : public KernelBase { public: POLYBENCH_FLOYD_WARSHALL(const RunParams& params); ~POLYBENCH_FLOYD_WARSHALL(); void setUp(VariantID vid); void runKernel(VariantID vid); void updateChecksum(VariantID vid); void tearDown(VariantID vid); void runCudaVariant(VariantID vid); void runOpenMPTargetVariant(VariantID vid); private: Index_type m_N; Real_ptr m_pin; Real_ptr m_pout; }; } // end namespace polybench } // end namespace rajaperf #endif // closing endif for header file include guard
26.433735
79
0.596627
woodard
6b01bb3f25456bcf86ee4a198f7e9291d1b90d51
752
cpp
C++
text file.cpp
lazarevtill/mirealabs
fcd57fd036ad987bc8b0545cb7b3f7bdd29fc215
[ "MIT" ]
1
2020-04-30T14:09:21.000Z
2020-04-30T14:09:21.000Z
text file.cpp
lazarevtill/mirealabs
fcd57fd036ad987bc8b0545cb7b3f7bdd29fc215
[ "MIT" ]
null
null
null
text file.cpp
lazarevtill/mirealabs
fcd57fd036ad987bc8b0545cb7b3f7bdd29fc215
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { //const std::string source;//где ищем const std::string lexeme = "g";//что ищем std::string source; std::ifstream inf; inf.open("myfile.txt");//if (!inf)cerr //------------------------- getline(inf, source, '\0'); //------------------------- inf.close(); unsigned lexeme_count = 0; for (std::size_t pos = 0; pos < source.size(); pos += lexeme.size()) { pos = source.find(lexeme, pos); if (pos != std::string::npos) { ++lexeme_count; } else { break; } } std::cout << "Result: " << lexeme_count << std::endl;//сколько вхождений }
20.324324
74
0.551862
lazarevtill
6b035add0b6daa8d234ad47186246d2cff5ee694
4,228
cc
C++
src/ast/decorated_variable_test.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
src/ast/decorated_variable_test.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
src/ast/decorated_variable_test.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint 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 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/ast/decorated_variable.h" #include "gtest/gtest.h" #include "src/ast/binding_decoration.h" #include "src/ast/builtin_decoration.h" #include "src/ast/constant_id_decoration.h" #include "src/ast/identifier_expression.h" #include "src/ast/location_decoration.h" #include "src/ast/set_decoration.h" #include "src/ast/type/f32_type.h" #include "src/ast/type/i32_type.h" #include "src/ast/variable.h" #include "src/ast/variable_decoration.h" namespace tint { namespace ast { namespace { using DecoratedVariableTest = testing::Test; TEST_F(DecoratedVariableTest, Creation) { type::I32Type t; auto var = std::make_unique<Variable>("my_var", StorageClass::kFunction, &t); DecoratedVariable dv(std::move(var)); EXPECT_EQ(dv.name(), "my_var"); EXPECT_EQ(dv.storage_class(), StorageClass::kFunction); EXPECT_EQ(dv.type(), &t); EXPECT_EQ(dv.line(), 0u); EXPECT_EQ(dv.column(), 0u); } TEST_F(DecoratedVariableTest, CreationWithSource) { Source s{27, 4}; type::F32Type t; auto var = std::make_unique<Variable>(s, "i", StorageClass::kPrivate, &t); DecoratedVariable dv(std::move(var)); EXPECT_EQ(dv.name(), "i"); EXPECT_EQ(dv.storage_class(), StorageClass::kPrivate); EXPECT_EQ(dv.type(), &t); EXPECT_EQ(dv.line(), 27u); EXPECT_EQ(dv.column(), 4u); } TEST_F(DecoratedVariableTest, NoDecorations) { type::I32Type t; auto var = std::make_unique<Variable>("my_var", StorageClass::kFunction, &t); DecoratedVariable dv(std::move(var)); EXPECT_FALSE(dv.HasLocationDecoration()); EXPECT_FALSE(dv.HasBuiltinDecoration()); EXPECT_FALSE(dv.HasConstantIdDecoration()); } TEST_F(DecoratedVariableTest, WithDecorations) { type::F32Type t; auto var = std::make_unique<Variable>("my_var", StorageClass::kFunction, &t); DecoratedVariable dv(std::move(var)); VariableDecorationList decos; decos.push_back(std::make_unique<LocationDecoration>(1)); decos.push_back(std::make_unique<BuiltinDecoration>(ast::Builtin::kPosition)); decos.push_back(std::make_unique<ConstantIdDecoration>(1200)); dv.set_decorations(std::move(decos)); EXPECT_TRUE(dv.HasLocationDecoration()); EXPECT_TRUE(dv.HasBuiltinDecoration()); EXPECT_TRUE(dv.HasConstantIdDecoration()); } TEST_F(DecoratedVariableTest, ConstantId) { type::F32Type t; auto var = std::make_unique<Variable>("my_var", StorageClass::kFunction, &t); DecoratedVariable dv(std::move(var)); VariableDecorationList decos; decos.push_back(std::make_unique<ConstantIdDecoration>(1200)); dv.set_decorations(std::move(decos)); EXPECT_EQ(dv.constant_id(), 1200u); } TEST_F(DecoratedVariableTest, IsValid) { type::I32Type t; auto var = std::make_unique<Variable>("my_var", StorageClass::kNone, &t); DecoratedVariable dv(std::move(var)); EXPECT_TRUE(dv.IsValid()); } TEST_F(DecoratedVariableTest, IsDecorated) { DecoratedVariable dv; EXPECT_TRUE(dv.IsDecorated()); } TEST_F(DecoratedVariableTest, to_str) { type::F32Type t; auto var = std::make_unique<Variable>("my_var", StorageClass::kFunction, &t); DecoratedVariable dv(std::move(var)); dv.set_constructor(std::make_unique<IdentifierExpression>("expr")); VariableDecorationList decos; decos.push_back(std::make_unique<BindingDecoration>(2)); decos.push_back(std::make_unique<SetDecoration>(1)); dv.set_decorations(std::move(decos)); std::ostringstream out; dv.to_str(out, 2); EXPECT_EQ(out.str(), R"( DecoratedVariable{ Decorations{ BindingDecoration{2} SetDecoration{1} } my_var function __f32 { Identifier{expr} } } )"); } } // namespace } // namespace ast } // namespace tint
29.985816
80
0.730369
dorba
6b068242a3f0dab24e125eb9d33607cfacdd1b8f
2,500
hpp
C++
DFNs/Executors/PerspectiveNPointSolving/PerspectiveNPointSolvingExecutor.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
DFNs/Executors/PerspectiveNPointSolving/PerspectiveNPointSolvingExecutor.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
DFNs/Executors/PerspectiveNPointSolving/PerspectiveNPointSolvingExecutor.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @addtogroup DFNs * @{ */ #ifndef PERSPECTIVENPOINTSOLVING_EXECUTOR_HPP #define PERSPECTIVENPOINTSOLVING_EXECUTOR_HPP #include "DFNCommonInterface.hpp" #include <PerspectiveNPointSolving/PerspectiveNPointSolvingInterface.hpp> #include <Types/CPP/Pose.hpp> #include <Types/CPP/VisualPointFeatureVector2D.hpp> #include <Types/CPP/PointCloud.hpp> namespace CDFF { namespace DFN { namespace Executors { /** * All the methods in this file execute the DFN for the computation of a camera pose from 3d points and matching 2d points. * A DFN instance has to be passed in the constructor of these class. Each method takes the following parameters: * @param inputMatches: input matches between 2d features of images taken by two cameras; * @param inputPose: pose of the second camera in the reference system of the first camera; * @param outputCloud: output point cloud. * * The main difference between the four methods are input and output types: * Methods (i) and (ii) have the constant pointer as input, Methods (iii) and (iv) have a constant reference as input; * Methods (i) and (iii) are non-creation methods, they give constant pointers as output, the output is just the output reference in the DFN; * When using creation methods, the output has to be initialized to NULL. * Methods (ii) and (iv) are creation methods, they copy the output of the DFN in the referenced output variable. Method (ii) takes a pointer, method (iv) takes a reference. */ void Execute(PerspectiveNPointSolvingInterface* dfn, PointCloudWrapper::PointCloudConstPtr inputCloud, VisualPointFeatureVector2DWrapper::VisualPointFeatureVector2DConstPtr inputKeypoints, PoseWrapper::Pose3DConstPtr& outputPose, bool& success); void Execute(PerspectiveNPointSolvingInterface* dfn, PointCloudWrapper::PointCloudConstPtr inputCloud, VisualPointFeatureVector2DWrapper::VisualPointFeatureVector2DConstPtr inputKeypoints, PoseWrapper::Pose3DPtr outputPose, bool& success); void Execute(PerspectiveNPointSolvingInterface* dfn, const PointCloudWrapper::PointCloud& inputCloud, const VisualPointFeatureVector2DWrapper::VisualPointFeatureVector2D& inputKeypoints, PoseWrapper::Pose3DConstPtr& outputPose, bool& success); void Execute(PerspectiveNPointSolvingInterface* dfn, const PointCloudWrapper::PointCloud& inputCloud, const VisualPointFeatureVector2DWrapper::VisualPointFeatureVector2D& inputKeypoints, PoseWrapper::Pose3D& outputPose, bool& success); } } } #endif // PERSPECTIVENPOINTSOLVING_EXECUTOR_HPP /** @} */
50
172
0.8108
H2020-InFuse
6b08b4ee5129bbb1564727a367e2e3bcdcd6b66f
1,845
cpp
C++
test/map_tests.cpp
jmsktm/CarND-Path-Planning-Project
f23f673655ba95a9e8c1e8b01f4d971631cb4880
[ "MIT" ]
1
2019-11-18T00:35:08.000Z
2019-11-18T00:35:08.000Z
test/map_tests.cpp
jmsktm/CarND-Path-Planning-Project
f23f673655ba95a9e8c1e8b01f4d971631cb4880
[ "MIT" ]
null
null
null
test/map_tests.cpp
jmsktm/CarND-Path-Planning-Project
f23f673655ba95a9e8c1e8b01f4d971631cb4880
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <string> #include <vector> #include "../src/map.h" #include "../src/waypoint.h" using std::string; using std::vector; TEST_CASE("Map should contain a list of endpoints on initialization") { Map map = Map(); vector<Waypoint> waypoints = map.getWaypoints(); REQUIRE(waypoints.size() == 181); // There are 181 waypoints in provided data file. REQUIRE(map.get_waypoints_x().size() == 181); REQUIRE(map.get_waypoints_y().size() == 181); REQUIRE(map.get_waypoints_s().size() == 181); REQUIRE(map.get_waypoints_dx().size() == 181); REQUIRE(map.get_waypoints_dy().size() == 181); } SCENARIO("Test for waypoints against data from provided file") { Map map = Map(); vector<Waypoint> waypoints = map.getWaypoints(); // Rounding off to account for unpredictably changing precision #define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d)) auto [row, x, y, s, dx, dy] = GENERATE(table<int, double, double, double, double, double> ({ { 0, 784.6, 1135.57, 0, -0.0235983, -0.999722}, { 1, 815.268, 1134.93, 30.6745, -0.0109948, -0.99994 } })); GIVEN("Given the records in data/highway_map.csv") WHEN("I consider row: " << row) THEN("I should have (x, y, s, dx, dy) == (" << x << ", " << y << ", " << s << ", " << dx << ", " << dy << ")") { std::cout << "(" << x << ", " << y << ", " << s << ", " << dx << ", " << dy << ")" << std::endl; REQUIRE(roundz(waypoints.at(row).get_x(), 2) == roundz(x, 2)); REQUIRE(roundz(waypoints.at(row).get_y(), 2) == roundz(y, 2)); REQUIRE(roundz(waypoints.at(row).get_s(), 2) == roundz(s, 2)); REQUIRE(roundz(waypoints.at(row).get_dx(), 2) == roundz(dx, 2)); REQUIRE(roundz(waypoints.at(row).get_dy(), 2) == roundz(dy, 2)); } }
40.108696
116
0.582114
jmsktm
6b08fe9f98e5c286507ff4b048e1f2c44830bd43
6,675
hpp
C++
Source/VkToolbox/Camera.hpp
glampert/VulkanDemo
cd9cae2dcbc790bbe6c42f811cb3aee792242ae0
[ "MIT" ]
null
null
null
Source/VkToolbox/Camera.hpp
glampert/VulkanDemo
cd9cae2dcbc790bbe6c42f811cb3aee792242ae0
[ "MIT" ]
null
null
null
Source/VkToolbox/Camera.hpp
glampert/VulkanDemo
cd9cae2dcbc790bbe6c42f811cb3aee792242ae0
[ "MIT" ]
null
null
null
#pragma once // ================================================================================================ // File: VkToolbox/Camera.hpp // Author: Guilherme R. Lampert // Created on: 24/04/17 // Brief: Simple first person camera. // ================================================================================================ #include "Utils.hpp" #include "External.hpp" namespace VkToolbox { // ======================================================== // class Camera: // ======================================================== class Camera final { public: // // First person camera // // (up) // +Y +Z (forward) // | / // | / // | / // + ------ +X (right) // (eye) // Vector3 right; Vector3 up; Vector3 forward; Vector3 eye; Matrix4 viewMatrix; Matrix4 projMatrix; Matrix4 vpMatrix; float rotateSpeed = 27.0f; // Mouse rotation float moveSpeed = 6.0f; // Keyboard camera movement float maxPitchAngle = 89.5f; // Max degrees of rotation to avoid lock float pitchAmount = 0.0f; // Stored from latest update float fovYDegrees = 0.0f; // Set via constructor or adjustFov() (in degrees!) float aspectRatio = 0.0f; // srcWidth / scrHeight float nearPlane = 0.0f; // zNear float farPlane = 0.0f; // zFar enum MoveDir { Forward, // Move forward relative to the camera's space Back, // Move backward relative to the camera's space Left, // Move left relative to the camera's space Right // Move right relative to the camera's space }; Camera() = default; void setup(const float scrWidth, const float scrHeight, const float fovYDegs, const float zNear, const float zFar, const Vector3 & rV, const Vector3 & upV, const Vector3 & fwdV, const Vector3 & eyePos) { right = rV; up = upV; forward = fwdV; eye = eyePos; viewMatrix = Matrix4::identity(); vpMatrix = Matrix4::identity(); adjustFov(scrWidth, scrHeight, fovYDegs, zNear, zFar); } void adjustFov(const float scrWidth, const float scrHeight, const float fovYDegs, const float zNear, const float zFar) { fovYDegrees = fovYDegs; aspectRatio = scrWidth / scrHeight; nearPlane = zNear; farPlane = zFar; projMatrix = Matrix4::perspective(fovYDegrees * DegToRad, aspectRatio, nearPlane, farPlane); } void pitch(const float angle) { // Pitches camera by 'angle' radians. forward = rotateAroundAxis(forward, right, angle); // Calculate new forward. up = cross(forward, right); // Calculate new camera up vector. } void rotate(const float angle) { // Rotates around world Y-axis by the given angle (in radians). const float sinAng = std::sin(angle); const float cosAng = std::cos(angle); float xxx, zzz; // Rotate forward vector: xxx = forward[0]; zzz = forward[2]; forward[0] = xxx * cosAng + zzz * sinAng; forward[2] = xxx * -sinAng + zzz * cosAng; // Rotate up vector: xxx = up[0]; zzz = up[2]; up[0] = xxx * cosAng + zzz * sinAng; up[2] = xxx * -sinAng + zzz * cosAng; // Rotate right vector: xxx = right[0]; zzz = right[2]; right[0] = xxx * cosAng + zzz * sinAng; right[2] = xxx * -sinAng + zzz * cosAng; } void move(const MoveDir dir, const float amount) { switch (dir) { case Camera::Forward : eye += forward * amount; break; case Camera::Back : eye -= forward * amount; break; case Camera::Left : eye -= right * amount; break; case Camera::Right : eye += right * amount; break; } // switch (dir) } void checkKeyboardMovement(const bool wDown, const bool sDown, const bool aDown, const bool dDown, const float deltaSeconds) { if (aDown) { move(Camera::Left, moveSpeed * deltaSeconds); } if (dDown) { move(Camera::Right, moveSpeed * deltaSeconds); } if (wDown) { move(Camera::Forward, moveSpeed * deltaSeconds); } if (sDown) { move(Camera::Back, moveSpeed * deltaSeconds); } } void checkMouseRotation(const int mouseDeltaX, const int mouseDeltaY, const float deltaSeconds) { // Rotate left/right: float amt = mouseDeltaX * rotateSpeed * deltaSeconds; rotate(amt * DegToRad); // Calculate amount to rotate up/down: amt = mouseDeltaY * rotateSpeed * deltaSeconds; // Clamp pitch amount: if ((pitchAmount + amt) <= -maxPitchAngle) { amt = -maxPitchAngle - pitchAmount; pitchAmount = -maxPitchAngle; } else if ((pitchAmount + amt) >= maxPitchAngle) { amt = maxPitchAngle - pitchAmount; pitchAmount = maxPitchAngle; } else { pitchAmount += amt; } pitch(-amt * DegToRad); } void updateMatrices() { viewMatrix = Matrix4::lookAt(Point3{ eye }, lookAtTarget(), -up); vpMatrix = projMatrix * viewMatrix; // Vectormath lib uses column-major OGL style, so multiply P*V*M } Point3 lookAtTarget() const { return { eye[0] + forward[0], eye[1] + forward[1], eye[2] + forward[2] }; } static Vector3 rotateAroundAxis(const Vector3 & vec, const Vector3 & axis, const float angle) { const float sinAng = std::sin(angle); const float cosAng = std::cos(angle); const float oneMinusCosAng = (1.0f - cosAng); const float aX = axis[0]; const float aY = axis[1]; const float aZ = axis[2]; float x = (aX * aX * oneMinusCosAng + cosAng) * vec[0] + (aX * aY * oneMinusCosAng + aZ * sinAng) * vec[1] + (aX * aZ * oneMinusCosAng - aY * sinAng) * vec[2]; float y = (aX * aY * oneMinusCosAng - aZ * sinAng) * vec[0] + (aY * aY * oneMinusCosAng + cosAng) * vec[1] + (aY * aZ * oneMinusCosAng + aX * sinAng) * vec[2]; float z = (aX * aZ * oneMinusCosAng + aY * sinAng) * vec[0] + (aY * aZ * oneMinusCosAng - aX * sinAng) * vec[1] + (aZ * aZ * oneMinusCosAng + cosAng) * vec[2]; return { x, y, z }; } }; } // namespace VkToolbox
32.560976
110
0.523296
glampert
6b0eef0248262580b298fe3acf93129e143788e5
221
cpp
C++
src/Native/search_bndm64.cpp
tcwz/vs-chromium
81b39383940f17c642f5a4fbfe2b881768c315bc
[ "BSD-3-Clause" ]
251
2015-02-26T21:28:34.000Z
2022-03-30T12:32:12.000Z
src/Native/search_bndm64.cpp
tcwz/vs-chromium
81b39383940f17c642f5a4fbfe2b881768c315bc
[ "BSD-3-Clause" ]
72
2015-03-11T03:54:46.000Z
2022-01-21T10:23:12.000Z
src/Native/search_bndm64.cpp
tcwz/vs-chromium
81b39383940f17c642f5a4fbfe2b881768c315bc
[ "BSD-3-Clause" ]
88
2015-03-04T07:02:26.000Z
2022-01-30T23:06:31.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 "stdafx.h" #include "search_bndm64.h"
27.625
74
0.723982
tcwz
6b107ce024a153f730255300ee26f9926cb7fff9
8,971
hpp
C++
INCLUDE/Vcl/fmtbcd.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
1
2022-01-13T01:03:55.000Z
2022-01-13T01:03:55.000Z
INCLUDE/Vcl/fmtbcd.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
INCLUDE/Vcl/fmtbcd.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'FMTBcd.pas' rev: 6.00 #ifndef FMTBcdHPP #define FMTBcdHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Variants.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Fmtbcd { //-- type declarations ------------------------------------------------------- struct TBcd; typedef TBcd *PBcd; #pragma pack(push, 1) struct TBcd { Byte Precision; Byte SignSpecialPlaces; Byte Fraction[32]; } ; #pragma pack(pop) class DELPHICLASS EBcdException; class PASCALIMPLEMENTATION EBcdException : public Sysutils::Exception { typedef Sysutils::Exception inherited; public: #pragma option push -w-inl /* Exception.Create */ inline __fastcall EBcdException(const AnsiString Msg) : Sysutils::Exception(Msg) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall EBcdException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall EBcdException(int Ident)/* overload */ : Sysutils::Exception(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall EBcdException(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall EBcdException(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall EBcdException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall EBcdException(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall EBcdException(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~EBcdException(void) { } #pragma option pop }; class DELPHICLASS EBcdOverflowException; class PASCALIMPLEMENTATION EBcdOverflowException : public EBcdException { typedef EBcdException inherited; public: #pragma option push -w-inl /* Exception.Create */ inline __fastcall EBcdOverflowException(const AnsiString Msg) : EBcdException(Msg) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall EBcdOverflowException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : EBcdException(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall EBcdOverflowException(int Ident)/* overload */ : EBcdException(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall EBcdOverflowException(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : EBcdException(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall EBcdOverflowException(const AnsiString Msg, int AHelpContext) : EBcdException(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall EBcdOverflowException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : EBcdException(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall EBcdOverflowException(int Ident, int AHelpContext)/* overload */ : EBcdException(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall EBcdOverflowException(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : EBcdException(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~EBcdOverflowException(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- static const Shortint MaxStringDigits = 0x64; static const short _NoDecimal = 0xffffff01; static const Shortint _DefaultDecimals = 0xa; static const Shortint MaxFMTBcdFractionSize = 0x40; static const Shortint MaxFMTBcdDigits = 0x20; static const Shortint DefaultFMTBcdScale = 0x6; static const Shortint MaxBcdPrecision = 0x12; static const Shortint MaxBcdScale = 0x4; extern PACKAGE TBcd NullBcd; extern PACKAGE Variant __fastcall VarFMTBcdCreate(const AnsiString AValue, Word Precision, Word Scale)/* overload */; extern PACKAGE Variant __fastcall VarFMTBcdCreate(const double AValue, Word Precision = (Word)(0x12), Word Scale = (Word)(0x4))/* overload */; extern PACKAGE void __fastcall VarFMTBcdCreate(Variant &ADest, const TBcd &ABcd)/* overload */; extern PACKAGE Variant __fastcall VarFMTBcdCreate()/* overload */; extern PACKAGE Variant __fastcall VarFMTBcdCreate(const TBcd &ABcd)/* overload */; extern PACKAGE bool __fastcall VarIsFMTBcd(const Variant &AValue)/* overload */; extern PACKAGE Word __fastcall VarFMTBcd(void); extern PACKAGE TBcd __fastcall StrToBcd(const AnsiString AValue); extern PACKAGE void __fastcall DoubleToBcd(const double AValue, TBcd &bcd)/* overload */; extern PACKAGE TBcd __fastcall DoubleToBcd(const double AValue)/* overload */; extern PACKAGE TBcd __fastcall VarToBcd(const Variant &AValue); extern PACKAGE TBcd __fastcall IntegerToBcd(const int AValue); extern PACKAGE double __fastcall BcdToDouble(const TBcd &Bcd); extern PACKAGE int __fastcall BcdToInteger(const TBcd &Bcd, bool Truncate = false); extern PACKAGE bool __fastcall TryStrToBcd(const AnsiString AValue, TBcd &Bcd); extern PACKAGE bool __fastcall NormalizeBcd(const TBcd &InBcd, TBcd &OutBcd, const Word Prec, const Word Scale); extern PACKAGE int __fastcall BcdCompare(const TBcd &bcd1, const TBcd &bcd2); extern PACKAGE void __fastcall BcdSubtract(const TBcd &bcdIn1, const TBcd &bcdIn2, TBcd &bcdOut); extern PACKAGE void __fastcall BcdMultiply(AnsiString StringIn1, AnsiString StringIn2, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdMultiply(const TBcd &bcdIn1, const TBcd &bcdIn2, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdMultiply(const TBcd &bcdIn, const double DoubleIn, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdMultiply(const TBcd &bcdIn, const AnsiString StringIn, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdDivide(AnsiString Dividend, AnsiString Divisor, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdDivide(const TBcd &Dividend, const TBcd &Divisor, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdDivide(const TBcd &Dividend, const double Divisor, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdDivide(const TBcd &Dividend, const AnsiString Divisor, TBcd &bcdOut)/* overload */; extern PACKAGE void __fastcall BcdAdd(const TBcd &bcdIn1, const TBcd &bcdIn2, TBcd &bcdOut); extern PACKAGE AnsiString __fastcall BcdToStr(const TBcd &Bcd)/* overload */; extern PACKAGE Word __fastcall BcdPrecision(const TBcd &Bcd); extern PACKAGE Word __fastcall BcdScale(const TBcd &Bcd); extern PACKAGE bool __fastcall IsBcdNegative(const TBcd &Bcd); extern PACKAGE bool __fastcall CurrToBCD(const System::Currency Curr, TBcd &BCD, int Precision = 0x20, int Decimals = 0x4); extern PACKAGE bool __fastcall BCDToCurr(const TBcd &BCD, System::Currency &Curr); extern PACKAGE AnsiString __fastcall BcdToStrF(const TBcd &Bcd, Sysutils::TFloatFormat Format, const int Precision, const int Digits); extern PACKAGE AnsiString __fastcall FormatBcd(const AnsiString Format, const TBcd &Bcd); } /* namespace Fmtbcd */ using namespace Fmtbcd; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // FMTBcd
53.718563
258
0.73916
earthsiege2
6b1081d6513a948256d0627c3f7a5c9c3779ccc1
294
hh
C++
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_BezierSymmetry.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_BezierSymmetry.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_BezierSymmetry.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Fri 5 Nov 2021 09:01:52 GMT-04:00 */ #ifndef J_BEZIERSYMMETRY_HH #define J_BEZIERSYMMETRY_HH namespace frost { namespace gen { void J_BezierSymmetry(double *p_output1, const double *var1); } } #endif // J_BEZIERSYMMETRY_HH
18.375
69
0.717687
prem-chand
6b1363396d0568fc04c2334fe9e37fe4992a1709
3,350
hpp
C++
include/geneticpp/individual.hpp
brentnd/geneticpp
e3a4e7c9e7985384a0546d1e96bdebaa458f77f2
[ "MIT" ]
null
null
null
include/geneticpp/individual.hpp
brentnd/geneticpp
e3a4e7c9e7985384a0546d1e96bdebaa458f77f2
[ "MIT" ]
null
null
null
include/geneticpp/individual.hpp
brentnd/geneticpp
e3a4e7c9e7985384a0546d1e96bdebaa458f77f2
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> // std::min, std::swap_ranges #include <functional> // std::function #include <iostream> #include <utility> // std::swap #include <vector> #include "attribute.hpp" #include "fitness.hpp" namespace genetic { class individual { public: individual(); // crossover template <typename... Args> static void crossover_method(void (*fcn)(individual *, individual *, Args...), Args... args) { crossover_function = std::bind(fcn, std::placeholders::_1, std::placeholders::_2, std::forward<Args>(args)...); } // Mate two individuals using static method static void mate(individual * ind1, individual * ind2); // crossover variants for crossover_method static void one_point_crossover(individual * ind1, individual * ind2); static void two_point_crossover(individual * ind1, individual * ind2); static void uniform_crossover(individual * ind1, individual * ind2, float indpb); static void ordered_crossover(individual * ind1, individual * ind2); static void blend_crossover(individual * ind1, individual * ind2, float alpha); // Evaluate this individuals fitness void evaluate(); float weighted_fitness() const; static std::vector<float> eval_sum(individual const & ind); float sum_attributes() const; // Custom function for evaluation static void evaluation_method(std::function<std::vector<float>(individual const &)> && fcn); // Mutation template <typename... Args> static void mutation_method(void (individual::* fcn)(Args...), Args... args) { mutation_function = std::bind(fcn, std::placeholders::_1, std::forward<Args>(args)...); } // Mutate this individual using mutation method void mutate(); // Mutation variants for mutation_method void uniform_int(float mutation_rate, int min, int max); void flip_bit(float mutation_rate); void shuffle_indexes(float mutation_rate); void gaussian(float mutation_rate, float mu, float sigma); void polynomial_bounded(float mutation_rate, float eta, float min, float max); // Initialize the attributes by seeding them void seed(); bool operator<(individual const & other) const; bool operator>(individual const & other) const; bool operator==(individual const & other) const; std::vector<attribute>::const_iterator begin() const; std::vector<attribute>::iterator begin(); std::vector<attribute>::const_iterator end() const; std::vector<attribute>::iterator end(); attribute const & at(std::size_t pos) const; std::size_t size() const; friend std::ostream& operator<<(std::ostream & stream, individual const & ind) { stream << "individual @ (" << static_cast<const void *>(&ind) << ") f=" << ind.weighted_fitness(); stream << " attr=["; for (auto const & attr : ind.attributes) { stream << attr << attribute::display_delimiter; } stream << "]"; return stream; } public: static std::size_t attribute_count; private: static std::function<std::vector<float>(individual const &)> evaluation_function; static std::function<void(individual *, individual *)> crossover_function; static std::function<void(individual &)> mutation_function; void throw_if_fitness_invalid() const; private: fitness fit; std::vector<attribute> attributes; }; } // namespace genetic
34.536082
117
0.699104
brentnd
6b17a6bd185b63bf401936f6c67ec2e8a9b27894
1,336
hpp
C++
src/Linux/ChildProcessExperiment/ChildProcessExperiment/BinaryWriter.hpp
asmichi/playground
08730da902c63c005817e98ec247eeb786ba15c4
[ "MIT" ]
null
null
null
src/Linux/ChildProcessExperiment/ChildProcessExperiment/BinaryWriter.hpp
asmichi/playground
08730da902c63c005817e98ec247eeb786ba15c4
[ "MIT" ]
null
null
null
src/Linux/ChildProcessExperiment/ChildProcessExperiment/BinaryWriter.hpp
asmichi/playground
08730da902c63c005817e98ec247eeb786ba15c4
[ "MIT" ]
null
null
null
// Copyright (c) @asmichi (https://github.com/asmichi). Licensed under the MIT License. See LICENCE in the project root for details. #pragma once #include <cstddef> #include <cstdint> #include <cstring> #include <numeric> #include <stdexcept> #include <string> #include <vector> class BinaryWriter final { public: template<typename T> void Write(T value) { Write(&value, sizeof(T)); } void Write(const void* data, std::size_t len) { std::memcpy(ExtendAndGetCurrent(len), data, len); } void WriteString(const char* s) { if (s == nullptr) { Write<std::uint32_t>(0); return; } auto bytes = std::char_traits<char>::length(s) + 1; if (bytes > std::numeric_limits<std::uint32_t>::max()) { throw std::out_of_range("string too long"); } Write<std::uint32_t>(static_cast<std::uint32_t>(bytes)); Write(s, bytes); } std::vector<std::byte> Detach() { return std::move(buf_); } private: std::byte* ExtendAndGetCurrent(std::size_t bytesToWrite) { auto cur = buf_.size(); buf_.resize(cur + bytesToWrite); return &buf_[cur]; } std::vector<std::byte> buf_; };
22.266667
133
0.554641
asmichi
6b1b3b50b2fe37bdc175b66be2446214213e58e4
1,088
cpp
C++
397_longest-increasing-continuous-subsequence/longest-increasing-continuous-subsequence.cpp
piguin/lintcode
382e0880f82480eb8153041e78c297dbaeb4b9ea
[ "CC0-1.0" ]
null
null
null
397_longest-increasing-continuous-subsequence/longest-increasing-continuous-subsequence.cpp
piguin/lintcode
382e0880f82480eb8153041e78c297dbaeb4b9ea
[ "CC0-1.0" ]
null
null
null
397_longest-increasing-continuous-subsequence/longest-increasing-continuous-subsequence.cpp
piguin/lintcode
382e0880f82480eb8153041e78c297dbaeb4b9ea
[ "CC0-1.0" ]
null
null
null
/* @Copyright:LintCode @Author: qili @Problem: http://www.lintcode.com/problem/longest-increasing-continuous-subsequence @Language: C++ @Datetime: 16-07-26 00:34 */ class Solution { public: int max(int a, int b) { return a > b ? a : b; } /** * @param A an array of Integer * @return an integer */ int longestIncreasingContinuousSubsequence(vector<int>& A) { if (A.size() == 0) return 0; int lenCurr = 1; int lenMax = 0; int dir = 0; int lastNum = A[0]; for (int i = 1; i < A.size(); ++i) { int n = A[i]; if (dir == 0) { dir = n - lastNum; // dir can only be set when we are after the 1st number lenCurr = (dir != 0) ? 2 : 1; } else if (dir * (n - lastNum) <= 0) { // if dir reversed dir = n - lastNum; lenMax = max(lenMax, lenCurr); lenCurr = (dir != 0) ? 2 : 1; } else { ++lenCurr; } lastNum = n; } lenMax = max(lenMax, lenCurr); return lenMax; } };
23.148936
84
0.488971
piguin
6b1c4adc798c9cf7f8a56fe994d78cc7db683229
6,050
cc
C++
src/filters/particle_filter.cc
jwidauer/refill
64947e0a8e15855f4a5ad048f09f8d38715bbe91
[ "MIT" ]
2
2021-06-13T07:28:51.000Z
2021-09-08T11:26:34.000Z
src/filters/particle_filter.cc
jwidauer/refill
64947e0a8e15855f4a5ad048f09f8d38715bbe91
[ "MIT" ]
null
null
null
src/filters/particle_filter.cc
jwidauer/refill
64947e0a8e15855f4a5ad048f09f8d38715bbe91
[ "MIT" ]
3
2021-06-01T13:21:41.000Z
2021-06-01T20:33:20.000Z
#include "refill/filters/particle_filter.h" using std::size_t; using Eigen::MatrixXd; using Eigen::VectorXd; namespace refill { ParticleFilter::ParticleFilter() : num_particles_(0), particles_(0, 0), weights_(0), system_model_(nullptr), measurement_model_(nullptr), resample_method_(nullptr) { } ParticleFilter::ParticleFilter(const size_t& n_particles, DistributionInterface* initial_state_dist) : num_particles_(n_particles), particles_(initial_state_dist->mean().rows(), n_particles), weights_(n_particles), system_model_(nullptr), measurement_model_(nullptr), resample_method_(nullptr) { reinitializeParticles(initial_state_dist); } ParticleFilter::ParticleFilter( const size_t& n_particles, DistributionInterface* initial_state_dist, const std::function<void(MatrixXd*, VectorXd*)>& resample_method) : num_particles_(n_particles), particles_(initial_state_dist->mean().rows(), n_particles), weights_(n_particles), system_model_(nullptr), measurement_model_(nullptr), resample_method_(resample_method) { reinitializeParticles(initial_state_dist); } ParticleFilter::ParticleFilter( const size_t& n_particles, DistributionInterface* initial_state_dist, const std::function<void(MatrixXd*, VectorXd*)>& resample_method, std::unique_ptr<SystemModelBase> system_model, std::unique_ptr<Likelihood> measurement_model) : num_particles_(n_particles), particles_(initial_state_dist->mean().rows(), n_particles), weights_(n_particles), system_model_(std::move(system_model)), measurement_model_(std::move(measurement_model)), resample_method_(resample_method) { reinitializeParticles(initial_state_dist); } void ParticleFilter::setFilterParameters( const size_t& n_particles, DistributionInterface* initial_state_dist) { num_particles_ = n_particles; this->reinitializeParticles(initial_state_dist); } void ParticleFilter::setFilterParameters( const size_t& n_particles, DistributionInterface* initial_state_dist, const std::function<void(MatrixXd*, VectorXd*)>& resample_method) { this->setFilterParameters(n_particles, initial_state_dist); resample_method_ = resample_method; } void ParticleFilter::setFilterParameters( const size_t& n_particles, DistributionInterface* initial_state_dist, const std::function<void(MatrixXd*, VectorXd*)>& resample_method, std::unique_ptr<SystemModelBase> system_model, std::unique_ptr<Likelihood> measurement_model) { this->setFilterParameters(n_particles, initial_state_dist, resample_method); system_model_ = std::move(system_model); measurement_model_ = std::move(measurement_model); } void ParticleFilter::setParticles(const Eigen::MatrixXd& particles) { CHECK_EQ(particles_.rows(), particles.rows()); CHECK_EQ(particles_.cols(), particles.cols()); particles_ = particles; weights_.setConstant(1.0 / num_particles_); } void ParticleFilter::setParticlesAndWeights(const Eigen::MatrixXd& particles, const Eigen::VectorXd& weights) { CHECK_EQ(particles_.rows(), particles.rows()); CHECK_EQ(weights.rows(), particles.cols()); CHECK_NE(weights.squaredNorm(), 0.0) << "Zero weight vector is not allowed!"; particles_ = particles; weights_ = weights / weights.sum(); } void ParticleFilter::reinitializeParticles( DistributionInterface* initial_state_dist) { particles_.resize(initial_state_dist->mean().rows(), num_particles_); weights_.resize(num_particles_); weights_.setConstant(1.0 / num_particles_); for (std::size_t i = 0; i < num_particles_; ++i) { particles_.col(i) = initial_state_dist->drawSample(); } } void ParticleFilter::predict() { CHECK(this->system_model_) << "No default system model provided!"; this->predict(Eigen::VectorXd::Zero(system_model_->getInputDim())); } void ParticleFilter::predict(const Eigen::VectorXd& input) { CHECK(this->system_model_) << "No default system model provided!"; this->predict(*system_model_, input); } void ParticleFilter::predict(const SystemModelBase& system_model) { this->predict(system_model, Eigen::VectorXd::Zero(system_model.getInputDim())); } void ParticleFilter::predict(const SystemModelBase& system_model, const Eigen::VectorXd& input) { CHECK_EQ(system_model.getInputDim(), input.rows()); CHECK_EQ(system_model.getStateDim(), particles_.rows()); CHECK_NE(particles_.cols(), 0)<< "Particle vector is empty."; for (std::size_t i = 0; i < num_particles_; ++i) { Eigen::VectorXd noise_sample = system_model.getNoise()->drawSample(); particles_.col(i) = system_model.propagate(particles_.col(i), input, noise_sample); } } void ParticleFilter::update(const Eigen::VectorXd& measurement) { CHECK(this->measurement_model_) << "No default measurement model provided!"; this->update(*measurement_model_, measurement); } void ParticleFilter::update(const Likelihood& measurement_model, const Eigen::VectorXd& measurement) { Eigen::VectorXd likelihoods = measurement_model.getLikelihoodVectorized( particles_, measurement); weights_ = weights_.cwiseProduct(likelihoods); weights_ /= weights_.sum(); // Resample using the provided resampling method if (resample_method_) { resample_method_(&particles_, &weights_); } } Eigen::VectorXd ParticleFilter::getExpectation() { return particles_ * weights_; } Eigen::VectorXd ParticleFilter::getMaxWeightParticle() { Eigen::VectorXd::Index index; weights_.maxCoeff(&index); return particles_.col(index); } Eigen::MatrixXd ParticleFilter::getParticles() { return particles_; } void ParticleFilter::getParticlesAndWeights(Eigen::MatrixXd* particles, Eigen::VectorXd* weights) { *particles = particles_; *weights = weights_; } } // namespace refill
33.611111
79
0.722314
jwidauer
6b1d21f6469f9edb73a2804840722da9fb79c90b
351
cpp
C++
tests/Issue45Example.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
1,853
2018-05-13T21:49:17.000Z
2022-03-30T10:34:45.000Z
tests/Issue45Example.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
398
2018-05-15T14:48:51.000Z
2022-03-24T12:14:33.000Z
tests/Issue45Example.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
104
2018-05-15T04:00:59.000Z
2022-03-17T02:04:15.000Z
int main() { int x = 0; for(; x < 20; ++x) { x += x; } for(int i=0; x < 20; ++x) { x += i; } for(int i = 0, y=2, t=4, o=5; i < 20; ++i) { x += i; } for(int *i = &x, *y=&x; i ; ++i) { x += *i; } for(;;); char data[5]{}; for(auto& x : data) { x = 2; } }
12.103448
48
0.270655
galorojo
6b1f4ef9f8f398bed644cd86cac558535e77194e
4,175
hh
C++
src/transport/ConnectionManager.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2016-01-17T20:41:39.000Z
2018-05-01T12:02:58.000Z
src/transport/ConnectionManager.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/transport/ConnectionManager.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2015-09-29T02:30:16.000Z
2022-03-30T12:11:22.000Z
/* * Copyright 2011 Nate Koenig & Andrew Howard * * 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 CONNECTION_MANAGER_HH #define CONNECTION_MANAGER_HH #include <boost/shared_ptr.hpp> #include <string> #include <list> #include <vector> #include "msgs/msgs.h" #include "common/SingletonT.hh" #include "transport/Publisher.hh" #include "transport/Connection.hh" namespace gazebo { namespace transport { /// \addtogroup gazebo_transport /// \{ /// \brief Manager of connections class ConnectionManager : public SingletonT<ConnectionManager> { /// \brief Constructor private: ConnectionManager(); /// \brief Destructor private: virtual ~ConnectionManager(); public: bool Init(const std::string &master_host, unsigned int master_port); /// \brief Run the connection manager loop public: void Run(); /// \brief Return true if running (not stopped) public: bool IsRunning() const; /// \brief Finalize the conneciton manager public: void Fini(); /// \brief Stop the conneciton manager public: void Stop(); public: void Subscribe(const std::string &_topic, const std::string &_msgType, bool _latching); public: void Unsubscribe(const msgs::Subscribe &_sub); public: void Unsubscribe(const std::string &_topic, const std::string &_msgType); public: void Advertise(const std::string &topic, const std::string &msgType); public: void Unadvertise(const std::string &topic); /// \brief Explicitly update the publisher list public: void GetAllPublishers(std::list<msgs::Publish> &publishers); /// \brief Remove a connection public: void RemoveConnection(ConnectionPtr &conn); /// \brief Register a new topic namespace public: void RegisterTopicNamespace(const std::string &_name); /// \brief Get all the topic namespaces public: void GetTopicNamespaces(std::list<std::string> &_namespaces); /// \brief Find a connection that matches a host and port private: ConnectionPtr FindConnection(const std::string &host, unsigned int port); /// \brief Connect to a remote server public: ConnectionPtr ConnectToRemoteHost(const std::string &host, unsigned int port); private: void OnMasterRead(const std::string &data); private: void OnAccept(const ConnectionPtr &new_connection); private: void OnRead(const ConnectionPtr &new_connection, const std::string &data); private: void ProcessMessage(const std::string &_packet); public: void RunUpdate(); private: ConnectionPtr masterConn; private: Connection *serverConn; private: std::list<ConnectionPtr> connections; protected: std::vector<event::ConnectionPtr> eventConnections; private: bool initialized; private: bool stop, stopped; private: boost::thread *thread; private: unsigned int tmpIndex; private: boost::recursive_mutex *listMutex; private: boost::recursive_mutex *masterMessagesMutex; private: boost::recursive_mutex *connectionMutex; private: std::list<msgs::Publish> publishers; private: std::list<std::string> namespaces; private: std::list<std::string> masterMessages; // Singleton implementation private: friend class SingletonT<ConnectionManager>; }; /// \} } } #endif
30.698529
75
0.651018
nherment
6b282cf7fc44dee5fc193d0a910f09c1aab123b5
555
cpp
C++
common/src/debug_test.cpp
honzatran/llvm-message-routing
6878dffb935efe44fa8fdf443bfb9905ea604d29
[ "MIT" ]
null
null
null
common/src/debug_test.cpp
honzatran/llvm-message-routing
6878dffb935efe44fa8fdf443bfb9905ea604d29
[ "MIT" ]
null
null
null
common/src/debug_test.cpp
honzatran/llvm-message-routing
6878dffb935efe44fa8fdf443bfb9905ea604d29
[ "MIT" ]
null
null
null
#include <routing/call_counter.h> #include <routing/debug.h> #include <routing/testing.h> #include <gtest/gtest.h> using namespace std; using namespace routing; TEST(Once_in_time_test, test) { auto call_counter = define_void_mock<>(2, DEFINED("once in time")); auto counter_fn = [&call_counter] { call_counter(); }; Once_in_time once_in_time(chrono::milliseconds{10}); auto now = chrono::system_clock::now(); while (chrono::system_clock::now() - now < chrono::milliseconds{22}) { once_in_time(counter_fn); } }
20.555556
72
0.686486
honzatran
6b2b010c58353d60391b0c4d878aa10f9547d3a9
3,314
cpp
C++
src/Threading/Thread.cpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
3
2015-09-15T06:57:50.000Z
2021-03-16T19:05:02.000Z
src/Threading/Thread.cpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
2
2015-09-26T12:41:10.000Z
2015-12-08T08:41:37.000Z
src/Threading/Thread.cpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
1
2015-07-09T02:56:34.000Z
2015-07-09T02:56:34.000Z
#include "RadonFramework/System/Threading/Thread.hpp" #include "RadonFramework/System/Hardware/Hardware.hpp" #include "RadonFramework/Threading/Scopelock.hpp" #include "RadonFramework/precompiled.hpp" namespace RadonFramework::Threading { Thread::Thread() { m_AffinityMask.Resize(RF_SysHardware::GetAvailableLogicalProcessorCount()); m_AffinityMask.Set(); } Thread::~Thread() { if(m_ImplData != nullptr) { RF_SysThread::Destroy(m_ImplData); } } void Thread::Run() {} void Thread::Start() { m_ImplData = RF_SysThread::Create(*this, m_Pid); RF_SysThread::SetPriority(m_ImplData, m_Priority); RF_SysThread::SetAffinityMask(m_ImplData, m_AffinityMask); RF_SysThread::PostConfigurationComplete(m_ImplData); } void Thread::Exit() { RF_SysThread::Stop(m_ImplData); RF_SysThread::Join(m_ImplData); } void Thread::Interrupt() {} ThreadPriority::Type Thread::Priority() { return m_Priority; } void Thread::Priority(ThreadPriority::Type Value) { if(Value != m_Priority) { m_Priority = Value; RF_SysThread::SetPriority(m_ImplData, m_Priority); } } void Thread::Join() { RF_SysThread::Join(m_ImplData); } void Thread::Join(const RF_Time::TimeSpan& Delta) { RF_SysThread::Wait(m_ImplData, Delta); } void Thread::Sleep(const RF_Time::TimeSpan& Delta) { RF_SysThread::Sleep(Delta); } RF_Type::Bool Thread::IsAlive() { return RF_SysThread::IsAlive(m_ImplData); } RF_Type::Bool Thread::Working() { return m_ImplData != nullptr; } void Thread::Finished() {} const RF_Type::String& Thread::Name() const { return m_Name; } void Thread::Name(const class RF_Type::String& NewName) { m_Name = NewName; return RF_SysThread::Rename(m_ImplData, NewName); } RF_Type::UInt64 Thread::Pid() const { return m_Pid; } void* Thread::MemAlloc(const RF_Type::UInt64 Bytes) { RF_Thread::Scopelock lock(m_ThreadBarrier); RF_Mem::AutoPointerArray<RF_Type::UInt8> m( static_cast<RF_Type::UInt32>(Bytes)); RF_Type::UInt8* p = m.Get(); m_ThreadAllocatedMemory.PushBack(m); return p; } void Thread::FreeMem(const void* Ptr) { RF_Thread::Scopelock lock(m_ThreadBarrier); Collections::AutoVector<RF_Type::UInt8>::Iterator it = m_ThreadAllocatedMemory.Begin(); for(; it != m_ThreadAllocatedMemory.End(); ++it) { if((*it) == Ptr) { m_ThreadAllocatedMemory.Erase(it); break; } } } RF_Type::Bool Thread::MemAccess(const void* Ptr) { RF_Thread::Scopelock lock(m_ThreadBarrier); Collections::AutoVector<RF_Type::UInt8>::Iterator it = m_ThreadAllocatedMemory.Begin(); for(; it != m_ThreadAllocatedMemory.End(); ++it) { if((*it) == Ptr) { return true; } } return false; } RF_Type::UInt64 Thread::CurrentPid() { return RF_SysThread::GetProcessId(); } RF_Type::Bool Thread::GetAffinityMask(RF_Collect::BitArray<>& Mask) const { return RF_SysThread::GetAffinityMask(m_ImplData, Mask); } RF_Type::Bool Thread::SetAffinityMask(const RF_Collect::BitArray<>& NewValue) { RF_Type::Bool result = true; if(NewValue != m_AffinityMask) { m_AffinityMask = NewValue; result = RF_SysThread::SetAffinityMask(m_ImplData, m_AffinityMask); } return result; } RF_Type::Bool Thread::ShouldRunning() { return RF_SysThread::IsRunning(m_ImplData); } } // namespace RadonFramework::Threading
20.331288
77
0.714544
tak2004
6b3042475334dcb0e3c53dc27d02adfc9ce82cb2
417
cpp
C++
examples/set/set.cpp
lostjared/cpp17_Examples
bd754ffca5e894d877624c45db64f9dda93d880a
[ "Unlicense" ]
20
2017-07-22T19:06:39.000Z
2021-07-12T06:46:24.000Z
examples/set/set.cpp
lostjared/cpp17_Examples
bd754ffca5e894d877624c45db64f9dda93d880a
[ "Unlicense" ]
null
null
null
examples/set/set.cpp
lostjared/cpp17_Examples
bd754ffca5e894d877624c45db64f9dda93d880a
[ "Unlicense" ]
7
2018-05-20T10:26:07.000Z
2021-07-12T04:11:18.000Z
#include<iostream> #include<set> #include<string> int main() { std::set<std::string> ideas; std::string idea; while(1) { std::cout << "Enter idea: "; std::getline(std::cin, idea); ideas.insert(idea); for(auto i = ideas.begin(); i != ideas.end(); ++i) { std::cout << *i << "\n"; if(*i == "quit") exit(EXIT_SUCCESS); } } return 0; }
21.947368
60
0.484412
lostjared
6b3636a660101397297e7fa40df26d6bd7c2cc15
1,043
hpp
C++
addons/ares_compositions/Ares/Walls/Wall Sections/Military Wall Corner.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
null
null
null
addons/ares_compositions/Ares/Walls/Wall Sections/Military Wall Corner.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
4
2018-12-21T06:57:25.000Z
2020-07-09T09:06:38.000Z
addons/ares_compositions/Ares/Walls/Wall Sections/Military Wall Corner.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
null
null
null
class Object0 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={-0.168457,-1.55762,0};dir=0;}; class Object1 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={3.63428,-1.54736,0};dir=0;}; class Object2 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={-3.98242,-1.59229,0};dir=0;}; class Object3 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={7.44824,-1.5127,0};dir=0;}; class Object4 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={-7.77002,-1.58789,0};dir=0;}; class Object5 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={11.2363,-1.51709,0};dir=0;}; class Object6 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={-11.5845,-1.62256,0};dir=0;}; class Object7 {side=8;rank="";vehicle="Land_Mil_WallBig_Corner_F";position[]={-15.0779,-1.59619,0};dir=0;}; class Object8 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={-15.0344,1.8916,0};dir=90.5571;}; class Object9 {side=8;rank="";vehicle="Land_Mil_WallBig_4m_F";position[]={15.0498,-1.48242,0};dir=0;};
104.3
107
0.717162
Braincrushy
6b38e9bcc5b8077f5061e261b171315aa5383851
1,972
cpp
C++
http_service/src/register.cpp
nchalkley2/ImgboardServer
6ee1fa06ef20442aef11c98b3e9588c116a1ef79
[ "MIT" ]
null
null
null
http_service/src/register.cpp
nchalkley2/ImgboardServer
6ee1fa06ef20442aef11c98b3e9588c116a1ef79
[ "MIT" ]
null
null
null
http_service/src/register.cpp
nchalkley2/ImgboardServer
6ee1fa06ef20442aef11c98b3e9588c116a1ef79
[ "MIT" ]
null
null
null
#include "routes.hpp" #include "database.hpp" #include "account_validation.hpp" #include <optional> #include <string> #include <utility> #include <acorn> #include <net/http/request.hpp> namespace chan::routes { using namespace mana; void acc_register(Request_ptr req, Response_ptr res) { http::Request src = req->source(); auto username = uri::decode(src.post_value("username")); auto username_valid = validate_username(username); auto password = uri::decode(src.post_value("password")); auto password_rep = uri::decode(src.post_value("password-repeat")); auto password_valid = validate_password(password, password_rep); // validate_username and validate_password return a <bool, string> pair. // The first bool has whether the username/password is valid if (username_valid.first && password_valid.first) { database::account::create( username, password, [=](bool created_account, std::string username, std::string db_err) { if (created_account) { res->source().add_body("Succesfully created account \"" + username + "\"."); res->source().set_status_code(http::Created); res->send(); } else { res->source().add_body("Failed to create account \"" + username + "\".\n" + "Error: " + db_err); res->source().set_status_code(http::Bad_Request); res->send(); } }); } else { // res->error expects rvalues so this has to be in a // function const auto create_error = [&]() -> std::string { const auto username_err = username_valid.second.has_value() ? username_valid.second.value() + "\n" : ""; const auto password_err = password_valid.second.has_value() ? password_valid.second.value() + "\n" : ""; return username_err + password_err; }; res->error({ http::Bad_Request, "Error creating account", create_error() }); } } }
26.293333
74
0.632353
nchalkley2
6b3f1f93fff25740320c65140bab2fa7a527e877
43
cpp
C++
vma.cpp
dylangentile/RayPath
3a7e0cf78f482554bcb4155f486f1708cdc126c0
[ "MIT" ]
null
null
null
vma.cpp
dylangentile/RayPath
3a7e0cf78f482554bcb4155f486f1708cdc126c0
[ "MIT" ]
null
null
null
vma.cpp
dylangentile/RayPath
3a7e0cf78f482554bcb4155f486f1708cdc126c0
[ "MIT" ]
null
null
null
#define VMA_IMPLEMENTATION #include "vma.h"
21.5
26
0.813953
dylangentile
6b412fe5dfc215d280ec0ea2565c47093f558bf2
1,558
hpp
C++
Kernel/Tasking/Processes/Threads/Thread.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
null
null
null
Kernel/Tasking/Processes/Threads/Thread.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
null
null
null
Kernel/Tasking/Processes/Threads/Thread.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
null
null
null
#pragma once #include "Signals.hpp" #include <Hardware/Trapframe.hpp> namespace Kernel::Tasking { constexpr size_t kernel_stack_size = 4096; constexpr size_t user_stack_size = 512 * 4096; // Not realy used inside the C++ code. // Just to clarify the sequence of push / pop opertions // inside Scheduling.s block routines. struct KernelContext { uint32_t ebx; uint32_t ebp; uint32_t esi; uint32_t edi; }; class Process; class Thread { friend class Process; friend class Process; public: Thread(Process& process, uintptr_t user_stack); ~Thread(); Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; inline Signals& signals() { return m_signals; } inline Process& process() { return m_process; } inline uintptr_t kernel_stack_top() { return m_kernel_stack + kernel_stack_size; } inline Trapframe* trapframe() { return (Trapframe*)(kernel_stack_top() - sizeof(Trapframe)); } inline KernelContext** kernel_context() { return &m_kernel_context; } inline bool blocked_in_kernel() { return m_kernel_context != nullptr; } void fork_from(Thread& other); void jump_to_signal_caller(int signo); void return_from_signal_caller(); private: void setup_trapframe(); uintptr_t user_stack() { return m_user_stack; } uintptr_t user_stack_top() { return m_user_stack + user_stack_size; } private: Process& m_process; Signals m_signals {}; uintptr_t m_kernel_stack {}; uintptr_t m_user_stack {}; KernelContext* m_kernel_context {}; }; }
27.333333
98
0.712452
Plunkerusr
6b41ae332b2907083c9533638081806b9caf3094
188
cpp
C++
lab5/1 - concrete types/main.cpp
uiowa-cs-3210-0001/cs3210-labs
d6263d719a45257ba056a1ead7cc3dd428d377f3
[ "MIT" ]
1
2019-01-24T14:04:45.000Z
2019-01-24T14:04:45.000Z
lab5/1 - concrete types/main.cpp
uiowa-cs-3210-0001/cs3210-labs
d6263d719a45257ba056a1ead7cc3dd428d377f3
[ "MIT" ]
1
2019-01-24T18:32:45.000Z
2019-01-28T04:10:28.000Z
lab5/1 - concrete types/main.cpp
uiowa-cs-3210-0001/cs3210-labs
d6263d719a45257ba056a1ead7cc3dd428d377f3
[ "MIT" ]
1
2019-02-07T00:28:20.000Z
2019-02-07T00:28:20.000Z
#include "complex.hpp" int main() { complex z = {1,0}; complex a{ 2.3 }; // construct {2.3,0.0} from 2.3 complex b{ a + z }; // ... if (a != b) a = -b; }
17.090909
59
0.420213
uiowa-cs-3210-0001
6b43103eb3798281232631c954ec08e0e4fa8b1a
1,261
cpp
C++
solutions/059.cpp
procrastiraptor/euler
1dd1040527c8de18e6325199a5939b32b8f76cac
[ "MIT" ]
1
2017-10-25T14:45:57.000Z
2017-10-25T14:45:57.000Z
solutions/059.cpp
procrastiraptor/euler
1dd1040527c8de18e6325199a5939b32b8f76cac
[ "MIT" ]
null
null
null
solutions/059.cpp
procrastiraptor/euler
1dd1040527c8de18e6325199a5939b32b8f76cac
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <iostream> #include <numeric> #include <string> #include <string_view> namespace { using Key = std::array<char, 3>; std::string tr(std::string_view input, Key key) { std::string res; res.reserve(input.size()); std::transform( input.begin(), input.end(), std::back_inserter(res), [key,i=0](char c) mutable { return c ^ key[i++ % std::tuple_size<Key>::value]; }); return res; } std::string read(std::string_view data) { std::string res{'\0'}; res.reserve(data.size()); for (char c : data) { if (c == ',') { res.push_back('\0'); } else { res.back() = res.back() * 10 + (c - '0'); } } return res; } bool plaintext(std::string_view text) { return text.find(" the ") != std::string_view::npos; } } int p59() { std::string data; std::getline(std::cin, data, '\n'); auto input = read(data); std::array<char, 'z' - 'a' + 1> lc; std::iota(lc.begin(), lc.end(), 'a'); for (char a : lc) { for (char b : lc) { for (char c : lc) { if (auto decoded = tr(input, { a, b, c, }); plaintext(decoded)) { return std::accumulate(decoded.begin(), decoded.end(), 0); } } } } return 0; }
20.33871
73
0.547978
procrastiraptor
6b48e70698ce77c3730b1b9fbe02a5c548756827
9,515
cpp
C++
mandelbrot/Program.cpp
08jne01/Mandelbrot-Explorer
40685555165138d7fd195a02ceee4db6ea511b0f
[ "MIT" ]
2
2018-03-22T21:47:40.000Z
2018-03-23T03:18:58.000Z
mandelbrot/Program.cpp
08jne01/Mandelbrot-Explorer
40685555165138d7fd195a02ceee4db6ea511b0f
[ "MIT" ]
14
2018-03-22T03:04:04.000Z
2018-09-26T16:29:15.000Z
mandelbrot/Program.cpp
08jne01/Mandelbrot-Explorer
40685555165138d7fd195a02ceee4db6ea511b0f
[ "MIT" ]
null
null
null
#include "Header.h" #include "Complex.h" #include "InMandel.h" #include "MandelClass.h" #include "Program.h" void program::init(int width_, int height_, double step_, double x_, double y_, double scale_, double greyScale_, double phase_, int fullScreen_) { //Set all starting parameters width = width_; height = height_; step = step_; x = x_; y = y_; scale = scale_; pointSize = 1; greyScale = greyScale_; phase = phase_; fullScreen = fullScreen_; calculated = 0; itters = 1000; if (width > height) { res = width; } else if (height > width) { res = height; } } void program::checkRatio() { //Checks ratio and defines depending whether width > height or not if (ratio > 1.0) { res = height; xRatio = 1.0 / ratio; yRatio = 1; } else { res = width; xRatio = 1; yRatio = ratio; } } void program::update(double local_step, int init) { //Define ratio of window based on window size ratio = height / (double)width; //Set calculated to 0 so that the renderer knows not to render otherwise there will be access violation calculated = 0; //Check and set Ratio checkRatio(); //Start clock to time render process int startS = clock(); //Choose next x, y based on cursor position if (init != 1) { x += ((2.0 / (width*0.5))*xCurs - 2.0) / scale; y += ((-ratio * 2.0 / (height*0.5))*(yCurs)+ratio * 2.0) / scale; } //Change scale based on settings scale *= local_step; mandel.scale = scale / 2.0; //Set the edge of the screen for rendering if (ratio > 1.0) { mandel.xEdge = -2.0 / ((double)scale) + x; mandel.yEdge = -2.0*ratio / ((double)scale) + y; } else { mandel.xEdge = -2.0 / ((double)scale) + x; mandel.yEdge = -2.0 / ((double)scale)*ratio + y; } //Print some info std::cout.precision(20); std::cout << "\nx = " << x << std::endl; std::cout << "y = " << y << std::endl; std::cout.precision(1); std::cout << "Zoom Level = " << scale << std::endl; std::cout << "Itterations = " << itters << std::endl; //Calculate the mandelbrot mandel.calcMandel(res, xRatio, yRatio, itters); //Stop the clock and calculate render time int stopS = clock(); std::cout << "\rRender Time: " << (stopS - startS) / double(CLOCKS_PER_SEC) * 1000 << " ms" << " " << std::endl; //Set calculated to 1 so that the render knows it can reach the variables without causing an access violation calculated = 1; } void program::draw() { //Check that the mandelbrot is not calculating so as to not cause an access violation if (calculated == 1) { double q, r, g, b; ratio = height / (double)width; //Check and set ratio checkRatio(); //Set phase increase or decrease for colour scheme phase += phaseincrease * 0.1; //Set pointsize and begin drawing points glPointSize(pointSize); glBegin(GL_POINTS); //Loop through each pixel and draw a point based on colour array for (int i = 0; i < ceil(mandel.size*xRatio); i++) { for (int j = 0; j < ceil(mandel.size*yRatio); j++) { //Invert values q = 1 - mandel.colorArr[i][j]; //Choose colour scheme based on config if (greyScale >= 1) { r = q; g = q; b = q; } else { r = sin(2 * PI *q)*sin(2 * PI *q); g = sin(phase* PI *q)*sin(2 * PI *q); b = q; } glColor3d(r, g, b); //glVertex2d(c.re*0.5*scale - x*0.5*scale, (c.im*0.5*scale - y*0.5*scale) / ratio); glVertex2d(coordTransform(i, width), coordTransform(j, height)); } } glEnd(); } } void program::mouseCallback(GLFWwindow* window, int button, int action, int mods) { //Update to zoom in if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { update(step, 0); } //Update to zoom out if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) { update(1.0 / step, 0); } } void program::keyCallBack(int key, int pressed) { if (pressed == GLFW_PRESS) { switch (key) { //Save coordinates and screenshot case GLFW_KEY_SPACE: { std::string s = "Screenshot "; s += currentTime(); s += ".bmp"; writeCoords(s); saveBMP(s); break; } //Change phase for colour scheme to on in either direction depending on keys case GLFW_KEY_LEFT: { phaseincrease = -1; break; } case GLFW_KEY_RIGHT: { phaseincrease = 1; break; } //Increase or decrease number of itterations for calculation case GLFW_KEY_UP: { itters *= 1.5; update(1.0, 1); break; } case GLFW_KEY_DOWN: { itters /= 1.5; update(1.0, 1); break; } } } else if (pressed == GLFW_RELEASE) { switch (key) { //Reset phase change when user releases the key case GLFW_KEY_LEFT: { phaseincrease = 0; break; } case GLFW_KEY_RIGHT: { phaseincrease = 0; break; } } } } void program::readConfig() { //Open the config std::ifstream file("config.ini"); //Check open and then read the config to variables if (file.is_open()) { file >> width; file >> height; file >> fullScreen; file >> step; file >> x; file >> y; file >> scale; file >> greyScale; if (greyScale != 1) { file >> phase; } //Close file file.close(); } else { std::cout << "File could not be opened. Please run again and create config!" << std::endl; system("PAUSE"); exit(EXIT_FAILURE); } //Set variables from file init(width, height, step, x, y, scale, greyScale, phase, fullScreen); } void program::writeConfig() { //Open config file std::ofstream file("config.ini"); //Check if it is open and write to config if (file.is_open()) { file << width << std::endl; file << height << std::endl; file << fullScreen << std::endl; file << step << std::endl; file << x << std::endl; file << y << std::endl; file << scale << std::endl; file << greyScale << std::endl; if (greyScale != 1) { file.precision(20); file << phase << std::endl; } file.close(); } else { std::cout << "File could not be opened." << std::endl; } } void program::saveBMP(std::string filename) { //Allocate memory for filename and convert filename to char array so that string can be used char *filenameCharArray = (char*)malloc(sizeof(char) * (filename.size() + 1)); strcpy_s(filenameCharArray, filename.size() + 1, filename.c_str()); //Open file and create write buffer FILE *out; fopen_s(&out, filenameCharArray, "wb"); byte* buff = new byte[width*height * 3]; //Round down to nearest multiple of 4 otherwise bmp will not work int tempWidth = roundDownNearest(width, 4); int tempHeight = height; //Read back buffer glReadBuffer(GL_BACK); glReadPixels(0, 0, tempWidth, tempHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, buff); //Check buffer was allocated and the file was opened if (!out || !buff) { std::cout << "Error Writing to File!" << std::endl; return; } //Create file and info header variables BITMAPFILEHEADER bitmapFileHeader; BITMAPINFOHEADER bitmapInfoHeader; //Setup file header bitmapFileHeader.bfType = 0x4D42; bitmapFileHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + tempWidth * tempHeight * 3; bitmapFileHeader.bfReserved1 = 0; bitmapFileHeader.bfReserved2 = 0; bitmapFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); //Setup info header bitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfoHeader.biWidth = tempWidth - 1; bitmapInfoHeader.biHeight = tempHeight - 1; bitmapInfoHeader.biPlanes = 1; bitmapInfoHeader.biBitCount = 24; bitmapInfoHeader.biCompression = BI_RGB; bitmapInfoHeader.biSizeImage = 0; bitmapInfoHeader.biXPelsPerMeter = 0; bitmapInfoHeader.biYPelsPerMeter = 0; bitmapInfoHeader.biClrUsed = 0; bitmapInfoHeader.biClrImportant = 0; //Write to file fwrite(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, out); fwrite(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, out); fwrite(buff, tempWidth*tempHeight * 3, 1, out); //Free memory and close files free(filenameCharArray); fclose(out); delete[] buff; std::cout << filename << " saved!" << std::endl; } void program::writeCoords(std::string s) { //Open file and appened to end of file std::ofstream file; file.open("coords.txt", std::ios::app); //Check file is open and then append the below values if (file.is_open()) { file.precision(20); file << "Re = " << x << " Im = " << y; file.precision(3); file << " Scale = " << scale; file << "Screenshot timestamp: " << s; file.close(); std::cout << "\nCoords copied to file!" << std::endl; } else { std::cout << "File could not be opened." << std::endl; } } double program::coordTransform(double pixel, int dimension) { //Transforms pixel coordinates to screen coordinates (1 dimensional function) double screenpos; screenpos = ((2 * pixel) / (float)dimension) - 1; return screenpos; } int program::roundDownNearest(int val, int multiple) { //Rounds down to the nearest multiple (used with bitmap output) if (val % multiple == 0) { return val; } else { return (val - (val % multiple)); } } std::string program::currentTime() { //Gets current time and formats to string to be appended to filename and coordinate file time_t rawTime; struct tm time_info; time(&rawTime); localtime_s(&time_info, &rawTime); std::ostringstream os; os << " " << time_info.tm_mday << "-" << time_info.tm_mon + 1 << "-" << time_info.tm_year + 1900 << "_" << time_info.tm_hour << time_info.tm_min << time_info.tm_sec; return os.str(); }
20.462366
166
0.6433
08jne01
6b52ed178bfc8f6caeacf021d832505c01e2d642
1,060
cpp
C++
demo/thread.cpp
Pawapek/ocilib
46ea6532e9ae0cf43ecc11dc2ca6542238b3d34d
[ "Apache-2.0" ]
290
2015-07-07T12:53:43.000Z
2022-02-19T13:17:56.000Z
demo/thread.cpp
Pawapek/ocilib
46ea6532e9ae0cf43ecc11dc2ca6542238b3d34d
[ "Apache-2.0" ]
270
2015-06-25T10:04:02.000Z
2022-03-29T11:48:19.000Z
demo/thread.cpp
ljx0305/ocilib
b3d9ce9658766cc4cbd225d22f55e9f50f112a31
[ "Apache-2.0" ]
135
2015-06-24T05:38:34.000Z
2022-03-12T06:58:55.000Z
#include <iostream> #include "ocilib.hpp" using namespace ocilib; const int MaxThreads = 50; void worker(ThreadHandle handle, void *data) { ThreadKey::SetValue("ID", const_cast<AnyPointer>(Thread::GetThreadId(handle))); /* ... do some more processing here... */ std::cout << " Thread handle = " << handle << " Key (Thread Id) = " << ThreadKey::GetValue("ID") << std::endl; } int main(void) { try { Environment::Initialize(Environment::Threaded); ThreadKey::Create("ID"); std::vector<ThreadHandle> threads; for (int i = 0; i < MaxThreads; i++) { ThreadHandle th = Thread::Create(); threads.push_back(th); Thread::Run(th, worker, 0); } for (int i = 0; i < MaxThreads; i++) { Thread::Join(threads[i]); Thread::Destroy(threads[i]); } } catch (std::exception &ex) { std::cout << ex.what() << std::endl; } Environment::Cleanup(); return EXIT_SUCCESS; }
20.384615
83
0.537736
Pawapek
6b5402c64b97a3fb70ff8a2121a4cdcac33377cd
1,344
hpp
C++
day_01/src/calculate_fuel.hpp
Krenth/Advent-of-Code-2019
1a8b3dadc0ee0852f12aa6788aef5c94bac06a5b
[ "MIT" ]
null
null
null
day_01/src/calculate_fuel.hpp
Krenth/Advent-of-Code-2019
1a8b3dadc0ee0852f12aa6788aef5c94bac06a5b
[ "MIT" ]
null
null
null
day_01/src/calculate_fuel.hpp
Krenth/Advent-of-Code-2019
1a8b3dadc0ee0852f12aa6788aef5c94bac06a5b
[ "MIT" ]
null
null
null
#ifndef CALCULATE_FUEL_HPP #define CALCULATE_FUEL_HPP #include <vector> #include <cmath> #include <iostream> using namespace std; /** Calculate Additional Fuel * Calculates the additional fuel required for the part specific fuel. * * COMMENT THIS FUNCTION OUT FOR PART ONE */ int calculate_additional_fuel (int partFuel) { int additionalFuel = partFuel / 3 - 2; if (additionalFuel > 0) { additionalFuel += calculate_additional_fuel(additionalFuel); } else if (additionalFuel < 0) { additionalFuel = 0; } return additionalFuel; } /** Calculate Fuel * Calculates the part specific fuel requirements, and then the total fuel required for launch. * */ int calculate_fuel (vector<int> &masses) { int partFuel; int totalFuel = 0; cout << "Calculating Required Fuel for Parts..." << endl; for (vector<int>::iterator it = begin(masses); it != end(masses); ++it) { partFuel = *it / 3 - 2; // totalFuel += partFuel // Part One totalFuel += partFuel + calculate_additional_fuel(partFuel); // Part Two cout << *it << ": " << partFuel + calculate_additional_fuel(partFuel) << endl; } cout << "Calculated Required Fuel for Parts!" << endl << endl; return totalFuel; } #endif
27.428571
95
0.629464
Krenth
6b579f458a33197559c108f4151b21ae7ffbd13d
6,103
hpp
C++
include/System/IO/Compression/Crc32Helper.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/IO/Compression/Crc32Helper.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/IO/Compression/Crc32Helper.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Type namespace: System.IO.Compression namespace System::IO::Compression { // Forward declaring type: Crc32Helper class Crc32Helper; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::IO::Compression::Crc32Helper); DEFINE_IL2CPP_ARG_TYPE(::System::IO::Compression::Crc32Helper*, "System.IO.Compression", "Crc32Helper"); // Type namespace: System.IO.Compression namespace System::IO::Compression { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.IO.Compression.Crc32Helper // [TokenAttribute] Offset: FFFFFFFF class Crc32Helper : public ::Il2CppObject { public: // Get static field: static private readonly System.UInt32[] s_crcTable_0 static ::ArrayW<uint> _get_s_crcTable_0(); // Set static field: static private readonly System.UInt32[] s_crcTable_0 static void _set_s_crcTable_0(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_1 static ::ArrayW<uint> _get_s_crcTable_1(); // Set static field: static private readonly System.UInt32[] s_crcTable_1 static void _set_s_crcTable_1(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_2 static ::ArrayW<uint> _get_s_crcTable_2(); // Set static field: static private readonly System.UInt32[] s_crcTable_2 static void _set_s_crcTable_2(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_3 static ::ArrayW<uint> _get_s_crcTable_3(); // Set static field: static private readonly System.UInt32[] s_crcTable_3 static void _set_s_crcTable_3(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_4 static ::ArrayW<uint> _get_s_crcTable_4(); // Set static field: static private readonly System.UInt32[] s_crcTable_4 static void _set_s_crcTable_4(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_5 static ::ArrayW<uint> _get_s_crcTable_5(); // Set static field: static private readonly System.UInt32[] s_crcTable_5 static void _set_s_crcTable_5(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_6 static ::ArrayW<uint> _get_s_crcTable_6(); // Set static field: static private readonly System.UInt32[] s_crcTable_6 static void _set_s_crcTable_6(::ArrayW<uint> value); // Get static field: static private readonly System.UInt32[] s_crcTable_7 static ::ArrayW<uint> _get_s_crcTable_7(); // Set static field: static private readonly System.UInt32[] s_crcTable_7 static void _set_s_crcTable_7(::ArrayW<uint> value); // static private System.Void .cctor() // Offset: 0x111B628 static void _cctor(); // static public System.UInt32 UpdateCrc32(System.UInt32 crc32, System.Byte[] buffer, System.Int32 offset, System.Int32 length) // Offset: 0x111AD1C static uint UpdateCrc32(uint crc32, ::ArrayW<uint8_t> buffer, int offset, int length); // static private System.UInt32 ManagedCrc32(System.UInt32 crc32, System.Byte[] buffer, System.Int32 offset, System.Int32 length) // Offset: 0x111B2C4 static uint ManagedCrc32(uint crc32, ::ArrayW<uint8_t> buffer, int offset, int length); }; // System.IO.Compression.Crc32Helper #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::IO::Compression::Crc32Helper::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::IO::Compression::Crc32Helper::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::Crc32Helper*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::Compression::Crc32Helper::UpdateCrc32 // Il2CppName: UpdateCrc32 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint (*)(uint, ::ArrayW<uint8_t>, int, int)>(&System::IO::Compression::Crc32Helper::UpdateCrc32)> { static const MethodInfo* get() { static auto* crc32 = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::Crc32Helper*), "UpdateCrc32", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{crc32, buffer, offset, length}); } }; // Writing MetadataGetter for method: System::IO::Compression::Crc32Helper::ManagedCrc32 // Il2CppName: ManagedCrc32 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint (*)(uint, ::ArrayW<uint8_t>, int, int)>(&System::IO::Compression::Crc32Helper::ManagedCrc32)> { static const MethodInfo* get() { static auto* crc32 = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::Crc32Helper*), "ManagedCrc32", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{crc32, buffer, offset, length}); } };
59.252427
196
0.729805
RedBrumbler
6b59eccfc19f7499f13abf641d0efaa774288378
556
cpp
C++
UnitTests/Source/Main-Tests-Run.cpp
jwolak/Equinox-Logger
982d4a8688133299a77671e927ae9506172fe16c
[ "BSD-3-Clause" ]
null
null
null
UnitTests/Source/Main-Tests-Run.cpp
jwolak/Equinox-Logger
982d4a8688133299a77671e927ae9506172fe16c
[ "BSD-3-Clause" ]
null
null
null
UnitTests/Source/Main-Tests-Run.cpp
jwolak/Equinox-Logger
982d4a8688133299a77671e927ae9506172fe16c
[ "BSD-3-Clause" ]
null
null
null
/*#include "Command-Line-Parser-Tests.cpp"*/ #include <gtest/gtest.h> #include "gmock/gmock.h" #include "EquinoxLoggerTests/File-Logger-Tests.cpp" #include "EquinoxLoggerTests/Console-Logger-Tests.cpp" #include "EquinoxLoggerTests/Logger-Level-Tests.cpp" #include "EquinoxLoggerTests/Logger-Output-Tests.cpp" #include "EquinoxLoggerTests/Logger-Log-Message-Macros-Tests.cpp" #include "EquinoxLoggerTests/Logger-Enable-Log-Levels-Macros-Tests.cpp" int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
32.705882
71
0.77518
jwolak
6b6cab436f17d7f013f10058d542b9d919b57719
3,943
cpp
C++
Gear/Win32/System.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
Gear/Win32/System.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
Gear/Win32/System.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
#include "Gear/System.h" #include "Gear/File.hpp" NAMESPACE_START(Gear) namespace System { #if defined(PLATFORM_WIN32) std::string getErrorMessage(uint32_t err) { static std::shared_ptr<char8_t> buffer(new char8_t[UINT16_MAX]()); memset(buffer.get(), 0, UINT16_MAX); VERIFY(::FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err == ~0u ? ::GetLastError() : err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer.get(), UINT16_MAX, nullptr) != 0); return std::string(buffer.get()); } std::string getModuleDirectory() { static std::shared_ptr<char8_t> buffer(new char8_t[UINT16_MAX]()); memset(buffer.get(), 0, UINT16_MAX); VERIFY_SYSTEM(::GetModuleFileNameA(nullptr, buffer.get(), UINT16_MAX) != 0); return File::directory(std::string(buffer.get())); } std::string getCurrentWorkingDirectory() { static std::shared_ptr<char8_t> buffer(new char8_t[UINT16_MAX]()); memset(buffer.get(), 0, UINT16_MAX); VERIFY_SYSTEM(::GetCurrentDirectoryA(UINT16_MAX, buffer.get()) != 0); return std::string(buffer.get()); } void setWorkingDirectory(const char8_t* path) { assert(File::exists(path, true)); VERIFY_SYSTEM(::SetCurrentDirectoryA(path) != 0); } void sleep(uint32_t milliseconds) { ::Sleep(milliseconds); } void executeProcess(const char8_t* commandline, bool8_t waitDone) { ::SECURITY_ATTRIBUTES security { sizeof(::SECURITY_ATTRIBUTES), nullptr, true }; ::HANDLE read = nullptr, write = nullptr; VERIFY_SYSTEM(::CreatePipe(&read, &write, &security, INT16_MAX) != 0); VERIFY_SYSTEM(::SetStdHandle(STD_OUTPUT_HANDLE, write) != 0); /// If an error occurs, the ANSI version of this function (GetStartupInfoA) can raise an exception. /// The Unicode version (GetStartupInfoW) does not fail ::STARTUPINFOA startupInfo; ::GetStartupInfoA(&startupInfo); startupInfo.cb = sizeof(::STARTUPINFOA); startupInfo.dwFlags = STARTF_USESTDHANDLES; startupInfo.hStdInput = read; startupInfo.hStdOutput = write; static std::shared_ptr<char8_t> buffer(new char8_t[INT16_MAX]()); memset(buffer.get(), 0, INT16_MAX); ::PROCESS_INFORMATION processInfo; if (::CreateProcessA( nullptr, const_cast<::LPSTR>(commandline), nullptr, nullptr, true, CREATE_NO_WINDOW, nullptr, nullptr, &startupInfo, &processInfo)) { if (waitDone) { ::DWORD exit = 0u; ::WaitForSingleObject(processInfo.hProcess, INFINITE); if (::GetExitCodeProcess(processInfo.hProcess, &exit) && exit != 0u) { ::DWORD bytes = 0u; VERIFY_SYSTEM(::ReadFile(read, buffer.get(), INT16_MAX, &bytes, nullptr) != 0); //buffer[bytes] = '\0'; LOG_ERROR("Failed to execute command \"%s\"", buffer.get()); } else { VERIFY_SYSTEM(0); } /// STILL_ACTIVE } ::CloseHandle(processInfo.hThread); ::CloseHandle(processInfo.hProcess); ::CloseHandle(read); ::CloseHandle(write); return; } VERIFY_SYSTEM(0); } std::string getEnvironmentVariable(const char8_t* var) { static std::shared_ptr<char8_t> buffer(new char8_t[UINT16_MAX]()); memset(buffer.get(), 0, UINT16_MAX); VERIFY_SYSTEM(::GetEnvironmentVariableA(var, buffer.get(), UINT16_MAX) != 0); return std::string(buffer.get()); } uint64_t getModuleHandle() { ::HMODULE handle = ::GetModuleHandleA(nullptr); VERIFY_SYSTEM(handle); return reinterpret_cast<uint64_t>(handle); } DynamicLibrary::DynamicLibrary(const char8_t* name) { m_Handle = reinterpret_cast<uint64_t>(::LoadLibraryA(name)); VERIFY_SYSTEM(m_Handle); } void* DynamicLibrary::getProcAddress(const char8_t* name) { assert(m_Handle); return ::GetProcAddress(reinterpret_cast<::HMODULE>(m_Handle), name); } DynamicLibrary::~DynamicLibrary() { VERIFY_SYSTEM(::FreeLibrary(reinterpret_cast<::HMODULE>(m_Handle)) != 0); } #else #error Unknown platform! #endif } NAMESPACE_END(Gear)
24.490683
102
0.697438
Alpha255
6b6dc43732deb51532d61f2c3d16c638d33f7740
74
cc
C++
src/aut_catch_flag.cc
schlepil/funnels_cpp_2
1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac
[ "MIT" ]
null
null
null
src/aut_catch_flag.cc
schlepil/funnels_cpp_2
1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac
[ "MIT" ]
null
null
null
src/aut_catch_flag.cc
schlepil/funnels_cpp_2
1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac
[ "MIT" ]
null
null
null
// // Created by philipp on 1/21/20. // #include "aut/aut_catch_flag.hh"
12.333333
33
0.662162
schlepil
6b73864347d969b4ad938fea3a345b4d4066bd25
6,683
cpp
C++
dali/internal/system/common/performance-server.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/system/common/performance-server.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-10-19T13:45:40.000Z
2020-12-10T20:21:03.000Z
dali/internal/system/common/performance-server.cpp
expertisesolutions/dali-adaptor
810bf4dea833ea7dfbd2a0c82193bc0b3b155011
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/internal/system/common/performance-server.h> // EXTERNAL INCLUDES #include <dali/integration-api/platform-abstraction.h> // INTERNAL INCLUDES #include <dali/internal/system/common/environment-options.h> #include <dali/internal/system/common/time-service.h> namespace Dali { namespace Internal { namespace Adaptor { namespace { const unsigned int NANOSECONDS_PER_MICROSECOND = 1000u; const float MICROSECONDS_TO_SECOND = 1e-6; } // unnamed namespace PerformanceServer::PerformanceServer( AdaptorInternalServices& adaptorServices, const EnvironmentOptions& environmentOptions) : mEnvironmentOptions( environmentOptions ), mKernelTrace( adaptorServices.GetKernelTraceInterface() ), mSystemTrace( adaptorServices.GetSystemTraceInterface() ), mLogMutex(), #if defined(NETWORK_LOGGING_ENABLED) mNetworkServer( adaptorServices, environmentOptions ), mNetworkControlEnabled( mEnvironmentOptions.GetNetworkControlMode()), #endif mStatContextManager( *this ), mStatisticsLogBitmask( 0 ), mPerformanceOutputBitmask( 0 ), mLoggingEnabled( false ), mLogFunctionInstalled( false ) { SetLogging( mEnvironmentOptions.GetPerformanceStatsLoggingOptions(), mEnvironmentOptions.GetPerformanceTimeStampOutput(), mEnvironmentOptions.GetPerformanceStatsLoggingFrequency()); #if defined(NETWORK_LOGGING_ENABLED) if( mNetworkControlEnabled ) { mLoggingEnabled = true; mNetworkServer.Start(); } #endif } PerformanceServer::~PerformanceServer() { #if defined(NETWORK_LOGGING_ENABLED) if( mNetworkControlEnabled ) { mNetworkServer.Stop(); } #endif if( mLogFunctionInstalled ) { mEnvironmentOptions.UnInstallLogFunction(); } } void PerformanceServer::SetLogging( unsigned int statisticsLogOptions, unsigned int timeStampOutput, unsigned int logFrequency ) { mStatisticsLogBitmask = statisticsLogOptions; mPerformanceOutputBitmask = timeStampOutput; mStatContextManager.SetLoggingLevel( mStatisticsLogBitmask, logFrequency); if( ( mStatisticsLogBitmask == 0) && ( mPerformanceOutputBitmask == 0 )) { mLoggingEnabled = false; } else { mLoggingEnabled = true; } } void PerformanceServer::SetLoggingFrequency( unsigned int logFrequency, ContextId contextId ) { mStatContextManager.SetLoggingFrequency( logFrequency, contextId ); } void PerformanceServer::EnableLogging( bool enable, ContextId contextId ) { mStatContextManager.EnableLogging( enable, contextId ); } PerformanceInterface::ContextId PerformanceServer::AddContext( const char* name ) { // for adding custom contexts return mStatContextManager.AddContext( name, PerformanceMarker::CUSTOM_EVENTS ); } void PerformanceServer::RemoveContext( ContextId contextId ) { mStatContextManager.RemoveContext( contextId ); } void PerformanceServer::AddMarker( MarkerType markerType, ContextId contextId ) { // called only for custom markers if( !mLoggingEnabled ) { return; } // Get the time stamp uint64_t timeStamp = 0; TimeService::GetNanoseconds( timeStamp ); timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds // Create a marker PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) ); // get the marker description for this context, e.g SIZE_NEGOTIATION_START const char* const description = mStatContextManager.GetMarkerDescription( markerType, contextId ); // log it LogMarker( marker, description ); // Add custom marker to statistics context manager mStatContextManager.AddCustomMarker( marker, contextId ); } void PerformanceServer::AddMarker( MarkerType markerType ) { // called only for internal markers if( !mLoggingEnabled ) { return; } if( markerType == VSYNC ) { // make sure log function is installed, note this will be called only from v-sync thread // if the v-sync thread has already installed one, it won't make any difference. if( ! mLogFunctionInstalled ) { mEnvironmentOptions.InstallLogFunction(); mLogFunctionInstalled = true; } } // Get the time uint64_t timeStamp = 0; TimeService::GetNanoseconds( timeStamp ); timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds // Create a marker PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) ); // log it LogMarker(marker, marker.GetName() ); // Add internal marker to statistics context manager mStatContextManager.AddInternalMarker( marker ); } void PerformanceServer::LogContextStatistics( const char* const text ) { Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, text ); } void PerformanceServer::LogMarker( const PerformanceMarker& marker, const char* const description ) { #if defined(NETWORK_LOGGING_ENABLED) // log to the network ( this is thread safe ) if( mNetworkControlEnabled ) { mNetworkServer.TransmitMarker( marker, description ); } #endif // log to kernel trace if( mPerformanceOutputBitmask & OUTPUT_KERNEL_TRACE ) { // Kernel tracing implementation may not be thread safe Mutex::ScopedLock lock( mLogMutex ); // description will be something like UPDATE_START or UPDATE_END mKernelTrace.Trace( marker, description ); } // log to system trace if( mPerformanceOutputBitmask & OUTPUT_SYSTEM_TRACE ) { // System tracing implementation may not be thread safe Mutex::ScopedLock lock( mLogMutex ); mSystemTrace.Trace( marker, description ); } // log to Dali log ( this is thread safe ) if ( mPerformanceOutputBitmask & OUTPUT_DALI_LOG ) { Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%.6f (seconds), %s\n", float( marker.GetTimeStamp().microseconds ) * MICROSECONDS_TO_SECOND, description ); } } } // namespace Internal } // namespace Adaptor } // namespace Dali
27.845833
105
0.724226
Coquinho
6b778df8d301b3f59ef70bd1de11b3578c4ef526
6,493
cpp
C++
code/src/apps/celldetection-class/CellDetectorClass.cpp
pkainz/MICCAI2015
933e9e52d244ad1179713fe2f1dbb749d9e1f8d5
[ "Apache-2.0" ]
23
2015-12-14T06:06:45.000Z
2022-03-25T10:51:42.000Z
code/src/apps/celldetection-class/CellDetectorClass.cpp
pkainz/MICCAI2015
933e9e52d244ad1179713fe2f1dbb749d9e1f8d5
[ "Apache-2.0" ]
3
2016-08-18T13:16:30.000Z
2017-04-01T15:04:00.000Z
code/src/apps/celldetection-class/CellDetectorClass.cpp
pkainz/MICCAI2015
933e9e52d244ad1179713fe2f1dbb749d9e1f8d5
[ "Apache-2.0" ]
8
2015-08-18T10:31:06.000Z
2020-12-30T13:55:01.000Z
/* * CellDetectorClass.cpp * * Author: Philipp Kainz, Martin Urschler, Samuel Schulter, Paul Wohlhart, Vincent Lepetit * Institution: Medical University of Graz and Graz University of Technology, Austria * */ #include "CellDetectorClass.h" CellDetectorClass::CellDetectorClass(TClassificationForest* rfin, AppContextCellDetClass* apphp) : m_apphp(apphp), m_rf(rfin) { this->m_pwidth = m_apphp->patch_size[1]; this->m_pheight = m_apphp->patch_size[0]; } /** * Predict the distance transform image. * * @param src_img the source image * @param pred_conf_img the confidence map of this image */ void CellDetectorClass::PredictImage(const cv::Mat& src_img, cv::Mat& pred_img){ if (!m_apphp->quiet) cout << "Predicting... " << flush; // 01) extract feature planes std::vector<cv::Mat> img_features; DataLoaderCellDetClass::ExtractFeatureChannelsObjectDetection(src_img, img_features, m_apphp); // 02) initialize the prediction image (forest predicts floats!) pred_img = cv::Mat::zeros(src_img.rows, src_img.cols, CV_32F); // 03) use the m_rf and predict each pixel position of the image // define the patch offsets int xoffset = (int)(m_pwidth/2); int yoffset = (int)(m_pheight/2); // Define the search region int startX = xoffset; int endX = src_img.cols - xoffset; int startY = yoffset; int endY = src_img.rows - yoffset; // set the pixel stride int pixel_step = 1; // iterate the image SampleImgPatch imgpatch; imgpatch.features = img_features; // ALWAYS! compute the normalization feature mask cv::Mat temp_mask; temp_mask.create(cv::Size(src_img.cols, src_img.rows), CV_8U); temp_mask.setTo(cv::Scalar::all(1.0)); cv::integral(temp_mask, imgpatch.normalization_feature_mask, CV_32F); // we only have to fill the Sample in the labelled sample for testing ... so we use a dummy label LabelMLClass dummy_label = LabelMLClass(); LabelledSample<SampleImgPatch, LabelMLClass>* labelled_sample = new LabelledSample<SampleImgPatch, LabelMLClass>(imgpatch, dummy_label, 1.0, 0); // move sliding window over the image // y,x is the center pixel position to be predicted float confidence_value_foreground; int predicted_class; for (int y = startY; y < endY; y += pixel_step) { for (int x = startX; x < endX; x += pixel_step) { // set the patch location in the image labelled_sample->m_sample.x = x-xoffset; labelled_sample->m_sample.y = y-yoffset; LeafNodeStatisticsMLClass<SampleImgPatch, AppContextCellDetClass> stats(m_apphp); stats = m_rf->TestAndAverage(labelled_sample); // for (size_t c = 0; c < stats.m_class_histogram.size(); c++) // cout << stats.m_class_histogram[c] << " "; // cout << endl; // get the maximum value from the histogram (this indicates the class) std::vector<double>::iterator result; result = std::max_element(stats.m_class_histogram.begin(), stats.m_class_histogram.end()); predicted_class = std::distance(stats.m_class_histogram.begin(), result); // nevertheless just use the probability for foreground in the prediction image confidence_value_foreground = stats.m_class_histogram[1]; pred_img.at<float>(y, x) = confidence_value_foreground; //std::cout << confidence_value_foreground << std::endl; } //cout << "max class response: " << predicted_class << ", fg-probability: "; //cout << confidence_value_foreground << endl; } if (!m_apphp->quiet) cout << " done." << endl; // delete the labelled sample, this is important otherwise, all the image features won't be free'd! delete(labelled_sample); { cout << "Clearing feature map of prediction image" << endl; std::vector<cv::Mat> tmp; img_features.clear(); tmp.swap(img_features); std::vector<cv::Mat> tmp2; imgpatch.features.clear(); tmp2.swap(imgpatch.features); } } // loads and predicts a single image cv::Mat CellDetectorClass::PredictSingleImage(boost::filesystem::path file){ string filename = file.filename().string(); // Load image cv::Mat src_img_raw = DataLoaderCellDetClass::ReadImageData(file.c_str(), false); // scaling cv::Mat src_img; cv::Size new_size = cv::Size((int)((double)src_img_raw.cols*this->m_apphp->general_scaling_factor), (int)((double)src_img_raw.rows*this->m_apphp->general_scaling_factor)); resize(src_img_raw, src_img, new_size, 0, 0, cv::INTER_LINEAR); // extend border if required ExtendBorder(m_apphp, src_img, src_img, true); // The predicted image cv::Mat pred_img; // predict the image this->PredictImage(src_img, pred_img); // cv::namedWindow("prediction", CV_WINDOW_AUTOSIZE ); // cv::imshow("prediction", _8bit); // cv::waitKey(0); // store the predicted image to the hd if (m_apphp->store_predictionimages == 1) { if (!m_apphp->quiet){ cout << "Storing prediction image to " << m_apphp->path_predictionimages << filename << endl; } // convert output image cv::Mat tmp; cv::normalize(pred_img, pred_img, 0, 255, cv::NORM_MINMAX, CV_8U); pred_img.convertTo(tmp, CV_8U); cv::imwrite(m_apphp->path_predictionimages + filename, tmp); } return pred_img; } /** * Loads the images from a directory and produces the prediction results. * Post-processing is done in matlab. */ void CellDetectorClass::PredictTestImages(){ // 01) read all images from the test path vector<boost::filesystem::path> testImgFilenames; testImgFilenames.clear(); ls(m_apphp->path_testdata, ".*png", testImgFilenames); // 1) read the source data if (!m_apphp->quiet) cout << "Using " << testImgFilenames.size() << " images for testing ..." << endl; // Run detector for each image #pragma omp parallel for for (size_t i = 0; i < testImgFilenames.size(); i++) { this->PredictSingleImage(testImgFilenames[i]); // Status message if (!m_apphp->quiet) cout << "Done predicting image " << i + 1 << " / " << testImgFilenames.size() << endl; } if (!m_apphp->quiet) cout << "Done predicting all images." << endl; }
35.097297
175
0.652087
pkainz
6b7b3a65f4277ffa6cf15de6369cc343a7ff1b03
6,188
cpp
C++
SDK/Examples/FilamentViewer/FilamentViewer/Quesa to Filament/GeomToRenderable.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
24
2019-10-28T07:01:48.000Z
2022-03-04T16:10:39.000Z
SDK/Examples/FilamentViewer/FilamentViewer/Quesa to Filament/GeomToRenderable.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
8
2020-04-22T19:42:45.000Z
2021-04-30T16:28:32.000Z
SDK/Examples/FilamentViewer/FilamentViewer/Quesa to Filament/GeomToRenderable.cpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
6
2019-09-22T14:44:15.000Z
2021-04-01T20:04:29.000Z
// // GeomToRenderable.cpp // FilamentViewer // // Created by James Walker on 6/3/21. // /* ___________________________________________________________________________ COPYRIGHT: Copyright (c) 2021, Quesa Developers. All rights reserved. For the current release of Quesa, please see: <https://github.com/jwwalker/Quesa> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: o Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. o 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. o Neither the name of Quesa nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ___________________________________________________________________________ */ #include "GeomToRenderable.h" #import "BaseMaterials.h" #import "CQ3AttributeSet_Inherit.h" #import "GeomCache.h" #import "LogToConsole.h" #import "MakeMaterialInstance.h" #import "ObjectName.h" #import "RenderableGeom.h" #import "TextureManager.h" #import <Quesa/QuesaGeometry.h> #import <Quesa/QuesaMath.h> #import <Quesa/QuesaSet.h> #import <Quesa/QuesaShader.h> #import <Quesa/QuesaStyle.h> #import <Quesa/QuesaView.h> #import <Quesa/CQ3ObjectRef_Gets.h> #import <filament/RenderableManager.h> #import <filament/Box.h> #import <filament/Material.h> #import <filament/MaterialInstance.h> #import <filament/TextureSampler.h> #import <filament/Color.h> #import <filamat/MaterialBuilder.h> #import <assert.h> #import <vector> #import <memory> #import <string> using namespace filament; static sharedRenderableGeom InnerGeomToRenderable( TQ3GeometryObject inGeom, sharedFilaGeom inFilaGeom, TQ3FillStyle inFillStyle, TQ3AttributeSet inOuterAtts, TQ3ViewObject inView, filament::Engine& inEngine, BaseMaterials& inBaseMaterials, const std::string& inPartName, TextureManager& inTxMgr, filament::Texture* inDummyTexture ) { sharedRenderableGeom result( new RenderableGeom( inEngine, inPartName ) ); result->_geom = inFilaGeom; result->_srcGeom.Assign( inGeom ); CQ3ObjectRef geomAtts( CQ3Geometry_GetAttributeSet( inGeom ) ); CQ3ObjectRef effectiveAtts( CQ3AttributeSet_Inherit( inOuterAtts, geomAtts.get() ) ); result->_mat = MakeMaterialInstance( inBaseMaterials, effectiveAtts.get(), inView, inPartName, inTxMgr, inDummyTexture, inFilaGeom->_primitiveType, inFilaGeom->_hasVertexColors, inEngine ); TQ3Boolean castShadows = kQ3True; TQ3Boolean receiveShadows = kQ3True; Q3View_GetCastShadowsStyleState( inView, &castShadows ); Q3View_GetReceiveShadowsStyleState( inView, &receiveShadows ); bool isPoint = (inFilaGeom->_primitiveType == filament::backend::PrimitiveType::POINTS); if (isPoint) { castShadows = receiveShadows = kQ3False; } RenderableManager::Builder myBuilder( 1 ); myBuilder .boundingBox( inFilaGeom->_localBounds ) .material( 0, result->_mat.get() ) .geometry( 0, inFilaGeom->EffectivePrimitiveType( inFillStyle ), inFilaGeom->_vb.get(), inFilaGeom->IndexBuffer( inFillStyle ).get() ) .culling( isPoint? false : true ) .receiveShadows( receiveShadows != kQ3False ) .castShadows( castShadows != kQ3False ); myBuilder.build( inEngine, result->_entity ); return result; } /*! @function GeomToRenderable @abstract Convert a Quesa geometry to a Filament renderable. @discussion We assume that this is called from within a submitting loop, so that you can get current style states from the view. @param inGeom A Quesa Geometry. @param inOuterAtts A set of attributes which will be combined with the attribute set of the geometry. @param inView The Quesa view in which the geometry is being submitted. @param inEngine A Filament Engine. @param inBaseMaterials Some parametrized Materials. @param inTxMgr Cache of textures. @param inDummyTexture A dummy texture to use if the geometry is not textured. @param inGeomCache Cache mapping Quesa geometry to Filament geometry buffers. @result A renderable. */ sharedRenderableGeom GeomToRenderable( TQ3GeometryObject inGeom, TQ3AttributeSet inOuterAtts, TQ3ViewObject inView, filament::Engine& inEngine, BaseMaterials& inBaseMaterials, TextureManager& inTxMgr, filament::Texture* inDummyTexture, GeomCache& inGeomCache ) { sharedRenderableGeom result; TQ3FillStyle fillStyle = kQ3FillStyleFilled; Q3View_GetFillStyleState( inView, &fillStyle ); sharedFilaGeom filaGeom = inGeomCache.GetGeom( inGeom, fillStyle ); if (filaGeom.get() != nullptr) { std::string name( ObjectName( inGeom ) ); result = InnerGeomToRenderable( inGeom, filaGeom, fillStyle, inOuterAtts, inView, inEngine, inBaseMaterials, name, inTxMgr, inDummyTexture ); } return result; }
34.960452
93
0.730608
h-haris
6b8616869162bc986ad83782fd880beb74c8a518
554
cpp
C++
src/demo/benchmark_suite/functions/Sphere.cpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
5
2015-08-25T15:40:09.000Z
2020-03-15T19:33:22.000Z
src/demo/benchmark_suite/functions/Sphere.cpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
null
null
null
src/demo/benchmark_suite/functions/Sphere.cpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
3
2019-01-24T13:14:51.000Z
2022-01-03T07:30:20.000Z
#include "Sphere.h" #include <numeric> #include <cmath> #include <iostream> double Sphere::compute(const std::vector<double>& coordinates) const { const double sum = std::accumulate(coordinates.begin(), coordinates.end(), 0.0, [](double a, double b) { return a + std::pow(b,2); }); return sum; } std::vector<double> Sphere::getMinima(const unsigned int num_dimension) const { unsigned int dimleft = num_dimension; std::vector<double> res; while(dimleft--) { res.emplace_back(0); } return res; }
21.307692
106
0.644404
geneial
6b87810b20a9ec133ef2907ef636a66a44de7510
1,098
cpp
C++
tests/texture_atlas.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
tests/texture_atlas.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
tests/texture_atlas.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #include "catch.hpp" #include "utility/texture_atlas.hpp" #include <vector> #include <iostream> using namespace ts; using utility::TextureAtlas; TEST_CASE("Let's see if the texture atlas works and packs in an efficient manner.") { TextureAtlas atlas; REQUIRE_FALSE(atlas.insert({ 100, 100 })); atlas = TextureAtlas({ 512, 512 }); atlas.set_padding(0); REQUIRE(atlas.insert({ 512, 256 })); // No room for this one REQUIRE_FALSE(atlas.insert({ 512, 300 })); std::vector<IntRect> rects; for (int i = 0; i != 20; ++i) { auto rect = atlas.insert({ 50, 128 }); REQUIRE(rect); if (rect) rects.push_back(*rect); } REQUIRE(atlas.insert({ 12, 128 })); REQUIRE(atlas.insert({ 12, 128 })); // Make sure none of the rectangles we got intersect with each other. for (auto outer = rects.begin(); outer != rects.end(); ++outer) { for (auto inner = std::next(outer); inner != rects.end(); ++inner) { REQUIRE_FALSE(intersects(*inner, *outer)); } } }
21.529412
83
0.641166
mnewhouse
6b8938d3b05591ed8a0822f19d89b89be68ab87a
5,135
hpp
C++
src/crypto/crypto/crypto.hpp
games-on-whales/wolf
cd5aa47e0547d1bc7b093fb6cdd0582eae78b391
[ "MIT" ]
1
2021-12-30T13:15:05.000Z
2021-12-30T13:15:05.000Z
src/crypto/crypto/crypto.hpp
games-on-whales/wolf
cd5aa47e0547d1bc7b093fb6cdd0582eae78b391
[ "MIT" ]
null
null
null
src/crypto/crypto/crypto.hpp
games-on-whales/wolf
cd5aa47e0547d1bc7b093fb6cdd0582eae78b391
[ "MIT" ]
null
null
null
#pragma once #include <openssl/aes.h> #include <openssl/x509.h> #include <optional> #include <string> namespace crypto { /** * @brief Generates length random bytes using a cryptographically secure pseudo random generator (CSPRNG) */ std::string random(int length); /** * Encrypt the given msg using AES ecb at 128 bit * * @param msg: the message to be encrypted * @param enc_key: the key used for encryption * @param iv: optional, if not provided a random one will be generated * @param padding: optional, enables or disables padding * @return: the encrypted string */ std::string aes_encrypt_ecb(const std::string &msg, const std::string &enc_key, const std::string &iv = random(AES_BLOCK_SIZE), bool padding = false); /** * Decrypt the given msg using AES ecb at 128 bit * * @param msg: the message to be encrypted * @param enc_key: the key used for encryption * @param iv: optional, if not provided a random one will be generated * @param padding: optional, enables or disables padding * @return: the decrypted string */ std::string aes_decrypt_ecb(const std::string &msg, const std::string &enc_key, const std::string &iv = random(AES_BLOCK_SIZE), bool padding = false); /** * Will sign the given message using the private key * @param msg: the message to be signed * @param private_key: the key used for signing * @return: the signature binary data */ std::string sign(const std::string &msg, const std::string &private_key); /** * Will verify that the signature for the given message has been generated by the public_key * @param msg: the message that was originally signed * @param signature: the signature data * @param public_key: the public key, used to verify the signature * @return: true if the signature is correct, false otherwise. */ bool verify(const std::string &msg, const std::string &signature, const std::string &public_key); /** * @brief returns the SHA256 hash of the given str */ std::string sha256(const std::string &str); /** * @brief converts the given input into a HEX string */ std::string str_to_hex(const std::string &input); /** * @brief takes an HEX vector and returns a string representation of it. */ std::string hex_to_str(const std::string &hex, bool reverse); } // namespace crypto /** * @brief Wrappers on top of OpenSSL methods in order to deal with x509 certificates * * Adapted from: https://gist.github.com/nathan-osman/5041136 */ namespace x509 { /** * @brief Generates a 2048-bit RSA key. * * @return EVP_PKEY*: a ptr to a private key */ EVP_PKEY *generate_key(); /** * @brief Generates a self-signed x509 certificate. * * @param pkey: a private key generated with generate_key() * @return X509*: a pointer to a x509 certificate */ X509 *generate_x509(EVP_PKEY *pkey); /** * @brief Reads a X509 certificate string */ X509 *cert_from_string(const std::string &cert); /** * @brief Reads a X509 certificate from file */ X509 *cert_from_file(const std::string &cert_path); /** * @brief Reads a private key from file */ EVP_PKEY *pkey_from_file(const std::string &pkey_path); /** * @brief Write cert and key to disk * * @param pkey: a private key generated with generate_key() * @param pkey_filename: the name of the key file to be saved * @param x509: a certificate generated with generate_x509() * @param cert_filename: the name of the cert file to be saved * @return true when both pkey and x509 are stored on disk * @return false when one or both failed */ bool write_to_disk(EVP_PKEY *pkey, const std::string &pkey_filename, X509 *x509, const std::string &cert_filename); /** * @param pkey_filename: the name of the key file to be saved * @param cert_filename: the name of the cert file to be saved * @return true when both files are present */ bool cert_exists(const std::string &pkey_filename, const std::string &cert_filename); /** * @return the certificate signature */ std::string get_cert_signature(const X509 *cert); /** * @param private_key: set to true if EVP_PKEY is a private key, set to false for public keys * @return the key content in plaintext */ std::string get_key_content(EVP_PKEY *pkey, bool private_key); /** * @return the private key content */ std::string get_pkey_content(EVP_PKEY *pkey); /** * @return the certificate in pem format */ std::string get_cert_pem(const X509 &x509); /** * * @return the certificate public key content */ std::string get_cert_public_key(X509 *cert); /** * Checks that the paired_cert is a valid chain for untrusted_cert. * @return std::nullopt if the verification runs fine, else the error message */ std::optional<std::string> verification_error(X509 *paired_cert, X509 *untrusted_cert); /** * @brief: cleanup pointers after use * * TODO: replace with smart pointers? * * @param pkey: a private key generated with generate_key() * @param x509: a certificate generated with generate_x509() */ void cleanup(EVP_PKEY *pkey, X509 *cert); } // namespace x509
29.511494
115
0.699708
games-on-whales
6b89f70aed90f8504ee7392cc765f50211d0aff9
968
hpp
C++
src/host/registry.hpp
Ghosty141/Terminal
c1220435bea5790ea3596b30568f724b74ce5dda
[ "MIT" ]
5
2019-05-10T19:37:22.000Z
2021-02-14T12:22:35.000Z
src/host/registry.hpp
Ghosty141/Terminal
c1220435bea5790ea3596b30568f724b74ce5dda
[ "MIT" ]
2
2019-05-27T11:40:16.000Z
2019-09-03T05:58:42.000Z
src/host/registry.hpp
Ghosty141/Terminal
c1220435bea5790ea3596b30568f724b74ce5dda
[ "MIT" ]
2
2019-12-21T19:14:22.000Z
2021-02-17T16:12:52.000Z
/*++ Copyright (c) Microsoft Corporation Licensed under the MIT license. Module Name: - registry.hpp Abstract: - This module is used for reading/writing registry operations Author(s): - Michael Niksa (MiNiksa) 23-Jul-2014 - Paul Campbell (PaulCam) 23-Jul-2014 Revision History: - From components of srvinit.c --*/ #pragma once #include "precomp.h" class Registry { public: Registry(_In_ Settings* const pSettings); ~Registry(); void LoadGlobalsFromRegistry(); void LoadDefaultFromRegistry(); void LoadFromRegistry(_In_ PCWSTR const pwszConsoleTitle); void GetEditKeys(_In_opt_ HKEY hConsoleKey) const; private: void _LoadMappedProperties(_In_reads_(cPropertyMappings) const RegistrySerialization::RegPropertyMap* const rgPropertyMappings, const size_t cPropertyMappings, const HKEY hKey); Settings* const _pSettings; };
22.511628
132
0.679752
Ghosty141
6b8d0938aeccd4302da2742c7bc8b8af96b1a92a
3,716
hpp
C++
gsMassAssembler.hpp
gismo/gsElasticity
a94347d4b8d8cd76de79d4b512023be9b68363bf
[ "BSD-3-Clause-Attribution" ]
7
2020-04-24T04:11:02.000Z
2021-09-18T19:24:10.000Z
gsMassAssembler.hpp
gismo/gsElasticity
a94347d4b8d8cd76de79d4b512023be9b68363bf
[ "BSD-3-Clause-Attribution" ]
1
2021-08-16T20:41:48.000Z
2021-08-16T20:41:48.000Z
gsMassAssembler.hpp
gismo/gsElasticity
a94347d4b8d8cd76de79d4b512023be9b68363bf
[ "BSD-3-Clause-Attribution" ]
6
2020-05-12T11:11:51.000Z
2021-10-21T14:13:46.000Z
/** @file gsElMassAssembler.hpp @brief Provides mass matrix for elasticity systems in 2D plain strain and 3D continua. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): O. Weeger (2012 - 2015, TU Kaiserslautern), A.Shamanskiy (2016 - ...., TU Kaiserslautern) */ #pragma once #include <gsElasticity/gsMassAssembler.h> #include <gsElasticity/gsBasePde.h> #include <gsElasticity/gsVisitorMass.h> namespace gismo { template<class T> gsMassAssembler<T>::gsMassAssembler(const gsMultiPatch<T> & patches, const gsMultiBasis<T> & basis, const gsBoundaryConditions<T> & bconditions, const gsFunction<T> & body_force) { // Originally concieved as a meaningful class, now gsPde is just a container for // the domain, boundary conditions and the right-hand side; // any derived class can surve this purpuse, for example gsPoissonPde; // TUDO: change/remove gsPde from gsAssembler logic gsPiecewiseFunction<T> rightHandSides; rightHandSides.addPiece(body_force); typename gsPde<T>::Ptr pde( new gsBasePde<T>(patches,bconditions,rightHandSides) ); // gsAssembler<>::initialize requires a vector of bases, one for each unknown; // different bases are used to compute Dirichlet DoFs; // but always the first basis is used for the assembly; // TODO: change gsAssembler logic m_dim = body_force.targetDim(); for (short_t d = 0; d < m_dim; ++d) m_bases.push_back(basis); Base::initialize(pde, m_bases, defaultOptions()); } template <class T> gsOptionList gsMassAssembler<T>::defaultOptions() { gsOptionList opt = Base::defaultOptions(); opt.addReal("Density","Density of the material",1.); return opt; } template <class T> void gsMassAssembler<T>::refresh() { GISMO_ENSURE(m_dim == m_pde_ptr->domain().parDim(), "The RHS dimension and the domain dimension don't match!"); GISMO_ENSURE(m_dim == 2 || m_dim == 3, "Only two- and three-dimenstion domains are supported!"); std::vector<gsDofMapper> m_dofMappers(m_bases.size()); for (unsigned d = 0; d < m_bases.size(); d++) m_bases[d].getMapper((dirichlet::strategy)m_options.getInt("DirichletStrategy"), iFace::glue,m_pde_ptr->bc(),m_dofMappers[d],d,true); m_system = gsSparseSystem<T>(m_dofMappers,gsVector<index_t>::Ones(m_bases.size())); m_options.setReal("bdO",m_bases.size()*(1+m_options.getReal("bdO"))-1); m_system.reserve(m_bases[0], m_options, 1); for (unsigned d = 0; d < m_bases.size(); ++d) Base::computeDirichletDofs(d); } template<class T> void gsMassAssembler<T>::assemble(bool saveEliminationMatrix) { // allocate space for the linear system m_system.matrix().setZero(); m_system.reserve(m_bases[0], m_options, 1); m_system.rhs().setZero(Base::numDofs(),1); if (saveEliminationMatrix) { eliminationMatrix.resize(Base::numDofs(),Base::numFixedDofs()); eliminationMatrix.setZero(); eliminationMatrix.reservePerColumn(m_system.numColNz(m_bases[0],m_options)); } gsVisitorMass<T> visitor(saveEliminationMatrix ? &eliminationMatrix : nullptr); Base::template push<gsVisitorMass<T> >(visitor); m_system.matrix().makeCompressed(); if (saveEliminationMatrix) { Base::rhsWithZeroDDofs = m_system.rhs(); eliminationMatrix.makeCompressed(); } } }// namespace gismo ends
34.728972
115
0.67465
gismo