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
e2e98f8fcc220abdabb4aebcef64a8f281d47cf5
402
cpp
C++
CtCI-6th-Edition-cpp/01_Arrays_And_Strings/01_Is_Unique/isUnique.test.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
CtCI-6th-Edition-cpp/01_Arrays_And_Strings/01_Is_Unique/isUnique.test.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
CtCI-6th-Edition-cpp/01_Arrays_And_Strings/01_Is_Unique/isUnique.test.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
#include "catch.hpp" #include "isUnique.hpp" TEST_CASE("true if a string is empty", "[isUnique]") { REQUIRE(isUnique("") == true); } TEST_CASE("true if a string has all unique characters", "[isUnique]") { REQUIRE(isUnique("abcde") == true); } TEST_CASE("false if a string has duplicate characters", "[isUnique]") { REQUIRE(isUnique("abbde") == false); REQUIRE(isUnique("abcda") == false); }
25.125
71
0.666667
longztian
e2ef02f25bbfd49d8769438446e5e088dd404f12
164
hpp
C++
editor/asset/archiver/asset_archiver.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
editor/asset/archiver/asset_archiver.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
editor/asset/archiver/asset_archiver.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "chokoeditor.hpp" CE_BEGIN_ED_NAMESPACE class EAssetArchiver { public: static void Exec(const std::string& tar); }; CE_END_ED_NAMESPACE
14.909091
45
0.77439
chokomancarr
e2f0a3c88330530a7e7280b294c5d3e278725a8d
9,235
cpp
C++
src/gfx/internal/ApplicationManager.cpp
pcbaecker/ananasgfx
0637554bf82b990713314a24e4a6ead299be949a
[ "MIT" ]
1
2019-01-28T13:48:17.000Z
2019-01-28T13:48:17.000Z
src/gfx/internal/ApplicationManager.cpp
pcbaecker/ananasgfx
0637554bf82b990713314a24e4a6ead299be949a
[ "MIT" ]
11
2019-01-28T13:59:36.000Z
2019-02-09T14:59:23.000Z
src/gfx/internal/ApplicationManager.cpp
pcbaecker/ananasgfx
0637554bf82b990713314a24e4a6ead299be949a
[ "MIT" ]
null
null
null
#include <ananasgfx/gfx/internal/ApplicationManager.hpp> #include <ananasgfx/gfx/Application.hpp> #include <ananasgfx/test/ApplicationTest.hpp> #include <ee/Log.hpp> #include <algorithm> namespace gfx::_internal { int ApplicationManager::ReturnCode = EXIT_FAILURE; void ApplicationManager::removeUnlisted( std::map<std::string, ApplicationProxyBase *> &mapOfApps, std::vector<std::string> &appsToKeep) noexcept { // Iterate through all applications auto it = mapOfApps.begin(); while (it != mapOfApps.end()) { auto &app = *it; // Check if app name is in the list of applications we want to keep auto jt = std::find(appsToKeep.begin(), appsToKeep.end(), app.first); if (jt != appsToKeep.end()) { // We found the app name in the list of applications we want to keep, keep it in map // Remove appName from the vector to signal that we found it appsToKeep.erase(jt); it++; } else { // We did not find the app name in the list of applications we want to keep it = mapOfApps.erase(it); } } // If we did not find some of the apps we want to keep, we show an warning if (!appsToKeep.empty()) { for (auto &app : appsToKeep) { ee::Log::log(ee::LogLevel::Warning, "", __PRETTY_FUNCTION__, "Application not found", { ee::Note("Name", app) }); } } } ApplicationManager::ApplicationManager( bool devmode, std::vector<std::string> appNames, long appLifetime, std::string resourceSpace, std::string userSpace, bool fullscreen, bool hideCursor ) noexcept : mDevmode(devmode), mMaxAppLifetime(appLifetime), mResourcePath(std::move(resourceSpace)), mUserPath(std::move(userSpace)), mFullscreen(fullscreen), mHideCursor(hideCursor), mApplications(ApplicationStore::getInstance().getApplications()) { // Set the ReturnCode to success ApplicationManager::ReturnCode = EXIT_SUCCESS; // Check if we got appNames, which means we should only execute that apps if (!appNames.empty()) { removeUnlisted(this->mApplications, appNames); } // Put the iterator to the first application this->mIterator = this->mApplications.cbegin(); } ApplicationManager::~ApplicationManager() noexcept { if (this->mTestThread && this->mTestThread->joinable()) { this->mTestThread->join(); } } void ApplicationManager::tick() noexcept { // If we have a current application running, we update it if (this->pCurrentApplication.use_count()) { // Tick the current application this->pCurrentApplication->tick(); // Check if the application has finished if (this->pCurrentApplication->isDone()) { this->pCurrentApplication.reset(); } return; } // There is currently no application running, check if we have some waiting if (this->mIterator != this->mApplications.cend()) { // Create a new application instance and increase the iterator auto &app = (*this->mIterator++); ee::Log::log(ee::LogLevel::Info, "", __PRETTY_FUNCTION__, "Creating application instance", { ee::Note("ApplicationName", app.first) }); this->pCurrentApplication = app.second->createInstance(); this->pCurrentApplication->setMaxLifetime(this->mMaxAppLifetime); this->pCurrentApplication->setDevmode(this->mDevmode); this->pCurrentApplication->setFileManager(std::make_shared<FileManager>(this->mResourcePath, this->mUserPath)); this->pCurrentApplication->setApplicationManager(this); // Setup ApplicationTest for the launched Application (if not test exist, nothing will be done) this->setupApplicationTest(app.first, this->pCurrentApplication); // Initialize the application ee::Log::log(ee::LogLevel::Trace, "", __PRETTY_FUNCTION__, "Initializing application", { ee::Note("ApplicationName", app.first) }); if (!this->pCurrentApplication->init()) { ee::Log::log(ee::LogLevel::Error, "", __PRETTY_FUNCTION__, "Unable to initialize application", { ee::Note("ApplicationName", app.first) }); this->pCurrentApplication.reset(); return; } // Initialize the windows ee::Log::log(ee::LogLevel::Trace, "", __PRETTY_FUNCTION__, "Initializing windows", { ee::Note("ApplicationName", app.first) }); if (!this->pCurrentApplication->initWindows()) { ee::Log::log(ee::LogLevel::Error, "", __PRETTY_FUNCTION__, "Unable to initialize windows", { ee::Note("ApplicationName", app.first) }); this->pCurrentApplication.reset(); return; } // To draw the first frame we call tick() again ee::Log::log(ee::LogLevel::Trace, "", __PRETTY_FUNCTION__, "Drawing first frame", { ee::Note("ApplicationName", app.first) }); this->tick(); } } bool ApplicationManager::isDone() const noexcept { // We are done if there is no current application running return this->pCurrentApplication.use_count() == 0 // And the iterator is at the end && this->mIterator == this->mApplications.end(); } const std::shared_ptr<Application>& ApplicationManager::getCurrentApplication() noexcept { return this->pCurrentApplication; } bool ApplicationManager::setNextApplication(const std::string &appname) noexcept { // Look if the application is already in the list if (this->mApplications.count(appname)) { // Just set the iterator to the app this->mIterator = this->mApplications.find(appname); return true; } // Look if the application is in the ApplicationStore auto& apps = ApplicationStore::getInstance().getApplications(); if (apps.count(appname)) { // Store the app in the applist this->mApplications.emplace(appname,apps.at(appname)); // Set the iterator to the app this->mIterator = this->mApplications.find(appname); return true; } // No application with given name found return false; } void ApplicationManager::setupApplicationTest(const std::string &appname, std::shared_ptr<Application> application) noexcept { // Check if we have a sidekick ApplicationTest if (test::_internal::ApplicationTestStore::getInstance().getApplicationTests().count(appname) && !test::_internal::ApplicationTestStore::getInstance().getApplicationTests().at(appname).empty()) { // Get a pointer to the ApplicationTest auto test = *test::_internal::ApplicationTestStore::getInstance().getApplicationTests().at(appname).begin(); // If the thread is already defined we have to reset it if (this->mTestThread) { if (this->mTestThread->joinable()) { this->mTestThread->join(); } this->mTestThread.release(); } // Start it in another thread this->mTestThread = std::make_unique<std::thread>([]( std::string appname, std::shared_ptr<Application> appinstance, test::_internal::ApplicationTestProxyBase *pApplicationTestProxyBase) { ee::Log::log(ee::LogLevel::Info, "", __PRETTY_FUNCTION__, "Starting ApplicationTest in another thread", { ee::Note("ApplicationName", appname) }); // Create the ApplicationTest instance auto applicationTest = pApplicationTestProxyBase->createInstance(appinstance); // Run the test try { applicationTest->run(); } catch (ee::Exception &e) { ee::Log::log(ee::LogLevel::Error, e); } catch (std::exception &e) { ee::Log::log(ee::LogLevel::Error, "", __PRETTY_FUNCTION__, "Caught std::exception", { ee::Note("what()", e.what()) }); } catch (...) { ee::Log::log(ee::LogLevel::Error, "", __PRETTY_FUNCTION__, "Caught unknown exception", {}); } }, appname, application, test); } } }
42.953488
123
0.56405
pcbaecker
e2f0ab25abaa7252309d90d65cb1bf8f23e5c4ad
1,214
hpp
C++
Engine/src/Platform/OpenGL/openGLRendererAPI.hpp
Niels04/Engine
2bc0f8d65ffb0f29035edc16958c60826da7f535
[ "Apache-2.0" ]
null
null
null
Engine/src/Platform/OpenGL/openGLRendererAPI.hpp
Niels04/Engine
2bc0f8d65ffb0f29035edc16958c60826da7f535
[ "Apache-2.0" ]
null
null
null
Engine/src/Platform/OpenGL/openGLRendererAPI.hpp
Niels04/Engine
2bc0f8d65ffb0f29035edc16958c60826da7f535
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Engine/Rendering/rendererAPI.hpp" namespace Engine { class OpenGLRendererAPI : public RendererAPI { public: virtual void init() const override; virtual void clear() const override; virtual void clearDepth() const override; virtual void setClearColor(const glm::vec4& color) const override; virtual void drawIndexed(const Ref_ptr<vertexArray> va) const override;//take in a shared_ptr here, cuz we would need to convert anyway, because we want to access it in this function virtual void setViewport(const uint32_t width, const uint32_t height) const override; virtual void setBlend(const uint32_t sfactor, const uint32_t dfactor) const override; virtual void enableBlend(const bool enabled) const override; virtual void setDepth(const uint32_t method) const override; virtual void enableDepth(const bool enabled) const override; virtual void enableCullFace(const bool enabled) const override; virtual void cullFace(const uint32_t face) const override; virtual void drawToBuffers(const uint32_t count, va_list params) const override; virtual const uint32_t getMaxGlobalBuffers() const override; virtual const uint8_t getMaxTextureBinds() const override; }; }
48.56
184
0.797364
Niels04
e2fac657453f80152cb697629eb5eaf41c9c9dac
11,608
cpp
C++
src/pumiMBBL_meshops.cpp
SCOREC/pumiMBBL
7f6e5fdb721f948d7929837dadfa841b42e547a6
[ "BSD-3-Clause" ]
null
null
null
src/pumiMBBL_meshops.cpp
SCOREC/pumiMBBL
7f6e5fdb721f948d7929837dadfa841b42e547a6
[ "BSD-3-Clause" ]
6
2020-06-19T19:44:27.000Z
2022-03-30T23:09:46.000Z
src/pumiMBBL_meshops.cpp
SCOREC/pumiMBBL
7f6e5fdb721f948d7929837dadfa841b42e547a6
[ "BSD-3-Clause" ]
2
2020-03-06T20:00:00.000Z
2021-03-22T14:44:29.000Z
#include "pumiMBBL_meshops.hpp" namespace pumi { Vector3 get_rand_point_in_mesh_host(MBBL pumi_obj){ if (pumi_obj.mesh.ndim == 1){ double rand_x1 = (double) rand()/RAND_MAX; double x1_min = get_global_x1_min_coord(pumi_obj); double x1_max = get_global_x1_max_coord(pumi_obj); double q1 = x1_min + (x1_max-x1_min)*rand_x1; // std::vector<double> q = {q1,0.0,0.0}; Vector3 q = Vector3(q1,0.0,0.0); return q; } else if (pumi_obj.mesh.ndim == 2){ bool part_set = false; double x1_min = get_global_x1_min_coord(pumi_obj); double x1_max = get_global_x1_max_coord(pumi_obj); double x2_min = get_global_x2_min_coord(pumi_obj); double x2_max = get_global_x2_max_coord(pumi_obj); double q1, q2; while (!part_set){ double rand_x1 = (double) rand()/RAND_MAX; double rand_x2 = (double) rand()/RAND_MAX; q1 = x1_min + (x1_max-x1_min)*rand_x1; q2 = x2_min + (x2_max-x2_min)*rand_x2; int isub=0; int jsub=0; for (int i=1; i<=pumi_obj.mesh.nsubmesh_x1; i++){ if (pumi_obj.host_submesh_x1[i]->xmin < q1 && pumi_obj.host_submesh_x1[i]->xmax > q1){ isub = i; break; } } for (int j=1; j<=pumi_obj.mesh.nsubmesh_x2; j++){ if (pumi_obj.host_submesh_x2[j]->xmin < q2 && pumi_obj.host_submesh_x2[j]->xmax > q2){ jsub = j; break; } } if (pumi_obj.mesh.host_isactive[isub][jsub]){ part_set = true; } } // std::vector<double> q = {q1,q2,0.0}; Vector3 q = Vector3(q1,q2,0.0); return q; } // std::vector<double> q = {-999.0,-999.0,-999.0}; Vector3 q = Vector3(-999.0,-999.0,-999.0); return q; } bool is_point_in_mesh_host(MBBL pumi_obj, Vector3 q){ if (pumi_obj.mesh.ndim == 1){ double x1_min = get_global_x1_min_coord(pumi_obj); double x1_max = get_global_x1_max_coord(pumi_obj); if (q[0]>x1_min && q[0]<x1_max){ return true; } return false; } else if (pumi_obj.mesh.ndim == 2){ int isub=0; int jsub=0; for (int i=1; i<=pumi_obj.mesh.nsubmesh_x1; i++){ if (pumi_obj.host_submesh_x1[i]->xmin < q[0] && pumi_obj.host_submesh_x1[i]->xmax > q[0]){ isub = i; break; } } for (int j=1; j<=pumi_obj.mesh.nsubmesh_x2; j++){ if (pumi_obj.host_submesh_x2[j]->xmin < q[1] && pumi_obj.host_submesh_x2[j]->xmax > q[1]){ jsub = j; break; } } if (pumi_obj.mesh.host_isactive[isub][jsub]){ return true; } return false; } return false; } void flatten_submeshID_and_cellID_host(MBBL pumi_obj, int isub, int icell, int jsub, int jcell, int* submeshID, int* cellID){ *submeshID = (isub-1) + (jsub-1)*pumi_obj.mesh.nsubmesh_x1; *cellID = icell + jcell*pumi_obj.host_submesh_x1[isub]->Nel; } /** * @brief Locate the submesh ID and local cell ID for a given x1-coordinate * Uses analytical formulae to locate the input coordinate * \param[in] Object of the wrapper mesh structure * \param[in] x1-coordinate to be located * \param[out] located x1-submesh ID * \param[out] located x1-localcell ID */ void locate_submesh_and_cell_x1_host(MBBL pumi_obj, double q, int* submeshID, int *cellID){ int isubmesh; int submesh_located = 0; // int nsubmesh = pumi_obj.submesh_x1.extent(0); int nsubmesh = pumi_obj.mesh.nsubmesh_x1; for (isubmesh=1; isubmesh<=nsubmesh; isubmesh++){ if (q >= (pumi_obj.host_submesh_x1[isubmesh]->xmin) && q <= (pumi_obj.host_submesh_x1[isubmesh]->xmax)){ *submeshID = isubmesh; submesh_located++; break; } } if (!(submesh_located)){ *submeshID = -1; *cellID = -1; return; } *cellID = pumi_obj.host_submesh_x1[*submeshID]->locate_cell_host(q); } /** * @brief Locate the submesh ID and local cell ID for a given x2-coordinate * Uses analytical formulae to locate the input coordinate * \param[in] Object of the wrapper mesh structure * \param[in] x2-coordinate to be located * \param[out] located x2-submesh ID * \param[out] located x2-localcell ID */ void locate_submesh_and_cell_x2_host(MBBL pumi_obj, double q, int* submeshID, int *cellID){ int isubmesh; int submesh_located = 0; // int nsubmesh = pumi_obj.submesh_x2.extent(0); int nsubmesh = pumi_obj.mesh.nsubmesh_x2; for (isubmesh=1; isubmesh<=nsubmesh; isubmesh++){ if (q >= (pumi_obj.host_submesh_x2[isubmesh]->xmin) && q <= (pumi_obj.host_submesh_x2[isubmesh]->xmax)){ *submeshID = isubmesh; submesh_located++; break; } } if (!(submesh_located)){ *submeshID = -1; *cellID = -1; return; } *cellID = pumi_obj.host_submesh_x2[*submeshID]->locate_cell_host(q); } /** * @brief Update the submesh ID and local cell ID for a given x1-coordinate * based on previous submesh and cell IDs. * Uses adjacency search to update the IDs * \param[in] Object of the wrapper mesh structure * \param[in] new x1-coordinate * \param[in] old x1-submesh ID * \param[in] old x1-localcell ID * \param[out] updated x1-submesh ID * \param[out] updated x1-localcell ID */ void update_submesh_and_cell_x1_host(MBBL pumi_obj, double q, int prev_submeshID, int prev_cellID, int *submeshID, int *cellID){ *submeshID = prev_submeshID; while(q < (pumi_obj.host_submesh_x1[*submeshID]->xmin)){ *submeshID -= 1; prev_cellID = pumi_obj.host_submesh_x1[*submeshID]->Nel - 1; } while(q > (pumi_obj.host_submesh_x1[*submeshID]->xmax)){ *submeshID += 1; prev_cellID = 0; } *cellID = pumi_obj.host_submesh_x1[*submeshID]->update_cell_host(q, prev_cellID); } /** * @brief Update the submesh ID and local cell ID for a given x2-coordinate * based on previous submesh and cell IDs. * Uses adjacency search to update the IDs * \param[in] Object of the wrapper mesh structure * \param[in] new x2-coordinate * \param[in] old x2-submesh ID * \param[in] old x2-localcell ID * \param[out] updated x2-submesh ID * \param[out] updated x2-localcell ID */ void update_submesh_and_cell_x2_host(MBBL pumi_obj, double q, int prev_submeshID, int prev_cellID, int *submeshID, int *cellID){ *submeshID = prev_submeshID; while(q < (pumi_obj.host_submesh_x2[*submeshID]->xmin)){ *submeshID -= 1; prev_cellID = pumi_obj.host_submesh_x2[*submeshID]->Nel - 1; } while(q > (pumi_obj.host_submesh_x2[*submeshID]->xmax)){ *submeshID += 1; prev_cellID = 0; } *cellID = pumi_obj.host_submesh_x2[*submeshID]->update_cell_host(q, prev_cellID); } /** * @brief Computes the partial weights (correspoding to node on the max-side i.e right side) * for a located particle coordinate and the global directional cell ID * \param[in] Object of the wrapper mesh structure * \param[in] x1-coordinate of the particle * \param[in] x1-submesh ID of the particle * \param[in] x1-localcell ID of the particle * \param[out] global cell ID in x1 direction * \param[out] partial weight */ void calc_weights_x1_host(MBBL pumi_obj, double q, int isubmesh, int icell, int *x1_global_cell, double *Wgh2){ pumi_obj.host_submesh_x1[isubmesh]->calc_weights_host(q, icell, x1_global_cell, Wgh2); } /** * @brief Computes the partial weights (correspoding to node on the max-side i.e top side) * for a located particle coordinate and the global directional cell ID * \param[in] Object of the wrapper mesh structure * \param[in] x2-coordinate of the particle * \param[in] x2-submesh ID of the particle * \param[in] x2-localcell ID of the particle * \param[out] global cell ID in x2 direction * \param[out] partial weight */ void calc_weights_x2_host(MBBL pumi_obj, double q, int isubmesh, int icell, int *x2_global_cell, double *Wgh2){ pumi_obj.host_submesh_x2[isubmesh]->calc_weights_host(q, icell, x2_global_cell, Wgh2); } /** * @brief Computes the gloabl cell ID and node ID in 2D for a full Mesh * with no-inactive blocks (mesh with inactive blocks will need separate implementations) * \param[in] global cell ID in x1-direction * \param[in] global cell ID in x2-direction * \param[out] global cell ID in 2D * \param[out] global node ID of the node in left-bottom corner * \param[out] global node ID of the node in left-top coner */ void calc_global_cellID_and_nodeID_fullmesh_host(MBBL pumi_obj, int kcell_x1, int kcell_x2, int *global_cell_2D, int *bottomleft_node, int *topleft_node){ *global_cell_2D = kcell_x1 + kcell_x2*pumi_obj.mesh.Nel_tot_x1; *bottomleft_node = *global_cell_2D + kcell_x2; *topleft_node = *bottomleft_node + pumi_obj.mesh.Nel_tot_x1 + 1; } /** * @brief Computes the gloabl cell ID and node ID in 2D for a full Mesh * with no-inactive blocks (mesh with inactive blocks will need separate implementations) * \param[in] global cell ID in x1-direction * \param[in] global cell ID in x2-direction * \param[out] global cell ID in 2D * \param[out] global node ID of the node in left-bottom corner * \param[out] global node ID of the node in left-top coner */ void calc_global_cellID_and_nodeID_host(MBBL pumi_obj, int isubmesh, int jsubmesh, int kcell_x1, int kcell_x2, int *global_cell_2D, int *bottomleft_node, int *topleft_node){ int icell_x2 = kcell_x2 - pumi_obj.host_submesh_x2[jsubmesh]->Nel_cumulative; int elemoffset = pumi_obj.mesh.offsets.host_elemoffset_start[isubmesh][jsubmesh] + icell_x2*pumi_obj.mesh.offsets.host_elemoffset_skip[jsubmesh]; int fullmesh_elem = kcell_x1 + kcell_x2*pumi_obj.mesh.Nel_tot_x1; *global_cell_2D = fullmesh_elem - elemoffset; int nodeoffset_bottom = pumi_obj.mesh.offsets.host_nodeoffset_start[isubmesh][jsubmesh] + pumi_obj.mesh.offsets.host_nodeoffset_skip_bot[isubmesh][jsubmesh] +(icell_x2-1)*pumi_obj.mesh.offsets.host_nodeoffset_skip_mid[isubmesh][jsubmesh]; int nodeoffset_top = nodeoffset_bottom + pumi_obj.mesh.offsets.host_nodeoffset_skip_mid[isubmesh][jsubmesh]; if (icell_x2==0){ nodeoffset_bottom = pumi_obj.mesh.offsets.host_nodeoffset_start[isubmesh][jsubmesh]; nodeoffset_top = pumi_obj.mesh.offsets.host_nodeoffset_start[isubmesh][jsubmesh] + pumi_obj.mesh.offsets.host_nodeoffset_skip_bot[isubmesh][jsubmesh]; } if (icell_x2==pumi_obj.host_submesh_x2[jsubmesh]->Nel-1){ nodeoffset_top = nodeoffset_bottom + pumi_obj.mesh.offsets.host_nodeoffset_skip_top[isubmesh][jsubmesh]; } *bottomleft_node = fullmesh_elem + kcell_x2 - nodeoffset_bottom; *topleft_node = fullmesh_elem + kcell_x2 + pumi_obj.mesh.Nel_tot_x1 + 1 - nodeoffset_top; } void get_directional_submeshID_and_cellID_host(MBBL pumi_obj, int submeshID, int cellID, int* isub, int *icell, int* jsub, int *jcell){ *jsub = submeshID/pumi_obj.mesh.nsubmesh_x1 + 1; *isub = submeshID - pumi_obj.mesh.nsubmesh_x1*(*jsub-1) + 1; *jcell = cellID/pumi_obj.host_submesh_x1[*isub]->Nel; *icell = cellID - pumi_obj.host_submesh_x1[*isub]->Nel*(*jcell); } void get_directional_submeshID_host(MBBL pumi_obj, int submeshID, int* isub, int* jsub){ *jsub = submeshID/pumi_obj.mesh.nsubmesh_x1 + 1; *isub = submeshID - pumi_obj.mesh.nsubmesh_x1*(*jsub-1) + 1; } } // namespace pumi
40.587413
160
0.668591
SCOREC
c3ad7425940b56501f0e45980977ec323a15b6b7
193
cpp
C++
tute01.cpp
SLIIT-FacultyOfComputing/tutorial-02b-IT21164330
d4ea011a8a13fedc19f3889620fbd25d6de00bd2
[ "MIT" ]
null
null
null
tute01.cpp
SLIIT-FacultyOfComputing/tutorial-02b-IT21164330
d4ea011a8a13fedc19f3889620fbd25d6de00bd2
[ "MIT" ]
null
null
null
tute01.cpp
SLIIT-FacultyOfComputing/tutorial-02b-IT21164330
d4ea011a8a13fedc19f3889620fbd25d6de00bd2
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ float cm, inches; cout << "Enter a length in cm : "; cin >> cm; inches = cm / 2.54; cout <<"Length in inches is %f \n" <<inches; }
19.3
46
0.601036
SLIIT-FacultyOfComputing
c3aec22c81cd06ca508f8b7bfad1cff399058cf9
5,780
hpp
C++
Libraries/Macaronlib/include/Macaronlib/List.hpp
vpachkov/MacaronOS
e2572761f0d73a435d5660eb88d4dc96c944a349
[ "MIT" ]
21
2021-08-22T19:06:54.000Z
2022-03-31T12:44:30.000Z
Libraries/Macaronlib/include/Macaronlib/List.hpp
Plunkerusr/WisteriaOS
14f853cb8fdd6b958dd94ab24e5f19ac0268a4f6
[ "MIT" ]
1
2021-09-01T22:55:59.000Z
2021-09-08T20:52:09.000Z
Libraries/Macaronlib/include/Macaronlib/List.hpp
Plunkerusr/WisteriaOS
14f853cb8fdd6b958dd94ab24e5f19ac0268a4f6
[ "MIT" ]
null
null
null
#pragma once #include "Common.hpp" #include "Runtime.hpp" template <typename T> class ListNode { public: ListNode() = default; ~ListNode() = default; explicit ListNode(const T& val) : m_val(val) { } explicit ListNode(T&& val) : m_val(move(val)) { } ListNode<T>* next() const { return m_next; } ListNode<T>* prev() const { return m_prev; } void set_next(ListNode<T>* next) { m_next = next; } void set_prev(ListNode<T>* prev) { m_prev = prev; } public: T m_val; private: ListNode<T>* m_next {}; ListNode<T>* m_prev {}; }; template <typename T> class List { public: using ValueType = T; List() { tie_tails(); } ~List() { clear(); } List(const List& list); List& operator=(const List& list); void push_front(const T& val) { push_front(new ListNode<ValueType>(val)); } void push_front(T&& val) { push_front(new ListNode<ValueType>(move(val))); } void push_back(const T& val) { push_back(new ListNode<ValueType>(val)); } void push_back(T&& val) { push_back(new ListNode<ValueType>(move(val))); } void clear(); uint32_t size() const { return m_size; } template <class NodeType> class Iterator { friend class List<ValueType>; public: explicit Iterator(NodeType* node_ptr = nullptr) : m_node_ptr(node_ptr) { } ValueType& operator*() const { return m_node_ptr->m_val; } ValueType operator*() { return m_node_ptr->m_val; } ValueType* operator->() { return &m_node_ptr->m_val; } ValueType const* operator->() const { return &m_node_ptr->m_val; } bool operator==(const Iterator& it) const { return m_node_ptr == it.m_node_ptr; } bool operator!=(const Iterator& it) const { return m_node_ptr != it.m_node_ptr; } Iterator operator++() { m_node_ptr = m_node_ptr->next(); return *this; } Iterator operator--() { m_node_ptr = m_node_ptr->prev(); return *this; } Iterator operator++(int) { auto cp = *this; m_node_ptr = m_node_ptr->next(); return cp; } Iterator operator--(int) { auto cp = *this; m_node_ptr = m_node_ptr->prev(); return cp; } protected: NodeType* m_node_ptr {}; }; using DefaultIterator = Iterator<ListNode<ValueType>>; using ConstIterator = Iterator<const ListNode<ValueType>>; ConstIterator begin() const { return ConstIterator(m_head.next()); } ConstIterator rbegin() const { return ConstIterator(m_tail.prev()); } ConstIterator end() const { return ConstIterator(&m_tail); } ConstIterator rend() const { return ConstIterator(&m_head); } DefaultIterator begin() { return DefaultIterator(m_head.next()); } DefaultIterator rbegin() { return DefaultIterator(m_tail.prev()); } DefaultIterator end() { return DefaultIterator(&m_tail); } DefaultIterator rend() { return DefaultIterator(&m_head); } DefaultIterator find(const ValueType& value); ConstIterator find(const ValueType& value) const; DefaultIterator remove(const DefaultIterator& del_it); void append(const DefaultIterator& it_begin, const DefaultIterator& it_end); public: void tie_tails(); void push_front(ListNode<ValueType>* node); void push_back(ListNode<ValueType>* node); public: ListNode<ValueType> m_head {}; ListNode<ValueType> m_tail {}; uint32_t m_size {}; }; template <typename T> void List<T>::push_front(ListNode<ValueType>* node) { node->set_prev(&m_head); m_head.next()->set_prev(node); node->set_next(m_head.next()); m_head.set_next(node); m_size++; } template <typename T> void List<T>::push_back(ListNode<ValueType>* node) { node->set_next(&m_tail); m_tail.prev()->set_next(node); node->set_prev(m_tail.prev()); m_tail.set_prev(node); m_size++; } template <typename T> void List<T>::clear() { auto cur_node = m_head.next(); while (cur_node != &m_tail) { auto next_node = cur_node->next(); delete cur_node; cur_node = next_node; } tie_tails(); } template <typename T> void List<T>::tie_tails() { m_head.set_next(&m_tail); m_tail.set_prev(&m_head); } template <typename T> typename List<T>::ConstIterator List<T>::find(const ValueType& value) const { for (auto it = this->begin(); it != this->end(); ++it) { if (*it == value) { return it; } } return end(); } template <typename T> typename List<T>::DefaultIterator List<T>::find(const ValueType& value) { for (auto it = this->begin(); it != this->end(); ++it) { if (*it == value) { return it; } } return end(); } template <typename T> typename List<T>::DefaultIterator List<T>::remove(const List::DefaultIterator& del_it) { auto node_ptr = del_it.m_node_ptr; if (node_ptr->prev()) { node_ptr->prev()->set_next(node_ptr->next()); } if (node_ptr->next()) { node_ptr->next()->set_prev(node_ptr->prev()); } auto prev = del_it; --prev; delete node_ptr; return prev; } template <typename T> List<T>::List(const List& list) { tie_tails(); for (const auto& el : list) { push_back(el); } } template <typename T> List<T>& List<T>::operator=(const List& list) { clear(); for (const auto& el : list) { push_back(el); } return *this; } template <typename T> void List<T>::append(const DefaultIterator& it_begin, const DefaultIterator& it_end) { for (auto it = it_begin; it != it_end; it++) { push_back(*it); } }
24.1841
89
0.606055
vpachkov
c3b2f74f2e541b2ecf585752c8245c72eaf1f1f7
26,719
hpp
C++
zed_wrapper/src/component/include/zed_component.hpp
mehmetkillioglu/zed-ros2-wrapper
b8328f5225e024907366b1cf550bd4655a27e3a1
[ "MIT" ]
null
null
null
zed_wrapper/src/component/include/zed_component.hpp
mehmetkillioglu/zed-ros2-wrapper
b8328f5225e024907366b1cf550bd4655a27e3a1
[ "MIT" ]
null
null
null
zed_wrapper/src/component/include/zed_component.hpp
mehmetkillioglu/zed-ros2-wrapper
b8328f5225e024907366b1cf550bd4655a27e3a1
[ "MIT" ]
null
null
null
#ifndef ZED_COMPONENT_HPP #define ZED_COMPONENT_HPP // ///////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, STEREOLABS. // // All rights reserved. // // 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 "visibility_control.h" #include <chrono> #include <iostream> #include <memory> #include <string> #include <thread> #include <lifecycle_msgs/msg/state.hpp> #include <lifecycle_msgs/msg/transition.hpp> #include <rclcpp/rclcpp.hpp> #include <rclcpp/publisher.hpp> #include <rclcpp_lifecycle/lifecycle_node.hpp> #include <rclcpp_lifecycle/lifecycle_publisher.hpp> #include <rcutils/logging_macros.h> #include <sensor_msgs/msg/image.hpp> #include <sensor_msgs/msg/camera_info.hpp> #include <sensor_msgs/msg/point_cloud2.hpp> #include <sensor_msgs/msg/imu.hpp> #include <stereo_msgs/msg/disparity_image.hpp> #include <geometry_msgs/msg/pose_stamped.hpp> #include <geometry_msgs/msg/pose_with_covariance_stamped.hpp> #include <nav_msgs/msg/odometry.hpp> #include <nav_msgs/msg/path.hpp> #include <tf2_ros/buffer.h> #include <tf2_ros/transform_listener.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> // Services (defined in the package "stereolabs_zed_interfaces") #include "stereolabs_zed_interfaces/srv/reset_odometry.hpp" #include "stereolabs_zed_interfaces/srv/restart_tracking.hpp" #include "stereolabs_zed_interfaces/srv/set_pose.hpp" #include "stereolabs_zed_interfaces/srv/start_svo_recording.hpp" #include "stereolabs_zed_interfaces/srv/stop_svo_recording.hpp" #include "sl/Camera.hpp" #include "sl_tools.h" namespace stereolabs { // ----> Typedefs to simplify declarations typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<sensor_msgs::msg::Image>> imagePub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<sensor_msgs::msg::CameraInfo>> camInfoPub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<stereo_msgs::msg::DisparityImage>> disparityPub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<sensor_msgs::msg::PointCloud2>> pointcloudPub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<sensor_msgs::msg::Imu>> imuPub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<geometry_msgs::msg::PoseStamped>> posePub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<geometry_msgs::msg::PoseWithCovarianceStamped>> poseCovPub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<nav_msgs::msg::Odometry>> odomPub; typedef std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<nav_msgs::msg::Path>> pathPub; typedef std::shared_ptr<sensor_msgs::msg::CameraInfo> camInfoMsgPtr; typedef std::shared_ptr<sensor_msgs::msg::PointCloud2> pointcloudMsgPtr; typedef std::shared_ptr<sensor_msgs::msg::Imu> imuMsgPtr; typedef std::shared_ptr<geometry_msgs::msg::PoseStamped> poseMsgPtr; typedef std::shared_ptr<geometry_msgs::msg::PoseWithCovarianceStamped> poseCovMsgPtr; typedef std::shared_ptr<nav_msgs::msg::Odometry> odomMsgPtr; typedef std::shared_ptr<nav_msgs::msg::Path> pathMsgPtr; typedef rclcpp::Service<stereolabs_zed_interfaces::srv::ResetOdometry>::SharedPtr resetOdomSrvPtr; typedef rclcpp::Service<stereolabs_zed_interfaces::srv::RestartTracking>::SharedPtr restartTrkSrvPtr; typedef rclcpp::Service<stereolabs_zed_interfaces::srv::SetPose>::SharedPtr setPoseSrvPtr; typedef rclcpp::Service<stereolabs_zed_interfaces::srv::StartSvoRecording>::SharedPtr startSvoRecSrvPtr; typedef rclcpp::Service<stereolabs_zed_interfaces::srv::StopSvoRecording>::SharedPtr stopSvoRecSrvPtr; // <---- Typedefs to simplify declarations /// ZedCameraComponent inheriting from rclcpp_lifecycle::LifecycleNode class ZedCameraComponent : public rclcpp_lifecycle::LifecycleNode { public: RCLCPP_SMART_PTR_DEFINITIONS(ZedCameraComponent) /// Create a new ZedCameraComponent/lifecycle node with the specified name. /** * \param[in] node_name Name of the node. * \param[in] namespace_ Namespace of the node. * \param[in] use_intra_process_comms True to use the optimized intra-process communication * pipeline to pass messages between nodes in the same process using shared memory. */ ZED_PUBLIC explicit ZedCameraComponent(const std::string& node_name = "zed_node", const std::string& ros_namespace = "zed"); /// Create a ZedCameraComponent/lifecycle node based on the node name and a rclcpp::Context. /** * \param[in] node_name Name of the node. * \param[in] namespace_ Namespace of the node. * \param[in] context The context for the node (usually represents the state of a process). * \param[in] arguments Command line arguments that should apply only to this node. * \param[in] initial_parameters a list of initial values for parameters on the node. * This can be used to provide remapping rules that only affect one instance. * \param[in] use_global_arguments False to prevent node using arguments passed to the process. * \param[in] use_intra_process_comms True to use the optimized intra-process communication * pipeline to pass messages between nodes in the same process using shared memory. * \param[in] start_parameter_services True to setup ROS interfaces for accessing parameters * in the node. */ ZED_PUBLIC explicit ZedCameraComponent( const std::string& node_name, const std::string& ros_namespace, const rclcpp::NodeOptions & options ); //explicit ZedCameraComponent( // const std::string& node_name, // const std::string& ros_namespace, // rclcpp::Context::SharedPtr context, // const std::vector<std::string>& arguments, // const std::vector<rclcpp::Parameter>& initial_parameters, // bool use_global_arguments = true, // bool use_intra_process_comms = false, // bool start_parameter_services = true); virtual ~ZedCameraComponent(); /// Transition callback for state error /** * on_error callback is being called when the lifecycle node * enters the "error" state. */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_error(const rclcpp_lifecycle::State& previous_state); /// Transition callback for state shutting down /** * on_shutdown callback is being called when the lifecycle node * enters the "shutting down" state. */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_shutdown( const rclcpp_lifecycle::State& previous_state); /// Transition callback for state configuring /** * on_configure callback is being called when the lifecycle node * enters the "configuring" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "inactive" state or stays * in "unconfigured". * TRANSITION_CALLBACK_SUCCESS transitions to "inactive" * TRANSITION_CALLBACK_FAILURE transitions to "unconfigured" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_configure(const rclcpp_lifecycle::State&); /// Transition callback for state activating /** * on_activate callback is being called when the lifecycle node * enters the "activating" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "active" state or stays * in "inactive". * TRANSITION_CALLBACK_SUCCESS transitions to "active" * TRANSITION_CALLBACK_FAILURE transitions to "inactive" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_activate(const rclcpp_lifecycle::State&); /// Transition callback for state deactivating /** * on_deactivate callback is being called when the lifecycle node * enters the "deactivating" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "inactive" state or stays * in "active". * TRANSITION_CALLBACK_SUCCESS transitions to "inactive" * TRANSITION_CALLBACK_FAILURE transitions to "active" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State&); /// Transition callback for state cleaningup /** * on_cleanup callback is being called when the lifecycle node * enters the "cleaningup" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "unconfigured" state or stays * in "inactive". * TRANSITION_CALLBACK_SUCCESS transitions to "unconfigured" * TRANSITION_CALLBACK_FAILURE transitions to "inactive" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_cleanup(const rclcpp_lifecycle::State&); /** \brief Service callback to ResetOdometry service * Odometry is reset to clear drift and odometry frame gets the latest pose * from ZED tracking. */ void on_reset_odometry(const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<stereolabs_zed_interfaces::srv::ResetOdometry::Request> req, std::shared_ptr<stereolabs_zed_interfaces::srv::ResetOdometry::Response> res); /** \brief Service callback to RestartTracking service * Tracking is restarted and pose set to the value of the parameter `initial_tracking_pose` or to * the latest value set by the `SetPose` service */ void on_restart_tracking(const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<stereolabs_zed_interfaces::srv::RestartTracking::Request> req, std::shared_ptr<stereolabs_zed_interfaces::srv::RestartTracking::Response> res); /** \brief Service callback to SetPose service * Tracking is restarted and pose set to values passed with the service */ void on_set_pose(const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<stereolabs_zed_interfaces::srv::SetPose::Request> req, std::shared_ptr<stereolabs_zed_interfaces::srv::SetPose::Response> res); /* \brief Service callback to StartSvoRecording service */ void on_start_svo_recording(const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<stereolabs_zed_interfaces::srv::StartSvoRecording::Request> req, std::shared_ptr<stereolabs_zed_interfaces::srv::StartSvoRecording::Response> res); /* \brief Service callback to StopSvoRecording service */ void on_stop_svo_recording(const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<stereolabs_zed_interfaces::srv::StopSvoRecording::Request> req, std::shared_ptr<stereolabs_zed_interfaces::srv::StopSvoRecording::Response> res); protected: void zedGrabThreadFunc(); void pointcloudThreadFunc(); void zedReconnectThreadFunc(); void initPublishers(); void initServices(); void getGeneralParams(); void getVideoParams(); void getDepthParams(); void getImuParams(); void getPoseParams(); void initParameters(); void publishImages(rclcpp::Time timeStamp); void publishDepthData(rclcpp::Time timeStamp); void publishOdom(tf2::Transform odom2baseTransf, sl::Pose& slPose, rclcpp::Time t); void initTransforms(); void startTracking(); bool set_pose(float xt, float yt, float zt, float rr, float pr, float yr); void processOdometry(); void processPose(); void publishPose(); void publishMapOdom(); /** \brief Get the information of the ZED cameras and store them in an * information message * \param zed : the sl::zed::Camera* pointer to an instance * \param left_cam_info_msg : the information message to fill with the left * camera informations * \param right_cam_info_msg : the information message to fill with the right * camera informations * \param left_frame_id : the id of the reference frame of the left camera * \param right_frame_id : the id of the reference frame of the right camera */ void fillCamInfo(sl::Camera& zed, std::shared_ptr<sensor_msgs::msg::CameraInfo> leftCamInfoMsg, std::shared_ptr<sensor_msgs::msg::CameraInfo> rightCamInfoMsg, std::string leftFrameId, std::string rightFrameId, bool rawParam = false); /** \brief Publish the informations of a camera with a ros Publisher * \param cam_info_msg : the information message to publish * \param pub_cam_info : the publisher object to use * \param timeStamp : the ros::Time to stamp the message */ void publishCamInfo(camInfoMsgPtr camInfoMsg, camInfoPub pubCamInfo, rclcpp::Time timeStamp); /** \brief Publish a cv::Mat image with a ros Publisher * \param img : the image to publish * \param pub_img : the publisher object to use (different image publishers * exist) * \param img_frame_id : the id of the reference frame of the image (different * image frames exist) * \param timeStamp : the ros::Time to stamp the image */ void publishImage(sl::Mat img, imagePub pubImg, std::string imgFrameId, rclcpp::Time timeStamp); /** \brief Publish a cv::Mat depth image with a ros Publisher * \param depth : the depth image to publish * \param timeStamp : the ros::Time to stamp the depth image */ void publishDepth(sl::Mat depth, rclcpp::Time timeStamp); /** \brief Publish a cv::Mat disparity image with a ros Publisher * \param disparity : the disparity image to publish * \param timestamp : the ros::Time to stamp the depth image */ void publishDisparity(sl::Mat disparity, rclcpp::Time timestamp); /** \brief Publish a pointCloud with a ros Publisher */ void publishPointCloud(); /** \brief Callback to publish IMU raw data with a ROS publisher */ void imuPubCallback(); /** \brief Callback to publish Odometry and Pose paths with a ROS publisher */ void pathPubCallback(); /** \brief Callback to handle parameters changing * \param e : the ros::TimerEvent binded to the callback */ rcl_interfaces::msg::SetParametersResult paramChangeCallback(std::vector<rclcpp::Parameter> parameters); /** \brief Utility to retrieve the static transform from Base to Depth Sensor * from static TF */ bool getSens2BaseTransform(); /** \brief Utility to retrieve the static transform from Camera center to Depth Sensor * from static TF */ bool getSens2CameraTransform(); /** \brief Utility to retrieve the static transform from Base Link to Camera center * from static TF */ bool getCamera2BaseTransform(); private: // Status variables uint8_t mPrevTransition = lifecycle_msgs::msg::Transition::TRANSITION_CREATE; // Timestamps rclcpp::Time mPrevFrameTimestamp; rclcpp::Time mFrameTimestamp; rclcpp::Time mPointCloudTime; // Grab thread std::thread mGrabThread; bool mThreadStop = false; bool mRunGrabLoop = false; // Pointcloud thread std::thread mPcThread; // Point Cloud thread // Reconnect thread std::thread mReconnectThread; std::mutex mReconnectMutex; std::mutex mPosTrkMutex; // IMU Timer rclcpp::TimerBase::SharedPtr mImuTimer = nullptr; // Path Timer rclcpp::TimerBase::SharedPtr mPathTimer = nullptr; // ZED SDK sl::Camera mZed; // Params sl::InitParameters mZedParams; int mZedId = 0; int mZedSerialNumber = 0; int mZedUserCamModel = 1; // Camera model set by ROS Param sl::MODEL mZedRealCamModel; // Camera model requested to SDK int mZedFrameRate = 30; std::string mSvoFilepath = ""; bool mSvoMode = false; bool mVerbose = true; int mGpuId = -1; int mZedResol = 2; // Default resolution: RESOLUTION_HD720 int mZedQuality = 1; // Default quality: DEPTH_MODE_PERFORMANCE int mDepthStabilization = 1; int mCamTimeoutSec = 5; int mMaxReconnectTemp = 5; bool mZedReactivate = false; bool mCameraFlip = false; int mZedSensingMode = 0; // Default Sensing mode: SENSING_MODE_STANDARD bool mOpenniDepthMode = false; // 16 bit UC data in mm else 32F in m, // for more info -> http://www.ros.org/reps/rep-0118.html double mZedMinDepth = 0.2; double mImuPubRate = 500.0; bool mImuTimestampSync = true; bool mPublishTF = true; bool mPublishMapTF = true; std::string mWorldFrameId = "map"; std::string mMapFrameId = "map"; std::string mOdomFrameId = "odom"; bool mPoseSmoothing = false; bool mSpatialMemory = true; bool mFloorAlignment = false; bool mTwoDMode = false; double mFixedZValue = 0.0; std::vector<double> mInitialBasePose; bool mInitOdomWithPose = true; double mPathPubRate = 2.0; int mPathMaxCount = -1; bool mPublishPoseCov = true; std::string mOdometryDb = ""; // QoS profiles // https://github.com/ros2/ros2/wiki/About-Quality-of-Service-Settings rmw_qos_profile_t mVideoQos = rmw_qos_profile_default; rmw_qos_profile_t mDepthQos = rmw_qos_profile_default; rmw_qos_profile_t mImuQos = rmw_qos_profile_default; rmw_qos_profile_t mPoseQos = rmw_qos_profile_default; // ZED dynamic params double mZedMatResizeFactor = 1.0; // Dynamic... int mZedConfidence = 80; // Dynamic... double mZedMaxDepth = 10.0; // Dynamic... bool mZedAutoExposure; // Dynamic... int mZedGain = 80; // Dynamic... int mZedExposure = 80; // Dynamic... // Publishers imagePub mPubRgb; imagePub mPubRawRgb; imagePub mPubLeft; imagePub mPubRawLeft; imagePub mPubRight; imagePub mPubRawRight; imagePub mPubDepth; imagePub mPubConfImg; imagePub mPubConfMap; camInfoPub mPubRgbCamInfo; camInfoPub mPubRgbCamInfoRaw; camInfoPub mPubLeftCamInfo; camInfoPub mPubLeftCamInfoRaw; camInfoPub mPubRightCamInfo; camInfoPub mPubRightCamInfoRaw; camInfoPub mPubDepthCamInfo; camInfoPub mPubConfidenceCamInfo; disparityPub mPubDisparity; pointcloudPub mPubPointcloud; imuPub mPubImu; imuPub mPubImuRaw; posePub mPubPose; poseCovPub mPubPoseCov; odomPub mPubOdom; odomPub mPubMapOdom; pathPub mPubPathPose; pathPub mPubPathOdom; // Topics std::string mLeftTopicRoot = "left"; std::string mRightTopicRoot = "right"; std::string mRgbTopicRoot = "rgb"; std::string mDepthTopicRoot = "depth"; std::string mConfTopicRoot = "confidence"; std::string mImuTopicRoot = "imu"; std::string mLeftTopic = "left"; std::string mLeftRawTopic; std::string mLeftCamInfoTopic; std::string mLeftCamInfoRawTopic; std::string mRightTopic = "right"; std::string mRightRawTopic; std::string mRightCamInfoTopic; std::string mRightCamInfoRawTopic; std::string mRgbTopic = "rgb"; std::string mRgbRawTopic; std::string mRgbCamInfoTopic; std::string mRgbCamInfoRawTopic; std::string mDepthTopic = "depth"; std::string mDepthCamInfoTopic; std::string mConfImgTopic = "confidence_image"; std::string mConfCamInfoTopic; std::string mConfMapTopic = "confidence_map"; std::string mDispTopic = "disparity/disparity_image"; std::string mPointcloudTopic = "point_cloud/cloud_registered"; std::string mImuTopic = "data"; std::string mImuRawTopic = "data_raw"; std::string mOdomTopic = "odom"; std::string mMapOdomTopic = "map2odom"; std::string mPoseTopic = "pose"; std::string mPoseCovTopic = "pose_with_covariance"; std::string mPosePathTopic = "path_pose"; std::string mOdomPathTopic = "path_odom"; // Messages // Camera info camInfoMsgPtr mRgbCamInfoMsg; camInfoMsgPtr mLeftCamInfoMsg; camInfoMsgPtr mRightCamInfoMsg; camInfoMsgPtr mRgbCamInfoRawMsg; camInfoMsgPtr mLeftCamInfoRawMsg; camInfoMsgPtr mRightCamInfoRawMsg; camInfoMsgPtr mDepthCamInfoMsg; camInfoMsgPtr mConfidenceCamInfoMsg; // Pointcloud pointcloudMsgPtr mPointcloudMsg; // IMU imuMsgPtr mImuMsg; imuMsgPtr mImuMsgRaw; // Pos. Tracking poseMsgPtr mPoseMsg; poseCovMsgPtr mPoseCovMsg; odomMsgPtr mOdomMsg; pathMsgPtr mPathPoseMsg; pathMsgPtr mPathOdomMsg; // Frame IDs std::string mRightCamFrameId = "zed_right_camera_frame"; std::string mRightCamOptFrameId = "zed_right_camera_optical_frame"; std::string mLeftCamFrameId = "zed_left_camera_frame"; std::string mLeftCamOptFrameId = "zed_left_camera_optical_frame"; std::string mDepthFrameId; std::string mDepthOptFrameId; std::string mBaseFrameId = "base_link"; std::string mCameraFrameId = "zed_camera_center"; std::string mImuFrameId = "zed_imu_link"; // SL Pointcloud sl::Mat mCloud; // Mats int mCamWidth; // Camera frame width int mCamHeight; // Camera frame height int mMatWidth; // Data width (mCamWidth*mZedMatResizeFactor) int mMatHeight; // Data height (mCamHeight*mZedMatResizeFactor) // Thread Sync std::mutex mImuMutex; std::mutex mCamDataMutex; std::mutex mPcMutex; std::mutex mRecMutex; std::condition_variable mPcDataReadyCondVar; bool mPcDataReady = false; bool mTriggerAutoExposure = false; // Diagnostic // TODO Publish Diagnostic when available std::unique_ptr<sl_tools::CSmartMean> mElabPeriodMean_sec; std::unique_ptr<sl_tools::CSmartMean> mGrabPeriodMean_usec; std::unique_ptr<sl_tools::CSmartMean> mPcPeriodMean_usec; std::unique_ptr<sl_tools::CSmartMean> mImuPeriodMean_usec; //Tracking variables sl::Pose mLastZedPose; // Sensor to Map transform sl::Transform mInitialPoseSl; std::vector<geometry_msgs::msg::PoseStamped> mOdomPath; std::vector<geometry_msgs::msg::PoseStamped> mMapPath; bool mTrackingActivated = false; bool mTrackingReady = false; sl::TRACKING_STATE mTrackingStatus; bool mResetOdom = false; // TF Transforms tf2::Transform mMap2OdomTransf; // Coordinates of the odometry frame in map frame tf2::Transform mOdom2BaseTransf; // Coordinates of the base in odometry frame tf2::Transform mMap2BaseTransf; // Coordinates of the base in map frame tf2::Transform mMap2CameraTransf; // Coordinates of the camera in base frame tf2::Transform mSensor2BaseTransf; // Coordinates of the base frame in sensor frame tf2::Transform mSensor2CameraTransf; // Coordinates of the camera frame in sensor frame tf2::Transform mCamera2BaseTransf; // Coordinates of the base frame in camera frame bool mSensor2BaseTransfValid = false; bool mSensor2CameraTransfValid = false; bool mCamera2BaseTransfValid = false; // initialization Transform listener std::shared_ptr<tf2_ros::Buffer> mTfBuffer; std::shared_ptr<tf2_ros::TransformListener> mTfListener; // SVO recording bool mRecording = false; sl::RecordingState mRecState; // Services resetOdomSrvPtr mResetOdomSrv; restartTrkSrvPtr mRestartTrkSrv; setPoseSrvPtr mSetPoseSrv; startSvoRecSrvPtr mStartSvoRecSrv; stopSvoRecSrvPtr mStopSvoRecSrv; }; } #endif
42.956592
128
0.665444
mehmetkillioglu
c3b7d4df00cf29cbd4e89df636c19f359a9ae876
7,348
cpp
C++
Projects/WebAthl/DBForeignKey.cpp
darianbridge/WebAthl
daf916b169983375022a39645419f79c7f3cbfed
[ "Apache-2.0" ]
null
null
null
Projects/WebAthl/DBForeignKey.cpp
darianbridge/WebAthl
daf916b169983375022a39645419f79c7f3cbfed
[ "Apache-2.0" ]
null
null
null
Projects/WebAthl/DBForeignKey.cpp
darianbridge/WebAthl
daf916b169983375022a39645419f79c7f3cbfed
[ "Apache-2.0" ]
1
2021-07-05T10:10:21.000Z
2021-07-05T10:10:21.000Z
// CDBForeignKey.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "BitMaskEnum.h" #include "DBForeignKey.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // DBForeignKey ///////////////////////////////////////////////////////////////////////////// // Constructor CDBForeignKey::CDBForeignKey( ) : CBitMaskEnum( ) { } ///////////////////////////////////////////////////////////////////////////// // Destructor //CDBForeignKey::~CDBForeignKey( ) //{ //} ///////////////////////////////////////////////////////////////////////////// // Member functions CString CDBForeignKey::GetName() { return CDBForeignKey::GetName(m_dwItemEnum); } UINT CDBForeignKey::GetId() { return CDBForeignKey::GetId(m_dwItemEnum); } UINT CDBForeignKey::GetIdDrop() { return CDBForeignKey::GetIdDrop(m_dwItemEnum); } CString CDBForeignKey::GetName(DWORD dwItem) { switch( dwItem ) { case CDBForeignKey::Event : return "Event"; break; case CDBForeignKey::EventRecord : return "EventRecord"; break; // case CDBForeignKey::EventType : // return "EventType"; // break; case CDBForeignKey::Financial : return "Financial"; break; case CDBForeignKey::Groups : return "Groups"; break; // case CDBForeignKey::Location : // return "Location"; // break; // case CDBForeignKey::Organisation : // return "Organisation"; // break; case CDBForeignKey::ParticipantForSeries : return "ParticipantForSeries"; break; // case CDBForeignKey::Person : // return "Person"; // break; case CDBForeignKey::PersonComments : return "PersonComments"; break; case CDBForeignKey::PostResults : return "PostResults"; break; case CDBForeignKey::PreResults : return "PreResults"; break; // case CDBForeignKey::RegistrationType : // return "RegistrationType"; // break; case CDBForeignKey::Results : return "Results"; break; case CDBForeignKey::Roster : return "Roster"; break; // case CDBForeignKey::RosterDescriptions : // return "RosterDescriptions"; // break; case CDBForeignKey::Rules : return "Rules"; break; case CDBForeignKey::RuleSubType : return "RuleSubType"; break; // case CDBForeignKey::RuleType : // return "RuleType"; // break; case CDBForeignKey::SecurityPerson : return "SecurityPerson"; break; case CDBForeignKey::SecurityPersonSeries : return "SecurityPersonSeries"; break; // case CDBForeignKey::SecurityRole : // return "SecurityRole"; // break; case CDBForeignKey::SeriesSeason : return "SeriesSeason"; break; // case CDBForeignKey::Series : // return "Series"; // break; case CDBForeignKey::WorldStandard : return "WorldStandard"; break; default : return ""; break; } } UINT CDBForeignKey::GetId(DWORD dwItem) { switch( dwItem ) { case CDBForeignKey::Event : return IDS_SQL_FK_CR_EVENT; break; case CDBForeignKey::EventRecord : return IDS_SQL_FK_CR_EVENTRECORD; break; // case CDBForeignKey::EventType : // return IDS_SQL_FK_CR_EVENTTYPE; // break; case CDBForeignKey::Financial : return IDS_SQL_FK_CR_FINANCIAL; break; case CDBForeignKey::Groups : return IDS_SQL_FK_CR_GROUPS; break; // case CDBForeignKey::Location : // return IDS_SQL_FK_CR_LOCATION; // break; // case CDBForeignKey::Organisation : // return IDS_SQL_FK_CR_ORGANISATION; // break; case CDBForeignKey::ParticipantForSeries : return IDS_SQL_FK_CR_PARTICIPANTFORSERIES; break; // case CDBForeignKey::Person : // return IDS_SQL_FK_CR_PERSON; // break; case CDBForeignKey::PersonComments : return IDS_SQL_FK_CR_PERSONCOMMENTS; break; case CDBForeignKey::PostResults : return IDS_SQL_FK_CR_POSTRESULTS; break; case CDBForeignKey::PreResults : return IDS_SQL_FK_CR_PRERESULTS; break; // case CDBForeignKey::RegistrationType : // return IDS_SQL_FK_CR_REGISTRATIONTYPE; // break; case CDBForeignKey::Results : return IDS_SQL_FK_CR_RESULTS; break; case CDBForeignKey::Roster : return IDS_SQL_FK_CR_ROSTER; break; // case CDBForeignKey::RosterDescriptions : // return IDS_SQL_FK_CR_ROSTERDESCRIPTIONS; // break; case CDBForeignKey::Rules : return IDS_SQL_FK_CR_RULES; break; case CDBForeignKey::RuleSubType : return IDS_SQL_FK_CR_RULESUBTYPE; break; // case CDBForeignKey::RuleType : // return IDS_SQL_FK_CR_RULETYPE; // break; case CDBForeignKey::SecurityPerson : return IDS_SQL_FK_CR_SECURITYPERSON; break; case CDBForeignKey::SecurityPersonSeries : return IDS_SQL_FK_CR_SECURITYPERSONSERIES; break; // case CDBForeignKey::SecurityRole : // return IDS_SQL_FK_CR_SECURITYROLE; // break; case CDBForeignKey::SeriesSeason : return IDS_SQL_FK_CR_SERIESSEASON; break; // case CDBForeignKey::Series : // return IDS_SQL_FK_CR_SERIES; // break; case CDBForeignKey::WorldStandard : return IDS_SQL_FK_CR_WORLDSTANDARD; break; default : return 0; break; } } UINT CDBForeignKey::GetIdDrop(DWORD dwItem) { switch( dwItem ) { case CDBForeignKey::Event : return IDS_SQL_FK_DR_EVENT; break; case CDBForeignKey::EventRecord : return IDS_SQL_FK_DR_EVENTRECORD; break; // case CDBForeignKey::EventType : // return IDS_SQL_FK_DR_EVENTTYPE; // break; case CDBForeignKey::Financial : return IDS_SQL_FK_DR_FINANCIAL; break; case CDBForeignKey::Groups : return IDS_SQL_FK_DR_GROUPS; break; // case CDBForeignKey::Location : // return IDS_SQL_FK_DR_LOCATION; // break; // case CDBForeignKey::Organisation : // return IDS_SQL_FK_DR_ORGANISATION; // break; case CDBForeignKey::ParticipantForSeries : return IDS_SQL_FK_DR_PARTICIPANTFORSERIES; break; // case CDBForeignKey::Person : // return IDS_SQL_FK_DR_PERSON; // break; case CDBForeignKey::PersonComments : return IDS_SQL_FK_DR_PERSONCOMMENTS; break; case CDBForeignKey::PostResults : return IDS_SQL_FK_DR_POSTRESULTS; break; case CDBForeignKey::PreResults : return IDS_SQL_FK_DR_PRERESULTS; break; // case CDBForeignKey::RegistrationType : // return IDS_SQL_FK_DR_REGISTRATIONTYPE; // break; case CDBForeignKey::Results : return IDS_SQL_FK_DR_RESULTS; break; case CDBForeignKey::Roster : return IDS_SQL_FK_DR_ROSTER; break; // case CDBForeignKey::RosterDescriptions : // return IDS_SQL_FK_DR_ROSTERDESCRIPTIONS; // break; case CDBForeignKey::Rules : return IDS_SQL_FK_DR_RULES; break; case CDBForeignKey::RuleSubType : return IDS_SQL_FK_DR_RULESUBTYPE; break; // case CDBForeignKey::RuleType : // return IDS_SQL_FK_DR_RULETYPE; // break; case CDBForeignKey::SecurityPerson : return IDS_SQL_FK_DR_SECURITYPERSON; break; case CDBForeignKey::SecurityPersonSeries : return IDS_SQL_FK_DR_SECURITYPERSONSERIES; break; // case CDBForeignKey::SecurityRole : // return IDS_SQL_FK_DR_SECURITYROLE; // break; case CDBForeignKey::SeriesSeason : return IDS_SQL_FK_DR_SERIESSEASON; break; // case CDBForeignKey::Series : // return IDS_SQL_FK_DR_SERIES; // break; case CDBForeignKey::WorldStandard : return IDS_SQL_FK_DR_WORLDSTANDARD; break; default : return 0; break; } }
23.253165
77
0.693114
darianbridge
c3befa0aa7796910d453dc9dcb88279530bb0caa
175
cpp
C++
Python/Source/Constant.cpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
null
null
null
Python/Source/Constant.cpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
30
2019-02-05T23:18:13.000Z
2019-07-05T14:19:04.000Z
Python/Source/Constant.cpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
1
2020-06-01T06:32:05.000Z
2020-06-01T06:32:05.000Z
#include "Rover/Python/Constant.hpp" using namespace pybind11; using namespace Rover; void Rover::export_constant(module& module) { export_constant<object>(module, ""); }
19.444444
45
0.76
kranar
c3bf059b87f6834e127769027b9e3408b884a478
1,009
cpp
C++
PIN64/pin64/block.cpp
MooglyGuy/pin64
aa411cbabbc400f752411d2c0a0711209d7f4826
[ "BSD-3-Clause" ]
1
2019-05-22T23:22:14.000Z
2019-05-22T23:22:14.000Z
PIN64/pin64/block.cpp
MooglyGuy/pin64
aa411cbabbc400f752411d2c0a0711209d7f4826
[ "BSD-3-Clause" ]
1
2019-07-04T10:12:06.000Z
2019-07-04T10:12:06.000Z
PIN64/pin64/block.cpp
MooglyGuy/pin64
aa411cbabbc400f752411d2c0a0711209d7f4826
[ "BSD-3-Clause" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Ryan Holtz #include "block.h" #ifdef PIN64_STANDALONE_BUILD #include <CRC.h> #endif const uint8_t pin64_block_t::BLOCK_ID[4] = { 'P', '6', '4', 'B' }; pin64_block_t::pin64_block_t(uint8_t* data, size_t size) : pin64_block_t() { m_data.put(data, size); finalize(); } pin64_block_t::pin64_block_t(pin64_data_t* data, size_t size) : pin64_block_t() { m_data.put(data, size); finalize(); } void pin64_block_t::finalize() { if (m_data.size() > 0) #ifdef PIN64_STANDALONE_BUILD m_crc32 = CRC::Calculate(m_data.bytes(), m_data.size(), CRC::CRC_32()); #else m_crc32 = (uint32_t)util::crc32_creator::simple(m_data.bytes(), (uint32_t)m_data.size()); #endif else m_crc32 = ~0; m_data.reset(); } void pin64_block_t::clear() { m_crc32 = 0; m_data.clear(); } size_t pin64_block_t::size() const { return sizeof(uint8_t) * 4 // block header + sizeof(uint32_t) // data CRC32 + sizeof(uint32_t) // data size + m_data.size(); // data }
21.468085
91
0.676908
MooglyGuy
c3bf2d234c0a0835ed4f306331c815e8d962cbbb
29,235
cpp
C++
lib/CodeGen/LiveInterval.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
16
2015-09-08T08:49:11.000Z
2019-07-20T14:46:20.000Z
src/llvm/lib/CodeGen/LiveInterval.cpp
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2019-02-10T08:27:48.000Z
2019-02-10T08:27:48.000Z
src/llvm/lib/CodeGen/LiveInterval.cpp
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
7
2016-05-26T17:31:46.000Z
2020-11-04T06:39:23.000Z
//===-- LiveInterval.cpp - Live Interval Representation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the LiveRange and LiveInterval classes. Given some // numbering of each the machine instructions an interval [i, j) is said to be a // live interval for register v if there is no instruction with number j' > j // such that v is live at j' and there is no instruction with number i' < i such // that v is live at i'. In this implementation intervals can have holes, // i.e. an interval might look like [1,20), [50,65), [1000,1001). Each // individual range is represented as an instance of LiveRange, and the whole // interval is represented as an instance of LiveInterval. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/LiveInterval.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegisterInfo.h" #include "RegisterCoalescer.h" #include <algorithm> using namespace llvm; LiveInterval::iterator LiveInterval::find(SlotIndex Pos) { // This algorithm is basically std::upper_bound. // Unfortunately, std::upper_bound cannot be used with mixed types until we // adopt C++0x. Many libraries can do it, but not all. if (empty() || Pos >= endIndex()) return end(); iterator I = begin(); size_t Len = ranges.size(); do { size_t Mid = Len >> 1; if (Pos < I[Mid].end) Len = Mid; else I += Mid + 1, Len -= Mid + 1; } while (Len); return I; } VNInfo *LiveInterval::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator) { assert(!Def.isDead() && "Cannot define a value at the dead slot"); iterator I = find(Def); if (I == end()) { VNInfo *VNI = getNextValue(Def, VNInfoAllocator); ranges.push_back(LiveRange(Def, Def.getDeadSlot(), VNI)); return VNI; } if (SlotIndex::isSameInstr(Def, I->start)) { assert(I->start == Def && "Cannot insert def, already live"); assert(I->valno->def == Def && "Inconsistent existing value def"); return I->valno; } assert(SlotIndex::isEarlierInstr(Def, I->start) && "Already live at def"); VNInfo *VNI = getNextValue(Def, VNInfoAllocator); ranges.insert(I, LiveRange(Def, Def.getDeadSlot(), VNI)); return VNI; } // overlaps - Return true if the intersection of the two live intervals is // not empty. // // An example for overlaps(): // // 0: A = ... // 4: B = ... // 8: C = A + B ;; last use of A // // The live intervals should look like: // // A = [3, 11) // B = [7, x) // C = [11, y) // // A->overlaps(C) should return false since we want to be able to join // A and C. // bool LiveInterval::overlapsFrom(const LiveInterval& other, const_iterator StartPos) const { assert(!empty() && "empty interval"); const_iterator i = begin(); const_iterator ie = end(); const_iterator j = StartPos; const_iterator je = other.end(); assert((StartPos->start <= i->start || StartPos == other.begin()) && StartPos != other.end() && "Bogus start position hint!"); if (i->start < j->start) { i = std::upper_bound(i, ie, j->start); if (i != ranges.begin()) --i; } else if (j->start < i->start) { ++StartPos; if (StartPos != other.end() && StartPos->start <= i->start) { assert(StartPos < other.end() && i < end()); j = std::upper_bound(j, je, i->start); if (j != other.ranges.begin()) --j; } } else { return true; } if (j == je) return false; while (i != ie) { if (i->start > j->start) { std::swap(i, j); std::swap(ie, je); } if (i->end > j->start) return true; ++i; } return false; } bool LiveInterval::overlaps(const LiveInterval &Other, const CoalescerPair &CP, const SlotIndexes &Indexes) const { assert(!empty() && "empty interval"); if (Other.empty()) return false; // Use binary searches to find initial positions. const_iterator I = find(Other.beginIndex()); const_iterator IE = end(); if (I == IE) return false; const_iterator J = Other.find(I->start); const_iterator JE = Other.end(); if (J == JE) return false; for (;;) { // J has just been advanced to satisfy: assert(J->end >= I->start); // Check for an overlap. if (J->start < I->end) { // I and J are overlapping. Find the later start. SlotIndex Def = std::max(I->start, J->start); // Allow the overlap if Def is a coalescable copy. if (Def.isBlock() || !CP.isCoalescable(Indexes.getInstructionFromIndex(Def))) return true; } // Advance the iterator that ends first to check for more overlaps. if (J->end > I->end) { std::swap(I, J); std::swap(IE, JE); } // Advance J until J->end >= I->start. do if (++J == JE) return false; while (J->end < I->start); } } /// overlaps - Return true if the live interval overlaps a range specified /// by [Start, End). bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const { assert(Start < End && "Invalid range"); const_iterator I = std::lower_bound(begin(), end(), End); return I != begin() && (--I)->end > Start; } /// ValNo is dead, remove it. If it is the largest value number, just nuke it /// (and any other deleted values neighboring it), otherwise mark it as ~1U so /// it can be nuked later. void LiveInterval::markValNoForDeletion(VNInfo *ValNo) { if (ValNo->id == getNumValNums()-1) { do { valnos.pop_back(); } while (!valnos.empty() && valnos.back()->isUnused()); } else { ValNo->markUnused(); } } /// RenumberValues - Renumber all values in order of appearance and delete the /// remaining unused values. void LiveInterval::RenumberValues(LiveIntervals &lis) { SmallPtrSet<VNInfo*, 8> Seen; valnos.clear(); for (const_iterator I = begin(), E = end(); I != E; ++I) { VNInfo *VNI = I->valno; if (!Seen.insert(VNI)) continue; assert(!VNI->isUnused() && "Unused valno used by live range"); VNI->id = (unsigned)valnos.size(); valnos.push_back(VNI); } } /// extendIntervalEndTo - This method is used when we want to extend the range /// specified by I to end at the specified endpoint. To do this, we should /// merge and eliminate all ranges that this will overlap with. The iterator is /// not invalidated. void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) { assert(I != ranges.end() && "Not a valid interval!"); VNInfo *ValNo = I->valno; // Search for the first interval that we can't merge with. Ranges::iterator MergeTo = llvm::next(I); for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) { assert(MergeTo->valno == ValNo && "Cannot merge with differing values!"); } // If NewEnd was in the middle of an interval, make sure to get its endpoint. I->end = std::max(NewEnd, prior(MergeTo)->end); // If the newly formed range now touches the range after it and if they have // the same value number, merge the two ranges into one range. if (MergeTo != ranges.end() && MergeTo->start <= I->end && MergeTo->valno == ValNo) { I->end = MergeTo->end; ++MergeTo; } // Erase any dead ranges. ranges.erase(llvm::next(I), MergeTo); } /// extendIntervalStartTo - This method is used when we want to extend the range /// specified by I to start at the specified endpoint. To do this, we should /// merge and eliminate all ranges that this will overlap with. LiveInterval::Ranges::iterator LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) { assert(I != ranges.end() && "Not a valid interval!"); VNInfo *ValNo = I->valno; // Search for the first interval that we can't merge with. Ranges::iterator MergeTo = I; do { if (MergeTo == ranges.begin()) { I->start = NewStart; ranges.erase(MergeTo, I); return I; } assert(MergeTo->valno == ValNo && "Cannot merge with differing values!"); --MergeTo; } while (NewStart <= MergeTo->start); // If we start in the middle of another interval, just delete a range and // extend that interval. if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) { MergeTo->end = I->end; } else { // Otherwise, extend the interval right after. ++MergeTo; MergeTo->start = NewStart; MergeTo->end = I->end; } ranges.erase(llvm::next(MergeTo), llvm::next(I)); return MergeTo; } LiveInterval::iterator LiveInterval::addRangeFrom(LiveRange LR, iterator From) { SlotIndex Start = LR.start, End = LR.end; iterator it = std::upper_bound(From, ranges.end(), Start); // If the inserted interval starts in the middle or right at the end of // another interval, just extend that interval to contain the range of LR. if (it != ranges.begin()) { iterator B = prior(it); if (LR.valno == B->valno) { if (B->start <= Start && B->end >= Start) { extendIntervalEndTo(B, End); return B; } } else { // Check to make sure that we are not overlapping two live ranges with // different valno's. assert(B->end <= Start && "Cannot overlap two LiveRanges with differing ValID's" " (did you def the same reg twice in a MachineInstr?)"); } } // Otherwise, if this range ends in the middle of, or right next to, another // interval, merge it into that interval. if (it != ranges.end()) { if (LR.valno == it->valno) { if (it->start <= End) { it = extendIntervalStartTo(it, Start); // If LR is a complete superset of an interval, we may need to grow its // endpoint as well. if (End > it->end) extendIntervalEndTo(it, End); return it; } } else { // Check to make sure that we are not overlapping two live ranges with // different valno's. assert(it->start >= End && "Cannot overlap two LiveRanges with differing ValID's"); } } // Otherwise, this is just a new range that doesn't interact with anything. // Insert it. return ranges.insert(it, LR); } /// extendInBlock - If this interval is live before Kill in the basic /// block that starts at StartIdx, extend it to be live up to Kill and return /// the value. If there is no live range before Kill, return NULL. VNInfo *LiveInterval::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) { if (empty()) return 0; iterator I = std::upper_bound(begin(), end(), Kill.getPrevSlot()); if (I == begin()) return 0; --I; if (I->end <= StartIdx) return 0; if (I->end < Kill) extendIntervalEndTo(I, Kill); return I->valno; } /// removeRange - Remove the specified range from this interval. Note that /// the range must be in a single LiveRange in its entirety. void LiveInterval::removeRange(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo) { // Find the LiveRange containing this span. Ranges::iterator I = find(Start); assert(I != ranges.end() && "Range is not in interval!"); assert(I->containsRange(Start, End) && "Range is not entirely in interval!"); // If the span we are removing is at the start of the LiveRange, adjust it. VNInfo *ValNo = I->valno; if (I->start == Start) { if (I->end == End) { if (RemoveDeadValNo) { // Check if val# is dead. bool isDead = true; for (const_iterator II = begin(), EE = end(); II != EE; ++II) if (II != I && II->valno == ValNo) { isDead = false; break; } if (isDead) { // Now that ValNo is dead, remove it. markValNoForDeletion(ValNo); } } ranges.erase(I); // Removed the whole LiveRange. } else I->start = End; return; } // Otherwise if the span we are removing is at the end of the LiveRange, // adjust the other way. if (I->end == End) { I->end = Start; return; } // Otherwise, we are splitting the LiveRange into two pieces. SlotIndex OldEnd = I->end; I->end = Start; // Trim the old interval. // Insert the new one. ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo)); } /// removeValNo - Remove all the ranges defined by the specified value#. /// Also remove the value# from value# list. void LiveInterval::removeValNo(VNInfo *ValNo) { if (empty()) return; Ranges::iterator I = ranges.end(); Ranges::iterator E = ranges.begin(); do { --I; if (I->valno == ValNo) ranges.erase(I); } while (I != E); // Now that ValNo is dead, remove it. markValNoForDeletion(ValNo); } /// join - Join two live intervals (this, and other) together. This applies /// mappings to the value numbers in the LHS/RHS intervals as specified. If /// the intervals are not joinable, this aborts. void LiveInterval::join(LiveInterval &Other, const int *LHSValNoAssignments, const int *RHSValNoAssignments, SmallVector<VNInfo*, 16> &NewVNInfo, MachineRegisterInfo *MRI) { verify(); // Determine if any of our live range values are mapped. This is uncommon, so // we want to avoid the interval scan if not. bool MustMapCurValNos = false; unsigned NumVals = getNumValNums(); unsigned NumNewVals = NewVNInfo.size(); for (unsigned i = 0; i != NumVals; ++i) { unsigned LHSValID = LHSValNoAssignments[i]; if (i != LHSValID || (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) { MustMapCurValNos = true; break; } } // If we have to apply a mapping to our base interval assignment, rewrite it // now. if (MustMapCurValNos && !empty()) { // Map the first live range. iterator OutIt = begin(); OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]]; for (iterator I = next(OutIt), E = end(); I != E; ++I) { VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]]; assert(nextValNo != 0 && "Huh?"); // If this live range has the same value # as its immediate predecessor, // and if they are neighbors, remove one LiveRange. This happens when we // have [0,4:0)[4,7:1) and map 0/1 onto the same value #. if (OutIt->valno == nextValNo && OutIt->end == I->start) { OutIt->end = I->end; } else { // Didn't merge. Move OutIt to the next interval, ++OutIt; OutIt->valno = nextValNo; if (OutIt != I) { OutIt->start = I->start; OutIt->end = I->end; } } } // If we merge some live ranges, chop off the end. ++OutIt; ranges.erase(OutIt, end()); } // Remember assignements because val# ids are changing. SmallVector<unsigned, 16> OtherAssignments; for (iterator I = Other.begin(), E = Other.end(); I != E; ++I) OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]); // Update val# info. Renumber them and make sure they all belong to this // LiveInterval now. Also remove dead val#'s. unsigned NumValNos = 0; for (unsigned i = 0; i < NumNewVals; ++i) { VNInfo *VNI = NewVNInfo[i]; if (VNI) { if (NumValNos >= NumVals) valnos.push_back(VNI); else valnos[NumValNos] = VNI; VNI->id = NumValNos++; // Renumber val#. } } if (NumNewVals < NumVals) valnos.resize(NumNewVals); // shrinkify // Okay, now insert the RHS live ranges into the LHS. unsigned RangeNo = 0; for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) { // Map the valno in the other live range to the current live range. I->valno = NewVNInfo[OtherAssignments[RangeNo]]; assert(I->valno && "Adding a dead range?"); } mergeIntervalRanges(Other); verify(); } /// \brief Helper function for merging in another LiveInterval's ranges. /// /// This is a helper routine implementing an efficient merge of another /// LiveIntervals ranges into the current interval. /// /// \param LHSValNo If non-NULL, set as the new value number for every range /// from RHS which is merged into the LHS. /// \param RHSValNo If non-NULL, then only ranges in RHS whose original value /// number maches this value number will be merged into LHS. void LiveInterval::mergeIntervalRanges(const LiveInterval &RHS, VNInfo *LHSValNo, const VNInfo *RHSValNo) { if (RHS.empty()) return; // Ensure we're starting with a valid range. Note that we don't verify RHS // because it may have had its value numbers adjusted in preparation for // merging. verify(); // The strategy for merging these efficiently is as follows: // // 1) Find the beginning of the impacted ranges in the LHS. // 2) Create a new, merged sub-squence of ranges merging from the position in // #1 until either LHS or RHS is exhausted. Any part of LHS between RHS // entries being merged will be copied into this new range. // 3) Replace the relevant section in LHS with these newly merged ranges. // 4) Append any remaning ranges from RHS if LHS is exhausted in #2. // // We don't follow the typical in-place merge strategy for sorted ranges of // appending the new ranges to the back and then using std::inplace_merge // because one step of the merge can both mutate the original elements and // remove elements from the original. Essentially, because the merge includes // collapsing overlapping ranges, a more complex approach is required. // We do an initial binary search to optimize for a common pattern: a large // LHS, and a very small RHS. const_iterator RI = RHS.begin(), RE = RHS.end(); iterator LE = end(), LI = std::upper_bound(begin(), LE, *RI); // Merge into NewRanges until one of the ranges is exhausted. SmallVector<LiveRange, 4> NewRanges; // Keep track of where to begin the replacement. iterator ReplaceI = LI; // If there are preceding ranges in the LHS, put the last one into NewRanges // so we can optionally extend it. Adjust the replacement point accordingly. if (LI != begin()) { ReplaceI = llvm::prior(LI); NewRanges.push_back(*ReplaceI); } // Now loop over the mergable portions of both LHS and RHS, merging into // NewRanges. while (LI != LE && RI != RE) { // Skip incoming ranges with the wrong value. if (RHSValNo && RI->valno != RHSValNo) { ++RI; continue; } // Select the first range. We pick the earliest start point, and then the // largest range. LiveRange R = *LI; if (*RI < R) { R = *RI; ++RI; if (LHSValNo) R.valno = LHSValNo; } else { ++LI; } if (NewRanges.empty()) { NewRanges.push_back(R); continue; } LiveRange &LastR = NewRanges.back(); if (R.valno == LastR.valno) { // Try to merge this range into the last one. if (R.start <= LastR.end) { LastR.end = std::max(LastR.end, R.end); continue; } } else { // We can't merge ranges across a value number. assert(R.start >= LastR.end && "Cannot overlap two LiveRanges with differing ValID's"); } // If all else fails, just append the range. NewRanges.push_back(R); } assert(RI == RE || LI == LE); // Check for being able to merge into the trailing sequence of ranges on the LHS. if (!NewRanges.empty()) for (; LI != LE && (LI->valno == NewRanges.back().valno && LI->start <= NewRanges.back().end); ++LI) NewRanges.back().end = std::max(NewRanges.back().end, LI->end); // Replace the ranges in the LHS with the newly merged ones. It would be // really nice if there were a move-supporting 'replace' directly in // SmallVector, but as there is not, we pay the price of copies to avoid // wasted memory allocations. SmallVectorImpl<LiveRange>::iterator NRI = NewRanges.begin(), NRE = NewRanges.end(); for (; ReplaceI != LI && NRI != NRE; ++ReplaceI, ++NRI) *ReplaceI = *NRI; if (NRI == NRE) ranges.erase(ReplaceI, LI); else ranges.insert(LI, NRI, NRE); // And finally insert any trailing end of RHS (if we have one). for (; RI != RE; ++RI) { LiveRange R = *RI; if (LHSValNo) R.valno = LHSValNo; if (!ranges.empty() && ranges.back().valno == R.valno && R.start <= ranges.back().end) ranges.back().end = std::max(ranges.back().end, R.end); else ranges.push_back(R); } // Ensure we finished with a valid new sequence of ranges. verify(); } /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live /// interval as the specified value number. The LiveRanges in RHS are /// allowed to overlap with LiveRanges in the current interval, but only if /// the overlapping LiveRanges have the specified value number. void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo) { mergeIntervalRanges(RHS, LHSValNo); } /// MergeValueInAsValue - Merge all of the live ranges of a specific val# /// in RHS into this live interval as the specified value number. /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the /// current interval, it will replace the value numbers of the overlaped /// live ranges with the specified value number. void LiveInterval::MergeValueInAsValue(const LiveInterval &RHS, const VNInfo *RHSValNo, VNInfo *LHSValNo) { mergeIntervalRanges(RHS, LHSValNo, RHSValNo); } /// MergeValueNumberInto - This method is called when two value nubmers /// are found to be equivalent. This eliminates V1, replacing all /// LiveRanges with the V1 value number with the V2 value number. This can /// cause merging of V1/V2 values numbers and compaction of the value space. VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) { assert(V1 != V2 && "Identical value#'s are always equivalent!"); // This code actually merges the (numerically) larger value number into the // smaller value number, which is likely to allow us to compactify the value // space. The only thing we have to be careful of is to preserve the // instruction that defines the result value. // Make sure V2 is smaller than V1. if (V1->id < V2->id) { V1->copyFrom(*V2); std::swap(V1, V2); } // Merge V1 live ranges into V2. for (iterator I = begin(); I != end(); ) { iterator LR = I++; if (LR->valno != V1) continue; // Not a V1 LiveRange. // Okay, we found a V1 live range. If it had a previous, touching, V2 live // range, extend it. if (LR != begin()) { iterator Prev = LR-1; if (Prev->valno == V2 && Prev->end == LR->start) { Prev->end = LR->end; // Erase this live-range. ranges.erase(LR); I = Prev+1; LR = Prev; } } // Okay, now we have a V1 or V2 live range that is maximally merged forward. // Ensure that it is a V2 live-range. LR->valno = V2; // If we can merge it into later V2 live ranges, do so now. We ignore any // following V1 live ranges, as they will be merged in subsequent iterations // of the loop. if (I != end()) { if (I->start == LR->end && I->valno == V2) { LR->end = I->end; ranges.erase(I); I = LR+1; } } } // Now that V1 is dead, remove it. markValNoForDeletion(V1); return V2; } unsigned LiveInterval::getSize() const { unsigned Sum = 0; for (const_iterator I = begin(), E = end(); I != E; ++I) Sum += I->start.distance(I->end); return Sum; } raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) { return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void LiveRange::dump() const { dbgs() << *this << "\n"; } #endif void LiveInterval::print(raw_ostream &OS) const { if (empty()) OS << "EMPTY"; else { for (LiveInterval::Ranges::const_iterator I = ranges.begin(), E = ranges.end(); I != E; ++I) { OS << *I; assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo"); } } // Print value number info. if (getNumValNums()) { OS << " "; unsigned vnum = 0; for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e; ++i, ++vnum) { const VNInfo *vni = *i; if (vnum) OS << " "; OS << vnum << "@"; if (vni->isUnused()) { OS << "x"; } else { OS << vni->def; if (vni->isPHIDef()) OS << "-phi"; } } } } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void LiveInterval::dump() const { dbgs() << *this << "\n"; } #endif #ifndef NDEBUG void LiveInterval::verify() const { for (const_iterator I = begin(), E = end(); I != E; ++I) { assert(I->start.isValid()); assert(I->end.isValid()); assert(I->start < I->end); assert(I->valno != 0); assert(I->valno == valnos[I->valno->id]); if (llvm::next(I) != E) { assert(I->end <= llvm::next(I)->start); if (I->end == llvm::next(I)->start) assert(I->valno != llvm::next(I)->valno); } } } #endif void LiveRange::print(raw_ostream &os) const { os << *this; } unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) { // Create initial equivalence classes. EqClass.clear(); EqClass.grow(LI->getNumValNums()); const VNInfo *used = 0, *unused = 0; // Determine connections. for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end(); I != E; ++I) { const VNInfo *VNI = *I; // Group all unused values into one class. if (VNI->isUnused()) { if (unused) EqClass.join(unused->id, VNI->id); unused = VNI; continue; } used = VNI; if (VNI->isPHIDef()) { const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); assert(MBB && "Phi-def has no defining MBB"); // Connect to values live out of predecessors. for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) if (const VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI))) EqClass.join(VNI->id, PVNI->id); } else { // Normal value defined by an instruction. Check for two-addr redef. // FIXME: This could be coincidental. Should we really check for a tied // operand constraint? // Note that VNI->def may be a use slot for an early clobber def. if (const VNInfo *UVNI = LI->getVNInfoBefore(VNI->def)) EqClass.join(VNI->id, UVNI->id); } } // Lump all the unused values in with the last used value. if (used && unused) EqClass.join(used->id, unused->id); EqClass.compress(); return EqClass.getNumClasses(); } void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI) { assert(LIV[0] && "LIV[0] must be set"); LiveInterval &LI = *LIV[0]; // Rewrite instructions. for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg), RE = MRI.reg_end(); RI != RE;) { MachineOperand &MO = RI.getOperand(); MachineInstr *MI = MO.getParent(); ++RI; // DBG_VALUE instructions should have been eliminated earlier. LiveRangeQuery LRQ(LI, LIS.getInstructionIndex(MI)); const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined(); // In the case of an <undef> use that isn't tied to any def, VNI will be // NULL. If the use is tied to a def, VNI will be the defined value. if (!VNI) continue; MO.setReg(LIV[getEqClass(VNI)]->reg); } // Move runs to new intervals. LiveInterval::iterator J = LI.begin(), E = LI.end(); while (J != E && EqClass[J->valno->id] == 0) ++J; for (LiveInterval::iterator I = J; I != E; ++I) { if (unsigned eq = EqClass[I->valno->id]) { assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) && "New intervals should be empty"); LIV[eq]->ranges.push_back(*I); } else *J++ = *I; } LI.ranges.erase(J, E); // Transfer VNInfos to their new owners and renumber them. unsigned j = 0, e = LI.getNumValNums(); while (j != e && EqClass[j] == 0) ++j; for (unsigned i = j; i != e; ++i) { VNInfo *VNI = LI.getValNumInfo(i); if (unsigned eq = EqClass[i]) { VNI->id = LIV[eq]->getNumValNums(); LIV[eq]->valnos.push_back(VNI); } else { VNI->id = j; LI.valnos[j++] = VNI; } } LI.valnos.resize(j); }
33.373288
83
0.613785
nettrino
c3bfc00158c4140b4b2dd560d031f8b650330300
331
cpp
C++
Pbinfo/SumSec1.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
7
2019-01-06T19:10:14.000Z
2021-10-16T06:41:23.000Z
Pbinfo/SumSec1.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
null
null
null
Pbinfo/SumSec1.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
6
2019-01-06T19:17:30.000Z
2020-02-12T22:29:17.000Z
#include <iostream> using namespace std; int main() { int n, a[1005], iPrim=0, iSecund=0, s=0; cin>>n; for(int i=1; i<=n; i++){ cin>>a[i]; if(iPrim==0 && a[i]%2==1) iPrim=i; if(a[i]%2==1) iSecund=i; } for(int i=iPrim; i<=iSecund; i++) s+=a[i]; cout<<s; return 0; }
14.391304
44
0.459215
Al3x76
c3c0abf3818a9b0444888a42727accfa9d1ddffa
15,981
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Game2D/collectible_item_05.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Game2D/collectible_item_05.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Game2D/collectible_item_05.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
// Generated by imageconverter. Please, do not edit! #include <touchgfx/hal/Config.hpp> LOCATION_EXTFLASH_PRAGMA KEEP extern const unsigned char _collectible_item_05[] LOCATION_EXTFLASH_ATTRIBUTE = { // 28x28 ARGB8888 pixels. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x20,0x1c,0x20,0x10,0x18,0x18,0x20,0x14,0x18,0x18,0x20,0x14,0x18,0x14,0x28,0x0c, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x24,0x28,0x38,0x28,0x30,0x38,0xae,0x20,0x30,0x38,0xba,0x20,0x30,0x38,0xbe,0x20,0x28,0x30,0x8e,0x28,0x18,0x28,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x24,0x20,0x08,0x48,0x60,0x60,0x8e,0x70,0xb0,0xb8,0xfb,0x30,0xac,0xc0,0xff,0x28,0xac,0xc0,0xff,0x28,0x7c,0x88,0xef,0x28,0x34,0x38,0x4d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x28,0x28,0x14,0x50,0x90,0x90,0xc3, 0x58,0xec,0xf0,0xff,0x40,0xd0,0xe0,0xff,0x28,0xc4,0xe0,0xff,0x28,0xb4,0xc8,0xfb,0x28,0x50,0x50,0x86,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x44,0x48,0x28,0x50,0xb0,0xb0,0xe3,0x58,0xec,0xf0,0xff,0x50,0xdc,0xe8,0xff,0x28,0xc4,0xd8,0xff,0x28,0xc4,0xd8,0xff, 0x28,0x64,0x70,0xba,0x20,0x20,0x20,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x54,0x60,0x41,0x58,0xb0,0xb8,0xeb,0x58,0x94,0x98,0xff,0x60,0xe4,0xf0,0xff,0x30,0xc4,0xe0,0xff,0x28,0xc4,0xe0,0xff,0x28,0x78,0x80,0xdf,0x28,0x24,0x30,0x1c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x5c,0x60,0x51,0x60,0xb4,0xb8,0xf3,0x50,0xb0,0xb8,0xff,0x68,0xd8,0xe0,0xff,0x30,0xc8,0xe0,0xff,0x28,0xc8,0xe0,0xff,0x28,0x80,0x90,0xf3,0x28,0x2c,0x38,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x68,0x70,0x65,0x58,0xc0,0xc8,0xfb, 0x48,0xd8,0xe0,0xff,0x68,0xd0,0xd0,0xff,0x38,0xcc,0xe0,0xff,0x28,0xc4,0xd8,0xff,0x30,0x90,0xa0,0xff,0x20,0x30,0x38,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x74,0x78,0x79,0x58,0xc8,0xd0,0xfb,0x40,0xe8,0xf0,0xff,0x68,0xc8,0xc8,0xff,0x38,0xd0,0xe8,0xff,0x28,0xc4,0xd8,0xff, 0x28,0x9c,0xb0,0xff,0x20,0x30,0x30,0x75,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x78,0x78,0x8e,0x58,0xd0,0xd8,0xff,0x40,0xf0,0xf8,0xff,0x70,0xd0,0xd0,0xff,0x40,0xd0,0xe0,0xff,0x28,0xc4,0xe0,0xff,0x28,0xa4,0xb8,0xff,0x20,0x2c,0x30,0x8a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x40,0x70,0x70,0x9a,0x58,0xd4,0xe0,0xff,0x40,0xf4,0xf8,0xff,0x60,0xd0,0xd8,0xff,0x40,0xd0,0xe0,0xff,0x28,0xc8,0xe0,0xff,0x28,0xac,0xc0,0xff,0x28,0x30,0x38,0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x48,0x70,0x70,0xa2,0x58,0xd8,0xe0,0xff, 0x38,0xf4,0xf8,0xff,0x50,0xd0,0xd8,0xff,0x40,0xcc,0xe0,0xff,0x28,0xc8,0xd8,0xff,0x28,0xb4,0xc8,0xff,0x28,0x34,0x38,0xae,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x00,0x58,0x04,0x48,0x70,0x78,0xa6,0x50,0xdc,0xe0,0xff,0x40,0xf4,0xf8,0xff,0x50,0xd0,0xd0,0xff,0x48,0xd0,0xe0,0xff,0x28,0xc4,0xe0,0xff, 0x30,0xb4,0xc8,0xff,0x28,0x34,0x38,0xb6,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x00,0x58,0x04,0x48,0x74,0x78,0xaa,0x50,0xdc,0xe0,0xff,0x40,0xf8,0xf8,0xff,0x50,0xd0,0xd8,0xff,0x48,0xd0,0xe0,0xff,0x28,0xc4,0xd8,0xff,0x30,0xb4,0xc8,0xff,0x28,0x34,0x38,0xbe,0x80,0x80,0x80,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x50,0x00,0x50,0x04,0x48,0x74,0x78,0xaa,0x50,0xdc,0xe0,0xff,0x38,0xf8,0xf8,0xff,0x50,0xd0,0xd8,0xff,0x48,0xd0,0xe0,0xff,0x28,0xc8,0xe0,0xff,0x28,0xb4,0xc8,0xff,0x28,0x38,0x38,0xba,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x48,0x70,0x78,0xa2,0x50,0xdc,0xe0,0xff, 0x40,0xf4,0xf8,0xff,0x50,0xd0,0xd0,0xff,0x40,0xcc,0xe0,0xff,0x28,0xc8,0xe0,0xff,0x28,0xb4,0xc8,0xff,0x28,0x34,0x38,0xb2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x40,0x6c,0x70,0x9e,0x58,0xd8,0xe0,0xff,0x40,0xf4,0xf8,0xff,0x58,0xd4,0xd8,0xff,0x40,0xcc,0xe0,0xff,0x28,0xc4,0xd8,0xff, 0x30,0xb4,0xc8,0xff,0x28,0x34,0x38,0xae,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x70,0x78,0x96,0x58,0xd4,0xd8,0xff,0x40,0xf0,0xf8,0xff,0x68,0xd0,0xd8,0xff,0x40,0xd0,0xe0,0xff,0x28,0xc4,0xd8,0xff,0x28,0xac,0xc0,0xff,0x28,0x30,0x38,0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x74,0x78,0x86,0x58,0xd0,0xd8,0xff,0x40,0xec,0xf0,0xff,0x68,0xcc,0xd0,0xff,0x40,0xd0,0xe0,0xff,0x20,0xc4,0xe0,0xff,0x28,0xa8,0xb8,0xff,0x20,0x2c,0x30,0x8a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x74,0x78,0x71,0x58,0xc8,0xd0,0xfb, 0x48,0xe8,0xf0,0xff,0x60,0xc8,0xd0,0xff,0x38,0xd0,0xe0,0xff,0x28,0xc8,0xe0,0xff,0x30,0xa0,0xb0,0xff,0x20,0x30,0x30,0x75,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x60,0x68,0x5d,0x58,0xbc,0xc0,0xfb,0x48,0xd4,0xd8,0xff,0x68,0xd4,0xd8,0xff,0x30,0xcc,0xe0,0xff,0x28,0xc4,0xe0,0xff, 0x30,0x94,0xa0,0xff,0x20,0x30,0x38,0x59,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x5c,0x60,0x4d,0x60,0xb4,0xb8,0xf3,0x58,0xa4,0xa8,0xff,0x68,0xe0,0xe8,0xff,0x28,0xc8,0xe0,0xff,0x28,0xc4,0xd8,0xff,0x28,0x84,0x98,0xf7,0x28,0x30,0x30,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x50,0x58,0x34,0x58,0xb4,0xb8,0xeb,0x60,0xc8,0xc8,0xff,0x58,0xe4,0xf0,0xff,0x28,0xc4,0xd8,0xff,0x28,0xc8,0xe0,0xff,0x28,0x7c,0x88,0xdf,0x20,0x2c,0x28,0x1c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x48,0x48,0x20,0x50,0xa8,0xb0,0xdb, 0x48,0xf4,0xf8,0xff,0x50,0xd8,0xe8,0xff,0x28,0xc4,0xd8,0xff,0x28,0xc4,0xd8,0xff,0x28,0x6c,0x78,0xc3,0x20,0x1c,0x20,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x24,0x20,0x0c,0x50,0x84,0x88,0xb2,0x60,0xe4,0xe8,0xff,0x40,0xcc,0xe0,0xff,0x28,0xc4,0xd8,0xff,0x28,0xb4,0xc8,0xfb, 0x30,0x54,0x60,0x96,0x28,0x28,0x28,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x40,0x48,0x48,0x6d,0x58,0x7c,0x80,0xeb,0x30,0x78,0x88,0xf3,0x28,0x78,0x88,0xf7,0x28,0x60,0x68,0xe7,0x20,0x30,0x38,0x4d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x20,0x18,0x20,0x24,0x28,0x55,0x20,0x20,0x28,0x61,0x20,0x20,0x28,0x61,0x20,0x20,0x20,0x51,0x28,0x24,0x20,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
202.291139
320
0.796446
ramkumarkoppu
c3c96dbc7122234e173dc5de3f37248c12aa354a
6,167
cpp
C++
lab4/Lists/lists.cpp
polinaKP/semester_2
11713c3f09bc9756f254e5f56b679ae06d2da657
[ "Unlicense" ]
null
null
null
lab4/Lists/lists.cpp
polinaKP/semester_2
11713c3f09bc9756f254e5f56b679ae06d2da657
[ "Unlicense" ]
null
null
null
lab4/Lists/lists.cpp
polinaKP/semester_2
11713c3f09bc9756f254e5f56b679ae06d2da657
[ "Unlicense" ]
null
null
null
#include <iostream> #include <list> typedef struct Node { int value; struct Node *next; } Node; void push_back(Node ** head, int value) { if (*head == NULL) { *head = new Node; (*head)->value = value; (*head)->next = NULL; return; } Node * p_node = *head; while (p_node->next != NULL) { p_node = p_node->next; } Node * new_node = new Node; p_node->next = new_node; new_node->value = value; new_node->next = NULL; } void push_left(Node ** head, int value) { Node * p_node = *head; Node * new_node = new Node; *head = new Node; (*head)->value = value; if (*head == NULL) { (*head)->next = NULL; return; } else (*head)->next = p_node; } void clear_list(Node **head) { Node *p_node = *head; Node *new_node = NULL; while (p_node != NULL){ new_node = p_node->next; delete p_node; p_node = new_node; } *head = NULL; } int pop(Node ** head, int index) { Node *p_node = *head; int value_delete = 0; if (p_node != NULL) { Node *new_node = NULL; Node *p_node_1 = NULL; if (index == 0){ new_node = p_node->next; value_delete = p_node->value; delete p_node; *head = new_node; } else { for (int i = 1; i < index; i++) p_node = p_node->next; p_node_1 = p_node->next; if (p_node_1 != NULL) new_node = p_node_1->next; else new_node = NULL; value_delete = (p_node->next)->value; delete p_node->next; p_node->next = new_node; } } return value_delete; } void print_list(Node *head) { Node *p_node = head; std::cout << "List: " << '\n'; while (p_node->next != NULL) { std::cout << p_node->value << ' '; p_node = p_node->next; } std::cout << p_node->value << ' '; std::cout << '\n'; } void remove(Node ** head, int value) { Node *p_node = *head; if (p_node != NULL) { Node *new_node = NULL; Node *p_node_1 = NULL; if (p_node->value == value){ new_node = p_node->next; delete p_node; *head = new_node; } else { while ((p_node->next)->value != value) p_node = p_node->next; p_node_1 = p_node->next; if (p_node_1 != NULL) new_node = p_node_1->next; else new_node = NULL; delete p_node->next; p_node->next = new_node; } } } void remove_all(Node ** head, int value) { Node *p_node = *head; if (p_node != NULL) { Node *new_node = NULL; Node *p_node_1 = NULL; while(p_node->value == value){ new_node = p_node->next; delete p_node; *head = new_node; p_node = *head; } while (p_node->next != NULL) { if ((p_node->next)->value == value) { p_node_1 = p_node->next; if (p_node_1 != NULL) new_node = p_node_1->next; else new_node = NULL; delete p_node->next; p_node->next = new_node; } else p_node = p_node->next; } } } void replace_all(Node *head, int old_value, int new_value) { Node *p_node = head; if (p_node != NULL) { while (p_node->next != NULL){ if (p_node->value == old_value) p_node->value = new_value; p_node = p_node->next; } if (p_node->value == old_value) p_node->value = new_value; } } void reverse(Node **head) { Node *p_node = *head; int value = 0, index = 0; int first_value = p_node->value; if (p_node != NULL) { while (p_node->next != NULL) { value = p_node->value; push_left(head, value); pop(head, index); p_node = p_node->next; index++; } value = p_node->value; push_left(head, value); pop(head, index); p_node->value = first_value; } } int unique(Node *head) { Node *p_node = head; bool flag = true; int count = 1; if (p_node != NULL) { std::list<int> elements{p_node->value}; while (p_node->next != NULL) { for (int i: elements) if (p_node->value == i) flag = false; if (flag) { count++; elements.push_back(p_node->value); } flag = true; p_node = p_node->next; } for (int i: elements) if (p_node->value == i) flag = false; if (flag) { count++; elements.push_back(p_node->value); } } return count; } int main(int argc, char const *argv[]) { int value,amount; Node * list = NULL; std::cout << "Enter list size: "; std::cin >> amount; std::cout << "Enter list:" << '\n'; for (int i = 1; i <= amount; ++i) { std::cin >> value; push_back(&list, value); } print_list(list); std::cout << "Enter index to remove: "; int index; std::cin >> index; int value_delete = pop(&list, index - 1); print_list(list); std::cout << "Enter value to remove: "; std::cin >> value; remove(&list, value); print_list(list); std::cout << "Enter value to remove all: "; int value_all; std::cin >> value_all; remove_all(&list, value_all); print_list(list); std::cout << "Enter old and new value to replace all: "; int old_value, new_value; std::cin >> old_value >> new_value; replace_all(list, old_value, new_value); print_list(list); std::cout << "Unique: " << unique(list) << '\n'; std::cout << "Reversed "; reverse(&list); print_list(list); clear_list(&list); std::cout << "Clear"; return 0; }
23.996109
60
0.483055
polinaKP
c3cac169931db87a8c151b472be302f5371a0c6c
1,529
cpp
C++
src/graphics/primitives/Animation.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
src/graphics/primitives/Animation.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
src/graphics/primitives/Animation.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
#include "inc/graphics/primitives/Animation.hpp" #include "inc/graphics/primitives/Animator.hpp" Animation::Animation(milliseconds duration, bool parallelToPrev, Animation::State state): started(false), duration(duration), state(state), onEndCallback(nullptr) { Animator::getInstance()->addAnimation(this, parallelToPrev); } Animation::~Animation() { try { Animator::getInstance()->removeAnimation(this); } catch (std::invalid_argument e) { } } float Animation::getProgress(float linearProgress) { return linearProgress; } void Animation::animate(float progress) { throw std::runtime_error("not implemented"); } Animation::State Animation::getState() { return state; } Animation::State Animation::animate() { if (state == FINISHED) { return FINISHED; } milliseconds now = time(); if (!started) { started = true; startTime = now; } if (now > startTime + duration) { state = FINISHED; animate(getProgress(1.0f)); } else { float linear = static_cast<float>((now - startTime).count()) / static_cast<float>(duration.count()); animate(getProgress(linear)); } if (state == FINISHED && onEndCallback) { onEndCallback(); } return state; } void Animation::onEnd(Animation::onEndCallbackType callback) { onEndCallback = callback; } void Animation::stop() { state = FINISHED; } milliseconds Animation::time() { return duration_cast<milliseconds>(system_clock::now().time_since_epoch()); } Animation::State operator&&(Animation::State x, Animation::State y) { return (x > y) ? x : y; }
21.535211
102
0.712884
petuzk
c3cb2b779a659459ce0016a678a25d145866e174
10,854
cpp
C++
Samples/Win7Samples/security/authorization/azman/azmigrate/AzHelper.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/security/authorization/azman/azmigrate/AzHelper.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/security/authorization/azman/azmigrate/AzHelper.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. File: AzHelper.cpp Abstract: Templatized helper routines used to aggregate common methods to createTasks, createRoles, createAppGroups used commonly for both CAzScopes and CAzApplications History: ***************************************************************************/ #include "AzHelper.h" template <class NativeInterfaceType> CAzHelper<NativeInterfaceType>::CAzHelper(void) { } template <class NativeInterfaceType> CAzHelper<NativeInterfaceType>::~CAzHelper(void) { } /*++ Routine description: This method copies tasks from the source native AzMan interface to the destination native AzMan interface Arguments: pNativeSource - Source native interface pNativeNew - destination native interface Return Value: Returns success, appropriate failure value of the get/set methods done within this method Description: 2 Pass method used. In the first pass, create all the task objects; In the second pass, create the links between the task objects. --*/ template <class NativeInterfaceType> HRESULT CAzHelper<NativeInterfaceType>::CreateTasks(CComPtr<NativeInterfaceType> &pNativeSource, CComPtr<NativeInterfaceType> &pNativeNew) { // Copy all tasks objects; donot create any links between then HRESULT hr=CreateTasks(pNativeSource,pNativeNew,false); //Create links between the tasks now. if (SUCCEEDED(hr)) hr=CreateTasks(pNativeSource,pNativeNew,true); return hr; } /*++ Routine description: This method copies appgroups from the source native AzMan interface to the destination native AzMan interface Arguments: pNativeSource - Source native interface pNativeNew - Destination native interface Return Value: Returns success, appropriate failure value of the get/set methods done within this method Description: 2 Pass method used. In the first pass, create all the appgroup objects; In the second pass, create the links between the appgroup objects. --*/ template <class NativeInterfaceType> HRESULT CAzHelper<NativeInterfaceType>::CreateAppGroups(CComPtr<NativeInterfaceType> &pNativeSource, CComPtr<NativeInterfaceType> &pNativeNew) { HRESULT hr=CreateAppGroups(pNativeSource,pNativeNew,false); if (SUCCEEDED(hr)) hr=CreateAppGroups(pNativeSource,pNativeNew,true); return hr; } /*++ Routine description: This method copies tasks from the source native AzMan interface to the destination native AzMan interface. If createlinks == true, then donot create tasks, only create links else create the new task objects Arguments: pNativeSource - Source native interface, pNativeNew - destination native interface, bCreateLinks - createLinks Return Value: Returns success, appropriate failure value of the get/set methods done within this method --*/ template <class NativeInterfaceType> HRESULT CAzHelper<NativeInterfaceType>::CreateTasks(CComPtr<NativeInterfaceType> &pNativeSource, CComPtr<NativeInterfaceType> &pNativeNew, bool bCreateLinks) { CAzLogging::Entering(_TEXT("CreateTasks")); CComPtr<IAzTasks> spAzTasks; long lCount=0; CComVariant cVappl; HRESULT hr=pNativeSource->get_Tasks(&spAzTasks); CAzLogging::Log(hr,_TEXT("Getting Tasks")); if (FAILED(hr)) goto lError1; hr=spAzTasks->get_Count(&lCount); CAzLogging::Log(hr,_TEXT("Getting Task Object count")); if (FAILED(hr)) goto lError1; if (lCount==0) goto lError1; for (long i = 1 ; i <= lCount ; i++) { CComPtr<IAzTask> spOldTask,spNewTask; hr=spAzTasks->get_Item(i,&cVappl); CAzLogging::Log(hr,_TEXT("Getting Task Item")); if (FAILED(hr)) goto lError1; CComPtr<IDispatch> spDispatchtmp(cVappl.pdispVal); cVappl.Clear(); hr = spDispatchtmp.QueryInterface(&spOldTask); if (FAILED(hr)) goto lError1; CAzTask oldTask=CAzTask(spOldTask,false); if (!bCreateLinks) { hr=pNativeNew->CreateTask(oldTask.getName(),CComVariant(),&spNewTask); CAzLogging::Log(hr,_TEXT("Creating New Task Object")); if (FAILED(hr)) goto lError1; } else { hr=pNativeNew->OpenTask(oldTask.getName(),CComVariant(),&spNewTask); CAzLogging::Log(hr,_TEXT("Opening New Task Object to create links")); if (FAILED(hr)) goto lError1; } CAzTask newTask=CAzTask(spNewTask,!bCreateLinks); hr=bCreateLinks ? newTask.CopyLinks(oldTask) : newTask.Copy(oldTask); CAzLogging::Log(hr,_TEXT("Copying Task properties")); if (FAILED(hr)) goto lError1; } lError1: CAzLogging::Exiting(_TEXT("CreateTasks")); return hr; } /*++ Routine description: This method copies roles from the source native AzMan interface to the destination native AzMan interface Arguments: pNativeSource - Source native interface, pNativeNew - destination native interface, Return Value: Returns success, appropriate failure value of the get/set methods done within this method --*/ template <class NativeInterfaceType> HRESULT CAzHelper<NativeInterfaceType>::CreateRoles(CComPtr<NativeInterfaceType> &pNativeSource, CComPtr<NativeInterfaceType> &pNativeNew) { CAzLogging::Entering(_TEXT("CreateRoles")); CComPtr<IAzRoles> spAzRoles; long lCount=0; CComVariant cVappl; HRESULT hr=pNativeSource->get_Roles(&spAzRoles); CAzLogging::Log(hr,_TEXT("Getting Roles")); if (FAILED(hr)) goto lError1; hr=spAzRoles->get_Count(&lCount); CAzLogging::Log(hr,_TEXT("Getting Role Object count")); if (FAILED(hr)) goto lError1; if (lCount==0) goto lError1; for (long i = 1;i <= lCount ; i++) { CComPtr<IAzRole> spRole,spNewRole; hr=spAzRoles->get_Item(i,&cVappl); CAzLogging::Log(hr,_TEXT("Getting Role Item")); if (FAILED(hr)) goto lError1; CComPtr<IDispatch> spDispatchtmp(cVappl.pdispVal); cVappl.Clear(); hr = spDispatchtmp.QueryInterface(&spRole); if (FAILED(hr)) goto lError1; CAzRole role=CAzRole(spRole,false); hr=pNativeNew->CreateRole(role.getName(),CComVariant(),&spNewRole); CAzLogging::Log(hr,_TEXT("Creating New Role Object")); if (FAILED(hr)) goto lError1; CAzRole newRole=CAzRole(spNewRole,true); hr=newRole.Copy(role); CAzLogging::Log(hr,_TEXT("Copying Role properties")); if (FAILED(hr)) goto lError1; } lError1: CAzLogging::Exiting(_TEXT("CreateRoles")); return hr; } /*++ Routine description: This method copies appgroups from the source native AzMan interface to the destination native AzMan interface. If createlinks == true, then donot create appgroups, only create links else create the new appgroup objects Arguments: pNativeSource - Source native interface, pNativeNew - destination native interface, bCreateLinks - createLinks Return Value: Returns success, appropriate failure value of the get/set methods done within this method --*/ template <class NativeInterfaceType> HRESULT CAzHelper<NativeInterfaceType>::CreateAppGroups(CComPtr<NativeInterfaceType> &pNativeSource, CComPtr<NativeInterfaceType> &pNativeNew, bool bCreateLinks) { CAzLogging::Entering(_TEXT("CreateAppGroups")); CComPtr<IAzApplicationGroups> spAzAppGroups; long lCount=0; CComVariant cVappl; HRESULT hr=pNativeSource->get_ApplicationGroups(&spAzAppGroups); CAzLogging::Log(hr,_TEXT("Getting App Groups")); if (FAILED(hr)) goto lError1; hr=spAzAppGroups->get_Count(&lCount); CAzLogging::Log(hr,_TEXT("Getting App Group Object count")); if (FAILED(hr)) goto lError1; if (lCount==0) goto lError1; for (long i = 1 ; i <= lCount ; i++) { CComPtr<IAzApplicationGroup> spSrcAppGroup,spNewAppGroup; hr=spAzAppGroups->get_Item(i,&cVappl); CAzLogging::Log(hr,_TEXT("Getting App Group Item")); if (FAILED(hr)) goto lError1; CComPtr<IDispatch> spDispatchtmp(cVappl.pdispVal); cVappl.Clear(); hr = spDispatchtmp.QueryInterface(&spSrcAppGroup); CAzLogging::Log(hr,_TEXT("Querying AppGroup interface")); if (FAILED(hr)) goto lError1; CAzAppGroup oldAppGroup=CAzAppGroup(spSrcAppGroup,false); if (!bCreateLinks) { hr=pNativeNew->CreateApplicationGroup(oldAppGroup.getName(),CComVariant(),&spNewAppGroup); CAzLogging::Log(hr,_TEXT("Creating New App Group Object")); if (FAILED(hr)) goto lError1; } else { hr=pNativeNew->OpenApplicationGroup(oldAppGroup.getName(),CComVariant(),&spNewAppGroup); CAzLogging::Log(hr,_TEXT("Opening New App Group Object to create links")); if (FAILED(hr)) goto lError1; } CAzAppGroup newAppGroup=CAzAppGroup(spNewAppGroup,!bCreateLinks); hr=bCreateLinks ? newAppGroup.CopyLinks(oldAppGroup) : newAppGroup.Copy(oldAppGroup); CAzLogging::Log(hr,_TEXT("Copying App Group properties")); if (FAILED(hr)) goto lError1; } lError1: CAzLogging::Exiting(_TEXT("CreateAppGroups")); return hr; } template class CAzHelper<IAzScope>; template class CAzHelper<IAzApplication>;
26.280872
105
0.615902
windows-development
c3ccec1090f2d963fbdff5ebf8e967ee3cbb4f90
3,651
hpp
C++
Axis.Core/application/parsing/preprocessing/InstructionFeeder.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Core/application/parsing/preprocessing/InstructionFeeder.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Core/application/parsing/preprocessing/InstructionFeeder.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include <boost/spirit/include/qi.hpp> #include "services/io/StreamReader.hpp" #include "AxisString.hpp" #include "application/parsing/core/ParseContext.hpp" namespace axis { namespace application { namespace parsing { namespace preprocessing { /// <summary> /// Reads data from an input stream and feeds instructions to the preprocessor, /// removing adornments such as blank lines and comments from the input. /// </summary> class InstructionFeeder { private: axis::services::io::StreamReader *_source; // our source stream axis::application::parsing::core::ParseContext& _parseContext; // We alway look ahead when reading so that we can predict // adornments that were put at the end of the file. Doing // this way, we can promptly say when we reached EOF. For us, // EOF occurs when no usable line can be found in the stream. axis::String _lastLineRead; // contents of the last line read bool _eofFlag; // is there any more usable lines? // In order to detect open comment blocks errors, we must // signal when we had encountered an open block delimiter. bool _isReadingComment; // Used when a dangling open comment block delimiter is found. // An exception is thrown and the location of the delimiter // is told by the contents stored in this attribute. unsigned long _blockStartingLine; unsigned long _lastLineNumber; public: /// <summary> /// Creates a new instance of this class. /// </summary> InstructionFeeder(axis::application::parsing::core::ParseContext& context); /// <summary> /// Creates a new instance of this class. /// </summary> /// <param name="source">Stream from which data shall be extracted.</param> InstructionFeeder(axis::services::io::StreamReader& source, axis::application::parsing::core::ParseContext& context); /// <summary> /// Destroys this object. /// </summary> virtual ~InstructionFeeder(void); /// <summary> /// Returns if there is any usable expressions left in the stream. /// </summary> bool IsEOF(void) const; /// <summary> /// Read the next expression in the stream. /// </summary> /// <param name="line">Reference to which extracted expression is put.</param> void ReadLine(axis::String& line); /// <summary> /// Returns the current stream used by this object. /// </summary> axis::services::io::StreamReader& GetCurrentSource(void) const; /// <summary> /// Changes the stream used by this object. EOF state is reevaluated /// in order to reflect the new stream state. /// </summary> /// <param name="reader">The new stream to use.</param> void ChangeSource(axis::services::io::StreamReader& reader); /// <summary> /// Pushes back the last line read from the stream so that /// it seems like the last line was never read. /// </summary> void Rewind(void); unsigned long GetLastLineReadIndex(void) const; /************************************************************************************************** * <summary> Resets the state of this object. </summary> **************************************************************************************************/ void Reset(void); private: /// <summary> /// Searches for the next following expression in the stream. /// </summary> void ReadNextRelevantLine(void); /// <summary> /// Checks if the line has an expression. If it has, comments and /// whitespaces are removed. /// </summary> /// <param name="line">String to be analysed.</param> /// <returns> /// True if an expression could be extracted, False otherwise. /// </returns> bool ParseLine(axis::String& line); }; } } } } // namespace axis::application::parsing::preprocessing
34.121495
101
0.671597
renato-yuzup
c3d20c5dad55370960e33cd00d0a831c318b5bc2
1,320
cpp
C++
src/noncasual_lp.cpp
despargy/KukaImplementation-kinetic
3a9ab106b117acfc6478fbf3e60e49b7e94b2722
[ "MIT" ]
1
2021-08-21T12:49:27.000Z
2021-08-21T12:49:27.000Z
src/noncasual_lp.cpp
despargy/KukaImplementation-kinetic
3a9ab106b117acfc6478fbf3e60e49b7e94b2722
[ "MIT" ]
null
null
null
src/noncasual_lp.cpp
despargy/KukaImplementation-kinetic
3a9ab106b117acfc6478fbf3e60e49b7e94b2722
[ "MIT" ]
null
null
null
#define SUBBLOCK SIZE 22 // for method 0, and 12 for methods 1 and 2 void fir(double * const x, const int Nx, const double * const h, const int Nh, double* r) { /* x: Nx: h: Nh: input data length of input data filter coefficients length of the filter 21r: the result after filtering */ } int main() { const double h[] = {. . .}; // the filter coefficients const int FILTER LEN = sizeof(h)/sizeof(double); const int HALF FILTER LEN = (FILTER LEN-1)/2; const int BLOCK SIZE = SUBBLOCK SIZE + (FILTER LEN-1); double x[BLOCK SIZE]; // input data double r[BLOCK SIZE]; // result int i = HALF FILTER LEN; memset(x, 0, sizeof(double)*BLOCK SIZE); // init x while(cin >> x[i]){ if(++i >= BLOCK SIZE){ // perform FIR filtering fir(x, BLOCK SIZE, h, FILTER LEN, r); // make result non-causal by shifting result to the left // so that only array values from 0 to SUBBLOCK SIZE-1 // are valid memmove(r, r+FILTER LEN-1, SUBBLOCK SIZE*sizeof(double)); // show the filtered result for(int j=0; j < SUBBLOCK SIZE; j++){ cout << r[j] << "\n"; } // copy the old x values at the end to the beginning of x memmove(x, x+(BLOCK SIZE-FILTER LEN+1), (FILTER LEN-1)*sizeof(double)); // reset counter i=FILTER LEN-1; } } }
25.882353
68
0.618939
despargy
c3d348a86b997bde2cf055764577167b1949bb91
68,385
cpp
C++
Plugins/Engine/Renderer.cpp
xycsoscyx/gekengine
cb9c933c6646169c0af9c7e49be444ff6f97835d
[ "MIT" ]
1
2019-04-22T00:10:49.000Z
2019-04-22T00:10:49.000Z
Plugins/Engine/Renderer.cpp
xycsoscyx/gekengine
cb9c933c6646169c0af9c7e49be444ff6f97835d
[ "MIT" ]
null
null
null
Plugins/Engine/Renderer.cpp
xycsoscyx/gekengine
cb9c933c6646169c0af9c7e49be444ff6f97835d
[ "MIT" ]
2
2017-10-16T15:40:55.000Z
2019-04-22T00:10:50.000Z
#include "GEK/Math/SIMD.hpp" #include "GEK/Shapes/Sphere.hpp" #include "GEK/Utility/String.hpp" #include "GEK/Utility/FileSystem.hpp" #include "GEK/Utility/JSON.hpp" #include "GEK/Utility/ContextUser.hpp" #include "GEK/Utility/ThreadPool.hpp" #include "GEK/Utility/Allocator.hpp" #include "GEK/Utility/Profiler.hpp" #include "GEK/GUI/Utilities.hpp" #include "GEK/API/Renderer.hpp" #include "GEK/API/Population.hpp" #include "GEK/API/Entity.hpp" #include "GEK/API/Component.hpp" #include "GEK/API/ComponentMixin.hpp" #include "GEK/Components/Transform.hpp" #include "GEK/Components/Color.hpp" #include "GEK/Components/Light.hpp" #include "GEK/Engine/Core.hpp" #include "GEK/Engine/Visual.hpp" #include "GEK/Engine/Shader.hpp" #include "GEK/Engine/Filter.hpp" #include "GEK/Engine/Material.hpp" #include "GEK/Engine/Resources.hpp" #include <concurrent_unordered_set.h> #include <concurrent_vector.h> #include <concurrent_queue.h> #include <imgui_internal.h> #include <smmintrin.h> #include <algorithm> #include <ppl.h> namespace Gek { namespace Implementation { static constexpr int32_t GridWidth = 16; static constexpr int32_t GridHeight = 8; static constexpr int32_t GridDepth = 24; static constexpr float ReciprocalGridDepth = (1.0f / float(GridDepth)); static constexpr int32_t GridSize = (GridWidth * GridHeight * GridDepth); static const Math::Float4 GridDimensions(GridWidth, GridWidth, GridHeight, GridHeight); GEK_CONTEXT_USER(Renderer, Engine::Core *) , public Plugin::Renderer { public: struct DirectionalLightData { Math::Float3 radiance; float padding1; Math::Float3 direction; float padding2; }; struct PointLightData { Math::Float3 radiance; float radius; Math::Float3 position; float range; }; struct SpotLightData { Math::Float3 radiance; float radius; Math::Float3 position; float range; Math::Float3 direction; float padding1; float innerAngle; float outerAngle; float coneFalloff; float padding2; }; struct EngineConstantData { float worldTime; float frameTime; uint32_t invertedDepthBuffer; uint32_t buffer; }; struct CameraConstantData { Math::Float2 fieldOfView; float nearClip; float farClip; Math::Float4x4 viewMatrix; Math::Float4x4 projectionMatrix; }; struct LightConstantData { Math::UInt3 gridSize; uint32_t directionalLightCount; Math::UInt2 tileSize; uint32_t pointLightCount; uint32_t spotLightCount; }; struct TileOffsetCount { uint32_t indexOffset; uint16_t pointLightCount; uint16_t spotLightCount; }; struct DrawCallValue { union { uint32_t value; struct { MaterialHandle material; VisualHandle plugin; ShaderHandle shader; }; }; std::function<void(Video::Device::Context *)> onDraw; DrawCallValue(MaterialHandle material, VisualHandle plugin, ShaderHandle shader, std::function<void(Video::Device::Context *)> &&onDraw) : material(material) , plugin(plugin) , shader(shader) , onDraw(std::move(onDraw)) { } }; using DrawCallList = concurrency::concurrent_vector<DrawCallValue>; struct DrawCallSet { Engine::Shader *shader = nullptr; DrawCallList::iterator begin; DrawCallList::iterator end; DrawCallSet(Engine::Shader *shader, DrawCallList::iterator begin, DrawCallList::iterator end) : shader(shader) , begin(begin) , end(end) { } }; struct Camera { std::string name; Shapes::Frustum viewFrustum; Math::Float4x4 viewMatrix; Math::Float4x4 projectionMatrix; float nearClip = 0.0f; float farClip = 0.0f; ResourceHandle cameraTarget; ShaderHandle forceShader; Camera(void) { } Camera(Camera const &renderCall) : name(renderCall.name) , viewFrustum(renderCall.viewFrustum) , viewMatrix(renderCall.viewMatrix) , projectionMatrix(renderCall.projectionMatrix) , nearClip(renderCall.nearClip) , farClip(renderCall.farClip) , cameraTarget(renderCall.cameraTarget) , forceShader(renderCall.forceShader) { } }; template <typename COMPONENT, typename DATA, size_t RESERVE = 200> struct LightData { Video::Device *videoDevice = nullptr; std::vector<Plugin::Entity *> entityList; concurrency::concurrent_vector<DATA, AlignedAllocator<DATA, 16>> lightList; Video::BufferPtr lightDataBuffer; concurrency::critical_section addSection; concurrency::critical_section removeSection; LightData(Video::Device *videoDevice) : videoDevice(videoDevice) { lightList.reserve(RESERVE); createBuffer(RESERVE); } void addEntity(Plugin::Entity * const entity) { if (entity->hasComponent<COMPONENT>()) { concurrency::critical_section::scoped_lock lock(addSection); auto search = std::find_if(std::begin(entityList), std::end(entityList), [entity](Plugin::Entity * const search) -> bool { return (entity == search); }); if (search == std::end(entityList)) { entityList.push_back(entity); } } } void removeEntity(Plugin::Entity * const entity) { concurrency::critical_section::scoped_lock lock(removeSection); auto search = std::find_if(std::begin(entityList), std::end(entityList), [entity](Plugin::Entity * const search) -> bool { return (entity == search); }); if (search != std::end(entityList)) { entityList.erase(search); } } void clearEntities(void) { entityList.clear(); } void createBuffer(int32_t size = 0) { auto createSize = (size > 0 ? size : lightList.size()); if (!lightDataBuffer || lightDataBuffer->getDescription().count < createSize) { lightDataBuffer = nullptr; Video::Buffer::Description lightBufferDescription; lightBufferDescription.type = Video::Buffer::Type::Structured; lightBufferDescription.flags = Video::Buffer::Flags::Mappable | Video::Buffer::Flags::Resource; lightBufferDescription.stride = sizeof(DATA); lightBufferDescription.count = createSize; lightDataBuffer = videoDevice->createBuffer(lightBufferDescription); lightDataBuffer->setName(String::Format("render:{}", COMPONENT::GetName())); } } bool updateBuffer(void) { bool updated = true; if (!lightList.empty()) { DATA *lightData = nullptr; if (updated = videoDevice->mapBuffer(lightDataBuffer.get(), lightData)) { std::copy(std::begin(lightList), std::end(lightList), lightData); videoDevice->unmapBuffer(lightDataBuffer.get()); } } return updated; } }; template <typename COMPONENT, typename DATA, size_t RESERVE = 200> struct LightVisibilityData : public LightData<COMPONENT, DATA, RESERVE> { Profiler * const profiler = nullptr; std::vector<float, AlignedAllocator<float, 16>> shapeXPositionList; std::vector<float, AlignedAllocator<float, 16>> shapeYPositionList; std::vector<float, AlignedAllocator<float, 16>> shapeZPositionList; std::vector<float, AlignedAllocator<float, 16>> shapeRadiusList; std::vector<bool> visibilityList; LightVisibilityData(Engine::Core *core) : LightData(core->getVideoDevice()) , profiler(core->getContext()->getProfiler()) { } void clearEntities(void) { LightData::clearEntities(); shapeXPositionList.clear(); shapeYPositionList.clear(); shapeZPositionList.clear(); shapeRadiusList.clear(); visibilityList.clear(); } void cull(Math::SIMD::Frustum const &frustum, Hash identifier) { const auto entityCount = entityList.size(); auto buffer = (entityCount % 4); buffer = (buffer ? (4 - buffer) : buffer); auto bufferedEntityCount = (entityCount + buffer); GEK_PROFILER_BEGIN_SCOPE(profiler, 0, identifier, "SIMD"sv, "Data Organization"sv, Profiler::EmptyArguments) { shapeXPositionList.resize(bufferedEntityCount); shapeYPositionList.resize(bufferedEntityCount); shapeZPositionList.resize(bufferedEntityCount); shapeRadiusList.resize(bufferedEntityCount); concurrency::parallel_for(0ULL, entityCount, [&](size_t entityIndex) -> void { auto entity = entityList[entityIndex]; auto &transformComponent = entity->getComponent<Components::Transform>(); auto &lightComponent = entity->getComponent<COMPONENT>(); shapeXPositionList[entityIndex] = transformComponent.position.x; shapeYPositionList[entityIndex] = transformComponent.position.y; shapeZPositionList[entityIndex] = transformComponent.position.z; shapeRadiusList[entityIndex] = (lightComponent.range + lightComponent.radius); }); visibilityList.resize(bufferedEntityCount); lightList.clear(); } GEK_PROFILER_END_SCOPE(); GEK_PROFILER_BEGIN_SCOPE(profiler, 0, identifier, "SIMD"sv, "Culling"sv, Profiler::EmptyArguments) { Math::SIMD::cullSpheres(frustum, bufferedEntityCount, shapeXPositionList, shapeYPositionList, shapeZPositionList, shapeRadiusList, visibilityList); } GEK_PROFILER_END_SCOPE(); } }; private: Engine::Core *core = nullptr; Video::Device *videoDevice = nullptr; Plugin::Population *population = nullptr; Engine::Resources *resources = nullptr; Video::SamplerStatePtr bufferSamplerState; Video::SamplerStatePtr textureSamplerState; Video::SamplerStatePtr mipMapSamplerState; std::vector<Video::Object *> samplerList; Video::BufferPtr engineConstantBuffer; Video::BufferPtr cameraConstantBuffer; std::vector<Video::Buffer *> shaderBufferList; std::vector<Video::Buffer *> filterBufferList; std::vector<Video::Buffer *> lightBufferList; std::vector<Video::Object *> lightResoruceList; Video::Program *deferredVertexProgram = nullptr; Video::Program *deferredPixelProgram = nullptr; Video::BlendStatePtr blendState; Video::RenderStatePtr renderState; Video::DepthStatePtr depthState; ThreadPool<3> workerPool; LightData<Components::DirectionalLight, DirectionalLightData> directionalLightData; LightVisibilityData<Components::PointLight, PointLightData> pointLightData; LightVisibilityData<Components::SpotLight, SpotLightData> spotLightData; concurrency::concurrent_vector<uint16_t> tilePointLightIndexList[GridSize]; concurrency::concurrent_vector<uint16_t> tileSpotLightIndexList[GridSize]; TileOffsetCount tileOffsetCountList[GridSize]; std::vector<uint16_t> lightIndexList; Video::BufferPtr lightConstantBuffer; Video::BufferPtr tileOffsetCountBuffer; Video::BufferPtr lightIndexBuffer; DrawCallList drawCallList; concurrency::concurrent_queue<Camera> cameraQueue; Camera currentCamera; float clipDistance; float reciprocalClipDistance; float depthScale; std::string screenOutput; struct GUI { struct DataBuffer { Math::Float4x4 projectionMatrix; }; ImGuiContext *context = nullptr; Video::Program *vertexProgram = nullptr; Video::ObjectPtr inputLayout; Video::BufferPtr constantBuffer; Video::Program *pixelProgram = nullptr; Video::ObjectPtr blendState; Video::ObjectPtr renderState; Video::ObjectPtr depthState; Video::TexturePtr fontTexture; Video::BufferPtr vertexBuffer; Video::BufferPtr indexBuffer; } gui; Hash directionalThreadIdentifier; Hash pointLightThreadIdentifier; Hash spotLightThreadIdentifier; public: Renderer(Context *context, Engine::Core *core) : ContextRegistration(context) , core(core) , videoDevice(core->getVideoDevice()) , population(core->getPopulation()) , resources(core->getFullResources()) , directionalLightData(core->getVideoDevice()) , pointLightData(core) , spotLightData(core) , directionalThreadIdentifier(Hash(&directionalLightData)) , pointLightThreadIdentifier(Hash(&pointLightData)) , spotLightThreadIdentifier(Hash(&spotLightData)) { population->onReset.connect(this, &Renderer::onReset); population->onEntityCreated.connect(this, &Renderer::onEntityCreated); population->onEntityDestroyed.connect(this, &Renderer::onEntityDestroyed); population->onComponentAdded.connect(this, &Renderer::onComponentAdded); population->onComponentRemoved.connect(this, &Renderer::onComponentRemoved); population->onUpdate[1000].connect(this, &Renderer::onUpdate); core->setOption("render"s, "invertedDepthBuffer"s, true); initializeSystem(); initializeUI(); } void initializeSystem(void) { LockedWrite{ std::cout } << "Initializing rendering system components"; GEK_PROFILER_SET_THREAD_NAME(getProfiler(), directionalThreadIdentifier, "Directional Light Worker"sv); GEK_PROFILER_SET_THREAD_SORT_INDEX(getProfiler(), directionalThreadIdentifier, 10); GEK_PROFILER_SET_THREAD_NAME(getProfiler(), pointLightThreadIdentifier, "Point Light Worker"sv); GEK_PROFILER_SET_THREAD_SORT_INDEX(getProfiler(), pointLightThreadIdentifier, 11); GEK_PROFILER_SET_THREAD_NAME(getProfiler(), spotLightThreadIdentifier, "Spot Light Worker"sv); GEK_PROFILER_SET_THREAD_SORT_INDEX(getProfiler(), spotLightThreadIdentifier, 12); Video::SamplerState::Description bufferSamplerStateData; bufferSamplerStateData.filterMode = Video::SamplerState::FilterMode::MinificationMagnificationMipMapPoint; bufferSamplerStateData.addressModeU = Video::SamplerState::AddressMode::Clamp; bufferSamplerStateData.addressModeV = Video::SamplerState::AddressMode::Clamp; bufferSamplerState = videoDevice->createSamplerState(bufferSamplerStateData); bufferSamplerState->setName("renderer:bufferSamplerState"); Video::SamplerState::Description textureSamplerStateData; textureSamplerStateData.maximumAnisotropy = 8; textureSamplerStateData.filterMode = Video::SamplerState::FilterMode::Anisotropic; textureSamplerStateData.addressModeU = Video::SamplerState::AddressMode::Wrap; textureSamplerStateData.addressModeV = Video::SamplerState::AddressMode::Wrap; textureSamplerState = videoDevice->createSamplerState(textureSamplerStateData); textureSamplerState->setName("renderer:textureSamplerState"); Video::SamplerState::Description mipMapSamplerStateData; mipMapSamplerStateData.maximumAnisotropy = 8; mipMapSamplerStateData.filterMode = Video::SamplerState::FilterMode::MinificationMagnificationMipMapLinear; mipMapSamplerStateData.addressModeU = Video::SamplerState::AddressMode::Clamp; mipMapSamplerStateData.addressModeV = Video::SamplerState::AddressMode::Clamp; mipMapSamplerState = videoDevice->createSamplerState(mipMapSamplerStateData); mipMapSamplerState->setName("renderer:mipMapSamplerState"); samplerList = { textureSamplerState.get(), mipMapSamplerState.get(), }; Video::BlendState::Description blendStateInformation; blendState = videoDevice->createBlendState(blendStateInformation); blendState->setName("renderer:blendState"); Video::RenderState::Description renderStateInformation; renderState = videoDevice->createRenderState(renderStateInformation); renderState->setName("renderer:renderState"); Video::DepthState::Description depthStateInformation; depthState = videoDevice->createDepthState(depthStateInformation); depthState->setName("renderer:depthState"); Video::Buffer::Description constantBufferDescription; constantBufferDescription.stride = sizeof(EngineConstantData); constantBufferDescription.count = 1; constantBufferDescription.type = Video::Buffer::Type::Constant; engineConstantBuffer = videoDevice->createBuffer(constantBufferDescription); engineConstantBuffer->setName("renderer:engineConstantBuffer"); constantBufferDescription.stride = sizeof(CameraConstantData); cameraConstantBuffer = videoDevice->createBuffer(constantBufferDescription); cameraConstantBuffer->setName("renderer:cameraConstantBuffer"); shaderBufferList = { engineConstantBuffer.get(), cameraConstantBuffer.get() }; filterBufferList = { engineConstantBuffer.get() }; constantBufferDescription.stride = sizeof(LightConstantData); lightConstantBuffer = videoDevice->createBuffer(constantBufferDescription); lightConstantBuffer->setName("renderer:lightConstantBuffer"); lightBufferList = { lightConstantBuffer.get() }; static constexpr std::string_view program = \ "struct Output\r\n"sv \ "{\r\n"sv \ " float4 screen : SV_POSITION;\r\n"sv \ " float2 texCoord : TEXCOORD0;\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "Output mainVertexProgram(in uint vertexID : SV_VertexID)\r\n"sv \ "{\r\n"sv \ " Output output;\r\n"sv \ " output.texCoord = float2((vertexID << 1) & 2, vertexID & 2);\r\n"sv \ " output.screen = float4(output.texCoord * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);\r\n"sv \ " return output;\r\n"sv \ "}\r\n"sv \ "\r\n"sv \ "struct Input\r\n"sv \ "{\r\n"sv \ " float4 screen : SV_POSITION;\r\n\r\n"sv \ " float2 texCoord : TEXCOORD0;\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "Texture2D<float3> inputBuffer : register(t0);\r\n"sv \ "float3 mainPixelProgram(in Input input) : SV_TARGET0\r\n"sv \ "{\r\n"sv \ " uint width, height, mipMapCount;\r\n"sv \ " inputBuffer.GetDimensions(0, width, height, mipMapCount);\r\n"sv \ " return inputBuffer[input.texCoord * float2(width, height)];\r\n"sv \ "}\r\n"sv; deferredVertexProgram = resources->getProgram(Video::Program::Type::Vertex, "deferredVertexProgram", "mainVertexProgram", program); deferredVertexProgram->setName("renderer:deferredVertexProgram"); deferredPixelProgram = resources->getProgram(Video::Program::Type::Pixel, "deferredPixelProgram", "mainPixelProgram", program); deferredPixelProgram->setName("renderer:deferredPixelProgram"); Video::Buffer::Description lightBufferDescription; lightBufferDescription.type = Video::Buffer::Type::Structured; lightBufferDescription.flags = Video::Buffer::Flags::Mappable | Video::Buffer::Flags::Resource; Video::Buffer::Description tileBufferDescription; tileBufferDescription.type = Video::Buffer::Type::Raw; tileBufferDescription.flags = Video::Buffer::Flags::Mappable | Video::Buffer::Flags::Resource; tileBufferDescription.format = Video::Format::R32G32_UINT; tileBufferDescription.count = GridSize; tileOffsetCountBuffer = videoDevice->createBuffer(tileBufferDescription); tileOffsetCountBuffer->setName("renderer:tileOffsetCountBuffer"); lightIndexList.reserve(GridSize * 10); tileBufferDescription.format = Video::Format::R16_UINT; tileBufferDescription.count = lightIndexList.capacity(); lightIndexBuffer = videoDevice->createBuffer(tileBufferDescription); lightIndexBuffer->setName("renderer:lightIndexBuffer"); } void initializeUI(void) { LockedWrite{ std::cout } << "Initializing user interface data"; gui.context = ImGui::CreateContext(); static constexpr std::string_view vertexShader = "cbuffer DataBuffer : register(b0)\r\n"sv \ "{\r\n"sv \ " float4x4 ProjectionMatrix;\r\n"sv \ " bool TextureHasAlpha;\r\n"sv \ " bool buffer[3];\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "struct VertexInput\r\n"sv \ "{\r\n"sv \ " float2 position : POSITION;\r\n"sv \ " float4 color : COLOR0;\r\n"sv \ " float2 texCoord : TEXCOORD0;\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "struct PixelOutput\r\n"sv \ "{\r\n"sv \ " float4 position : SV_POSITION;\r\n"sv \ " float4 color : COLOR0;\r\n"sv \ " float2 texCoord : TEXCOORD0;\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "PixelOutput main(in VertexInput input)\r\n"sv \ "{\r\n"sv \ " PixelOutput output;\r\n"sv \ " output.position = mul(ProjectionMatrix, float4(input.position.xy, 0.0f, 1.0f));\r\n"sv \ " output.color = input.color;\r\n"sv \ " output.texCoord = input.texCoord;\r\n"sv \ " return output;\r\n"sv \ "}\r\n"sv; gui.vertexProgram = resources->getProgram(Video::Program::Type::Vertex, "uiVertexProgram", "main", vertexShader); gui.vertexProgram->setName("core:vertexProgram"); std::vector<Video::InputElement> elementList; Video::InputElement element; element.format = Video::Format::R32G32_FLOAT; element.semantic = Video::InputElement::Semantic::Position; elementList.push_back(element); element.format = Video::Format::R32G32_FLOAT; element.semantic = Video::InputElement::Semantic::TexCoord; elementList.push_back(element); element.format = Video::Format::R8G8B8A8_UNORM; element.semantic = Video::InputElement::Semantic::Color; elementList.push_back(element); gui.inputLayout = videoDevice->createInputLayout(elementList, gui.vertexProgram->getInformation()); gui.inputLayout->setName("core:inputLayout"); Video::Buffer::Description constantBufferDescription; constantBufferDescription.stride = sizeof(GUI::DataBuffer); constantBufferDescription.count = 1; constantBufferDescription.type = Video::Buffer::Type::Constant; gui.constantBuffer = videoDevice->createBuffer(constantBufferDescription); gui.constantBuffer->setName("core:constantBuffer"); static constexpr std::string_view pixelShader = "cbuffer DataBuffer : register(b0)\r\n"sv \ "{\r\n"sv \ " float4x4 ProjectionMatrix;\r\n"sv \ " bool TextureHasAlpha;\r\n"sv \ " bool buffer[3];\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "struct PixelInput\r\n"sv \ "{\r\n"sv \ " float4 position : SV_POSITION;\r\n"sv \ " float4 color : COLOR0;\r\n"sv \ " float2 texCoord : TEXCOORD0;\r\n"sv \ "};\r\n"sv \ "\r\n"sv \ "sampler uiSampler;\r\n"sv \ "Texture2D<float4> uiTexture : register(t0);\r\n"sv \ "\r\n"sv \ "float4 main(PixelInput input) : SV_Target\r\n"sv \ "{\r\n"sv \ " return (input.color * uiTexture.Sample(uiSampler, input.texCoord));\r\n"sv \ "}\r\n"sv; gui.pixelProgram = resources->getProgram(Video::Program::Type::Pixel, "uiPixelProgram", "main", pixelShader); gui.pixelProgram->setName("core:pixelProgram"); Video::BlendState::Description blendStateInformation; blendStateInformation[0].enable = true; blendStateInformation[0].colorSource = Video::BlendState::Source::SourceAlpha; blendStateInformation[0].colorDestination = Video::BlendState::Source::InverseSourceAlpha; blendStateInformation[0].colorOperation = Video::BlendState::Operation::Add; blendStateInformation[0].alphaSource = Video::BlendState::Source::InverseSourceAlpha; blendStateInformation[0].alphaDestination = Video::BlendState::Source::Zero; blendStateInformation[0].alphaOperation = Video::BlendState::Operation::Add; gui.blendState = videoDevice->createBlendState(blendStateInformation); gui.blendState->setName("core:blendState"); Video::RenderState::Description renderStateInformation; renderStateInformation.fillMode = Video::RenderState::FillMode::Solid; renderStateInformation.cullMode = Video::RenderState::CullMode::None; renderStateInformation.scissorEnable = true; renderStateInformation.depthClipEnable = true; gui.renderState = videoDevice->createRenderState(renderStateInformation); gui.renderState->setName("core:renderState"); Video::DepthState::Description depthStateInformation; depthStateInformation.enable = true; depthStateInformation.comparisonFunction = Video::ComparisonFunction::LessEqual; depthStateInformation.writeMask = Video::DepthState::Write::Zero; gui.depthState = videoDevice->createDepthState(depthStateInformation); gui.depthState->setName("core:depthState"); ImGuiIO &imGuiIo = ImGui::GetIO(); imGuiIo.Fonts->AddFontFromFileTTF(getContext()->findDataPath(FileSystem::CombinePaths("fonts", "Ruda-Bold.ttf")).getString().data(), 14.0f); ImFontConfig fontConfig; fontConfig.MergeMode = true; fontConfig.GlyphOffset.y = 1.0f; const ImWchar fontAwesomeRanges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; imGuiIo.Fonts->AddFontFromFileTTF(getContext()->findDataPath(FileSystem::CombinePaths("fonts", "fontawesome-webfont.ttf")).getString().data(), 16.0f, &fontConfig, fontAwesomeRanges); fontConfig.GlyphOffset.y = 3.0f; const ImWchar googleIconRanges[] = { ICON_MIN_MD, ICON_MAX_MD, 0 }; imGuiIo.Fonts->AddFontFromFileTTF(getContext()->findDataPath(FileSystem::CombinePaths("fonts", "MaterialIcons-Regular.ttf")).getString().data(), 16.0f, &fontConfig, googleIconRanges); imGuiIo.Fonts->Build(); uint8_t *pixels = nullptr; int32_t fontWidth = 0, fontHeight = 0; imGuiIo.Fonts->GetTexDataAsRGBA32(&pixels, &fontWidth, &fontHeight); Video::Texture::Description fontDescription; fontDescription.format = Video::Format::R8G8B8A8_UNORM; fontDescription.width = fontWidth; fontDescription.height = fontHeight; fontDescription.flags = Video::Texture::Flags::Resource; gui.fontTexture = videoDevice->createTexture(fontDescription, pixels); imGuiIo.Fonts->TexID = static_cast<ImTextureID>(gui.fontTexture.get()); imGuiIo.UserData = this; imGuiIo.RenderDrawListsFn = [](ImDrawData *drawData) { ImGuiIO &imGuiIo = ImGui::GetIO(); Renderer *renderer = static_cast<Renderer *>(imGuiIo.UserData); renderer->renderUI(drawData); }; ImGui::ResetStyle(ImGuiStyle_GrayCodz01); auto &style = ImGui::GetStyle(); style.WindowPadding.x = style.WindowPadding.y; style.FramePadding.x = style.FramePadding.y; } ~Renderer(void) { workerPool.drain(); population->onReset.disconnect(this, &Renderer::onReset); population->onEntityCreated.disconnect(this, &Renderer::onEntityCreated); population->onEntityDestroyed.disconnect(this, &Renderer::onEntityDestroyed); population->onComponentAdded.disconnect(this, &Renderer::onComponentAdded); population->onComponentRemoved.disconnect(this, &Renderer::onComponentRemoved); population->onUpdate[1000].disconnect(this, &Renderer::onUpdate); ImGui::GetIO().Fonts->TexID = 0; ImGui::DestroyContext(gui.context); } void addEntity(Plugin::Entity * const entity) { if (entity->hasComponents<Components::Transform, Components::Color>()) { directionalLightData.addEntity(entity); pointLightData.addEntity(entity); spotLightData.addEntity(entity); } } void removeEntity(Plugin::Entity * const entity) { directionalLightData.removeEntity(entity); pointLightData.removeEntity(entity); spotLightData.removeEntity(entity); } // ImGui std::vector<Math::UInt4> scissorBoxList = std::vector<Math::UInt4>(1); std::vector<Video::Object *> textureList = std::vector<Video::Object *>(1); void renderUI(ImDrawData *drawData) { if (!gui.vertexBuffer || gui.vertexBuffer->getDescription().count < uint32_t(drawData->TotalVtxCount)) { Video::Buffer::Description vertexBufferDescription; vertexBufferDescription.stride = sizeof(ImDrawVert); vertexBufferDescription.count = drawData->TotalVtxCount; vertexBufferDescription.type = Video::Buffer::Type::Vertex; vertexBufferDescription.flags = Video::Buffer::Flags::Mappable; gui.vertexBuffer = videoDevice->createBuffer(vertexBufferDescription); gui.vertexBuffer->setName(String::Format("core:vertexBuffer:{}", gui.vertexBuffer.get())); } if (!gui.indexBuffer || gui.indexBuffer->getDescription().count < uint32_t(drawData->TotalIdxCount)) { Video::Buffer::Description vertexBufferDescription; vertexBufferDescription.count = drawData->TotalIdxCount; vertexBufferDescription.type = Video::Buffer::Type::Index; vertexBufferDescription.flags = Video::Buffer::Flags::Mappable; switch (sizeof(ImDrawIdx)) { case 2: vertexBufferDescription.format = Video::Format::R16_UINT; break; case 4: vertexBufferDescription.format = Video::Format::R32_UINT; break; }; gui.indexBuffer = videoDevice->createBuffer(vertexBufferDescription); gui.indexBuffer->setName(String::Format("core:vertexBuffer:{}", gui.indexBuffer.get())); } bool dataUploaded = false; ImDrawVert* vertexData = nullptr; ImDrawIdx* indexData = nullptr; if (videoDevice->mapBuffer(gui.vertexBuffer.get(), vertexData)) { if (videoDevice->mapBuffer(gui.indexBuffer.get(), indexData)) { for (int32_t commandListIndex = 0; commandListIndex < drawData->CmdListsCount; ++commandListIndex) { const ImDrawList* commandList = drawData->CmdLists[commandListIndex]; std::copy(commandList->VtxBuffer.Data, (commandList->VtxBuffer.Data + commandList->VtxBuffer.Size), vertexData); std::copy(commandList->IdxBuffer.Data, (commandList->IdxBuffer.Data + commandList->IdxBuffer.Size), indexData); vertexData += commandList->VtxBuffer.Size; indexData += commandList->IdxBuffer.Size; } dataUploaded = true; videoDevice->unmapBuffer(gui.indexBuffer.get()); } videoDevice->unmapBuffer(gui.vertexBuffer.get()); } if (dataUploaded) { auto backBuffer = videoDevice->getBackBuffer(); uint32_t width = backBuffer->getDescription().width; uint32_t height = backBuffer->getDescription().height; GUI::DataBuffer dataBuffer; dataBuffer.projectionMatrix = Math::Float4x4::MakeOrthographic(0.0f, 0.0f, float(width), float(height), 0.0f, 1.0f); videoDevice->updateResource(gui.constantBuffer.get(), &dataBuffer); auto videoContext = videoDevice->getDefaultContext(); videoContext->setRenderTargetList({ videoDevice->getBackBuffer() }, nullptr); videoContext->setViewportList({ Video::ViewPort(Math::Float2::Zero, Math::Float2(width, height), 0.0f, 1.0f) }); videoContext->setInputLayout(gui.inputLayout.get()); videoContext->setVertexBufferList({ gui.vertexBuffer.get() }, 0); videoContext->setIndexBuffer(gui.indexBuffer.get(), 0); videoContext->setPrimitiveType(Video::PrimitiveType::TriangleList); videoContext->vertexPipeline()->setProgram(gui.vertexProgram); videoContext->pixelPipeline()->setProgram(gui.pixelProgram); videoContext->vertexPipeline()->setConstantBufferList({ gui.constantBuffer.get() }, 0); videoContext->pixelPipeline()->setSamplerStateList({ bufferSamplerState.get() }, 0); videoContext->setBlendState(gui.blendState.get(), Math::Float4::Black, 0xFFFFFFFF); videoContext->setDepthState(gui.depthState.get(), 0); videoContext->setRenderState(gui.renderState.get()); uint32_t vertexOffset = 0; uint32_t indexOffset = 0; for (int32_t commandListIndex = 0; commandListIndex < drawData->CmdListsCount; ++commandListIndex) { const ImDrawList* commandList = drawData->CmdLists[commandListIndex]; for (int32_t commandIndex = 0; commandIndex < commandList->CmdBuffer.Size; ++commandIndex) { const ImDrawCmd* command = &commandList->CmdBuffer[commandIndex]; if (command->UserCallback) { command->UserCallback(commandList, command); } else { scissorBoxList[0].minimum.x = uint32_t(command->ClipRect.x); scissorBoxList[0].minimum.y = uint32_t(command->ClipRect.y); scissorBoxList[0].maximum.x = uint32_t(command->ClipRect.z); scissorBoxList[0].maximum.y = uint32_t(command->ClipRect.w); videoContext->setScissorList(scissorBoxList); textureList[0] = reinterpret_cast<Video::Texture *>(command->TextureId); videoContext->pixelPipeline()->setResourceList(textureList, 0); videoContext->drawIndexedPrimitive(command->ElemCount, indexOffset, vertexOffset); } indexOffset += command->ElemCount; } vertexOffset += commandList->VtxBuffer.Size; } } } // Clustered Lighting inline Math::Float3 getLightDirection(Math::Quaternion const &quaternion) const { const float xx(quaternion.x * quaternion.x); const float yy(quaternion.y * quaternion.y); const float zz(quaternion.z * quaternion.z); const float ww(quaternion.w * quaternion.w); const float length(xx + yy + zz + ww); if (length == 0.0f) { return Math::Float3(0.0f, 1.0f, 0.0f); } else { const float determinant(1.0f / length); const float xy(quaternion.x * quaternion.y); const float xw(quaternion.x * quaternion.w); const float yz(quaternion.y * quaternion.z); const float zw(quaternion.z * quaternion.w); return -Math::Float3((2.0f * (xy - zw) * determinant), ((-xx + yy - zz + ww) * determinant), (2.0f * (yz + xw) * determinant)); } } inline void updateClipRegionRoot(float tangentCoordinate, float lightCoordinate, float lightDepth, float radius, float radiusSquared, float lightRangeSquared, float cameraScale, float& minimum, float& maximum) const { const float nz = ((radius - tangentCoordinate * lightCoordinate) / lightDepth); const float pz = ((lightRangeSquared - radiusSquared) / (lightDepth - (nz / tangentCoordinate) * lightCoordinate)); if (pz >= 0.0f) { const float clip = (-nz * cameraScale / tangentCoordinate); if (tangentCoordinate >= 0.0f) { // Left side boundary minimum = std::max(minimum, clip); } else { // Right side boundary maximum = std::min(maximum, clip); } } } inline void updateClipRegion(float lightCoordinate, float lightDepth, float lightDepthSquared, float radius, float radiusSquared, float cameraScale, float& minimum, float& maximum) const { const float lightCoordinateSquared = (lightCoordinate * lightCoordinate); const float lightRangeSquared = (lightCoordinateSquared + lightDepthSquared); const float distanceSquared = ((radiusSquared * lightCoordinateSquared) - (lightRangeSquared * (radiusSquared - lightDepthSquared))); if (distanceSquared > 0.0f) { const float projectedRadius = (radius * lightCoordinate); const float distance = std::sqrt(distanceSquared); const float positiveTangent = ((projectedRadius + distance) / lightRangeSquared); const float negativeTangent = ((projectedRadius - distance) / lightRangeSquared); updateClipRegionRoot(positiveTangent, lightCoordinate, lightDepth, radius, radiusSquared, lightRangeSquared, cameraScale, minimum, maximum); updateClipRegionRoot(negativeTangent, lightCoordinate, lightDepth, radius, radiusSquared, lightRangeSquared, cameraScale, minimum, maximum); } } // Returns bounding box [min.xy, max.xy] in clip [-1, 1] space. inline Math::Float4 getClipBounds(Math::Float3 const &position, float radius) const { // Early out with empty rectangle if the light is too far behind the view frustum Math::Float4 clipRegion(1.0f, 1.0f, 0.0f, 0.0f); if ((position.z + radius) >= currentCamera.nearClip) { clipRegion.set(-1.0f, -1.0f, 1.0f, 1.0f); const float radiusSquared = (radius * radius); const float lightDepthSquared = (position.z * position.z); updateClipRegion(position.x, position.z, lightDepthSquared, radius, radiusSquared, currentCamera.projectionMatrix.rx.x, clipRegion.minimum.x, clipRegion.maximum.x); updateClipRegion(position.y, position.z, lightDepthSquared, radius, radiusSquared, currentCamera.projectionMatrix.ry.y, clipRegion.minimum.y, clipRegion.maximum.y); } return clipRegion; } inline Math::Float4 getScreenBounds(Math::Float3 const &position, float radius) const { const auto clipBounds((getClipBounds(position, radius) + 1.0f) * 0.5f); return Math::Float4(clipBounds.x, (1.0f - clipBounds.w), clipBounds.z, (1.0f - clipBounds.y)); } bool isSeparated(uint32_t x, uint32_t y, uint32_t z, Math::Float3 const &position, float radius) const { static const Math::Float4 GridScaleNegator(Math::Float2(-1.0f), Math::Float2(1.0f)); static const Math::Float4 GridScaleOne(1.0f); static const Math::Float4 GridScaleTwo(2.0f); static const Math::Float4 TileBoundsOffset(-0.1f, 1.1f, 0.1f, 1.1f); // sub-frustrum bounds in view space const float minimumZ = ((z - 0.1f) * depthScale); const float maximumZ = ((z + 1.1f) * depthScale); const Math::Float4 tileBounds(Math::Float4(x, x, y, y) + TileBoundsOffset); const Math::Float4 projectionScale(GridScaleOne / Math::Float4( currentCamera.projectionMatrix.rx.x, currentCamera.projectionMatrix.rx.x, currentCamera.projectionMatrix.ry.y, currentCamera.projectionMatrix.ry.y)); const auto gridScale = (GridScaleNegator * (GridScaleOne - GridScaleTwo / GridDimensions * tileBounds)); const auto minimum = (gridScale * minimumZ * projectionScale); const auto maximum = (gridScale * maximumZ * projectionScale); // heuristic plane separation test - works pretty well in practice const Math::Float3 minimumZcenter(((minimum.x + minimum.y) * 0.5f), ((minimum.z + minimum.w) * 0.5f), minimumZ); const Math::Float3 maximumZcenter(((maximum.x + maximum.y) * 0.5f), ((maximum.z + maximum.w) * 0.5f), maximumZ); const Math::Float3 center((minimumZcenter + maximumZcenter) * 0.5f); const Math::Float3 normal((center - position).getNormal()); // compute distance of all corners to the tangent plane, with a few shortcuts (saves 14 muls) Math::Float2 tileCorners(-normal.dot(position)); tileCorners.minimum += std::min((normal.x * minimum.x), (normal.x * minimum.y)); tileCorners.minimum += std::min((normal.y * minimum.z), (normal.y * minimum.w)); tileCorners.minimum += (normal.z * minimumZ); tileCorners.maximum += std::min((normal.x * maximum.x), (normal.x * maximum.y)); tileCorners.maximum += std::min((normal.y * maximum.z), (normal.y * maximum.w)); tileCorners.maximum += (normal.z * maximumZ); return (std::min(tileCorners.minimum, tileCorners.maximum) >= radius); } void addLightCluster(Math::Float3 const &position, float radius, uint32_t lightIndex, concurrency::concurrent_vector<uint16_t> *gridLightList) { const Math::Float4 screenBounds(getScreenBounds(position, radius)); const Math::Int4 gridBounds( std::max(0, int32_t(std::floor(screenBounds.x * GridWidth))), std::max(0, int32_t(std::floor(screenBounds.y * GridHeight))), std::min(int32_t(std::ceil(screenBounds.z * GridWidth)), GridWidth), std::min(int32_t(std::ceil(screenBounds.w * GridHeight)), GridHeight) ); /*const float centerDepth = ((position.z - currentCamera.nearClip) * reciprocalClipDistance); const float radiusDepth = (radius * reciprocalClipDistance); const Math::Int2 depthBounds( std::max(0, int32_t(std::floor((centerDepth - radiusDepth) * GridDepth))), std::min(int32_t(std::ceil((centerDepth + radiusDepth) * GridDepth)), GridDepth) );*/ const float minimumDepth = (((position.z - radius) - currentCamera.nearClip) * reciprocalClipDistance); const float maximumDepth = (((position.z + radius) - currentCamera.nearClip) * reciprocalClipDistance); const Math::Int2 depthBounds( std::max(0, int32_t(std::floor(minimumDepth * GridDepth))), std::min(int32_t(std::ceil(maximumDepth * GridDepth)), GridDepth) ); concurrency::parallel_for(depthBounds.minimum, depthBounds.maximum, [&](auto z) -> void { const uint32_t zSlice = (z * GridHeight); for (auto y = gridBounds.minimum.y; y < gridBounds.maximum.y; ++y) { const uint32_t ySlize = ((zSlice + y) * GridWidth); for (auto x = gridBounds.minimum.x; x < gridBounds.maximum.x; ++x) { if (!isSeparated(x, y, z, position, radius)) { const uint32_t gridIndex = (ySlize + x); auto &gridData = gridLightList[gridIndex]; gridData.push_back(lightIndex); } } } }); } void addPointLight(Plugin::Entity * const entity, Components::PointLight const &lightComponent) { auto const &transformComponent = entity->getComponent<Components::Transform>(); auto const &colorComponent = entity->getComponent<Components::Color>(); auto lightIterator = pointLightData.lightList.grow_by(1); PointLightData &lightData = (*lightIterator); lightData.radiance = (colorComponent.value.xyz * lightComponent.intensity); lightData.position = currentCamera.viewMatrix.transform(transformComponent.position); lightData.radius = lightComponent.radius; lightData.range = lightComponent.range; const auto lightIndex = std::distance(std::begin(pointLightData.lightList), lightIterator); addLightCluster(lightData.position, (lightData.radius + lightData.range), lightIndex, tilePointLightIndexList); } void addSpotLight(Plugin::Entity * const entity, Components::SpotLight const &lightComponent) { auto const &transformComponent = entity->getComponent<Components::Transform>(); auto const &colorComponent = entity->getComponent<Components::Color>(); auto lightIterator = spotLightData.lightList.grow_by(1); SpotLightData &lightData = (*lightIterator); lightData.radiance = (colorComponent.value.xyz * lightComponent.intensity); lightData.position = currentCamera.viewMatrix.transform(transformComponent.position); lightData.radius = lightComponent.radius; lightData.range = lightComponent.range; lightData.direction = currentCamera.viewMatrix.rotate(getLightDirection(transformComponent.rotation)); lightData.innerAngle = lightComponent.innerAngle; lightData.outerAngle = lightComponent.outerAngle; lightData.coneFalloff = lightComponent.coneFalloff; const auto lightIndex = std::distance(std::begin(spotLightData.lightList), lightIterator); addLightCluster(lightData.position, (lightData.radius + lightData.range), lightIndex, tileSpotLightIndexList); } // Plugin::Population Slots void onReset(void) { directionalLightData.clearEntities(); pointLightData.clearEntities(); spotLightData.clearEntities(); } void onEntityCreated(Plugin::Entity * const entity) { addEntity(entity); } void onEntityDestroyed(Plugin::Entity * const entity) { removeEntity(entity); } void onComponentAdded(Plugin::Entity * const entity) { addEntity(entity); } void onComponentRemoved(Plugin::Entity * const entity) { removeEntity(entity); } // Renderer Video::Device * getVideoDevice(void) const { return videoDevice; } ImGuiContext * const getGuiContext(void) const { return gui.context; } void queueCamera(Math::Float4x4 const &viewMatrix, Math::Float4x4 const &perspectiveMatrix, float nearClip, float farClip, std::string const &name, ResourceHandle cameraTarget, std::string const &forceShader) { Camera renderCall; renderCall.viewMatrix = viewMatrix; renderCall.projectionMatrix = perspectiveMatrix; renderCall.viewFrustum.create(renderCall.viewMatrix * renderCall.projectionMatrix); renderCall.nearClip = nearClip; renderCall.farClip = farClip; renderCall.cameraTarget = cameraTarget; renderCall.name = name; if (!forceShader.empty()) { renderCall.forceShader = resources->getShader(forceShader); } cameraQueue.push(renderCall); } void queueCamera(Math::Float4x4 const &viewMatrix, float fieldOfView, float aspectRatio, float nearClip, float farClip, std::string const &name, ResourceHandle cameraTarget, std::string const &forceShader) { if (core->getOption("render"s, "invertedDepthBuffer"s).convert(true)) { queueCamera(viewMatrix, Math::Float4x4::MakePerspective(fieldOfView, aspectRatio, farClip, nearClip), nearClip, farClip, name, cameraTarget, forceShader); } else { queueCamera(viewMatrix, Math::Float4x4::MakePerspective(fieldOfView, aspectRatio, nearClip, farClip), nearClip, farClip, name, cameraTarget, forceShader); } } void queueCamera(Math::Float4x4 const &viewMatrix, float left, float top, float right, float bottom, float nearClip, float farClip, std::string const &name, ResourceHandle cameraTarget, std::string const &forceShader) { queueCamera(viewMatrix, Math::Float4x4::MakeOrthographic(left, top, right, bottom, nearClip, farClip), nearClip, farClip, name, cameraTarget, forceShader); } void queueDrawCall(VisualHandle plugin, MaterialHandle material, std::function<void(Video::Device::Context *videoContext)> &&draw) { if (plugin && material && draw) { ShaderHandle shader = (currentCamera.forceShader ? currentCamera.forceShader : resources->getMaterialShader(material)); if (shader) { drawCallList.push_back(DrawCallValue(material, plugin, shader, std::move(draw))); } } } // Plugin::Core Slots void onUpdate(float frameTime) { assert(videoDevice); assert(population); videoDevice->beginProfilerBlock(); GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Update"sv, Profiler::EmptyArguments) { EngineConstantData engineConstantData; engineConstantData.frameTime = frameTime; engineConstantData.worldTime = 0.0f; engineConstantData.invertedDepthBuffer = (core->getOption("render"s, "invertedDepthBuffer"s).convert(true) ? 1 : 0); videoDevice->updateResource(engineConstantBuffer.get(), &engineConstantData); Video::Device::Context *videoContext = videoDevice->getDefaultContext(); while (cameraQueue.try_pop(currentCamera)) { GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, currentCamera.name, Profiler::EmptyArguments) { clipDistance = (currentCamera.farClip - currentCamera.nearClip); reciprocalClipDistance = (1.0f / clipDistance); depthScale = ((ReciprocalGridDepth * clipDistance) + currentCamera.nearClip); drawCallList.clear(); onQueueDrawCalls(currentCamera.viewFrustum, currentCamera.viewMatrix, currentCamera.projectionMatrix); if (!drawCallList.empty()) { const auto backBuffer = videoDevice->getBackBuffer(); const auto width = backBuffer->getDescription().width; const auto height = backBuffer->getDescription().height; GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Sort Draw Calls"sv, Profiler::EmptyArguments) { concurrency::parallel_sort(std::begin(drawCallList), std::end(drawCallList), [](DrawCallValue const &leftValue, DrawCallValue const &rightValue) -> bool { return (leftValue.value < rightValue.value); }); } GEK_PROFILER_END_SCOPE(); bool isLightingRequired = false; ShaderHandle currentShader; std::map<uint32_t, std::vector<DrawCallSet>> drawCallSetMap; GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Split Draw Calls"sv, Profiler::EmptyArguments) { for (auto &drawCall = std::begin(drawCallList); drawCall != std::end(drawCallList); ) { currentShader = drawCall->shader; auto beginShaderList = drawCall; while (drawCall != std::end(drawCallList) && drawCall->shader == currentShader) { ++drawCall; }; auto endShaderList = drawCall; Engine::Shader *shader = resources->getShader(currentShader); if (!shader) { continue; } isLightingRequired |= shader->isLightingRequired(); auto &shaderList = drawCallSetMap[shader->getDrawOrder()]; shaderList.push_back(DrawCallSet(shader, beginShaderList, endShaderList)); } } GEK_PROFILER_END_SCOPE(); if (isLightingRequired) { auto directionalLightsDone = workerPool.enqueue([&](void) -> void { GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, directionalThreadIdentifier, "Render"sv, "Cull Directional Lights"sv, Profiler::EmptyArguments) { directionalLightData.lightList.clear(); directionalLightData.lightList.reserve(directionalLightData.entityList.size()); std::for_each(std::begin(directionalLightData.entityList), std::end(directionalLightData.entityList), [&](Plugin::Entity * const entity) -> void { auto const &transformComponent = entity->getComponent<Components::Transform>(); auto const &colorComponent = entity->getComponent<Components::Color>(); auto const &lightComponent = entity->getComponent<Components::DirectionalLight>(); DirectionalLightData lightData; lightData.radiance = (colorComponent.value.xyz * lightComponent.intensity); lightData.direction = currentCamera.viewMatrix.rotate(getLightDirection(transformComponent.rotation)); directionalLightData.lightList.push_back(lightData); }); directionalLightData.createBuffer(); } GEK_PROFILER_END_SCOPE(); }, __FILE__, __LINE__); auto frustum = Math::SIMD::loadFrustum((Math::Float4 *)currentCamera.viewFrustum.planeList); concurrency::parallel_for_each(std::begin(tilePointLightIndexList), std::end(tilePointLightIndexList), [&](auto &gridData) -> void { gridData.clear(); }); concurrency::parallel_for_each(std::begin(tileSpotLightIndexList), std::end(tileSpotLightIndexList), [&](auto &gridData) -> void { gridData.clear(); }); auto pointLightsDone = workerPool.enqueue([&](void) -> void { GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, pointLightThreadIdentifier, "Render"sv, "Point Directional Lights"sv, Profiler::EmptyArguments) { pointLightData.cull(frustum, pointLightThreadIdentifier); concurrency::parallel_for(size_t(0), pointLightData.entityList.size(), [&](size_t index) -> void { if (pointLightData.visibilityList[index]) { auto entity = pointLightData.entityList[index]; auto &lightComponent = entity->getComponent<Components::PointLight>(); addPointLight(entity, lightComponent); } }); pointLightData.createBuffer(); } GEK_PROFILER_END_SCOPE(); }, __FILE__, __LINE__); auto spotLightsDone = workerPool.enqueue([&](void) -> void { GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, spotLightThreadIdentifier, "Render"sv, "Spot Directional Lights"sv, Profiler::EmptyArguments) { spotLightData.cull(frustum, spotLightThreadIdentifier); concurrency::parallel_for(size_t(0), spotLightData.entityList.size(), [&](size_t index) -> void { if (spotLightData.visibilityList[index]) { auto entity = spotLightData.entityList[index]; auto &lightComponent = entity->getComponent<Components::SpotLight>(); addSpotLight(entity, lightComponent); } }); spotLightData.createBuffer(); } GEK_PROFILER_END_SCOPE(); }, __FILE__, __LINE__); directionalLightsDone.get(); pointLightsDone.get(); spotLightsDone.get(); GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Update Lighting Buffers"sv, Profiler::EmptyArguments) { concurrency::combinable<size_t> lightIndexCount; concurrency::parallel_for_each(std::begin(tilePointLightIndexList), std::end(tilePointLightIndexList), [&](auto &gridData) -> void { lightIndexCount.local() += gridData.size(); }); concurrency::parallel_for_each(std::begin(tileSpotLightIndexList), std::end(tileSpotLightIndexList), [&](auto &gridData) -> void { lightIndexCount.local() += gridData.size(); }); lightIndexList.clear(); lightIndexList.reserve(lightIndexCount.combine(std::plus<size_t>())); for (uint32_t tileIndex = 0; tileIndex < GridSize; ++tileIndex) { auto &tileOffsetCount = tileOffsetCountList[tileIndex]; auto const &tilePointLightIndex = tilePointLightIndexList[tileIndex]; auto const &tileSpotightIndex = tileSpotLightIndexList[tileIndex]; tileOffsetCount.indexOffset = lightIndexList.size(); tileOffsetCount.pointLightCount = uint16_t(tilePointLightIndex.size() & 0xFFFF); tileOffsetCount.spotLightCount = uint16_t(tileSpotightIndex.size() & 0xFFFF); lightIndexList.insert(std::end(lightIndexList), std::begin(tilePointLightIndex), std::end(tilePointLightIndex)); lightIndexList.insert(std::end(lightIndexList), std::begin(tileSpotightIndex), std::end(tileSpotightIndex)); } if (!directionalLightData.updateBuffer() || !pointLightData.updateBuffer() || !spotLightData.updateBuffer()) { return; } TileOffsetCount *tileOffsetCountData = nullptr; if (videoDevice->mapBuffer(tileOffsetCountBuffer.get(), tileOffsetCountData)) { std::copy(std::begin(tileOffsetCountList), std::end(tileOffsetCountList), tileOffsetCountData); videoDevice->unmapBuffer(tileOffsetCountBuffer.get()); } else { return; } if (!lightIndexList.empty()) { if (!lightIndexBuffer || lightIndexBuffer->getDescription().count < lightIndexList.size()) { lightIndexBuffer = nullptr; Video::Buffer::Description tileBufferDescription; tileBufferDescription.type = Video::Buffer::Type::Raw; tileBufferDescription.flags = Video::Buffer::Flags::Mappable | Video::Buffer::Flags::Resource; tileBufferDescription.format = Video::Format::R16_UINT; tileBufferDescription.count = lightIndexList.size(); lightIndexBuffer = videoDevice->createBuffer(tileBufferDescription); lightIndexBuffer->setName(String::Format("renderer:lightIndexBuffer:{}", lightIndexBuffer.get())); } uint16_t *lightIndexData = nullptr; if (videoDevice->mapBuffer(lightIndexBuffer.get(), lightIndexData)) { std::copy(std::begin(lightIndexList), std::end(lightIndexList), lightIndexData); videoDevice->unmapBuffer(lightIndexBuffer.get()); } else { return; } } LightConstantData lightConstants; lightConstants.directionalLightCount = directionalLightData.lightList.size(); lightConstants.pointLightCount = pointLightData.lightList.size(); lightConstants.spotLightCount = spotLightData.lightList.size(); lightConstants.gridSize.x = GridWidth; lightConstants.gridSize.y = GridHeight; lightConstants.gridSize.z = GridDepth; lightConstants.tileSize.x = (width / GridWidth); lightConstants.tileSize.y = (height / GridHeight); videoDevice->updateResource(lightConstantBuffer.get(), &lightConstants); } GEK_PROFILER_END_SCOPE(); } CameraConstantData cameraConstantData; GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Update Engine Buffers"sv, Profiler::EmptyArguments) { cameraConstantData.fieldOfView.x = (1.0f / currentCamera.projectionMatrix._11); cameraConstantData.fieldOfView.y = (1.0f / currentCamera.projectionMatrix._22); cameraConstantData.nearClip = currentCamera.nearClip; cameraConstantData.farClip = currentCamera.farClip; cameraConstantData.viewMatrix = currentCamera.viewMatrix; cameraConstantData.projectionMatrix = currentCamera.projectionMatrix; videoDevice->updateResource(cameraConstantBuffer.get(), &cameraConstantData); videoContext->clearState(); videoContext->geometryPipeline()->setConstantBufferList(shaderBufferList, 0); videoContext->vertexPipeline()->setConstantBufferList(shaderBufferList, 0); videoContext->pixelPipeline()->setConstantBufferList(shaderBufferList, 0); videoContext->computePipeline()->setConstantBufferList(shaderBufferList, 0); videoContext->pixelPipeline()->setSamplerStateList(samplerList, 0); videoContext->setPrimitiveType(Video::PrimitiveType::TriangleList); if (isLightingRequired) { lightResoruceList = { directionalLightData.lightDataBuffer.get(), pointLightData.lightDataBuffer.get(), spotLightData.lightDataBuffer.get(), tileOffsetCountBuffer.get(), lightIndexBuffer.get() }; videoContext->pixelPipeline()->setConstantBufferList(lightBufferList, 3); videoContext->pixelPipeline()->setResourceList(lightResoruceList, 0); } } GEK_PROFILER_END_SCOPE(); //static const auto bufferManagement = this->registerName("Buffer Management"); uint8_t shaderIndex = 0; std::string finalOutput; auto forceShader = (currentCamera.forceShader ? resources->getShader(currentCamera.forceShader) : nullptr); GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Handle Shaders", Profiler::EmptyArguments) { for (auto const &shaderDrawCallList : drawCallSetMap) { for (auto const &shaderDrawCall : shaderDrawCallList.second) { auto &shader = shaderDrawCall.shader; GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, shader->getName(), Profiler::EmptyArguments) { finalOutput = shader->getOutput(); for (auto pass = shader->begin(videoContext, cameraConstantData.viewMatrix, currentCamera.viewFrustum); pass; pass = pass->next()) { if (pass->isEnabled()) { GEK_VIDEO_PROFILER_BEGIN_SCOPE(videoDevice, pass->getName(), pass->getIdentifier()) { VisualHandle currentVisual; MaterialHandle currentMaterial; resources->startResourceBlock(); switch (pass->prepare()) { case Engine::Shader::Pass::Mode::Forward: GEK_VIDEO_PROFILER_BEGIN_SCOPE(videoDevice, "Draw Geometry"sv, CombineHashes(pass->getIdentifier(), 0xFFFFFFFF)) { for (auto drawCall = shaderDrawCall.begin; drawCall != shaderDrawCall.end; ++drawCall) { if (currentVisual != drawCall->plugin) { currentVisual = drawCall->plugin; resources->setVisual(videoContext, currentVisual); } if (currentMaterial != drawCall->material) { currentMaterial = drawCall->material; resources->setMaterial(videoContext, pass.get(), currentMaterial, (forceShader == shader)); } drawCall->onDraw(videoContext); } } GEK_VIDEO_PROFILER_END_SCOPE(); break; case Engine::Shader::Pass::Mode::Deferred: videoContext->vertexPipeline()->setProgram(deferredVertexProgram); resources->drawPrimitive(videoContext, 3, 0); break; case Engine::Shader::Pass::Mode::Compute: break; }; pass->clear(); } GEK_VIDEO_PROFILER_END_SCOPE(); } } } GEK_PROFILER_END_SCOPE(); } } } GEK_PROFILER_END_SCOPE(); videoContext->geometryPipeline()->clearConstantBufferList(2, 0); videoContext->vertexPipeline()->clearConstantBufferList(2, 0); videoContext->pixelPipeline()->clearConstantBufferList(2, 0); videoContext->computePipeline()->clearConstantBufferList(2, 0); if (currentCamera.cameraTarget) { auto finalHandle = resources->getResourceHandle(finalOutput); renderOverlay(videoDevice->getDefaultContext(), finalHandle, currentCamera.cameraTarget); } else { screenOutput = finalOutput; } } } GEK_PROFILER_END_SCOPE(); }; auto screenHandle = resources->getResourceHandle(screenOutput); if (screenHandle) { videoContext->clearState(); videoContext->geometryPipeline()->setConstantBufferList(filterBufferList, 0); videoContext->vertexPipeline()->setConstantBufferList(filterBufferList, 0); videoContext->pixelPipeline()->setConstantBufferList(filterBufferList, 0); videoContext->computePipeline()->setConstantBufferList(filterBufferList, 0); videoContext->pixelPipeline()->setSamplerStateList(samplerList, 0); videoContext->setPrimitiveType(Video::PrimitiveType::TriangleList); uint8_t filterIndex = 0; videoContext->vertexPipeline()->setProgram(deferredVertexProgram); GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Handle Filters", Profiler::EmptyArguments) { for (auto const &filterName : { "tonemap" }) { auto const filter = resources->getFilter(filterName); if (filter) { GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, filter->getName(), Profiler::EmptyArguments) { for (auto pass = filter->begin(videoContext, screenHandle, ResourceHandle()); pass; pass = pass->next()) { if (pass->isEnabled()) { GEK_VIDEO_PROFILER_BEGIN_SCOPE(videoDevice, pass->getName(), pass->getIdentifier()) { switch (pass->prepare()) { case Engine::Filter::Pass::Mode::Deferred: resources->drawPrimitive(videoContext, 3, 0); break; case Engine::Filter::Pass::Mode::Compute: break; }; pass->clear(); } GEK_VIDEO_PROFILER_END_SCOPE(); } } } GEK_PROFILER_END_SCOPE(); } } } GEK_PROFILER_END_SCOPE(); videoContext->geometryPipeline()->clearConstantBufferList(1, 0); videoContext->vertexPipeline()->clearConstantBufferList(1, 0); videoContext->pixelPipeline()->clearConstantBufferList(1, 0); videoContext->computePipeline()->clearConstantBufferList(1, 0); } else { static const JSON Black = JSON::Array({ 0.0f, 0.0f, 0.0f, 1.0f }); auto blackPattern = resources->createPattern("color", Black); renderOverlay(videoContext, blackPattern, ResourceHandle()); } bool reloadRequired = false; GEK_PROFILER_BEGIN_SCOPE(getProfiler(), 0, 0, "Render"sv, "Prepare User Interface"sv, Profiler::EmptyArguments) { ImGuiIO &imGuiIo = ImGui::GetIO(); imGuiIo.DeltaTime = (1.0f / 60.0f); auto backBuffer = videoDevice->getBackBuffer(); uint32_t width = backBuffer->getDescription().width; uint32_t height = backBuffer->getDescription().height; imGuiIo.DisplaySize = ImVec2(float(width), float(height)); ImGui::NewFrame(); onShowUserInterface(); auto mainMenu = ImGui::FindWindowByName("##MainMenuBar"); auto mainMenuShowing = (mainMenu ? mainMenu->Active : false); if (mainMenuShowing) { ImGui::BeginMainMenuBar(); ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(5.0f, 10.0f)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(5.0f, 10.0f)); if (ImGui::BeginMenu("Render")) { auto invertedDepthBuffer = core->getOption("render"s, "invertedDepthBuffer"s).convert(true); if (ImGui::MenuItem("Inverted Depth Buffer", "CTRL+I", &invertedDepthBuffer)) { core->setOption("render"s, "invertedDepthBuffer"s, invertedDepthBuffer); reloadRequired = true; } ImGui::EndMenu(); } ImGui::PopStyleVar(2); ImGui::EndMainMenuBar(); } } GEK_PROFILER_END_SCOPE(); GEK_VIDEO_PROFILER_BEGIN_SCOPE(videoDevice, "Draw User Interface"sv, 0) { ImGui::Render(); } GEK_VIDEO_PROFILER_END_SCOPE(); videoDevice->present(true); if (reloadRequired) { resources->reload(); } } GEK_PROFILER_END_SCOPE(); videoDevice->endProfilerBlock(); } void renderOverlay(Video::Device::Context *videoContext, ResourceHandle input, ResourceHandle target) { videoContext->setBlendState(blendState.get(), Math::Float4::Black, 0xFFFFFFFF); videoContext->setDepthState(depthState.get(), 0); videoContext->setRenderState(renderState.get()); videoContext->setPrimitiveType(Video::PrimitiveType::TriangleList); resources->startResourceBlock(); resources->setResourceList(videoContext->pixelPipeline(), { input }, 0); videoContext->vertexPipeline()->setProgram(deferredVertexProgram); videoContext->pixelPipeline()->setProgram(deferredPixelProgram); resources->setRenderTargetList(videoContext, { target }, nullptr); resources->drawPrimitive(videoContext, 3, 0); resources->clearRenderTargetList(videoContext, 1, false); resources->clearResourceList(videoContext->pixelPipeline(), 1, 0); } }; GEK_REGISTER_CONTEXT_USER(Renderer); }; // namespace Implementation }; // namespace Gek
41.749084
220
0.66149
xycsoscyx
c3d4a9bbcccfb662694cf0299e05f708deb9cb81
6,403
hpp
C++
include/UnityEngine/TestTools/Utils/CoroutineRunner.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/TestTools/Utils/CoroutineRunner.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/TestTools/Utils/CoroutineRunner.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::TestTools::Utils namespace UnityEngine::TestTools::Utils { } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: MonoBehaviour class MonoBehaviour; // Forward declaring type: Coroutine class Coroutine; } // Forward declaring namespace: UnityEngine::TestRunner::NUnitExtensions::Runner namespace UnityEngine::TestRunner::NUnitExtensions::Runner { // Forward declaring type: UnityTestExecutionContext class UnityTestExecutionContext; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IEnumerator class IEnumerator; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action class Action; } // Completed forward declares // Type namespace: UnityEngine.TestTools.Utils namespace UnityEngine::TestTools::Utils { // Size: 0x38 #pragma pack(push, 1) // Autogenerated type: UnityEngine.TestTools.Utils.CoroutineRunner class CoroutineRunner : public ::Il2CppObject { public: // Nested type: UnityEngine::TestTools::Utils::CoroutineRunner::$HandleEnumerableTest$d__8 class $HandleEnumerableTest$d__8; // Nested type: UnityEngine::TestTools::Utils::CoroutineRunner::$ExMethod$d__10 class $ExMethod$d__10; // Nested type: UnityEngine::TestTools::Utils::CoroutineRunner::$StartTimer$d__11 class $StartTimer$d__11; // private System.Boolean m_Running // Size: 0x1 // Offset: 0x10 bool m_Running; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean m_Timeout // Size: 0x1 // Offset: 0x11 bool m_Timeout; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_Timeout and: m_Controller char __padding1[0x6] = {}; // private readonly UnityEngine.MonoBehaviour m_Controller // Size: 0x8 // Offset: 0x18 UnityEngine::MonoBehaviour* m_Controller; // Field size check static_assert(sizeof(UnityEngine::MonoBehaviour*) == 0x8); // private readonly UnityEngine.TestRunner.NUnitExtensions.Runner.UnityTestExecutionContext m_Context // Size: 0x8 // Offset: 0x20 UnityEngine::TestRunner::NUnitExtensions::Runner::UnityTestExecutionContext* m_Context; // Field size check static_assert(sizeof(UnityEngine::TestRunner::NUnitExtensions::Runner::UnityTestExecutionContext*) == 0x8); // private UnityEngine.Coroutine m_TimeOutCoroutine // Size: 0x8 // Offset: 0x28 UnityEngine::Coroutine* m_TimeOutCoroutine; // Field size check static_assert(sizeof(UnityEngine::Coroutine*) == 0x8); // private System.Collections.IEnumerator m_TestCoroutine // Size: 0x8 // Offset: 0x30 System::Collections::IEnumerator* m_TestCoroutine; // Field size check static_assert(sizeof(System::Collections::IEnumerator*) == 0x8); // Creating value type constructor for type: CoroutineRunner CoroutineRunner(bool m_Running_ = {}, bool m_Timeout_ = {}, UnityEngine::MonoBehaviour* m_Controller_ = {}, UnityEngine::TestRunner::NUnitExtensions::Runner::UnityTestExecutionContext* m_Context_ = {}, UnityEngine::Coroutine* m_TimeOutCoroutine_ = {}, System::Collections::IEnumerator* m_TestCoroutine_ = {}) noexcept : m_Running{m_Running_}, m_Timeout{m_Timeout_}, m_Controller{m_Controller_}, m_Context{m_Context_}, m_TimeOutCoroutine{m_TimeOutCoroutine_}, m_TestCoroutine{m_TestCoroutine_} {} // public System.Void .ctor(UnityEngine.MonoBehaviour playmodeTestsController, UnityEngine.TestRunner.NUnitExtensions.Runner.UnityTestExecutionContext context) // Offset: 0x23C3248 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static CoroutineRunner* New_ctor(UnityEngine::MonoBehaviour* playmodeTestsController, UnityEngine::TestRunner::NUnitExtensions::Runner::UnityTestExecutionContext* context) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TestTools::Utils::CoroutineRunner::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<CoroutineRunner*, creationType>(playmodeTestsController, context))); } // public System.Collections.IEnumerator HandleEnumerableTest(System.Collections.IEnumerator testEnumerator) // Offset: 0x23C3280 System::Collections::IEnumerator* HandleEnumerableTest(System::Collections::IEnumerator* testEnumerator); // private System.Void StopAllRunningCoroutines() // Offset: 0x23C3328 void StopAllRunningCoroutines(); // private System.Collections.IEnumerator ExMethod(System.Collections.IEnumerator e, System.Int32 timeout) // Offset: 0x23C3380 System::Collections::IEnumerator* ExMethod(System::Collections::IEnumerator* e, int timeout); // private System.Collections.IEnumerator StartTimer(System.Collections.IEnumerator coroutineToBeKilled, System.Int32 timeout, System.Action onTimeout) // Offset: 0x23C3430 System::Collections::IEnumerator* StartTimer(System::Collections::IEnumerator* coroutineToBeKilled, int timeout, System::Action* onTimeout); // public System.Boolean HasFailedWithTimeout() // Offset: 0x23C34F0 bool HasFailedWithTimeout(); // private System.Void <ExMethod>b__10_0() // Offset: 0x23C34F8 void $ExMethod$b__10_0(); }; // UnityEngine.TestTools.Utils.CoroutineRunner #pragma pack(pop) static check_size<sizeof(CoroutineRunner), 48 + sizeof(System::Collections::IEnumerator*)> __UnityEngine_TestTools_Utils_CoroutineRunnerSizeCheck; static_assert(sizeof(CoroutineRunner) == 0x38); } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestTools::Utils::CoroutineRunner*, "UnityEngine.TestTools.Utils", "CoroutineRunner");
52.056911
500
0.738872
darknight1050
c3db8f36982be28143335f40bf0b7c380c6e696e
9,365
hpp
C++
src/HALib/protocol/node/HANode.hpp
SBKila/homeassistantlibrary
7adf8a950d4c428141ac92920bd2630341b3a261
[ "MIT" ]
null
null
null
src/HALib/protocol/node/HANode.hpp
SBKila/homeassistantlibrary
7adf8a950d4c428141ac92920bd2630341b3a261
[ "MIT" ]
null
null
null
src/HALib/protocol/node/HANode.hpp
SBKila/homeassistantlibrary
7adf8a950d4c428141ac92920bd2630341b3a261
[ "MIT" ]
null
null
null
#pragma once #include <Arduino.h> #include "../../tools/LinkedList.hpp" #include "../../tools/HAUtils.hpp" #include "../HASubscribCmd.hpp" #include "../HAMessage.hpp" #include "../IHANode.h" #include "../IHAComponent.h" #include "../components/HAComponentType.hpp" //#include "../components/HAComponentProperty.hpp" //#include "../components/HAComponentPropertyConstante.hpp" namespace HALIB_NAMESPACE { const char AVAILABILITY_TOPIC_TEMPLATE[] PROGMEM = "homeassistant/%s-%08X/avty"; class HANode : public IHANode { friend class HAComponent; public: HANode(const char *pName) { mName = strdup(pName); mId = HAUtils::generateId(pName, DEVICE); /* AVAILABILILY */ char *out = (char *)calloc(strlen(mName) + 20 + 8 + 1, sizeof(char)); sprintf_P(out, AVAILABILITY_TOPIC_TEMPLATE, mName, mId); mProperties.append(new HAComponentProperty(PROP_AVAILABILITY_TOPIC, out)); mProperties.append(new HAComponentProperty(PROP_PAYLOAD_AVAILABLE, "online")); mProperties.append(new HAComponentProperty(PROP_PAYLOAD_NOT_AVAILABLE, "offline")); free(out); } virtual ~HANode() { if (NULL != mName) { free(mName); } HAAction* pAction = mOutboxAction.shift(); while (NULL != pAction) { delete (pAction); pAction = mOutboxAction.shift(); } HAUtils::deleteProperties(mProperties); } void setDeviceInfo(const char *pManuf, const char *pModel, const char *pRelease) { LinkedList<HAComponentProperty *> lProperties; if (NULL != pManuf) { lProperties.append(new HAComponentProperty(PROP_DEVICE_MANUFACTURER, pManuf)); } if (NULL != pModel) { lProperties.append(new HAComponentProperty(PROP_DEVICE_MODEL, pModel)); } if (NULL != pRelease) { lProperties.append(new HAComponentProperty(PROP_DEVICE_RELEASE, pRelease)); } lProperties.append(new HAComponentProperty(PROP_NAME, mName)); char *out = (char *)malloc(9 * sizeof(char)); memset(out, 0, 9 * sizeof(char)); sprintf(out, "%08X", mId); lProperties.append(new HAComponentProperty(PROP_DEVICE_IDENTIFIER, out)); free(out); out = HAUtils::propertyListToJson(lProperties); HAUtils::deleteProperties(lProperties); mProperties.append(new HAComponentProperty(PROP_DEVICE, out)); free(out); } //IHANode const char *getName() { return mName; } uint32_t getId() { return mId; }; const char* getProperty(HAComponentPropertyKey name){ return HAUtils::getProperty(mProperties, name); } void addComponent(IHAComponent *p_pComponent) { if(NULL != p_pComponent) { p_pComponent->setNode(this); mComponents.append(p_pComponent); } } void postAutoDiscovery() { DEBUG_PRINTLN("===>postAutoDiscovery"); char *tempDeviceInfo = HAUtils::propertyListToJson(mProperties); size_t deviceInfoLength = strlen(tempDeviceInfo) - 2; // -2 remove {} // Treat all component for (int index = 0; index < mComponents.getSize(); index++) { IHAComponent *pComponent = (IHAComponent *)mComponents.get(index); char *topic = pComponent->buildDiscoveryTopic("homeassistant", mName); char *componentDiscoveryMessage = pComponent->buildDiscoveryMessage(); char *discoveryMessage = componentDiscoveryMessage; // if device info present patch component discovery message if (deviceInfoLength != 0) { size_t discoveryMessagesLength = strlen(componentDiscoveryMessage); discoveryMessage = (char *)malloc(discoveryMessagesLength + 1 + deviceInfoLength + 1); strcpy(discoveryMessage, componentDiscoveryMessage); strcpy(discoveryMessage + discoveryMessagesLength - 1, ","); strncpy(discoveryMessage + discoveryMessagesLength - 1 + 1, tempDeviceInfo + 1, deviceInfoLength); //+1 to skip first { strcpy(discoveryMessage + discoveryMessagesLength - 1 + 1 + deviceInfoLength, "}"); free(componentDiscoveryMessage); } //DEBUG_PRINTLN(topic); //DEBUG_PRINTLN(discoveryMessage); postMessage(new HAMessage(topic, discoveryMessage, true)); } free(tempDeviceInfo); }; void postDiscoveryMessage(IHAComponent *pComponent){ DEBUG_PRINTLN("===>postDiscoveryMessage"); char *tempDeviceInfo = HAUtils::propertyListToJson(mProperties); size_t deviceInfoLength = strlen(tempDeviceInfo) - 2; char *topic = pComponent->buildDiscoveryTopic("homeassistant", mName); char *componentDiscoveryMessage = pComponent->buildDiscoveryMessage(); char *discoveryMessage = componentDiscoveryMessage; // if device info present patch component discovery message if (deviceInfoLength != 0) { size_t discoveryMessagesLength = strlen(componentDiscoveryMessage); discoveryMessage = (char *)malloc(discoveryMessagesLength + 1 + deviceInfoLength + 1); strcpy(discoveryMessage, componentDiscoveryMessage); strcpy(discoveryMessage + discoveryMessagesLength - 1, ","); strncpy(discoveryMessage + discoveryMessagesLength - 1 + 1, tempDeviceInfo + 1, deviceInfoLength); //+1 to skip first { strcpy(discoveryMessage + discoveryMessagesLength - 1 + 1 + deviceInfoLength, "}"); free(componentDiscoveryMessage); } // DEBUG_PRINT("topic: "); // DEBUG_PRINTLN(topic); // DEBUG_PRINT("discoveryMessage: "); // DEBUG_PRINTLN(discoveryMessage); postMessage(new HAMessage(topic, discoveryMessage, true)); free(topic); free(discoveryMessage); free(tempDeviceInfo); } bool onHAMessage(const char *topic, const byte* p_pPayload, const unsigned int length) { for (int index = 0; index < mComponents.getSize(); index++) { // get component at index IHAComponent *pComponent = (IHAComponent *)mComponents.get(index); if (pComponent->onHAMessage(topic, p_pPayload, length)) { return true; } } return false; } void postMessage(HAMessage *pMessage) { mOutboxAction.append(pMessage); } void onHAConnect() { for (int index = 0; index < mComponents.getSize(); index++) { // get component at index IHAComponent *pComponent = (IHAComponent *)mComponents.get(index); pComponent->_onHAConnect(); } } int getDiscoveryMessages(HAMessage *pMessages) { if (NULL != pMessages) { for (int index = 0; index < mComponents.getSize(); index++) { IHAComponent *pComponent = (IHAComponent *)mComponents.get(index); char *topic = pComponent->buildDiscoveryTopic("homeassistant", mName); char *discoveryMessage = pComponent->buildDiscoveryMessage(); pMessages[index].setTopic(topic); pMessages[index].setMessage(discoveryMessage); } } return mComponents.getSize(); ; } HAAction *pickupAction() { // DEBUG_PRINT("pickupAction "); // DEBUG_PRINTLN(mOutboxAction.getSize()); return mOutboxAction.shift(); } int actionsSize(){ return mOutboxAction.getSize(); } void retryAction(HAAction* p_pAction){ mOutboxAction.append(p_pAction); } private: #ifdef UNIT_TEST public: #endif void postMessage(const char *pTopic, const char *pMessage, boolean retain) { postMessage(new HAMessage(pTopic, pMessage, retain)); } void registerToHA(const char *topic, boolean subscription = true) { DEBUG_PRINTLN("===>postSupscribe"); mOutboxAction.append(new HASubscribCmd(topic, subscription)); } private: char *mName; uint32_t mId; LinkedList<IHAComponent *> mComponents; LinkedList<HAAction *> mOutboxAction; LinkedList<HAComponentProperty *> mProperties; }; } // namespace HALIB_NAMESPACE
36.019231
139
0.564015
SBKila
c3dbb8fda99d81e17ea07d6124cfde316b16e0de
634
hpp
C++
src/Chip8.hpp
azadad96/chip8_emulator
fed45202269fe7d41692f05144c8f04a5c97fb04
[ "MIT" ]
null
null
null
src/Chip8.hpp
azadad96/chip8_emulator
fed45202269fe7d41692f05144c8f04a5c97fb04
[ "MIT" ]
null
null
null
src/Chip8.hpp
azadad96/chip8_emulator
fed45202269fe7d41692f05144c8f04a5c97fb04
[ "MIT" ]
null
null
null
#ifndef CHIP8 #define CHIP8 #include "Display.hpp" #include <SDL2/SDL.h> #include <string> #include <cstdint> #include <cstring> #include <cstdlib> #include <cstdio> class Chip8 { private: uint8_t memory[4096]; uint8_t V[16]; uint16_t I; uint16_t pc; uint16_t stack[16]; int stackpointer; int delay_timer; int sound_timer; bool halted; Display *display; bool drawflag; public: Chip8(); ~Chip8(); bool run(); void events(); void render(); bool needsRedraw(); void clearDrawflag(); void loadFile(std::string filename); void loadFontset(); }; #endif
15.095238
40
0.635647
azadad96
c3eaf7b377736236ded5380bb4cc9a390737f63b
236
hpp
C++
ext/bindings/util.hpp
evizitei/pulsar-client-ruby
173c8e2536743e1756d8e99d7a8e90d7fc688941
[ "Apache-2.0" ]
8
2019-10-25T07:55:44.000Z
2021-02-18T19:58:16.000Z
ext/bindings/util.hpp
evizitei/pulsar-client-ruby
173c8e2536743e1756d8e99d7a8e90d7fc688941
[ "Apache-2.0" ]
20
2019-10-03T17:57:36.000Z
2022-02-12T15:29:08.000Z
ext/bindings/util.hpp
evizitei/pulsar-client-ruby
173c8e2536743e1756d8e99d7a8e90d7fc688941
[ "Apache-2.0" ]
8
2019-10-03T17:55:59.000Z
2021-12-15T02:48:31.000Z
#ifndef __PULSAR_RUBY_CLIENT_UTIL_HPP #define __PULSAR_RUBY_CLIENT_UTIL_HPP #include "rice/Module.hpp" #include <pulsar/Client.h> using namespace pulsar; void CheckResult(Result res); void bind_errors(Rice::Module& module); #endif
16.857143
39
0.805085
evizitei
c3ed9360f77f4b1cf93cbb788d3a9fba164c9528
2,382
cpp
C++
ecs/src/v2/model/ServerInterfaceFixedIp.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
ecs/src/v2/model/ServerInterfaceFixedIp.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
ecs/src/v2/model/ServerInterfaceFixedIp.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/ecs/v2/model/ServerInterfaceFixedIp.h" namespace HuaweiCloud { namespace Sdk { namespace Ecs { namespace V2 { namespace Model { ServerInterfaceFixedIp::ServerInterfaceFixedIp() { ipAddress_ = ""; ipAddressIsSet_ = false; subnetId_ = ""; subnetIdIsSet_ = false; } ServerInterfaceFixedIp::~ServerInterfaceFixedIp() = default; void ServerInterfaceFixedIp::validate() { } web::json::value ServerInterfaceFixedIp::toJson() const { web::json::value val = web::json::value::object(); if(ipAddressIsSet_) { val[utility::conversions::to_string_t("ip_address")] = ModelBase::toJson(ipAddress_); } if(subnetIdIsSet_) { val[utility::conversions::to_string_t("subnet_id")] = ModelBase::toJson(subnetId_); } return val; } bool ServerInterfaceFixedIp::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("ip_address"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("ip_address")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setIpAddress(refVal); } } if(val.has_field(utility::conversions::to_string_t("subnet_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("subnet_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setSubnetId(refVal); } } return ok; } std::string ServerInterfaceFixedIp::getIpAddress() const { return ipAddress_; } void ServerInterfaceFixedIp::setIpAddress(const std::string& value) { ipAddress_ = value; ipAddressIsSet_ = true; } bool ServerInterfaceFixedIp::ipAddressIsSet() const { return ipAddressIsSet_; } void ServerInterfaceFixedIp::unsetipAddress() { ipAddressIsSet_ = false; } std::string ServerInterfaceFixedIp::getSubnetId() const { return subnetId_; } void ServerInterfaceFixedIp::setSubnetId(const std::string& value) { subnetId_ = value; subnetIdIsSet_ = true; } bool ServerInterfaceFixedIp::subnetIdIsSet() const { return subnetIdIsSet_; } void ServerInterfaceFixedIp::unsetsubnetId() { subnetIdIsSet_ = false; } } } } } }
20.358974
101
0.672964
yangzhaofeng
c3efb64cbf192518c0e74a860a2bf2a824468ded
1,423
cpp
C++
Chapter03/Chapter3_Source_Code/OddEven_Cond_var.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
98
2018-07-03T08:55:31.000Z
2022-03-21T22:16:58.000Z
Chapter03/Chapter3_Source_Code/OddEven_Cond_var.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
1
2020-11-30T10:38:58.000Z
2020-12-15T06:56:20.000Z
Chapter03/Chapter3_Source_Code/OddEven_Cond_var.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
54
2018-07-06T02:09:27.000Z
2021-11-10T08:42:50.000Z
//==================================================================== // C++ concurrency - Thread synchronization using condition variable. // Program to print 1-100 in order using odd and even number threads. //==================================================================== #include <iostream> #include <thread> #include <mutex> #include <condition_variable> // Global mutex std::mutex numMutex; std::condition_variable syncCond; auto bEvenReady = false; auto bOddReady = false; // Function to print even numbers void printEven(int max) { for (unsigned i = 0; i <= max; i +=2) { std::unique_lock<std::mutex> lk(numMutex); syncCond.wait(lk, []{return bEvenReady;}); std::cout << i << ","; bEvenReady = false; bOddReady = true; syncCond.notify_one(); } } // Function to print odd numbers void printOdd(int max) { for (unsigned i = 1; i <= max; i +=2) { std::unique_lock<std::mutex> lk(numMutex); syncCond.wait(lk, []{return bOddReady;}); std::cout << i << ","; bEvenReady = true; bOddReady = false; syncCond.notify_one(); } } int main() { auto max = 100; bEvenReady = true; std::thread t1(printEven, max); std::thread t2(printOdd, max); if (t1.joinable()) t1.join(); if (t2.joinable()) t2.join(); }
22.951613
70
0.516514
ngdzu
7f0fd286ef82fc860d4d422cb5b3118467a8d111
1,270
hpp
C++
hallow/src/engine/renderer/render_system/RenderSystem.hpp
Lugo-Studio/Hallow
e2851051ae839c7b3d4d37ef7ab6947d7b23b117
[ "MIT" ]
null
null
null
hallow/src/engine/renderer/render_system/RenderSystem.hpp
Lugo-Studio/Hallow
e2851051ae839c7b3d4d37ef7ab6947d7b23b117
[ "MIT" ]
null
null
null
hallow/src/engine/renderer/render_system/RenderSystem.hpp
Lugo-Studio/Hallow
e2851051ae839c7b3d4d37ef7ab6947d7b23b117
[ "MIT" ]
null
null
null
// // Created by galex on 5/18/2021. // #ifndef HALLOW_RENDERSYSTEM_HPP #define HALLOW_RENDERSYSTEM_HPP #include "helpers/RootDir.h" #include "engine/time/Time.hpp" #include "engine/device/HallowDevice.hpp" #include "engine/pipeline/HallowPipeline.hpp" #include <string> #include <memory> #include <vector> #include <engine/game_object/GameObject.hpp> namespace Hallow { class RenderSystem { public: RenderSystem(Time& time, HallowDevice& device, VkRenderPass render_pass); virtual ~RenderSystem(); RenderSystem(const RenderSystem&) = delete; RenderSystem& operator=(const RenderSystem&) = delete; virtual void initilizePipeline(); virtual void renderGameObjects(VkCommandBuffer command_buffer, std::vector<std::shared_ptr<GameObject>>& game_objects); protected: // RendererOptions m_renderer_options; Time& m_time; const std::string m_shader_path{"res/shaders/simple_shader"}; HallowDevice& m_hallow_device; VkRenderPass m_render_pass; std::unique_ptr<HallowPipeline> m_hallow_pipeline; VkPipelineLayout m_pipeline_layout; bool m_pipeline_created{false}; virtual void createPipelineLayout(); virtual void createPipeline(VkRenderPass render_pass); }; } #endif //HALLOW_RENDERSYSTEM_HPP
25.918367
123
0.759843
Lugo-Studio
7f1287c293135a7e747186f41bb1bf134014be2c
671
hpp
C++
src/ModelBase/tdataunit.hpp
TKUICLab-humanoid/imageprocess_submodule
76b08611f1ef38e67b89e95b5d3e3459906ab908
[ "MIT" ]
null
null
null
src/ModelBase/tdataunit.hpp
TKUICLab-humanoid/imageprocess_submodule
76b08611f1ef38e67b89e95b5d3e3459906ab908
[ "MIT" ]
null
null
null
src/ModelBase/tdataunit.hpp
TKUICLab-humanoid/imageprocess_submodule
76b08611f1ef38e67b89e95b5d3e3459906ab908
[ "MIT" ]
null
null
null
#ifndef TDATAUNIT_H #define TDATAUNIT_H #include <fstream> #include <string> #include <stdlib.h> #include <string.h> #include "tku_libs/TKU_tool.h" //include "../../../strategy/src/StrategyNameAndPath.h" using namespace std; struct ColorRange { float HueMin; float HueMax; float SaturationMin; float SaturationMax; float BrightnessMin; float BrightnessMax; string LabelName; }; class TdataUnit { public: TdataUnit(); ~TdataUnit(); int strategyname; void SaveColorRangeFile(); void LoadColorRangeFile(); Tool *tool = new Tool(); ColorRange** HSVColorRange; }; extern TdataUnit* DataUnit; #endif // TDATAUNIT_H
17.205128
55
0.695976
TKUICLab-humanoid
7f1a5f3a892ee030e5b7af7eb6d392cd0cdfcb52
2,619
cc
C++
http/hpack/dynamic_metadata.cc
larrystd/muduohttp
7ba68e4359b520598f6a2c3d81ab810f5e737336
[ "Apache-2.0" ]
2
2021-01-08T09:49:55.000Z
2021-09-29T04:25:43.000Z
src/hpack/dynamic_metadata.cc
shadow-yuan/libhttp2
fa5fbca9a3fd836bb40b53ef51b6dc4cc53995d1
[ "Apache-2.0" ]
null
null
null
src/hpack/dynamic_metadata.cc
shadow-yuan/libhttp2
fa5fbca9a3fd836bb40b53ef51b6dc4cc53995d1
[ "Apache-2.0" ]
null
null
null
#include "src/hpack/dynamic_metadata.h" #include <stdio.h> namespace hpack { dynamic_metadata_table::dynamic_metadata_table(uint32_t default_max_size) : _max_table_size_limit(default_max_size) , _max_table_size(default_max_size) , _current_table_size(0) {} dynamic_metadata_table::~dynamic_metadata_table() {} bool dynamic_metadata_table::get_mdelem_data(size_t index, mdelem_data *mdel) { auto n = _dynamic_table.size(); if (index >= n) { return false; } *mdel = _dynamic_table[index]; return true; } void dynamic_metadata_table::push_mdelem_data(const mdelem_data &md) { _dynamic_table.push_front(md); _current_table_size += MDELEM_SIZE(md); _current_table_size += 32; adjust_dynamic_table_size(); printf("dynamic_metadata_table => key:[%s] value:[%s]\n", md.key.to_string().c_str(), md.value.to_string().c_str()); printf("---- Scan the dynamic table ----\n"); for (size_t i = 0; i < _dynamic_table.size(); i++) { uint32_t idx = i + 61 + 1; std::string str_key = _dynamic_table[i].key.to_string(); std::string str_value = _dynamic_table[i].value.to_string(); printf("index:%u key:[%s] value:[%s]\n", idx, str_key.c_str(), str_value.c_str()); } printf("---- ---- ---- ---- ---- ---- ----\n"); } // when recv SETTINGS FRAME // SETTINGS_HEADER_TABLE_SIZE void dynamic_metadata_table::update_max_table_size_limit(uint32_t limit) { _max_table_size_limit = limit; } // when recv header frame (RFC 7540) // 6.3. Dynamic Table Size Update void dynamic_metadata_table::update_max_table_size(uint32_t size) { _max_table_size = size; adjust_dynamic_table_size(); } size_t dynamic_metadata_table::entry_count() { return _dynamic_table.size(); } uint32_t dynamic_metadata_table::max_table_size_limit() { return _max_table_size; } uint32_t dynamic_metadata_table::max_table_size() { return _max_table_size; } int32_t dynamic_metadata_table::get_mdelem_data_index(const mdelem_data &mdel) { size_t count = _dynamic_table.size(); for (size_t i = 0; i < count; i++) { if (mdel.key == _dynamic_table[i].key && mdel.value == _dynamic_table[i].value) { return static_cast<int32_t>(i); } } return -1; } void dynamic_metadata_table::adjust_dynamic_table_size() { while (_current_table_size > _max_table_size && !_dynamic_table.empty()) { auto entry = _dynamic_table.back(); auto element_size = MDELEM_SIZE(entry); _current_table_size -= element_size + 32; _dynamic_table.pop_back(); } } } // namespace hpack
31.554217
120
0.686522
larrystd
7f2521eb29df63e21370b3dec11b7776024f2e48
1,059
cpp
C++
backup/2/codesignal/c++/number-minimization.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/codesignal/c++/number-minimization.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/codesignal/c++/number-minimization.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codesignal/number-minimization.html . std::set<std::vector<int>> cache; int numberMinimization(int n, int d) { using namespace std; string item = to_string(n); sort(item.begin(), item.end()); int res = stoi(item); do { int n1 = stoi(item); if (n1 % d == 0 && cache.find({d, n1}) == cache.end()) { cache.insert({d, n1}); res = min(res, numberMinimization(n1 / d, d)); } } while (next_permutation(item.begin(), item.end())); return res; }
48.136364
345
0.666667
yangyanzhan
7f2a0bc5aab40b856864fb0abc9a497f21a7c6b8
513
cpp
C++
arquivos .h e .cpp/Inimigo.cpp
moises-dias/hunter-adventures
a403bc09d3583005ad689ed2ebbfe1361e678788
[ "MIT" ]
2
2020-05-26T22:46:48.000Z
2022-01-12T12:32:06.000Z
arquivos .h e .cpp/Inimigo.cpp
moises-dias/hunter-adventures
a403bc09d3583005ad689ed2ebbfe1361e678788
[ "MIT" ]
null
null
null
arquivos .h e .cpp/Inimigo.cpp
moises-dias/hunter-adventures
a403bc09d3583005ad689ed2ebbfe1361e678788
[ "MIT" ]
null
null
null
#include "Inimigo.h" Inimigo::Inimigo() { ID=4; permiteColisaoChao = true; permiteColisaoEnt = true; funcionando=false; estado = PARADO; jogadores[0] = NULL; jogadores[1] = NULL; colisao = new bool[NUM_COLISOES]; for(int i = 0; i < NUM_COLISOES; i++) colisao[i] = false; danoGolpe=0; danoGolpeRand=0; } Inimigo::~Inimigo() { } void Inimigo::setJogador(Jogador* j, int i) { jogadores[i] = j; } void Inimigo::setMapaAtual(Mapa* m) { mapaAtual = m; }
15.545455
43
0.608187
moises-dias
7f2d66ba25bd22a70f6c3db1d77392c4a176d7c7
2,005
cc
C++
rst/defer/defer_test.cc
sabbakumov/rst
c0257ab1fb17dea7b022cc4955f715d80a9b32f6
[ "BSD-2-Clause" ]
4
2016-12-15T13:06:36.000Z
2022-01-10T16:34:00.000Z
rst/defer/defer_test.cc
sabbakumov/rst
c0257ab1fb17dea7b022cc4955f715d80a9b32f6
[ "BSD-2-Clause" ]
103
2019-01-24T18:06:35.000Z
2021-11-02T13:33:34.000Z
rst/defer/defer_test.cc
sabbakumov/rst
c0257ab1fb17dea7b022cc4955f715d80a9b32f6
[ "BSD-2-Clause" ]
4
2018-04-24T06:59:59.000Z
2022-02-04T18:10:03.000Z
// Copyright (c) 2017, Sergey Abbakumov // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "rst/defer/defer.h" #include <string> #include <gtest/gtest.h> namespace rst { namespace { auto g_int = 0; void Foo() { g_int = 1; } class Defer : public testing::Test { public: Defer() { g_int = 0; } }; } // namespace TEST_F(Defer, Lambda) { auto i = 0; { RST_DEFER([&i]() { i = 1; }); } EXPECT_EQ(i, 1); } TEST_F(Defer, Function) { { RST_DEFER(Foo); } EXPECT_EQ(g_int, 1); } TEST_F(Defer, MultipleTimesDeclaration) { std::string result; { RST_DEFER([&result]() { result += '1'; }); RST_DEFER([&result]() { result += '2'; }); } EXPECT_EQ(result, "21"); } } // namespace rst
27.094595
73
0.709227
sabbakumov
b523dcdd72030528b6de09cca417219c83050814
23
cpp
C++
source/vzero_102/config.cpp
slafi/VoltaZero
c361bf9d4b207364fa43b337f946f2a0d1a8b321
[ "MIT" ]
null
null
null
source/vzero_102/config.cpp
slafi/VoltaZero
c361bf9d4b207364fa43b337f946f2a0d1a8b321
[ "MIT" ]
null
null
null
source/vzero_102/config.cpp
slafi/VoltaZero
c361bf9d4b207364fa43b337f946f2a0d1a8b321
[ "MIT" ]
null
null
null
#include "config.h"
5.75
19
0.608696
slafi
b5246043ed8422f371130d3f0d5c34c87eb326ec
3,915
cpp
C++
src/simulation/FindBoundingBoxOperation.cpp
citron0xa9/FluidSim
2c2c3ac15b0bfa60bf40a8aebff1010309a65029
[ "MIT" ]
1
2016-05-26T13:07:34.000Z
2016-05-26T13:07:34.000Z
src/simulation/FindBoundingBoxOperation.cpp
citron0xa9/FluidSim
2c2c3ac15b0bfa60bf40a8aebff1010309a65029
[ "MIT" ]
null
null
null
src/simulation/FindBoundingBoxOperation.cpp
citron0xa9/FluidSim
2c2c3ac15b0bfa60bf40a8aebff1010309a65029
[ "MIT" ]
null
null
null
#include "FindBoundingBoxOperation.h" #include "ParticleSystem.h" #include <cassert> FindBoundingBoxOperation::FindBoundingBoxOperation(ParticleSystem& parent, const std::vector<std::reference_wrapper<ParticleSystem>>& respectedParticleSystems, const std::vector<std::reference_wrapper<RigidBodySim>>& respectedRigidBodySims) : ParticleOperation{parent}, m_RespectedParticleSystems{respectedParticleSystems}, m_RespectedRigidBodySims{respectedRigidBodySims} { assert(!respectedParticleSystems.empty() || !respectedRigidBodySims.empty()); calculateBoundingBox(); } void FindBoundingBoxOperation::process(const double stepSecondsPassed, const double secondsPassedTotal) { calculateBoundingBox(); } const fsmath::BoundingBox & FindBoundingBoxOperation::currentBoundingBox() const { return m_CurrentBoundingBox; } glm::dvec3 FindBoundingBoxOperation::calculateMaxCorner() const { if (m_CurrentBoundingBox.m_Extent == glm::dvec3{ -std::numeric_limits<double>::infinity() }) { return glm::dvec3{ -std::numeric_limits<double>::infinity() }; } else { return (m_CurrentBoundingBox.m_MinCorner + m_CurrentBoundingBox.m_Extent); } } void FindBoundingBoxOperation::calculateBoundingBox() { resetBoundingBox(); for (auto particleSystem : m_RespectedParticleSystems) { updateBoundingBox(particleSystem); } for (auto sim : m_RespectedRigidBodySims) { updateBoundingBox(sim); } expandBoundingBox(); //slightly expand to allow rounding errors etc. } void FindBoundingBoxOperation::resetBoundingBox() { m_CurrentBoundingBox.m_MinCorner = glm::dvec3{ std::numeric_limits<double>::infinity() }; m_CurrentBoundingBox.m_Extent = glm::dvec3{ -std::numeric_limits<double>::infinity() }; } void FindBoundingBoxOperation::updateBoundingBox(std::reference_wrapper<ParticleSystem> particleSystem) { if (particleSystem.get().particlePtrs().empty()) { return; } glm::dvec3 minCorner = m_CurrentBoundingBox.m_MinCorner; glm::dvec3 maxCorner = calculateMaxCorner(); for (auto& particlePtr : particleSystem.get().particlePtrs()) { minCorner = fsmath::allMin(minCorner, particlePtr->position() - glm::dvec3{2*particlePtr->radius()}); maxCorner = fsmath::allMax(maxCorner, particlePtr->position() + glm::dvec3{2*particlePtr->radius()}); } updateBoundingBox(minCorner, maxCorner); } void FindBoundingBoxOperation::updateBoundingBox(std::reference_wrapper<RigidBodySim> rigidBodySim) { if (rigidBodySim.get().spheres().empty()) { return; } glm::dvec3 minCorner = m_CurrentBoundingBox.m_MinCorner; glm::dvec3 maxCorner = calculateMaxCorner(); for (auto& sphere : rigidBodySim.get().spheres()) { minCorner = fsmath::allMin(minCorner, sphere.position() - glm::dvec3{2*sphere.radius()}); maxCorner = fsmath::allMax(maxCorner, sphere.position() + glm::dvec3{2*sphere.radius()}); } updateBoundingBox(minCorner, maxCorner); } void FindBoundingBoxOperation::updateBoundingBox(const glm::dvec3& newMinCorner, const glm::dvec3& newMaxCorner) { assert(newMinCorner != glm::dvec3{ std::numeric_limits<double>::infinity() }); assert(newMaxCorner != glm::dvec3{ -std::numeric_limits<double>::infinity() }); m_CurrentBoundingBox.m_Extent = fsmath::allMax(glm::dvec3{std::numeric_limits<float>::epsilon()}, (newMaxCorner - newMinCorner)); m_CurrentBoundingBox.m_MinCorner = newMinCorner; } void FindBoundingBoxOperation::expandBoundingBox() { glm::dvec3 adjustment = static_cast<double>(std::numeric_limits<float>::epsilon()) * m_CurrentBoundingBox.m_Extent; //use float epsilon for slightly larger expansion m_CurrentBoundingBox.m_MinCorner -= adjustment; m_CurrentBoundingBox.m_Extent += adjustment + adjustment; }
35.27027
112
0.723116
citron0xa9
b527d652b3ebf0bed3b67d1cfe19c7c6e60baeb6
1,700
cpp
C++
src/Engine/Geometry/MathFunctions.cpp
Chainsawkitten/Deathcap
37ed5afccd3113d34612d89c6e6508e8da9a0d7f
[ "MIT" ]
3
2017-09-08T06:05:10.000Z
2017-10-28T04:22:20.000Z
src/Engine/Geometry/MathFunctions.cpp
Chainsawkitten/Deathcap
37ed5afccd3113d34612d89c6e6508e8da9a0d7f
[ "MIT" ]
894
2017-08-30T09:57:28.000Z
2018-01-30T12:35:38.000Z
src/Engine/Geometry/MathFunctions.cpp
Chainsawkitten/LargeGameProjectEngine
37ed5afccd3113d34612d89c6e6508e8da9a0d7f
[ "MIT" ]
1
2020-11-06T23:59:58.000Z
2020-11-06T23:59:58.000Z
#include "MathFunctions.hpp" #include <glm/gtc/quaternion.hpp> float Geometry::DotQuat(const glm::quat& q1, const glm::quat& q2) { return q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w; } void Geometry::NormalizeQuat(glm::quat& q) { float d = sqrt(DotQuat(q, q)); if (d >= 0.00001) { d = 1 / d; q.x *= d; q.y *= d; q.z *= d; q.w *= d; } else { q.x = q.y = q.z = 0; q.w = 1; } } void Geometry::CpyVec(glm::vec3& glmVec, const aiVector3D& aiVec) { glmVec.x = aiVec.x; glmVec.y = aiVec.y; glmVec.z = aiVec.z; } void Geometry::CpyVec(glm::vec2& glmVec, const aiVector3D& aiVec) { glmVec.x = aiVec.x; glmVec.y = aiVec.y; } void Geometry::CpyVec(glm::vec2& glmVec, const aiVector2D& aiVec) { glmVec.x = aiVec.x; glmVec.y = aiVec.y; } void Geometry::CpyMat(glm::mat4& glmMat, const aiMatrix4x4& aiMat) { glmMat[0][0] = aiMat.a1; glmMat[0][1] = aiMat.a2; glmMat[0][2] = aiMat.a3; glmMat[0][3] = aiMat.a4; glmMat[1][0] = aiMat.b1; glmMat[1][1] = aiMat.b2; glmMat[1][2] = aiMat.b3; glmMat[1][3] = aiMat.b4; glmMat[2][0] = aiMat.c1; glmMat[2][1] = aiMat.c2; glmMat[2][2] = aiMat.c3; glmMat[2][3] = aiMat.c4; glmMat[3][0] = aiMat.d1; glmMat[3][1] = aiMat.d2; glmMat[3][2] = aiMat.d3; glmMat[3][3] = aiMat.d4; } void Geometry::CpyMat(aiMatrix3x3& aiMat3, const aiMatrix4x4& aiMat4) { aiMat3.a1 = aiMat4.a1; aiMat3.a2 = aiMat4.a2; aiMat3.a3 = aiMat4.a3; aiMat3.b1 = aiMat4.b1; aiMat3.b2 = aiMat4.b2; aiMat3.b3 = aiMat4.b3; aiMat3.c1 = aiMat4.c1; aiMat3.c2 = aiMat4.c2; aiMat3.c3 = aiMat4.c3; }
22.666667
71
0.561176
Chainsawkitten
b52f642c514ab34d332991df23ddb22492de0f55
1,112
hpp
C++
injection.hpp
TomGlint/ANSim
f02edc65a80fbbcf3bc812f4f6841658571c2024
[ "MIT" ]
null
null
null
injection.hpp
TomGlint/ANSim
f02edc65a80fbbcf3bc812f4f6841658571c2024
[ "MIT" ]
null
null
null
injection.hpp
TomGlint/ANSim
f02edc65a80fbbcf3bc812f4f6841658571c2024
[ "MIT" ]
null
null
null
// $Id$ #ifndef _INJECTION_HPP_ #define _INJECTION_HPP_ #include "config_utils.hpp" using namespace std; class InjectionProcess { protected: long long int _nodes; double _rate; InjectionProcess(long long int nodes, double rate); public: virtual ~InjectionProcess() {} virtual bool test(long long int source) = 0; virtual void reset(); static InjectionProcess *New(string const &inject, long long int nodes, double load, Configuration const *const config = NULL); }; class BernoulliInjectionProcess : public InjectionProcess { public: BernoulliInjectionProcess(long long int nodes, double rate); virtual bool test(long long int source); }; class OnOffInjectionProcess : public InjectionProcess { private: double _alpha; double _beta; double _r1; vector<long long int> _initial; vector<long long int> _state; public: OnOffInjectionProcess(long long int nodes, double rate, double alpha, double beta, double r1, vector<long long int> initial); virtual void reset(); virtual bool test(long long int source); }; #endif
22.693878
86
0.716727
TomGlint
b52f7a8c4bae20d4e59cacb17e0d70a79b2a6d3a
3,670
hpp
C++
Bitcoin/le.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
108
2020-10-01T17:12:40.000Z
2022-03-30T09:18:03.000Z
Bitcoin/le.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
94
2020-10-03T13:40:30.000Z
2022-03-30T09:18:00.000Z
Bitcoin/le.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
17
2020-10-29T13:27:59.000Z
2022-03-18T13:05:03.000Z
#ifndef BITCOIN_LE_HPP #define BITCOIN_LE_HPP #include"Ln/Amount.hpp" #include<cstdint> #include<iostream> namespace Bitcoin { namespace Detail { class Le16; }} namespace Bitcoin { namespace Detail { class Le16Const; }} namespace Bitcoin { namespace Detail { class Le32; }} namespace Bitcoin { namespace Detail { class Le32Const; }} namespace Bitcoin { namespace Detail { class Le64; }} namespace Bitcoin { namespace Detail { class Le64Const; }} namespace Bitcoin { namespace Detail { class LeAmount; }} namespace Bitcoin { namespace Detail { class LeAmountConst; }} namespace Bitcoin { /** Bitcoin::le * * @brief wraps a uint64, int64, uint32, int32, or * `Ln::Amount` so it is encoded in little-endian * form. * * @desc intended use is: * * std::cout << Bitcoin::le(expr); * std::cin >> Bitcoin::le(var); */ Detail::Le16 le(std::uint16_t& v); Detail::Le16Const le(std::uint16_t const& v); Detail::Le16 le(std::int16_t& v); Detail::Le16Const le(std::int16_t const& v); Detail::Le32 le(std::uint32_t& v); Detail::Le32Const le(std::uint32_t const& v); Detail::Le32 le(std::int32_t& v); Detail::Le32Const le(std::int32_t const& v); Detail::Le64 le(std::uint64_t& v); Detail::Le64Const le(std::uint64_t const& v); Detail::Le64 le(std::int64_t& v); Detail::Le64Const le(std::int64_t const& v); Detail::LeAmount le(Ln::Amount& v); Detail::LeAmountConst le(Ln::Amount const& v); } std::ostream& operator<<(std::ostream&, Bitcoin::Detail::Le16Const); std::ostream& operator<<(std::ostream&, Bitcoin::Detail::Le32Const); std::ostream& operator<<(std::ostream&, Bitcoin::Detail::Le64Const); std::ostream& operator<<(std::ostream&, Bitcoin::Detail::LeAmountConst); std::istream& operator>>(std::istream&, Bitcoin::Detail::Le16); std::istream& operator>>(std::istream&, Bitcoin::Detail::Le32); std::istream& operator>>(std::istream&, Bitcoin::Detail::Le64); std::istream& operator>>(std::istream&, Bitcoin::Detail::LeAmount); namespace Bitcoin { namespace Detail { class Le16Const { private: std::uint16_t v; friend std::ostream& ::operator<<(std::ostream&, Bitcoin::Detail::Le16Const); public: Le16Const(std::uint16_t const& v_) : v(v_) { } }; class Le16 { private: std::uint16_t& v; friend std::istream& ::operator>>(std::istream&, Bitcoin::Detail::Le16); public: Le16(std::uint16_t& v_) : v(v_) { } operator Le16Const() const { return Le16Const(v); } }; class Le32Const { private: std::uint32_t v; friend std::ostream& ::operator<<(std::ostream&, Bitcoin::Detail::Le32Const); public: Le32Const(std::uint32_t const& v_) : v(v_) { } }; class Le32 { private: std::uint32_t& v; friend std::istream& ::operator>>(std::istream&, Bitcoin::Detail::Le32); public: Le32(std::uint32_t& v_) : v(v_) { } operator Le32Const() const { return Le32Const(v); } }; class Le64Const { private: std::uint64_t v; friend std::ostream& ::operator<<(std::ostream&, Bitcoin::Detail::Le64Const); public: Le64Const(std::uint64_t const& v_) : v(v_) { } }; class Le64 { private: std::uint64_t& v; friend std::istream& ::operator>>(std::istream&, Bitcoin::Detail::Le64); public: Le64(std::uint64_t& v_) : v(v_) { } operator Le64Const() const { return Le64Const(v); } }; class LeAmountConst { private: Ln::Amount v; friend std::ostream& ::operator<<(std::ostream&, Bitcoin::Detail::LeAmountConst); public: LeAmountConst(Ln::Amount const& v_) : v(v_) { } }; class LeAmount { private: Ln::Amount& v; friend std::istream& ::operator>>(std::istream&, Bitcoin::Detail::LeAmount); public: LeAmount(Ln::Amount& v_) : v(v_) { } operator LeAmountConst() const { return LeAmountConst(v); } }; }} #endif /* !defined(BITCOIN_LE_HPP) */
23.986928
75
0.688828
3nprob
b530cac05020f34cbf6f83321b858f6c71ea71d9
949
cpp
C++
OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_UserAndRoomArray.cpp
InnerLoopLLC/OculusPlatformBP
d4bfb5568c56aa781e2ee76896d69a0ade1f57a2
[ "MIT" ]
29
2020-10-22T13:46:23.000Z
2022-03-18T14:32:51.000Z
OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_UserAndRoomArray.cpp
InnerLoopLLC/OculusPlatformBP
d4bfb5568c56aa781e2ee76896d69a0ade1f57a2
[ "MIT" ]
2
2021-05-06T18:14:39.000Z
2021-05-25T01:12:15.000Z
OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_UserAndRoomArray.cpp
InnerLoopLLC/OculusPlatformBP
d4bfb5568c56aa781e2ee76896d69a0ade1f57a2
[ "MIT" ]
null
null
null
// OculusPlatformBP plugin by InnerLoop LLC 2020 #include "OBP_UserAndRoomArray.h" // -------------------- // Initializers // -------------------- UOBP_UserAndRoomArray::UOBP_UserAndRoomArray(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } // -------------------- // OVR_UserAndRoomArray.h // -------------------- UOBP_UserAndRoom* UOBP_UserAndRoomArray::GetElement(int32 Index) { auto UserAndRoomToGet = NewObject<UOBP_UserAndRoom>(); UserAndRoomToGet->ovrUserAndRoomHandle = ovr_UserAndRoomArray_GetElement(ovrUserAndRoomArrayHandle, Index); return UserAndRoomToGet; } FString UOBP_UserAndRoomArray::GetNextUrl() { return ovr_UserAndRoomArray_GetNextUrl(ovrUserAndRoomArrayHandle); } int32 UOBP_UserAndRoomArray::GetSize() { return ovr_UserAndRoomArray_GetSize(ovrUserAndRoomArrayHandle); } bool UOBP_UserAndRoomArray::HasNextPage() { return ovr_UserAndRoomArray_HasNextPage(ovrUserAndRoomArrayHandle); }
24.973684
108
0.755532
InnerLoopLLC
b53258701e2368a14fd035e0b530268b6954082c
1,357
cpp
C++
lib/Builder/FloatsToFloat/FloatsToFloat.cpp
digirea/HIVE
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
[ "MIT" ]
null
null
null
lib/Builder/FloatsToFloat/FloatsToFloat.cpp
digirea/HIVE
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
[ "MIT" ]
null
null
null
lib/Builder/FloatsToFloat/FloatsToFloat.cpp
digirea/HIVE
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
[ "MIT" ]
null
null
null
/** * @file FloatsToFloat.cpp * 複数Floatデータ再構築モジュール */ #include "FloatsToFloat.h" /// コンストラクタ FloatsToFloat::FloatsToFloat(){ m_volume = 0; } /** * BufferVolumeData再構築 * @param volume 再構築対象のBufferVolumeData * @param offset 再構築対象のバッファオフセット * @return 作成されたバッファ数 */ int FloatsToFloat::Create(BufferVolumeData *volume, int offset){ if (!volume) return 0; m_offset = offset; m_volume = volume; } /// コンポーネント数取得(1固定) int FloatsToFloat::Component() { return 1; } /** * 再構築されたバッファへの参照 * @retval m_volume VolumeDataへの参照 */ BufferVolumeData* FloatsToFloat::VolumeData() { if (!m_volume) { return 0; } const int component = m_volume->Component(); const int n = m_volume->Buffer()->GetNum() / component; int ofs = m_offset; if (component <= m_offset) { ofs = component - 1; } BufferVolumeData* volume = BufferVolumeData::CreateInstance(); const int w = m_volume->Width(); const int h = m_volume->Height(); const int d = m_volume->Depth(); volume->Create(w, h, d, 1); printf("FloatsToFloat : %d %d %d\n", w, h, d); float* tarbuf = volume->Buffer()->GetBuffer(); const float* srcbuf = m_volume->Buffer()->GetBuffer(); for (int i = 0; i < n; ++i){ tarbuf[i] = srcbuf[component * i + ofs]; } return volume; }
20.253731
66
0.613854
digirea
b5364184b2fb1afa3a3b89d9b8b077dce5e1eec8
2,461
cpp
C++
thirdparty/qtvesta/LocalImageLoader.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
thirdparty/qtvesta/LocalImageLoader.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
thirdparty/qtvesta/LocalImageLoader.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
// Copyright (C) 2010 Chris Laurel <claurel@gmail.com> // // This file is a part of qtvesta, a set of classes for using // the VESTA library with the Qt framework. // // qtvesta is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // qtvesta is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with qtvesta. If not, see <http://www.gnu.org/licenses/>. #include "LocalImageLoader.h" #include <QDebug> #include <QFileInfo> using namespace vesta; LocalImageLoader::LocalImageLoader() { } LocalImageLoader::~LocalImageLoader() { } void LocalImageLoader::addSearchPath(const QString &path) { m_searchPaths << path; } void LocalImageLoader::loadTexture(TextureMap* texture) { if (texture) { QString textureName(texture->name().c_str()); QFileInfo info(textureName); if (!textureName.startsWith(":") && !info.exists()) { foreach (QString path, m_searchPaths) { QString testName = path + "/" + textureName; if (QFileInfo(testName).exists()) { textureName = testName; break; } } } if (info.suffix() == "dds") { // Handle DDS textures QFile ddsFile(textureName); ddsFile.open(QIODevice::ReadOnly); QByteArray data = ddsFile.readAll(); if (!data.isEmpty()) { emit ddsTextureLoaded(texture, new DataChunk(data.data(), data.size())); } else { emit textureLoadFailed(texture); } } else { // Let Qt handle all file formats other than DDS QImage image(textureName); if (!image.isNull()) { emit textureLoaded(texture, image); } else { emit textureLoadFailed(texture); } } } }
25.905263
88
0.576189
hoehnp
b53931b37d620011083a7ce995bef5b64e02b70f
1,459
cpp
C++
Chapter_5_Mathematics/Number_Theory/kattis_pascal.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_5_Mathematics/Number_Theory/kattis_pascal.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_5_Mathematics/Number_Theory/kattis_pascal.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/* Kattis - pascal The function given stops at the largest divisor of n. This is n/i where i is the smallest prime factor of n. So after doing sieve, we just find the first prime factor of n (<= sqrt n). If we still cannot find such a factor. N is prime, so we ouput n-1. Else if n == 1, just output 0. Time: O(1e6 log log(1e6) + pi(sqrt(n))) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); typedef long long ll; typedef vector<ll> vll; ll _sieve_size; bitset<10000010> bs; vll primes; // Able to handle 1e7 in < 1s void sieve(ll upperbound = (ll) 1e6){ // 1e6 ** 2 > max_n _sieve_size = upperbound + 1; bs.set(); bs[0] = bs[1] = 0; for(ll i = 2; i <= _sieve_size; i++){ if(bs[i]){ for(ll j = i * i; j <= _sieve_size; j += i){ bs[j] = 0; } primes.push_back(i); } } } int main(){ sieve(); ll n; cin >> n; if (n == 1){ cout << "0" << endl; return 0; } for (auto i: primes){ if (i > sqrt(n))break; if (n % i == 0){ cout << n - n/i << endl; return 0; } } cout << n - 1 << endl; return 0; }
23.532258
98
0.557916
BrandonTang89
b53b6683e8416118684cd9d7a6d3d5a8de4a4f64
2,135
cpp
C++
source/RenderColorMap.cpp
xzrunner/painting2
c16e0133adf27a877b40b8fce642b5a42e043d09
[ "MIT" ]
null
null
null
source/RenderColorMap.cpp
xzrunner/painting2
c16e0133adf27a877b40b8fce642b5a42e043d09
[ "MIT" ]
null
null
null
source/RenderColorMap.cpp
xzrunner/painting2
c16e0133adf27a877b40b8fce642b5a42e043d09
[ "MIT" ]
null
null
null
#include "painting2/RenderColorMap.h" namespace pt2 { static const pt0::Color R_IDENTITY(255, 0, 0, 0); static const pt0::Color G_IDENTITY(0, 255, 0, 0); static const pt0::Color B_IDENTITY(0, 0, 255, 0); static const float INV_255 = 1.0f / 255; RenderColorMap::RenderColorMap() : rmap(255, 0, 0, 0) , gmap(0, 255, 0, 0) , bmap(0, 0, 255, 0) { } RenderColorMap::RenderColorMap(const pt0::Color& rmap, const pt0::Color& gmap, const pt0::Color& bmap) : rmap(rmap) , gmap(gmap) , bmap(bmap) { } RenderColorMap RenderColorMap::operator * (const RenderColorMap& rc) const { RenderColorMap ret; Mul(*this, rc, ret); return ret; } bool RenderColorMap::operator == (const RenderColorMap& rc) const { return rmap == rc.rmap && gmap == rc.gmap && bmap == rc.bmap; } void RenderColorMap::Reset() { rmap.FromRGBA(0xff000000); gmap.FromRGBA(0x00ff0000); bmap.FromRGBA(0x0000ff00); } void RenderColorMap::Mul(const RenderColorMap& c0, const RenderColorMap& c1, RenderColorMap& c) { auto& r0 = c0.rmap; auto& g0 = c0.gmap; auto& b0 = c0.bmap; auto& r1 = c1.rmap; auto& g1 = c1.gmap; auto& b1 = c1.bmap; if (r0 == R_IDENTITY && g0 == G_IDENTITY && b0 == B_IDENTITY) { c = c1; } else if (r1 == R_IDENTITY && g1 == G_IDENTITY && b1 == B_IDENTITY) { c = c0; } else { auto& r = c.rmap; auto& g = c.gmap; auto& b = c.bmap; r.r = static_cast<uint8_t>((r0.r * r1.r + r0.g * g1.r + r0.b * b1.r) * INV_255); r.g = static_cast<uint8_t>((r0.r * r1.g + r0.g * g1.g + r0.b * b1.g) * INV_255); r.b = static_cast<uint8_t>((r0.r * r1.b + r0.g * g1.b + r0.b * b1.b) * INV_255); r.a = 0; g.r = static_cast<uint8_t>((g0.r * r1.r + g0.g * g1.r + g0.b * b1.r) * INV_255); g.g = static_cast<uint8_t>((g0.r * r1.g + g0.g * g1.g + g0.b * b1.g) * INV_255); g.b = static_cast<uint8_t>((g0.r * r1.b + g0.g * g1.b + g0.b * b1.b) * INV_255); g.a = 0; b.r = static_cast<uint8_t>((b0.r * r1.r + b0.g * g1.r + b0.b * b1.r) * INV_255); b.g = static_cast<uint8_t>((b0.r * r1.g + b0.g * g1.g + b0.b * b1.g) * INV_255); b.b = static_cast<uint8_t>((b0.r * r1.b + b0.g * g1.b + b0.b * b1.b) * INV_255); b.a = 0; } } }
26.6875
102
0.608431
xzrunner
b53d8742434867cb3aeac03975006a7247581f97
1,483
cpp
C++
atcoder/abc/abc116/d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/abc/abc116/d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/abc/abc116/d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<ll, ll>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; int main(){ ll k,n,ans=0,osum=0, tmp=0; cin>>n>>k; vector<pll> v(n); //oishisa, neta priority_queue<pll> pqall; priority_queue<pll, vector<pll>, greater<pll>> pqkaburi; unordered_set<ll> us; for(int i = 0; i < n; i++) { ll t,d; cin>>t>>d; v[i]=make_pair(d,t); pqall.push(v[i]); } for(int i = 0; i < k; i++) { pll top = pqall.top(); pqall.pop(); if(us.find(top.second)==us.end()) { us.insert(top.second); osum+=top.first; } else { pqkaburi.push(top); osum+=top.first; } } tmp=osum+us.size()*us.size(); ans=max(ans,tmp); while(us.size()<k && pqall.size()>0){ pll top = pqall.top(); pqall.pop(); if(us.find(top.second)==us.end()) { us.insert(top.second); osum+=top.first; pll del = pqkaburi.top(); pqkaburi.pop(); osum-=del.first; tmp=osum+us.size()*us.size(); ans=max(ans,tmp); } } cout<<ans<<endl; return 0; }
23.539683
60
0.473365
yu3mars
b55b80c61d2b6d2a8ed6b3c0358267840425bee3
1,172
cpp
C++
2021/day2/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2021/day2/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2021/day2/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
#include "common/types.h" #include "utils/file.h" #include "utils/utils.h" #define DEBUG_LEVEL 5 #include "common/debug.h" int main(int argc, char *argv[]) { auto lines = File::readAllLines(argv[1]); { Point3d<int> pos; for (auto &r : lines) { int val; if (sscanf(r.c_str(), "forward %d", &val) == 1) { pos.setX(pos.getX() + val); } else if (sscanf(r.c_str(), "down %d", &val) == 1) { pos.setZ(pos.getZ() + val); } else if (sscanf(r.c_str(), "up %d", &val) == 1) { pos.setZ(pos.getZ() - val); } else { ERR(("Not supported rule! %s", r.c_str())); } } PRINTF(("PART_A: %d", pos.getX() * pos.getZ())); } { Point3d<int64_t> pos; for (auto &r : lines) { int val; if (sscanf(r.c_str(), "forward %d", &val) == 1) { pos.setX(pos.getX() + val); pos.setZ(pos.getZ() + pos.getY() * val); } else if (sscanf(r.c_str(), "down %d", &val) == 1) { pos.setY(pos.getY() + val); } else if (sscanf(r.c_str(), "up %d", &val) == 1) { pos.setY(pos.getY() - val); } else { ERR(("Not supported rule! %s", r.c_str())); } } PRINTF(("PART_B: %ld", pos.getX() * pos.getZ())); } return 0; }
19.213115
56
0.524744
bielskij
b5696a6bbc80994055fcbcf5d858e7df0afdde2f
220
cpp
C++
E9_tabelline tra 2 e 10.cpp
LeccaMelo/informatica_3
dcb30e3277d238bbe2dbbadeda40df20b6971b40
[ "MIT" ]
null
null
null
E9_tabelline tra 2 e 10.cpp
LeccaMelo/informatica_3
dcb30e3277d238bbe2dbbadeda40df20b6971b40
[ "MIT" ]
null
null
null
E9_tabelline tra 2 e 10.cpp
LeccaMelo/informatica_3
dcb30e3277d238bbe2dbbadeda40df20b6971b40
[ "MIT" ]
2
2016-11-24T08:29:36.000Z
2017-04-20T13:59:28.000Z
#include<stdio.h> main() { int N; int L; int I; int tab; N=2; L=0; while(L<=7){ N=N+1; I=1; while(I<=10){ tab=N*I; printf("%d",tab); I++; } L++; printf("\n"); } }
9.565217
21
0.377273
LeccaMelo
b573236b227067155c8346752b604e095ac88978
395
cpp
C++
Clase_17_DynamicProgramming/fibonacci.cpp
EdgarEspinozaPE/ProgramacionCompetitivaA
53c3eb3e2bc9f1dd1033e0c24b0cb24f96def1e9
[ "BSD-3-Clause" ]
null
null
null
Clase_17_DynamicProgramming/fibonacci.cpp
EdgarEspinozaPE/ProgramacionCompetitivaA
53c3eb3e2bc9f1dd1033e0c24b0cb24f96def1e9
[ "BSD-3-Clause" ]
null
null
null
Clase_17_DynamicProgramming/fibonacci.cpp
EdgarEspinozaPE/ProgramacionCompetitivaA
53c3eb3e2bc9f1dd1033e0c24b0cb24f96def1e9
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; long fibonacci(long n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; n = 8; cout << fibonacci(n) << "\n"; n = 12; cout << fibonacci(n) << "\n"; return 0; }
14.107143
45
0.56962
EdgarEspinozaPE
b573beae4f1fc4de07c059fe5805cfa80a3798ec
20,314
cpp
C++
src/main/VRMain.cpp
jtveite/MinVR
7a4f26371d434096388840ed61bea9dcd3527167
[ "BSD-3-Clause" ]
null
null
null
src/main/VRMain.cpp
jtveite/MinVR
7a4f26371d434096388840ed61bea9dcd3527167
[ "BSD-3-Clause" ]
null
null
null
src/main/VRMain.cpp
jtveite/MinVR
7a4f26371d434096388840ed61bea9dcd3527167
[ "BSD-3-Clause" ]
null
null
null
#include <main/VRMain.h> #include <stdio.h> #ifdef WIN32 #include <windows.h> #else #include <unistd.h> #endif #include <display/VRConsoleNode.h> #include <display/VRGraphicsWindowNode.h> #include <display/VRGroupNode.h> #include <display/VROffAxisProjectionNode.h> #include <display/VRStereoNode.h> #include <display/VRViewportNode.h> #include <display/VRLookAtNode.h> #include <display/VRTrackedLookAtNode.h> #include <net/VRNetClient.h> #include <net/VRNetServer.h> #include <plugin/VRPluginManager.h> namespace MinVR { /** This helper class is a wrapper around a list of VRRenderHandlers that makes the collection of render handlers act like a single render handler. VRMain holds a list of render handlers. Technically, we could pass this list into the DisplayNode::render(..) method, so the composite render handler is not strictly necessary, but it simplifies the implmentation of display nodes a bit to be able to write them as if they only need to handle a single render handler object. TO DISCUSS: Should we expose this to the application programer? It could be useful, but not sure we want to encourage using this outside of MinVR when we already have a way to register multiple renderhandlers. Might be best to keep it simple. */ class VRCompositeRenderHandler : public VRRenderHandler { public: VRCompositeRenderHandler(std::vector<VRRenderHandler*> &handlers) { _handlers = handlers; } virtual ~VRCompositeRenderHandler() {} virtual void onVRRenderScene(VRDataIndex *renderState, VRDisplayNode *callingNode) { for (std::vector<VRRenderHandler*>::iterator it = _handlers.begin(); it != _handlers.end(); it++) { (*it)->onVRRenderScene(renderState, callingNode); } } virtual void onVRRenderContext(VRDataIndex *renderState, VRDisplayNode *callingNode) { for (std::vector<VRRenderHandler*>::iterator it = _handlers.begin(); it != _handlers.end(); it++) { (*it)->onVRRenderContext(renderState, callingNode); } } protected: std::vector<VRRenderHandler*> _handlers; }; std::string getCurrentWorkingDir() { #ifdef WIN32 //not tested char cwd[1024]; GetCurrentDirectory( 1024, cwd); return std::string(cwd); #else char cwd[1024]; char * tmp = getcwd(cwd, sizeof(cwd)); return std::string(tmp); #endif } VRMain::VRMain() : _initialized(false), _config(NULL), _net(NULL), _factory(NULL), _pluginMgr(NULL), _frame(0) { _factory = new VRFactory(); // add sub-factories that are part of the MinVR core library right away _factory->registerItemType<VRDisplayNode, VRConsoleNode>("VRConsoleNode"); _factory->registerItemType<VRDisplayNode, VRGraphicsWindowNode>("VRGraphicsWindowNode"); _factory->registerItemType<VRDisplayNode, VRGroupNode>("VRGroupNode"); _factory->registerItemType<VRDisplayNode, VROffAxisProjectionNode>("VROffAxisProjectionNode"); _factory->registerItemType<VRDisplayNode, VRStereoNode>("VRStereoNode"); _factory->registerItemType<VRDisplayNode, VRViewportNode>("VRViewportNode"); _factory->registerItemType<VRDisplayNode, VRLookAtNode>("VRLookAtNode"); _factory->registerItemType<VRDisplayNode, VRTrackedLookAtNode>("VRTrackedLookAtNode"); _factory->registerItemType<VRDisplayNode, VRViewportNode>("VRViewportNode"); _pluginMgr = new VRPluginManager(this); } VRMain::~VRMain() { if (_config) { delete _config; } if (!_inputDevices.empty()) { for (std::vector<VRInputDevice*>::iterator it = _inputDevices.begin(); it != _inputDevices.end(); ++it) delete *it; } if (!_displayGraphs.empty()) { for (std::vector<VRDisplayNode*>::iterator it = _displayGraphs.begin(); it != _displayGraphs.end(); ++it) delete *it; } if (!_gfxToolkits.empty()) { for (std::vector<VRGraphicsToolkit*>::iterator it = _gfxToolkits.begin(); it != _gfxToolkits.end(); ++it) delete *it; } if (!_winToolkits.empty()) { for (std::vector<VRWindowToolkit*>::iterator it = _winToolkits.begin(); it != _winToolkits.end(); ++it) delete *it; } if (_factory) { delete _factory; } if (_net) { delete _net; } if (_pluginMgr) { delete _pluginMgr; } } void VRMain::initialize(int argc, char** argv) { if ((argc < 2) || ((argc >= 2) && (std::string(argv[1]) == "-h"))) { std::cout << "MinVR Program Usage:" << std::endl; std::cout << std::string(argv[0]) + " <config-file-name.xml> [vrsetup-name]" << std::endl; std::cout << " <config-file-name.xml> is required and is the name of a MinVR config file." << std::endl; std::cout << " optional: list of arguments in the form of DataIndexEntry=Value" << std::endl; exit(0); } std::string configFile = argv[1]; _config = new VRDataIndex(); if (!_config->processXMLFile(configFile,"/")) { } for(int i = 2; i < argc ; i ++){ std::string argument(argv[i]); int pos = argument.find("="); if(pos >=0){ std::string valueName = argument.substr(0,pos); std::string value = argument.substr(pos+1); _config->addData(valueName,value); } } VRStringArray vrSetupsToStartArray; if (!_config->exists("VRSetupsToStart","/")) { // no vrSetupsToStart are specified, start all of VRSetups listed in the config file std::list<std::string> names = _config->selectByAttribute("hostType","*"); for (std::list<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { vrSetupsToStartArray.push_back(*it); } } else { // a comma-separated list of vrSetupsToStart was provided std::string vrSetupsToStart = _config->getValue("VRSetupsToStart","/"); VRString elem; std::stringstream ss(vrSetupsToStart); while (std::getline(ss, elem, ',')) { vrSetupsToStartArray.push_back(elem); } } if (vrSetupsToStartArray.empty()) { cerr << "VRMain Error: No VRSetups to start are defined" << endl; exit(1); } { vector<std::string>::iterator it = vrSetupsToStartArray.begin(); for ( ; it != vrSetupsToStartArray.end(); ) { if(_config->exists("HostIP",*it) && !_config->exists("StartedSSH","/")){ //Setup needs to be started via ssh. // First get the path were it has to be started std::string workingDirectory = getCurrentWorkingDir(); std::string nodeIP = _config->getValue("HostIP",*it); std::string command = "cd " + workingDirectory + ";"; if(_config->exists("HostDisplay",*it)){ std::string displayVar = _config->getValue("HostDisplay",*it); command = command + "DISPLAY=" + displayVar + " "; } command = command + argv[0]; for (int i = 1; i < argc; i++) command = command + " " + argv[i]; command = command + " VRSetupsToStart=" + *it + " StartedSSH=1"; std::string sshcmd; if(_config->exists("LogToFile",*it)){ std::string logFile = _config->getValue("LogToFile",*it); sshcmd = "ssh " + nodeIP + " '" + command + " > " + logFile + " " + "2>&1 &'"; }else{ sshcmd = "ssh " + nodeIP + " '" + command + " > /dev/null 2>&1 &'"; } std::cerr << "Start " << sshcmd << std::endl; //we start and remove all clients which are started remotely via ssh it = vrSetupsToStartArray.erase(it); system(sshcmd.c_str()); }else{ //setup does not need to be started remotely or was already started remotely ++it; } } } if (vrSetupsToStartArray.empty()) { cerr << "All machines started via SSH - Exiting" << endl; exit(1); } // This process will be the first one listed _name = vrSetupsToStartArray[0]; // Fork a new process for each remaining vrsetup #ifdef WIN32 // Windows doesn't support forking, but it does allow us to create processes, // so we just create a new process with the config file to load as the first // command line argument and the vrsetup to start as the second command line // argument -- this means we need to enforce this convention for command line // arguments for all MinVR programs that want to support multiple processes. for (int i = 1; i < vrSetupsToStartArray.size(); i++) { // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); LPSTR title = new char[vrSetupsToStartArray[i].size() + 1]; strcpy(title, vrSetupsToStartArray[i].c_str()); si.lpTitle = title; std::string cmdLine = std::string(argv[0]); for (int i = 1; i < argc; i++) cmdLine = cmdLine + " " + argv[i]; cmdLine = cmdLine + " VRSetupsToStart=" + vrSetupsToStartArray[i]; LPSTR cmd = new char[cmdLine.size() + 1]; strcpy(cmd, cmdLine.c_str()); // Start the child process. if (!CreateProcess(NULL, // No module name (use command line) cmd, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_NEW_CONSOLE, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { std::cerr << "CreateProcess failed: " << GetLastError() << std::endl; exit(1); } delete[] title; delete[] cmd; } #else // On linux and OSX we can simply fork a new process for each vrsetup to start for (int i=1; i < vrSetupsToStartArray.size(); i++) { pid_t pid = fork(); if (pid == 0) { break; } _name = vrSetupsToStartArray[i]; } #endif // sanity check to make sure the vrSetup we are continuing with is actually defined in the config file if (!_config->exists(_name)) { cerr << "VRMain Error: The VRSetup " << _name << " was not found in the config file " << configFile << endl; exit(1); } // for everything from this point on, the VRSetup name for this process is stored in _name, and this // becomes the base namespace for all of the VRDataIndex lookups that we do. // LOAD PLUGINS: // Load plugins from the plugin directory. This will add their factories to the master VRFactory. { std::list<std::string> names = _config->selectByAttribute("pluginType", "*", _name); for (std::list<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { if (_config->exists("PluginPath", *it)){ std::string path = _config->getValue("PluginPath", *it); std::string file = _config->getDatum(*it)->getAttributeValue("pluginType"); path = path + "/" + file; string buildType = ""; #ifdef MinVR_DEBUG buildType = "d"; #endif if (!_pluginMgr->loadPlugin(path, file + buildType)) { cerr << "VRMain Error: Problem loading plugin " << path << file << buildType << endl; } } //else if(_config->getDatum(*it)->hasAttribute("pluginlibfile")){ // std::string file = _config->getDatum(*it)->getAttributeValue("pluginlibfile"); // if (!_pluginMgr->loadPlugin(file)) { // cerr << "VRMain Error: Problem loading plugin " << file << endl; // } //} } } // CONFIGURE NETWORKING: // check the type of this VRSetup, it should be either "VRServer", "VRClient", or "VRStandAlone" if(_config->getDatum(_name)->hasAttribute("hostType")){ std::string type = _config->getDatum(_name)->getAttributeValue("hostType"); if (type == "VRServer") { std::string port = _config->getValue("Port", _name); int numClients = _config->getValue("NumClients", _name); _net = new VRNetServer(port, numClients); } else if (type == "VRClient") { std::string port = _config->getValue("Port", _name); std::string ipAddress = _config->getValue("ServerIP", _name); _net = new VRNetClient(ipAddress, port); } else { // type == "VRStandAlone" // no networking, leave _net=NULL } } // CONFIGURE INPUT DEVICES: { std::list<std::string> names = _config->selectByAttribute("inputdeviceType", "*", _name); for (std::list<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { // create a new input device for each one in the list VRInputDevice *dev = _factory->create<VRInputDevice>(this, _config, *it); if (dev) { _inputDevices.push_back(dev); } else{ std::cerr << "Problem creating inputdevice: " << *it << " with inputdeviceType=" << _config->getDatum(*it)->getAttributeValue("inputdeviceType") << std::endl; } } } // CONFIGURE WINDOWS { std::list<std::string> names = _config->selectByAttribute("displaynodeType", "*", _name); for (std::list<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { // CONFIGURE WINDOW TOOLKIT { int counttk = 0; std::string usedToolkit; std::list<std::string> namestk = _config->selectByAttribute("graphicstoolkitType", "*", *it); for (std::list<std::string>::reverse_iterator ittk = namestk.rbegin(); ittk != namestk.rend(); ++ittk) { // create a new graphics toolkit for each one in the list VRGraphicsToolkit *tk = _factory->create<VRGraphicsToolkit>(this, _config, *ittk); if (tk) { if (counttk == 0){ _config->addData(_config->validateNameSpace(*it) + "GraphicsToolkit", tk->getName()); usedToolkit = *ittk; counttk++; } else { std::cerr << "Warning : Only 1 graphics toolkit can be defined for : " << *it << " using graphicstoolkitType=" << _config->getDatum(_config->validateNameSpace(*it) + "GraphicsToolkit")->getValueString() << " defined at " << usedToolkit << std::endl; delete tk; break; } bool exists = false; for (std::vector<VRGraphicsToolkit*>::iterator it_gfxToolkits = _gfxToolkits.begin(); it_gfxToolkits != _gfxToolkits.end(); ++it_gfxToolkits) { if ((*it_gfxToolkits)->getName() == tk->getName()) { exists = true; delete tk; break; } } if(!exists) _gfxToolkits.push_back(tk); } else{ std::cerr << "Problem creating graphics toolkit: " << *ittk << " with graphicstoolkit=" << _config->getDatum(*ittk)->getAttributeValue("graphicstoolkitType") << std::endl; } } } // CONFIGURE GRAPHICS TOOLKIT { int counttk = 0; std::string usedToolkit; std::list<std::string> namestk = _config->selectByAttribute("windowtoolkitType", "*", *it); for (std::list<std::string>::reverse_iterator ittk = namestk.rbegin(); ittk != namestk.rend(); ++ittk) { // create a new graphics toolkit for each one in the list VRWindowToolkit *tk = _factory->create<VRWindowToolkit>(this, _config, *ittk); if (tk) { if (counttk == 0){ _config->addData(_config->validateNameSpace(*it) + "WindowToolkit", tk->getName()); usedToolkit = *ittk; counttk++; } else { std::cerr << "Warning : Only 1 window toolkit can be defined for: " << *it << " using windowtoolkitType=" << _config->getDatum(_config->validateNameSpace(*it) + "WindowToolkit")->getValueString() << " defined at " << usedToolkit << std::endl; delete tk; break; } bool exists = false; for (std::vector<VRWindowToolkit*>::iterator it_winToolkits = _winToolkits.begin(); it_winToolkits != _winToolkits.end(); ++it_winToolkits) { if ((*it_winToolkits)->getName() == tk->getName()) { exists = true; delete tk; break; } } if (!exists) _winToolkits.push_back(tk); } else{ std::cerr << "Problem creating window toolkit: " << *ittk << " with windowtoolkitType=" << _config->getDatum(*it)->getAttributeValue("windowtoolkitType") << std::endl; } } } // add window to the displayGraph list VRDisplayNode *dg = _factory->create<VRDisplayNode>(this, _config, *it); if (dg) { _displayGraphs.push_back(dg); } else{ std::cerr << "Problem creating window: " << *it << " with windowType=" << _config->getDatum(*it)->getAttributeValue("windowType") << std::endl; } } } _initialized = true; } void VRMain::synchronizeAndProcessEvents() { if (!_initialized) { std::cerr << "VRMain not initialized." << std::endl; return; } VRDataQueue eventsFromDevices; for (int f = 0; f < _inputDevices.size(); f++) { _inputDevices[f]->appendNewInputEventsSinceLastCall(&eventsFromDevices); } //eventsFromDevices.printQueue(); // SYNCHRONIZATION POINT #1: When this function returns, we know // that all MinVR nodes have the same list of input events generated // since the last call to synchronizeAndProcessEvents(..). So, // every node will process the same set of input events this frame. VRDataQueue::serialData eventData; if (_net != NULL) { eventData = _net->syncEventDataAcrossAllNodes(eventsFromDevices.serialize()); } else if (eventsFromDevices.notEmpty()) { // TODO: There is no need to serialize here if we are not a network node eventData = eventsFromDevices.serialize(); } VRDataQueue *events = new VRDataQueue(eventData); while (events->notEmpty()) { // Unpack the next item from the queue. std::string event = _config->addSerializedValue( events->getSerializedObject() ); // Invoke the user's callback on the new event for (int f = 0; f < _eventHandlers.size(); f++) { _eventHandlers[f]->onVREvent(event, _config); } // Get the next item from the queue. events->pop(); } delete events; } void VRMain::renderOnAllDisplays() { if (!_initialized) { std::cerr << "VRMain not initialized." << std::endl; return; } VRDataIndex renderState; renderState.addData("InitRender", _frame == 0); if (!_displayGraphs.empty()) { VRCompositeRenderHandler compositeHandler(_renderHandlers); for (std::vector<VRDisplayNode*>::iterator it = _displayGraphs.begin(); it != _displayGraphs.end(); ++it) (*it)->render(&renderState, &compositeHandler); // TODO: Advanced: if you are really trying to optimize performance, this // is where you might want to add an idle callback. Here, it's // possible that the CPU is idle, but the GPU is still processing // graphics comamnds. for (std::vector<VRDisplayNode*>::iterator it = _displayGraphs.begin(); it != _displayGraphs.end(); ++it) (*it)->waitForRenderToComplete(&renderState); } // SYNCHRONIZATION POINT #2: When this function returns we know that // all nodes have finished rendering on all their attached display // devices. So, after this, we will be ready to "swap buffers", // simultaneously displaying these new renderings on all nodes. if (_net != NULL) { _net->syncSwapBuffersAcrossAllNodes(); } if (!_displayGraphs.empty()) { for (std::vector<VRDisplayNode*>::iterator it = _displayGraphs.begin(); it != _displayGraphs.end(); ++it) (*it)->displayFinishedRendering(&renderState); } _frame++; } void VRMain::shutdown() { // TODO _renderHandlers.clear(); _eventHandlers.clear(); } void VRMain::addEventHandler(VREventHandler* eventHandler) { _eventHandlers.push_back(eventHandler); } void VRMain::addRenderHandler(VRRenderHandler* renderHandler) { _renderHandlers.push_back(renderHandler); } VRGraphicsToolkit* VRMain::getGraphicsToolkit(const std::string &name) { for (std::vector<VRGraphicsToolkit*>::iterator it = _gfxToolkits.begin(); it < _gfxToolkits.end(); ++it) { if ((*it)->getName() == name) { return *it; } } return NULL; } VRWindowToolkit* VRMain::getWindowToolkit(const std::string &name) { for (std::vector<VRWindowToolkit*>::iterator it = _winToolkits.begin(); it < _winToolkits.end(); ++it) { if ((*it)->getName() == name) { return *it; } } return NULL; } void VRMain::addInputDevice(VRInputDevice* dev) { _inputDevices.push_back(dev); } /** void VRMain::removeEventHandler(VREventHandler* eventHandler) { for (int f = 0; f < _eventHandlers.size(); f++) { if (_eventHandlers[f] == eventHandler) { _eventHandlers.erase(_eventHandlers.begin()+f); break; } } } **/ } // end namespace
33.744186
257
0.651177
jtveite
b583c4962b4ea41a97bb42e9b2db3ad59effcb88
2,533
cpp
C++
HDUOJ/1253/bfs_priority_queue.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
HDUOJ/1253/bfs_priority_queue.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
HDUOJ/1253/bfs_priority_queue.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> #include <vector> #include <queue> #include <set> #include <map> #define SIZE 51 using namespace std; typedef struct _Node { int x, y, z; int step; bool operator < (const struct _Node b) const { return step > b.step; } bool operator == (const struct _Node b) const { return x == b.x && y == b.y && z == b.z; } } Node; bool arr[SIZE][SIZE][SIZE], hasVisited[SIZE][SIZE][SIZE]; int dir[3][6] = {1, -1, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 1, -1}; int row, height, column, timeLimit; bool canMove(Node &nextPt) { if (nextPt.x < 0 || nextPt.x >= row || nextPt.y < 0 || nextPt.y >= height || nextPt.z < 0 || nextPt.z >= column || arr[nextPt.x][nextPt.y][nextPt.z] || hasVisited[nextPt.x][nextPt.y][nextPt.z] || nextPt.step >= timeLimit) return false; return true; } int bfs(Node &startPt, Node &endPt) { memset(hasVisited, false, sizeof(hasVisited)); priority_queue<Node> pq; startPt.step = 0; pq.push(startPt); while (!pq.empty()) { Node cntPt = pq.top(); pq.pop(); for (int i = 0; i < 6; i++) { Node nextPt = {cntPt.x + dir[0][i], cntPt.y + dir[1][i], cntPt.z + dir[2][i], cntPt.step + 1}; if (!canMove(nextPt)) continue; if (abs(endPt.x - nextPt.x) + abs(endPt.y - nextPt.y) + abs(endPt.z - nextPt.z) > timeLimit - nextPt.step) continue; if (nextPt == endPt) { return nextPt.step; } hasVisited[nextPt.x][nextPt.y][nextPt.z] = true; pq.push(nextPt); } } return -1; } int main() { ios::sync_with_stdio(false); int caseNum; cin >> caseNum; while (caseNum--) { cin >> row >> height >> column >> timeLimit; for (int i = 0; i < row; i++) { for (int j = 0; j < height; j++) { for (int k = 0; k < column; k++) { cin >> arr[i][j][k]; } } } Node startPt = {0, 0, 0, 0}, endPt = {row - 1, height - 1, column - 1}; if (abs(endPt.x - startPt.x) + abs(endPt.y - startPt.y) + abs(endPt.z - startPt.z) > timeLimit) cout << -1 << endl; else cout << bfs(startPt, endPt) << endl; } return 0; }
25.079208
225
0.498223
codgician
b5872c559be2f727bea7f9a26a80ad5a79fee6e4
5,850
cpp
C++
project3/main.cpp
Inscrupulous/CPE212
cc4462d5c42ce16894b79117ef88111e728e098c
[ "Apache-2.0" ]
null
null
null
project3/main.cpp
Inscrupulous/CPE212
cc4462d5c42ce16894b79117ef88111e728e098c
[ "Apache-2.0" ]
null
null
null
project3/main.cpp
Inscrupulous/CPE212
cc4462d5c42ce16894b79117ef88111e728e098c
[ "Apache-2.0" ]
null
null
null
#include "classroom.hpp" #include "list.hpp" #include "student.hpp" #include <iostream> #include <fstream> #include <string> List<Assignment> ReadGradesFile(const std::string &file, bool &successful) { std::ifstream infile; List<Assignment> list; infile.open(file.c_str()); if(!infile.is_open()) { std::cout << "Failed to open a file" << std::endl; successful = false; return list; } while(true) { Assignment a; infile >> a.StudentUID; infile >> a.Grade; if(infile.eof()) { break; } list.AppendItem(a); } return list; } int main(int argc, char * const argv[]) { // Output usage message if test input file name is not provided if (argc != 2) { std::cout << "Usage:\n P3 <inputfile>\n"; return -1; } std::ifstream input; // Attempt to open test input file -- terminate if file does not open input.open(argv[1]); if (!input) { std::cout << "Error - unable to open input file" << std::endl; return 1; } { Student testStudent; Classroom classroom; std::string line; std::getline(input, line); char op; input >> op; while(input) { switch(op) { /// comment case '#': getline(input, line); std::cout << "# " << line << std::endl; break; /// test student case 'z': { std::string studentFirst; input >> studentFirst; std::string studentLast; input >> studentLast; unsigned int id; input >> id; testStudent = Student(studentFirst, studentLast, id); } break; /// add student to classroom case 's': { std::string studentFirst; input >> studentFirst; std::string studentLast; input >> studentLast; unsigned int id; input >> id; classroom.AddStudent(studentFirst, studentLast, id); } break; /// Test Student Exam case 'n': { float grade; input >> grade; testStudent.AddExam(grade); } break; /// Test student project case 'l': { float grade; input >> grade; testStudent.AddProject(grade); } break; /// Test student final case 'k': { float grade; input >> grade; testStudent.SetFinalExam(grade); } break; /// exams case 'e': { std::string examFile; input >> examFile; bool successful = true; List<Assignment> exams = ReadGradesFile(examFile, successful); if(!successful) { std::cout << "Failure" << std::endl; return -1; } classroom.AddExams(exams); } break; /// projects case 'p': { std::string projectFile; input >> projectFile; bool successful = true; List<Assignment> projects = ReadGradesFile(projectFile, successful); if(!successful) { std::cout << "Failure" << std::endl; return -1; } classroom.AddProjects(projects); } break; /// projects case 'f': { std::string finalsFile; input >> finalsFile; bool successful = true; List<Assignment> finals = ReadGradesFile(finalsFile, successful); if(!successful) { std::cout << "Failure" << std::endl; return -1; } classroom.SetFinalExams(finals); } break; /// Remove student UID case 'r': { unsigned int uid; input >> uid; if(!classroom.RemoveStudent(uid)) { std::cout << "UID not found: " << uid << std::endl; } else { std::cout << "Removed: " << uid << std::endl; } } break; /// print test student case 't': testStudent.PrintData(); break; /// print full classroom case 'a': classroom.PrintClassroomInformation(); break; default: std::cout << "Unknown input found" << std::endl; return -1; break; } input >> op; } } return 0; }
27.209302
88
0.372479
Inscrupulous
b58755b8a9838713b6b8f0f13d7fb510d9481f0a
1,929
cpp
C++
mr.Sadman/Classes/GameAct/Objects/Physical/Radiation.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Physical/Radiation.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Tech/Radiation.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#include "Radiation.hpp" #include "Game/Levels/Chunk.hpp" namespace Objects { namespace Tech { Radiation::Radiation() : _particle( cocos2d::ParticleFlower::create() ) { } Radiation::~Radiation() { _particle->removeFromParentAndCleanup( true ); } void Radiation::initialize() { _particle->setDuration( cocos2d::ParticleSystem::DURATION_INFINITY ); _particle->setBlendFunc( cocos2d::BlendFunc::ALPHA_NON_PREMULTIPLIED ); _particle->setPositionType( cocos2d::ParticleSystem::PositionType::RELATIVE ); _particle->setEmissionRate( 12.0f ); _particle->setLife( 0.1f ); _particle->setStartColor( cocos2d::Color4F::GREEN ); _particle->setEndColor( cocos2d::Color4F::GREEN ); DecorateObject::initialize(); } std::string Radiation::getName() const { return "Radiation"; } void Radiation::setPosition( cocos2d::Vec2 position ) { _particle->setPosition( position ); DecorateObject::setPosition( position ); } void Radiation::setSize( cocos2d::Size size ) { _particle->setEmitterMode( cocos2d::ParticleSystem::Mode::RADIUS ); float elSize = ( size.width + size.height ) * 0.2f; float radSize = ( size.width + size.height ) / 5.0f; _particle->setStartSize( elSize ); _particle->setEndSize( elSize ); _particle->setStartSizeVar( 0.0f ); _particle->setEndSizeVar( 0.0f ); _particle->setStartRadius( radSize ); _particle->setStartRadiusVar( 0.0f ); _particle->setEndRadius( radSize * 2.0f ); _particle->setEndRadiusVar( 0.0f ); DecorateObject::setSize( size ); } void Radiation::hide() { _particle->setVisible( false ); DecorateObject::hide(); } void Radiation::show() { _particle->setVisible( true ); DecorateObject::show(); } void Radiation::attachToChunk( Levels::Chunk & chunk, int zIndex ) { chunk.getLayer()->addChild( _particle, zIndex + 1 ); DecorateObject::attachToChunk( chunk, zIndex ); } } }
20.741935
80
0.692068
1pkg
b58b30b20f882aa1a826cb6d0ec1392f72947038
1,860
hpp
C++
src/interfaces/IConnection.hpp
LesGameDevToolsMagique/MagiqueMessenger
66c502b9b97f0a8761114f7b601216005a73e907
[ "MIT" ]
null
null
null
src/interfaces/IConnection.hpp
LesGameDevToolsMagique/MagiqueMessenger
66c502b9b97f0a8761114f7b601216005a73e907
[ "MIT" ]
null
null
null
src/interfaces/IConnection.hpp
LesGameDevToolsMagique/MagiqueMessenger
66c502b9b97f0a8761114f7b601216005a73e907
[ "MIT" ]
null
null
null
// // Created by Jean-Antoine Dupont on 14/03/2016. // #ifndef __ICONNECTION_HPP__ #define __ICONNECTION_HPP__ #include <string> // std::string #include <sys/types.h> // socket - bind - listen - accept #include <sys/socket.h> // socket - bind - listen - accept #include <netinet/in.h> // sockaddr_in #define SOCKET_FD_DEFAULT_VALUE (-2) struct client { int fd; sockaddr_in addr; socklen_t size; bool is_used; }; class IConnection { protected: int socket_fd; std::string ip_address; unsigned int port; struct sockaddr_in my_addr; /* Function */ public: virtual ~IConnection() {}; /* Getter / Setter */ virtual int getSocketFd() const = 0; virtual const std::string &getIpAddress() const = 0; virtual unsigned int getPort() const = 0; virtual const struct sockaddr_in *getMySockaddr() const = 0; /* Socket management */ virtual int createSocket(const int domain, const int type , const std::string &protocol = "") = 0; virtual int destroySocket(int fd) = 0; virtual int connectSocket() = 0; virtual int bindSocket() = 0; virtual int listenSocket(const int max_listened = 256) = 0; virtual int acceptSocket(struct client *client) = 0; protected: /* Configuration */ virtual int sockaddrConfig(struct sockaddr_in *sockaddr, const int domain = AF_INET) = 0; }; #endif /* __ICONNECTION_HPP__ */
33.214286
126
0.509677
LesGameDevToolsMagique
b58ca32dca61b144c57673c4278aacc0c201fa28
2,138
cpp
C++
C++/freeCodeCamp.org_C++ Tutorial for Beginners/src/025_Constructor Functions/ConstructorFunctions.cpp
JCOCA-Tech/coding-2021
180f8cd8830abf386dcd2399309a1b203a22ee3b
[ "MIT" ]
1
2021-10-14T02:26:41.000Z
2021-10-14T02:26:41.000Z
C++/freeCodeCamp.org_C++ Tutorial for Beginners/src/025_Constructor Functions/ConstructorFunctions.cpp
JCOCA-Tech/coding-2021
180f8cd8830abf386dcd2399309a1b203a22ee3b
[ "MIT" ]
null
null
null
C++/freeCodeCamp.org_C++ Tutorial for Beginners/src/025_Constructor Functions/ConstructorFunctions.cpp
JCOCA-Tech/coding-2021
180f8cd8830abf386dcd2399309a1b203a22ee3b
[ "MIT" ]
null
null
null
#include <iostream> /* Simple C++ program that uses constructor functions */ using namespace std; class Book // A class is a custom datatype template or blueprint { public: string title; string author; int pages; Book(string aTitle, string aAuthor, int aPages) // constructor using all 3 arguments { cout << "[DEBUG]: Creating book object [\"" << aTitle << "\", \"" << aAuthor << "\", \"" << aPages <<"\"]..." << endl; title = aTitle; author = aAuthor; pages = aPages; cout << "[DEBUG]: Done" << endl; } Book() // empty constructor { cout << "[DEBUG]: Creating book object [\"No title\", \"No author\", \"0\"]..." << endl; title = "No title"; author = "No author"; pages = 0; cout << "[DEBUG]: Done" << endl; } }; int main() { /* Book book1; // An object is an instance of a class book1.title = "Harry Potter"; // The objects public attributes can be directly modified book1.author = "JK Rowling"; book1.pages = 500; Book book2; book2.title = "Lord of the Rings"; book2.author = "Tolkien"; book2.pages = 700; cout << "Title:\t" << book1.title << endl; // Prints the title of the first book object cout << "Title:\t" << book2.title << endl; // Prints the title of the second book object */ Book book1("Harry Potter","JK Rowling",500); // Does the same as the above using the classes constructor Book book2("Lord of the Rings","Tolkien",700); book1.author = "J.K. Rowling"; // Public attributes can still be directly accessed Book book3; // New book object using the empty constructor /* This prints all the books attributes */ Book bookshelf[3] = {book1, book2, book3}; // Array with all 3 books for(int i = 0; i < 3; i++) { cout << endl << "Title:\t" << bookshelf[i].title << endl; cout << "Author:\t" << bookshelf[i].author << endl; cout << "Pages:\t" << bookshelf[i].pages << endl; } return 0; }
29.287671
130
0.552853
JCOCA-Tech
b58ced8e2150447e03387a46dcfa56f66b7c428c
1,122
cpp
C++
gearoenix/render/camera/gx-rnd-cmr-manager.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/render/camera/gx-rnd-cmr-manager.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/render/camera/gx-rnd-cmr-manager.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#include "gx-rnd-cmr-manager.hpp" #include "../engine/gx-rnd-eng-engine.hpp" #include "gx-rnd-cmr-orthographic.hpp" #include "gx-rnd-cmr-perspective.hpp" gearoenix::render::camera::Manager::Manager(std::unique_ptr<system::stream::Stream> s, engine::Engine* const e) noexcept : e(e) , cache(std::move(s)) { } std::shared_ptr<gearoenix::render::camera::Camera> gearoenix::render::camera::Manager::get_gx3d(const core::Id id, core::sync::EndCaller<Camera>& call) noexcept { std::shared_ptr<Camera> data = cache.get<Camera>( id, [this, id, call](std::string name) noexcept -> std::shared_ptr<Camera> { system::stream::Stream* const file = cache.get_file(); const auto t = file->read<core::TypeId>(); switch (t) { case 1: return std::make_shared<Perspective>(id, std::move(name), file, e); case 2: return std::make_shared<Orthographic>(id, std::move(name), file, e); default: GXLOGF("Unexpected camera type " << t) } }); call.set_data(data); return data; }
37.4
160
0.605169
Hossein-Noroozpour
b5904cc1966466510355afdcd9748a21457091d2
51,465
cpp
C++
proj.android/Photon-AndroidNDK_SDK/LoadBalancing-cpp/src/Client.cpp
h-iwata/MultiplayPaint
b170ec60bdda93c041ef59625ac2d6eba54d0335
[ "MIT" ]
1
2016-05-31T22:56:26.000Z
2016-05-31T22:56:26.000Z
proj.ios_mac/Photon-iOS_SDK/LoadBalancing-cpp/src/Client.cpp
h-iwata/MultiplayPaint
b170ec60bdda93c041ef59625ac2d6eba54d0335
[ "MIT" ]
null
null
null
proj.ios_mac/Photon-iOS_SDK/LoadBalancing-cpp/src/Client.cpp
h-iwata/MultiplayPaint
b170ec60bdda93c041ef59625ac2d6eba54d0335
[ "MIT" ]
null
null
null
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2015 by Exit Games GmbH. All rights reserved. * http://www.exitgames.com * mailto:developer@exitgames.com */ #include "LoadBalancing-cpp/inc/Client.h" #include "LoadBalancing-cpp/inc/Enums/CustomAuthenticationType.h" #include "LoadBalancing-cpp/inc/Enums/DisconnectCause.h" #include "LoadBalancing-cpp/inc/Internal/AuthenticationValuesSecretSetter.h" #include "LoadBalancing-cpp/inc/Internal/PlayerMovementInformant.h" #include "LoadBalancing-cpp/inc/Internal/Utils.h" #include "LoadBalancing-cpp/inc/Internal/Enums/EventCode.h" #include "LoadBalancing-cpp/inc/Internal/Enums/JoinType.h" #include "LoadBalancing-cpp/inc/Internal/Enums/OperationCode.h" #include "LoadBalancing-cpp/inc/Internal/Enums/ParameterCode.h" #include "LoadBalancing-cpp/inc/Internal/Enums/Properties/Player.h" #include "LoadBalancing-cpp/inc/Internal/Enums/Properties/Room.h" /** @file LoadBalancing-cpp/inc/Client.h */ namespace ExitGames { namespace LoadBalancing { using namespace Common; using namespace Common::MemoryManagement; using namespace Photon; using namespace Photon::StatusCode; using namespace Internal; const JString Client::NAMESERVER = L"ns.exitgamescloud.com"; // default name server address const bool SEND_AUTHENTICATE_ENCRYPTED = true; int Client::getServerTimeOffset(void) const { return mPeer.getServerTimeOffset(); } int Client::getServerTime(void) const { return mPeer.getServerTime(); } int Client::getBytesOut(void) const { return mPeer.getBytesOut(); } int Client::getBytesIn(void) const { return mPeer.getBytesIn(); } int Client::getByteCountCurrentDispatch(void) const { return mPeer.getByteCountCurrentDispatch(); } int Client::getByteCountLastOperation(void) const { return mPeer.getByteCountLastOperation(); } int Client::getSentCountAllowance(void) const { return mPeer.getSentCountAllowance(); } void Client::setSentCountAllowance(int setSentCountAllowance) { mPeer.setSentCountAllowance(setSentCountAllowance); } int Client::getTimePingInterval(void) const { return mPeer.getTimePingInterval(); } void Client::setTimePingInterval(int setTimePingInterval) { mPeer.setTimePingInterval(setTimePingInterval); } int Client::getRoundTripTime(void) const { return mPeer.getRoundTripTime(); } int Client::getRoundTripTimeVariance(void) const { return mPeer.getRoundTripTimeVariance(); } int Client::getTimestampOfLastSocketReceive(void) const { return mPeer.getTimestampOfLastSocketReceive(); } Common::DebugLevel::DebugLevel Client::getDebugOutputLevel(void) const { return mPeer.getDebugOutputLevel(); } bool Client::setDebugOutputLevel(Common::DebugLevel::DebugLevel debugLevel) { return mLogger.setDebugOutputLevel(debugLevel) && mPeer.setDebugOutputLevel(debugLevel); } int Client::getIncomingReliableCommandsCount(void) const { return mPeer.getIncomingReliableCommandsCount(); } short Client::getPeerId(void) const { return mPeer.getPeerId(); } int Client::getDisconnectTimeout(void) const { return mPeer.getDisconnectTimeout(); } void Client::setDisconnectTimeout(int disconnectTimeout) { mPeer.setDisconnectTimeout(disconnectTimeout); } int Client::getQueuedIncomingCommands(void) const { return mPeer.getQueuedIncomingCommands(); } int Client::getQueuedOutgoingCommands(void) const { return mPeer.getQueuedOutgoingCommands(); } bool Client::getIsEncryptionAvailable(void) const { return mPeer.getIsEncryptionAvailable(); } int Client::getResentReliableCommands(void) const { return mPeer.getResentReliableCommands(); } int Client::getLimitOfUnreliableCommands(void) const { return mPeer.getLimitOfUnreliableCommands(); } void Client::setLimitOfUnreliableCommands(int value) { mPeer.setLimitOfUnreliableCommands(value); } void Client::setCrcEnabled(bool crcEnabled) { mPeer.setCrcEnabled(crcEnabled); } bool Client::getCrcEnabled(void) const { return mPeer.getCrcEnabled(); } int Client::getPacketLossByCrc(void) const { return mPeer.getPacketLossByCrc(); } void Client::setTrafficStatsEnabled(bool trafficStatsEnabled) { mPeer.setTrafficStatsEnabled(trafficStatsEnabled); } bool Client::getTrafficStatsEnabled(void) const { return mPeer.getTrafficStatsEnabled(); } int Client::getTrafficStatsElapsedMs(void) const { return mPeer.getTrafficStatsElapsedMs(); } const Photon::TrafficStats& Client::getTrafficStatsIncoming(void) const { return mPeer.getTrafficStatsIncoming(); } const Photon::TrafficStats& Client::getTrafficStatsOutgoing(void) const { return mPeer.getTrafficStatsOutgoing(); } const Photon::TrafficStatsGameLevel& Client::getTrafficStatsGameLevel(void) const { return mPeer.getTrafficStatsGameLevel(); } short Client::getPeerCount(void) { return Peer::getPeerCount(); } PeerStates::PeerStates Client::getState(void) const { return mState; } const JString& Client::getMasterserverAddress(void) const { return mMasterserver; } int Client::getCountPlayersIngame(void) const { return mPeerCount; } int Client::getCountGamesRunning(void) const { return mRoomCount; } int Client::getCountPlayersOnline(void) const { return mPeerCount + mMasterPeerCount; } MutableRoom& Client::getCurrentlyJoinedRoom(void) { if(!mpCurrentlyJoinedRoom) mpCurrentlyJoinedRoom = createMutableRoom(L"", Hashtable(), Common::JVector<Common::JString>(), 0, 0); return *mpCurrentlyJoinedRoom; } const JVector<Room*>& Client::getRoomList(void) const { return mRoomList; } const JVector<JString>& Client::getRoomNameList(void) const { return mRoomNameList; } bool Client::getIsInRoom(void) const { return getIsInGameRoom() || getIsInLobby(); } bool Client::getIsInGameRoom(void) const { return mState == PeerStates::Joined; } bool Client::getIsInLobby(void) const { return mState == PeerStates::JoinedLobby; } bool Client::getAutoJoinLobby(void) const { return mAutoJoinLobby; } void Client::setAutoJoinLobby(bool onConnect) { mAutoJoinLobby = onConnect; } MutablePlayer& Client::getLocalPlayer(void) { if(!mpLocalPlayer) mpLocalPlayer = createMutablePlayer(-1, Hashtable()); return *mpLocalPlayer; } const JVector<FriendInfo>& Client::getFriendList(void) { return mFriendList; } int Client::getFriendListAge(void) { return mIsFetchingFriendList||!mFriendListTimestamp ? 0 : GETTIMEMS()-mFriendListTimestamp; } /** Summarizes (aggregates) the different causes for disconnects of a client. A disconnect can be caused by: errors in the network connection or some vital operation failing (which is considered "high level"). While operations always trigger a call to OnOperationResponse, connection related changes are treated in OnStatusChanged. The DisconnectCause is set in either case and summarizes the causes for any disconnect in a single state value which can be used to display (or debug) the cause for disconnection. */ int Client::getDisconnectedCause(void) { return mDisconnectedCause; } Client::Client(Listener& listener, const JString& applicationID, const JString& appVersion, const JString& username, nByte connectionProtocol, AuthenticationValues authenticationValues, bool autoLobbyStats, bool useDefaultRegion) #if defined _EG_MS_COMPILER # pragma warning(push) # pragma warning(disable:4355) #endif : mPeer(*this, connectionProtocol) , mListener(listener) , mAppVersion(appVersion) , mAppID(applicationID) , mPeerCount(0) , mRoomCount(0) , mMasterPeerCount(0) , mLastJoinType(0) , mLastLobbyJoinType(0) , mLastJoinCreateIfNotExists(false) , mLastJoinPlayerNumber(0) , mLastCacheSliceIndex(0) , mpCurrentlyJoinedRoom(NULL) , mCachedErrorCodeFromGameServer(ErrorCode::OK) , mAutoJoinLobby(true) , mpLocalPlayer(NULL) , mIsFetchingFriendList(false) , mState(PeerStates::Uninitialized) , mAuthenticationValues(authenticationValues) , mAutoLobbyStats(autoLobbyStats) , mDisconnectedCause(DisconnectCause::NONE) , M_USE_DEFAULT_REGION(useDefaultRegion) , M_CONNECTION_PROTOCOL(connectionProtocol) #ifdef _EG_MS_COMPILER # pragma warning(pop) #endif { mLogger.setListener(*this); getLocalPlayer().setName(username); } Client::~Client(void) { destroyMutableRoom(mpCurrentlyJoinedRoom); destroyMutablePlayer(mpLocalPlayer); for(unsigned int i=0; i<mRoomList.getSize(); ++i) destroyRoom(mRoomList[i]); } bool Client::connect(const JString& serverAddress, nByte serverType) { AuthenticationValuesSecretSetter::setSecret(mAuthenticationValues, L""); //reset secret mState = serverType==ServerType::NAME_SERVER?PeerStates::ConnectingToNameserver:PeerStates::Connecting; static const int NAMESERVER_PORT_GAP = 3; if(serverType == ServerType::MASTER_SERVER) mMasterserver = serverAddress; return mPeer.connect(serverAddress + (serverAddress.indexOf(L':') == -1?JString(L":")+((M_CONNECTION_PROTOCOL==ConnectionProtocol::UDP?NetworkPort::UDP:NetworkPort::TCP)+(serverType==ServerType::NAME_SERVER?NAMESERVER_PORT_GAP:0)):JString())); } void Client::disconnect(void) { mState = PeerStates::Disconnecting; mPeer.disconnect(); } void Client::service(bool dispatchIncomingCommands) { mPeer.service(dispatchIncomingCommands); } void Client::serviceBasic(void) { mPeer.serviceBasic(); } bool Client::opCustom(const Photon::OperationRequest& operationRequest, bool sendReliable, nByte channelID, bool encrypt) { return mPeer.opCustom(operationRequest, sendReliable, channelID, encrypt); } bool Client::sendOutgoingCommands(void) { return mPeer.sendOutgoingCommands(); } bool Client::sendAcksOnly(void) { return mPeer.sendAcksOnly(); } bool Client::dispatchIncomingCommands(void) { return mPeer.dispatchIncomingCommands(); } bool Client::establishEncryption(void) { return mPeer.establishEncryption(); } void Client::fetchServerTimestamp(void) { mPeer.fetchServerTimestamp(); } void Client::resetTrafficStats(void) { mPeer.resetTrafficStats(); } void Client::resetTrafficStatsMaximumCounters(void) { mPeer.resetTrafficStatsMaximumCounters(); } Common::JString Client::vitalStatsToString(bool all) const { return mPeer.vitalStatsToString(all); } bool Client::opJoinLobby(const JString& lobbyName, nByte lobbyType) { if(getIsInRoom()) { EGLOG(DebugLevel::ERRORS, L"already in a room"); return false; } mLastLobbyJoinType = JoinType::EXPLICIT_JOIN_LOBBY; return mPeer.opJoinLobby(lobbyName, lobbyType); } bool Client::opLeaveLobby(void) { if(!getIsInLobby()) { EGLOG(DebugLevel::ERRORS, L"lobby isn't currently joined"); return false; } return opCustom(OperationRequest(OperationCode::LEAVE_LOBBY), true); } bool Client::opCreateRoom(const JString& gameID, bool isVisible, bool isOpen, nByte maxPlayers, const Hashtable& customRoomProperties, const JVector<JString>& propsListedInLobby, const Common::JString& lobbyName, nByte lobbyType, int playerTtl, int emptyRoomTtl) { if(getIsInGameRoom()) { EGLOG(DebugLevel::ERRORS, L"already in a gameroom"); return false; } mRoomName = gameID; OperationRequestParameters op(mPeer.opCreateRoomImplementation(gameID, isVisible, isOpen, maxPlayers, getIsOnGameServer()?customRoomProperties:Hashtable(), getIsOnGameServer()?getLocalPlayer().getCustomProperties():Hashtable(), getIsOnGameServer()?propsListedInLobby:JVector<JString>(), lobbyName, lobbyType, playerTtl, emptyRoomTtl)); if(getLocalPlayer().getName().length()) { if((ValueObject<Hashtable>*)op.getValue(static_cast<nByte>(ParameterCode::PLAYER_PROPERTIES))) ((ValueObject<Hashtable>*)op.getValue(static_cast<nByte>(ParameterCode::PLAYER_PROPERTIES)))->getDataAddress()->put(static_cast<nByte>(Properties::Player::PLAYERNAME), getLocalPlayer().getName()); else { Hashtable playerProp; playerProp.put(static_cast<nByte>(Properties::Player::PLAYERNAME), getLocalPlayer().getName()); op.put(static_cast<nByte>(ParameterCode::PLAYER_PROPERTIES), ValueObject<Hashtable>(playerProp)); } } if(!opCustom(OperationRequest(OperationCode::CREATE_ROOM, op), true)) return false; Hashtable roomProps(Utils::stripToCustomProperties(customRoomProperties)); roomProps.put(static_cast<nByte>(Properties::Room::IS_OPEN), isOpen); roomProps.put(static_cast<nByte>(Properties::Room::IS_VISIBLE), isVisible); roomProps.put(static_cast<nByte>(Properties::Room::MAX_PLAYERS), maxPlayers); JString* propsListedInLobbyArr = allocateArray<JString>(propsListedInLobby.getSize()); for(unsigned int i=0; i<propsListedInLobby.getSize(); ++i) propsListedInLobbyArr[i] = propsListedInLobby[i]; roomProps.put(static_cast<nByte>(Properties::Room::PROPS_LISTED_IN_LOBBY), propsListedInLobbyArr, propsListedInLobby.getSize()); deallocateArray(propsListedInLobbyArr); MutableRoom* oldRoom = mpCurrentlyJoinedRoom; mpCurrentlyJoinedRoom = createMutableRoom(gameID, roomProps, propsListedInLobby, playerTtl, emptyRoomTtl); destroyMutableRoom(oldRoom); return true; } bool Client::opJoinRoom(const JString& gameID, bool createIfNotExists, int playerNumber, int cacheSliceIndex, int playerTtl, int emptyRoomTtl) { if(getIsInGameRoom()) { EGLOG(DebugLevel::ERRORS, L"already in a gameroom"); return false; } // TODO: if(playerNumber) // (workaround for some server issue we will fix) createIfNotExists = true; mRoomName = gameID; OperationRequestParameters op = mPeer.opJoinRoomImplementation(gameID, getIsOnGameServer()?getLocalPlayer().getCustomProperties():Hashtable(), createIfNotExists, playerNumber, getIsOnGameServer()?cacheSliceIndex:0, playerTtl, emptyRoomTtl); if(getLocalPlayer().getName().length()) { if((ValueObject<Hashtable>*)op.getValue(static_cast<nByte>(ParameterCode::PLAYER_PROPERTIES))) ((ValueObject<Hashtable>*)op.getValue(static_cast<nByte>(ParameterCode::PLAYER_PROPERTIES)))->getDataAddress()->put(static_cast<nByte>(Properties::Player::PLAYERNAME), getLocalPlayer().getName()); else { Hashtable playerProp; playerProp.put(static_cast<nByte>(Properties::Player::PLAYERNAME), getLocalPlayer().getName()); op.put(static_cast<nByte>(ParameterCode::PLAYER_PROPERTIES), ValueObject<Hashtable>(playerProp)); } } if(!gameID.length() || !opCustom(OperationRequest(OperationCode::JOIN_ROOM, op), true)) return false; MutableRoom* oldRoom = mpCurrentlyJoinedRoom; mpCurrentlyJoinedRoom = createMutableRoom(gameID, Hashtable(), JVector<JString>(), playerTtl, emptyRoomTtl); destroyMutableRoom(oldRoom); mLastJoinCreateIfNotExists = createIfNotExists; mLastJoinPlayerNumber = playerNumber; mLastCacheSliceIndex = cacheSliceIndex; return true; } bool Client::opJoinRandomRoom(const Hashtable& customRoomProperties, nByte maxPlayers, nByte matchmakingMode, const JString& lobbyName, nByte lobbyType, const JString& sqlLobbyFilter) { if(getIsInGameRoom()) { EGLOG(DebugLevel::ERRORS, L"already in a gameroom"); return false; } if(!mPeer.opJoinRandomRoom(customRoomProperties, maxPlayers, matchmakingMode, lobbyName, lobbyType, sqlLobbyFilter)) return false; MutableRoom* oldRoom = mpCurrentlyJoinedRoom; mpCurrentlyJoinedRoom = createMutableRoom(L"", Utils::stripToCustomProperties(customRoomProperties), Common::JVector<Common::JString>(), 0, 0); destroyMutableRoom(oldRoom); return true; } bool Client::opLeaveRoom(bool willComeBack) { if(!getIsInGameRoom()) { EGLOG(DebugLevel::ERRORS, L"no gameroom is currently joined"); return false; } if(willComeBack) { mState = PeerStates::DisconnectingFromGameserver; mPeer.disconnect(); } else { if(!mPeer.opLeaveRoom()) return false; mState = PeerStates::Leaving; } return true; } bool Client::opFindFriends(const JString* friendsToFind, short numFriendsToFind) { if(getIsOnGameServer() || mIsFetchingFriendList) return false; mLastFindFriendsRequest.removeAllElements(); for(short i=0; i<numFriendsToFind; ++i) mLastFindFriendsRequest.addElement(friendsToFind[i]); return mIsFetchingFriendList = mPeer.opFindFriends(friendsToFind, numFriendsToFind); } bool Client::opLobbyStats(const Common::JVector<LoadBalancing::LobbyStatsRequest>& lobbiesToQuery) { if(!getIsInLobby()) { EGLOG(DebugLevel::ERRORS, L"lobby isn't currently joined"); return false; } mLobbyStatsRequestList = lobbiesToQuery; return mPeer.opLobbyStats(lobbiesToQuery); } bool Client::opCustomAuthenticationSendNextStepData(const AuthenticationValues& authenticationValues) { if(mState != PeerStates::WaitingForCustomAuthenticationNextStepCall) return false; mState = PeerStates::ConnectedToNameserver; return mPeer.opAuthenticate(mAppID, mAppVersion, SEND_AUTHENTICATE_ENCRYPTED, getLocalPlayer().getName(), authenticationValues, mAutoLobbyStats, mSelectedRegion); } bool Client::selectRegion(const JString& selectedRegion) { if(M_USE_DEFAULT_REGION) { EGLOG(DebugLevel::ERRORS, L"this function should only be called, when you have explicitly specified in the constructor not to use the default region."); return false; } else return mPeer.opAuthenticate(mAppID, mAppVersion, SEND_AUTHENTICATE_ENCRYPTED, getLocalPlayer().getName(), mAuthenticationValues, mAutoLobbyStats, mSelectedRegion=selectedRegion); } // protocol implementations void Client::onOperationResponse(const OperationResponse& operationResponse) { EGLOG(operationResponse.getReturnCode()?DebugLevel::ERRORS:DebugLevel::INFO, operationResponse.toString(true)); // Use the secret whenever we get it, no matter the operation code. if(operationResponse.getParameters().contains(ParameterCode::SECRET) && mAuthenticationValues.getType() != CustomAuthenticationType::NONE) { AuthenticationValuesSecretSetter::setSecret(mAuthenticationValues, ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::SECRET)).getDataCopy()); EGLOG(DebugLevel::INFO, L"Server returned secret"); mListener.onSecretReceival(mAuthenticationValues.getSecret()); } switch(operationResponse.getOperationCode()) { case OperationCode::AUTHENTICATE: { PeerStates::PeerStates oldState = mState; if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"authentication failed with errorcode %d: %ls", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); switch(operationResponse.getReturnCode()) { case ErrorCode::INVALID_AUTHENTICATION: mDisconnectedCause = DisconnectCause::INVALID_AUTHENTICATION; break; case ErrorCode::CUSTOM_AUTHENTICATION_FAILED: mDisconnectedCause = DisconnectCause::CUSTOM_AUTHENTICATION_FAILED; break; case ErrorCode::INVALID_REGION: mDisconnectedCause = DisconnectCause::INVALID_REGION; break; case ErrorCode::MAX_CCU_REACHED: mDisconnectedCause = DisconnectCause::MAX_CCU_REACHED; break; case ErrorCode::OPERATION_DENIED: mDisconnectedCause = DisconnectCause::OPERATION_NOT_ALLOWED_IN_CURRENT_STATE; break; } handleConnectionFlowError(oldState, operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; } else { if(mState == PeerStates::ConnectedToNameserver) { if(operationResponse.getParameters().contains(ParameterCode::DATA)) { mState = PeerStates::WaitingForCustomAuthenticationNextStepCall; mListener.onCustomAuthenticationIntermediateStep(*ValueObject<Dictionary<JString, Object> >(operationResponse.getParameterForCode(ParameterCode::DATA)).getDataAddress()); break; } else { mState = PeerStates::DisconnectingFromNameserver; mMasterserver = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::ADDRESS)).getDataCopy(); mPeer.disconnect(); } } else if(mState == PeerStates::Connected || mState == PeerStates::ConnectedComingFromGameserver) { mState = mState==PeerStates::Connected?PeerStates::Authenticated:PeerStates::AuthenticatedComingFromGameserver; if(mAutoJoinLobby) { opJoinLobby(); mLastLobbyJoinType = JoinType::AUTO_JOIN_LOBBY; } else onConnectToMasterFinished(oldState==PeerStates::ConnectedComingFromGameserver); } else if(mState == PeerStates::ConnectedToGameserver) { mState = PeerStates::Joining; if(mLastJoinType == JoinType::CREATE_ROOM) opCreateRoom(mRoomName, mpCurrentlyJoinedRoom->getIsVisible(), mpCurrentlyJoinedRoom->getIsOpen(), mpCurrentlyJoinedRoom->getMaxPlayers(), mpCurrentlyJoinedRoom->getCustomProperties(), mpCurrentlyJoinedRoom->getPropsListedInLobby(), Common::JString(), LobbyType::DEFAULT, mpCurrentlyJoinedRoom->getPlayerTtl(), mpCurrentlyJoinedRoom->getRoomTtl()); // lobbyName and lobbyType not used on game server else if(mLastJoinType == JoinType::JOIN_ROOM) opJoinRoom(mRoomName, mLastJoinCreateIfNotExists, mLastJoinPlayerNumber, mLastCacheSliceIndex, mpCurrentlyJoinedRoom->getPlayerTtl(), mpCurrentlyJoinedRoom->getRoomTtl()); else if(mLastJoinType == JoinType::JOIN_RANDOM_ROOM) opJoinRoom(mRoomName); } } } break; case OperationCode::CREATE_ROOM: case OperationCode::JOIN_ROOM: { if(getIsOnGameServer()) { if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"%ls failed with errorcode %d: %ls. Client is therefore returning to masterserver!", operationResponse.getOperationCode()==OperationCode::CREATE_ROOM?L"opCreateRoom":L"opJoinRoom", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); handleConnectionFlowError(mState, operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; } mState = PeerStates::Joined; int nr = ValueObject<int>(operationResponse.getParameterForCode(ParameterCode::PLAYERNR)).getDataCopy(); Hashtable properties = getLocalPlayer().getCustomProperties(); properties.put(static_cast<nByte>(Properties::Player::PLAYERNAME), getLocalPlayer().getName()); destroyMutablePlayer(mpLocalPlayer); PlayerMovementInformant::onEnterLocal(*mpCurrentlyJoinedRoom, *(mpLocalPlayer=createMutablePlayer(nr, properties))); Hashtable roomProperties(ValueObject<Hashtable>(operationResponse.getParameterForCode(ParameterCode::ROOM_PROPERTIES)).getDataCopy()); Hashtable playerProperties(ValueObject<Hashtable>(operationResponse.getParameterForCode(ParameterCode::PLAYER_PROPERTIES)).getDataCopy()); const JVector<Object>& numbers = playerProperties.getKeys(); for(unsigned int i=0 ; i<numbers.getSize() ; ++i) PlayerMovementInformant::onEnterRemote(*mpCurrentlyJoinedRoom, KeyObject<int>(numbers[i]).getDataCopy(), ValueObject<Hashtable>(playerProperties.getValue(numbers[i])).getDataCopy()); readoutProperties(roomProperties, playerProperties, true, 0); switch(mLastJoinType) { case JoinType::CREATE_ROOM: mListener.createRoomReturn(nr, roomProperties, playerProperties, operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; case JoinType::JOIN_ROOM: mListener.joinRoomReturn(nr, roomProperties, playerProperties, operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; case JoinType::JOIN_RANDOM_ROOM: mListener.joinRandomRoomReturn(nr, roomProperties, playerProperties, operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; default: break; } break; } else { switch(operationResponse.getOperationCode()) { case OperationCode::CREATE_ROOM: { if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"opCreateRoom failed with errorcode %d: %ls. Client is therefore staying on masterserver!", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); mListener.createRoomReturn(0, Hashtable(), Hashtable(), operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; } JString gameID = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::ROOM_NAME)).getDataCopy(); if(gameID.length()) // is only sent by the server's response, if it has not been sent with the client's request before! mRoomName = gameID; mGameserver = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::ADDRESS)).getDataCopy(); mState = PeerStates::DisconnectingFromMasterserver; mPeer.disconnect(); mLastJoinType = JoinType::CREATE_ROOM; } break; case OperationCode::JOIN_ROOM: if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"opJoinRoom failed with errorcode %d: %ls. Client is therefore staying on masterserver!", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); mListener.joinRoomReturn(0, Hashtable(), Hashtable(), operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; } mGameserver = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::ADDRESS)).getDataCopy(); mState = PeerStates::DisconnectingFromMasterserver; mPeer.disconnect(); mLastJoinType = JoinType::JOIN_ROOM; break; default: break; } } } break; case OperationCode::JOIN_RANDOM_ROOM: if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"opJoinRandomRoom failed with errorcode %d: %ls. Client is therefore staying on masterserver!", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); mListener.joinRandomRoomReturn(0, Hashtable(), Hashtable(), operationResponse.getReturnCode(), operationResponse.getDebugMessage()); break; } // store the ID of the random game, joined on the masterserver, so that we know, which game to join on the gameserver mRoomName = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::ROOM_NAME)).getDataCopy(); mGameserver = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::ADDRESS)).getDataCopy(); mState = PeerStates::DisconnectingFromMasterserver; mPeer.disconnect(); mLastJoinType = JoinType::JOIN_RANDOM_ROOM; break; case OperationCode::JOIN_LOBBY: { PeerStates::PeerStates oldState = mState; mState = PeerStates::JoinedLobby; if(mLastLobbyJoinType == JoinType::AUTO_JOIN_LOBBY) onConnectToMasterFinished(oldState==PeerStates::AuthenticatedComingFromGameserver); else mListener.joinLobbyReturn(); } break; case OperationCode::LEAVE_LOBBY: { mState = PeerStates::Authenticated; mListener.leaveLobbyReturn(); } break; case OperationCode::LEAVE: { PlayerMovementInformant::onLeaveLocal(*mpCurrentlyJoinedRoom, getLocalPlayer().getNumber()); Hashtable op = getLocalPlayer().getCustomProperties(); op.put(static_cast<nByte>(Properties::Player::PLAYERNAME), getLocalPlayer().getName()); destroyMutablePlayer(mpLocalPlayer); mpLocalPlayer = createMutablePlayer(-1, op); mIsFetchingFriendList = false; mState = PeerStates::DisconnectingFromGameserver; mPeer.disconnect(); } break; case OperationCode::FIND_FRIENDS: { mIsFetchingFriendList = false; if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"opFindFriends failed with errorcode %d: %ls.", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); break; } ValueObject<bool*> onlineList = operationResponse.getParameterForCode(ParameterCode::FIND_FRIENDS_RESPONSE_ONLINE_LIST); ValueObject<JString*> roomList = operationResponse.getParameterForCode(ParameterCode::FIND_FRIENDS_RESPONSE_ROOM_ID_LIST); bool* pOnlineList = *onlineList.getDataAddress(); JString* pRoomList = *roomList.getDataAddress(); mFriendList.removeAllElements(); for(unsigned int i=0; i<mLastFindFriendsRequest.getSize(); ++i) { if((int)i < onlineList.getSizes()[0] && (int)i < roomList.getSizes()[0]) { mFriendList.addElement(FriendInfo(mLastFindFriendsRequest[i], pOnlineList[i], pRoomList[i])); } } if(!(mFriendListTimestamp=GETTIMEMS())) mFriendListTimestamp = 1; mListener.onFindFriendsResponse(); } break; case OperationCode::LOBBY_STATS: { if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"opLobbyStats failed with errorcode %d: %ls.", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); break; } ValueObject<JString*> namesList = operationResponse.getParameterForCode(ParameterCode::LOBBY_NAME); ValueObject<nByte*> typesList = operationResponse.getParameterForCode(ParameterCode::LOBBY_TYPE); ValueObject<int*> peersList = operationResponse.getParameterForCode(ParameterCode::PEER_COUNT); ValueObject<int*> roomsList = operationResponse.getParameterForCode(ParameterCode::ROOM_COUNT); int* peers = *peersList.getDataAddress(); int* rooms = *roomsList.getDataAddress(); JVector<LobbyStatsResponse> res; if(namesList.getType() != TypeCode::EG_NULL) { JString* names = *namesList.getDataAddress(); nByte* types = *typesList.getDataAddress(); for(int i=0; i<*namesList.getSizes(); ++i) res.addElement(LobbyStatsResponse(names[i], types[i], peers[i], rooms[i])); } else { for(int i=0; i<static_cast<int>(mLobbyStatsRequestList.getSize()); ++i) { int peerCount = i < *peersList.getSizes() ? peers[i] : 0; int roomCount = i < *roomsList.getSizes() ? rooms[i] : 0; res.addElement(LobbyStatsResponse(mLobbyStatsRequestList[i].getName(), mLobbyStatsRequestList[i].getType(), peerCount, roomCount)); } } mListener.onLobbyStatsResponse(res); } break; case OperationCode::GET_REGIONS: { if(operationResponse.getReturnCode()) { EGLOG(DebugLevel::ERRORS, L"GetRegions failed with errorcode %d: %ls.", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); break; } JVector<JString> availableRegions(*ValueObject<JString*>(operationResponse.getParameterForCode(ParameterCode::REGION)).getDataAddress(), *ValueObject<JString*>(operationResponse.getParameterForCode(ParameterCode::REGION)).getSizes()); JVector<JString> availableRegionServers(*ValueObject<JString*>(operationResponse.getParameterForCode(ParameterCode::ADDRESS)).getDataAddress(), *ValueObject<JString*>(operationResponse.getParameterForCode(ParameterCode::ADDRESS)).getSizes()); if(M_USE_DEFAULT_REGION) mPeer.opAuthenticate(mAppID, mAppVersion, SEND_AUTHENTICATE_ENCRYPTED, getLocalPlayer().getName(), mAuthenticationValues, mAutoLobbyStats, mSelectedRegion=availableRegions[0]); else mListener.onAvailableRegions(availableRegions, availableRegionServers); } break; case OperationCode::RPC: { if(operationResponse.getReturnCode()) EGLOG(DebugLevel::ERRORS, L"WebRpc failed with errorcode %d: %ls.", operationResponse.getReturnCode(), operationResponse.getDebugMessage().cstr()); int returnCode = ValueObject<int>(operationResponse.getParameterForCode(ParameterCode::RPC_CALL_RET_CODE)).getDataCopy(); ValueObject<JString> uriPathObj = ValueObject<JString>(operationResponse.getParameterForCode(ParameterCode::URI_PATH)); Common::JString* uriPath = uriPathObj.getDataAddress(); ValueObject<Dictionary<Object, Object> > returnDataObj = ValueObject<Dictionary<Object, Object> >(operationResponse.getParameterForCode(ParameterCode::RPC_CALL_PARAMS)); Dictionary<Object, Object>* returnData = returnDataObj.getDataAddress(); mListener.webRpcReturn(operationResponse.getReturnCode(), operationResponse.getDebugMessage(), uriPath?*uriPath:JString(), returnCode, returnData?*returnData:Dictionary<Object, Object>()); } break; default: break; } } void Client::onStatusChanged(int statusCode) { switch(statusCode) { case StatusCode::CONNECT: { if(mState == PeerStates::ConnectingToNameserver) { EGLOG(DebugLevel::INFO, L"connected to nameserver"); mState = PeerStates::ConnectedToNameserver; } else if(mState == PeerStates::ConnectingToGameserver) { EGLOG(DebugLevel::INFO, L"connected to gameserver"); mState = PeerStates::ConnectedToGameserver; } else { EGLOG(DebugLevel::INFO, L"connected to masterserver"); mState = mState == PeerStates::Connecting ? PeerStates::Connected : PeerStates::ConnectedComingFromGameserver; } if(SEND_AUTHENTICATE_ENCRYPTED) mPeer.establishEncryption(); else if(mState == PeerStates::ConnectedToNameserver) mPeer.opGetRegions(false, mAppID); else mPeer.opAuthenticate(mAppID, mAppVersion, false, getLocalPlayer().getName(), mAuthenticationValues, mAutoLobbyStats); // secret is encrypted anyway break; } break; case StatusCode::DISCONNECT: { mIsFetchingFriendList = false; if(mState == PeerStates::DisconnectingFromNameserver) { mPeer.connect(mMasterserver); mState = PeerStates::Connecting; } else if(mState == PeerStates::DisconnectingFromMasterserver) { mPeer.connect(mGameserver); mState = PeerStates::ConnectingToGameserver; } else if(mState == PeerStates::DisconnectingFromGameserver) { mPeer.connect(mMasterserver); mState = PeerStates::ConnectingToMasterserver; } else { mState = PeerStates::PeerCreated; mListener.disconnectReturn(); } } break; case StatusCode::ENCRYPTION_ESTABLISHED: if(mState == PeerStates::ConnectedToNameserver) mPeer.opGetRegions(true, mAppID); else mPeer.opAuthenticate(mAppID, mAppVersion, true, getLocalPlayer().getName(), mAuthenticationValues, mAutoLobbyStats); break; case StatusCode::ENCRYPTION_FAILED_TO_ESTABLISH: handleConnectionFlowError(mState, statusCode, "Encryption failed to establish"); break; // cases till next break should set mDisconnectedCause below case StatusCode::EXCEPTION: case StatusCode::EXCEPTION_ON_CONNECT: case StatusCode::INTERNAL_RECEIVE_EXCEPTION: case StatusCode::TIMEOUT_DISCONNECT: case StatusCode::DISCONNECT_BY_SERVER: case StatusCode::DISCONNECT_BY_SERVER_USER_LIMIT: case StatusCode::DISCONNECT_BY_SERVER_LOGIC: mListener.connectionErrorReturn(statusCode); if(mPeer.getPeerState() != PeerState::DISCONNECTED && mPeer.getPeerState() != PeerState::DISCONNECTING) disconnect(); break; case StatusCode::SEND_ERROR: mListener.clientErrorReturn(statusCode); break; case QUEUE_OUTGOING_RELIABLE_WARNING: case QUEUE_OUTGOING_UNRELIABLE_WARNING: case QUEUE_OUTGOING_ACKS_WARNING: case QUEUE_INCOMING_RELIABLE_WARNING: case QUEUE_INCOMING_UNRELIABLE_WARNING: case QUEUE_SENT_WARNING: mListener.warningReturn(statusCode); break; case ErrorCode::OPERATION_INVALID: case ErrorCode::INTERNAL_SERVER_ERROR: mListener.serverErrorReturn(statusCode); break; default: EGLOG(DebugLevel::ERRORS, L"received unknown status-code from server"); break; } // above cases starting from StatusCode::EXCEPTION till next break should set mDisconnectedCause here switch(statusCode) { case StatusCode::DISCONNECT_BY_SERVER_USER_LIMIT: mDisconnectedCause = DisconnectCause::DISCONNECT_BY_SERVER_USER_LIMIT; break; case StatusCode::EXCEPTION_ON_CONNECT: mDisconnectedCause = DisconnectCause::EXCEPTION_ON_CONNECT; break; case StatusCode::DISCONNECT_BY_SERVER: mDisconnectedCause = DisconnectCause::DISCONNECT_BY_SERVER; break; case StatusCode::DISCONNECT_BY_SERVER_LOGIC: mDisconnectedCause = DisconnectCause::DISCONNECT_BY_SERVER_LOGIC; break; case StatusCode::TIMEOUT_DISCONNECT: mDisconnectedCause = DisconnectCause::TIMEOUT_DISCONNECT; break; case StatusCode::EXCEPTION: case StatusCode::INTERNAL_RECEIVE_EXCEPTION: mDisconnectedCause = DisconnectCause::EXCEPTION; break; } } void Client::onEvent(const EventData& eventData) { EGLOG(DebugLevel::INFO, L"%ls", eventData.toString().cstr()); // don't print out the payload here, as that can get too expensive for big events switch(eventData.getCode()) { case EventCode::ROOM_LIST: { for(unsigned int i=0; i<mRoomList.getSize(); ++i) destroyRoom(mRoomList[i]); mRoomList.removeAllElements(); mRoomNameList.removeAllElements(); Hashtable roomList = ValueObject<Hashtable>(eventData.getParameterForCode(ParameterCode::ROOM_LIST)).getDataCopy(); const JVector<Object>& keys = roomList.getKeys(); JString roomNameValue; for(unsigned int i=0 ; i<keys.getSize(); ++i) { roomNameValue = KeyObject<JString>(keys[i]).getDataCopy(); mRoomList.addElement(createRoom(roomNameValue, ValueObject<Hashtable>(roomList.getValue(keys[i])).getDataCopy())); mRoomNameList.addElement(roomNameValue); } mListener.onRoomListUpdate(); } break; case EventCode::ROOM_LIST_UPDATE: { Hashtable roomListUpdate(ValueObject<Hashtable>(eventData.getParameterForCode(ParameterCode::ROOM_LIST)).getDataCopy()); const JVector<Object>& keys = roomListUpdate.getKeys(); for(unsigned int i=0; i<keys.getSize(); i++) { Hashtable val(ValueObject<Hashtable>(roomListUpdate.getValue(keys[i])).getDataCopy()); bool removed = ValueObject<bool>(val.getValue(static_cast<nByte>(Properties::Room::REMOVED))).getDataCopy(); int index = mRoomNameList.getIndexOf(KeyObject<JString>(keys[i]).getDataCopy()); if(!removed) { if(index == -1) //add room { JString roomNameValue = KeyObject<JString>(keys[i]).getDataCopy(); mRoomList.addElement(createRoom(roomNameValue, val)); mRoomNameList.addElement(roomNameValue); } else // update room (only entries, which have been changed, have been sent) RoomPropertiesCacher::cache(*mRoomList[index], val); } else if(index > -1) // remove room { destroyRoom(mRoomList[index]); mRoomList.removeElementAt(index); mRoomNameList.removeElementAt(index); } } mListener.onRoomListUpdate(); } break; case EventCode::APP_STATS: { mPeerCount = ValueObject<int>(eventData.getParameterForCode(ParameterCode::PEER_COUNT)).getDataCopy(); mRoomCount = ValueObject<int>(eventData.getParameterForCode(ParameterCode::ROOM_COUNT)).getDataCopy(); mMasterPeerCount = ValueObject<int>(eventData.getParameterForCode(ParameterCode::MASTER_PEER_COUNT)).getDataCopy(); mListener.onAppStatsUpdate(); } break; case EventCode::LOBBY_STATS: { ValueObject<JString*> namesList = eventData.getParameterForCode(ParameterCode::LOBBY_NAME); ValueObject<nByte*> typesList = eventData.getParameterForCode(ParameterCode::LOBBY_TYPE); ValueObject<int*> peersList = eventData.getParameterForCode(ParameterCode::PEER_COUNT); ValueObject<int*> roomsList = eventData.getParameterForCode(ParameterCode::ROOM_COUNT); JString* names = *namesList.getDataAddress(); nByte* types = *typesList.getDataAddress(); int* peers = *peersList.getDataAddress(); int* rooms = *roomsList.getDataAddress(); JVector<LobbyStatsResponse> res; for(int i=0; i<*namesList.getSizes(); ++i) res.addElement(LobbyStatsResponse(names[i], types[i], peers[i], rooms[i])); mListener.onLobbyStatsUpdate(res); } break; case EventCode::JOIN: { int nr = ValueObject<int>(eventData.getParameterForCode(ParameterCode::PLAYERNR)).getDataCopy(); if(nr != getLocalPlayer().getNumber()) // the local player already got added in onOperationResponse cases OperationCode::CREATE_ROOM / OperationCode::JOIN_ROOM PlayerMovementInformant::onEnterRemote(getCurrentlyJoinedRoom(), nr, ValueObject<Hashtable>(eventData.getParameterForCode(ParameterCode::PLAYER_PROPERTIES)).getDataCopy()); Object playersObj = eventData.getParameterForCode(ParameterCode::PLAYER_LIST); int* players = ValueObject<int*>(playersObj).getDataCopy(); JVector<int> playerArr; int* playersPtr = players; for(int i=0 ; i<playersObj.getSizes()[0] ; ++i, playersPtr++) playerArr.addElement(*playersPtr); mListener.joinRoomEventAction(nr, playerArr, *getCurrentlyJoinedRoom().getPlayerForNumber(nr)); deallocateArray(players); } break; case EventCode::LEAVE: { ValueObject<int> nr = eventData.getParameterForCode(ParameterCode::PLAYERNR); ValueObject<bool> isInactive = eventData.getParameterForCode(ParameterCode::IS_INACTIVE); if(isInactive.getDataCopy()) { if(!PlayerPropertiesUpdateInformant::setIsInactive(*mpCurrentlyJoinedRoom, nr.getDataCopy(), true)) EGLOG(DebugLevel::WARNINGS, L"EventCode::LEAVE - player %d who is leaving the room, has not been found in list of players, who are currently in the room", nr.getDataCopy()); } else if(!PlayerMovementInformant::onLeaveRemote(getCurrentlyJoinedRoom(), nr.getDataCopy())) EGLOG(DebugLevel::WARNINGS, L"EventCode::LEAVE - player %d who is leaving the room, has not been found in list of players, who are currently in the room", nr.getDataCopy()); mListener.leaveRoomEventAction(nr.getDataCopy(), isInactive.getDataCopy()); } break; case EventCode::DISCONNECT: { ValueObject<int> nr = eventData.getParameterForCode(ParameterCode::PLAYERNR); if(!PlayerPropertiesUpdateInformant::setIsInactive(*mpCurrentlyJoinedRoom, nr.getDataCopy(), true)) EGLOG(DebugLevel::WARNINGS, L"EventCode::DISCONNECT - player %d who is diconnecting the room, has not been found in list of players, who are currently in the room", nr.getDataCopy()); mListener.disconnectEventAction(nr.getDataCopy()); } case EventCode::PROPERTIES_CHANGED: { ValueObject<int> target = eventData.getParameterForCode(ParameterCode::TARGET_PLAYERNR); Hashtable playerProperties; Hashtable roomProperties; if(target.getDataCopy()) playerProperties = ValueObject<Hashtable>(eventData.getParameterForCode(ParameterCode::PROPERTIES)).getDataCopy(); else roomProperties = ValueObject<Hashtable>(eventData.getParameterForCode(ParameterCode::PROPERTIES)).getDataCopy(); readoutProperties(roomProperties, playerProperties, false, target.getDataCopy()); if(playerProperties.getSize()) mListener.onPlayerPropertiesChange(target.getDataCopy(), playerProperties); else mListener.onRoomPropertiesChange(roomProperties); } break; case EventCode::CACHE_SLICE_CHANGED: mListener.onCacheSliceChanged(ValueObject<int>(eventData.getParameterForCode(ParameterCode::CACHE_SLICE_INDEX)).getDataCopy()); break; default: // custom events are forwarded to the app { ValueObject<int> nr = eventData.getParameterForCode(ParameterCode::PLAYERNR); // all custom event data is stored at ParameterCode::DATA mListener.customEventAction(nr.getDataCopy(), eventData.getCode(), eventData.getParameterForCode(ParameterCode::DATA)); } break; } } void Client::debugReturn(DebugLevel::DebugLevel debugLevel, const JString& string) { mListener.debugReturn(debugLevel, string); } bool Client::getIsOnGameServer(void) const { return mState >= PeerStates::ConnectingToGameserver && mState < PeerStates::ConnectingToMasterserver; } void Client::readoutProperties(Hashtable& roomProperties, Hashtable& playerProperties, bool multiplePlayers, int targetPlayerNr) { if(roomProperties.getSize()) { RoomPropertiesCacher::cache(*mpCurrentlyJoinedRoom, roomProperties); roomProperties = Utils::stripKeysWithNullValues(Utils::stripToCustomProperties(roomProperties)); } if(playerProperties.getSize()) { for(unsigned int i=0; i<(multiplePlayers?playerProperties.getSize():1); ++i) PlayerPropertiesUpdateInformant::onUpdate(*mpCurrentlyJoinedRoom, multiplePlayers?ValueObject<int>(playerProperties.getKeys()[i]).getDataCopy():targetPlayerNr, multiplePlayers?ValueObject<Hashtable>(playerProperties[i]).getDataCopy():playerProperties); if(multiplePlayers) for(unsigned int i=0; i<playerProperties.getSize(); ++i) playerProperties[i] = ValueObject<Hashtable>(Utils::stripKeysWithNullValues(Utils::stripToCustomProperties(ValueObject<Hashtable>(playerProperties[i]).getDataCopy()))); else playerProperties = Utils::stripKeysWithNullValues(Utils::stripToCustomProperties(playerProperties)); } } void Client::handleConnectionFlowError(PeerStates::PeerStates oldState, int errorCode, const JString& errorString) { if(oldState == PeerStates::ConnectedToGameserver || oldState == PeerStates::AuthenticatedOnGameServer || oldState == PeerStates::Joining) { mCachedErrorCodeFromGameServer = errorCode; mCachedErrorStringFromGameServer = errorString; mState = PeerStates::DisconnectingFromGameserver; mPeer.disconnect(); // response to app has to wait until back on master } else { mState = PeerStates::Disconnecting; mPeer.disconnect(); mListener.connectReturn(errorCode, errorString); } } bool Client::opAuthenticate(const JString& appID, const JString& appVersion, bool encrypted, const JString& userID) { return mPeer.opAuthenticate(appID, appVersion, encrypted, userID); } bool Client::opChangeGroups(const JVector<nByte>* pGroupsToRemove, const JVector<nByte>* pGroupsToAdd) { if(!getIsInGameRoom()) return false; return mPeer.opChangeGroups(pGroupsToRemove, pGroupsToAdd); } bool Client::opGetRegions(bool encrypted, const JString& appID) { return mPeer.opGetRegions(encrypted, appID); } bool Client::opWebRpc(const JString& uriPath, const Object& parameters) { return mPeer.opWebRpc(uriPath, parameters); } bool Client::opSetPropertiesOfPlayer(int playerNr, const Hashtable& properties) { if(!getIsInGameRoom()) return false; return mPeer.opSetPropertiesOfPlayer(playerNr, properties); } bool Client::opSetPropertiesOfRoom(const Hashtable& properties, bool webForward) { if(!getIsInGameRoom()) return false; return mPeer.opSetPropertiesOfRoom(properties, webForward); } void Client::onConnectToMasterFinished(bool comingFromGameserver) { if(comingFromGameserver) { if(mCachedErrorCodeFromGameServer) { switch(mLastJoinType) { case JoinType::CREATE_ROOM: mListener.createRoomReturn(0, Hashtable(), Hashtable(), mCachedErrorCodeFromGameServer, mCachedErrorStringFromGameServer); break; case JoinType::JOIN_ROOM: mListener.joinRoomReturn(0, Hashtable(), Hashtable(), mCachedErrorCodeFromGameServer, mCachedErrorStringFromGameServer); break; case JoinType::JOIN_RANDOM_ROOM: mListener.joinRandomRoomReturn(0, Hashtable(), Hashtable(), mCachedErrorCodeFromGameServer, mCachedErrorStringFromGameServer); break; default: EGLOG(DebugLevel::ERRORS, L"unexpected cached join type value"); break; } mCachedErrorCodeFromGameServer = LoadBalancing::ErrorCode::OK; mCachedErrorStringFromGameServer = L""; } else mListener.leaveRoomReturn(0, L""); } else mListener.connectReturn(0, L""); } MutablePlayer* Client::createMutablePlayer(int number, const Hashtable& properties) { mpMutablePlayerFactory = getMutablePlayerFactory(); return mpMutablePlayerFactory->create(number, properties, mpCurrentlyJoinedRoom, this); } void Client::destroyMutablePlayer(const MutablePlayer* pPlayer) const { if(pPlayer) mpMutablePlayerFactory->destroy(pPlayer); } Room* Client::createRoom(const JString& name, const Hashtable& properties) { return RoomFactory::create(name, properties); } void Client::destroyRoom(const Room* pRoom) const { RoomFactory::destroy(pRoom); } MutableRoom* Client::createMutableRoom(const JString& name, const Hashtable& properties, const JVector<JString>& propsListedInLobby, int playerTtl, int roomTtl) { mpMutableRoomFactory = getMutableRoomFactory(); return mpMutableRoomFactory->create(name, properties, this, propsListedInLobby, playerTtl, roomTtl); } void Client::destroyMutableRoom(const MutableRoom* pRoom) const { if(pRoom) mpMutableRoomFactory->destroy(pRoom); } MutablePlayerFactory* Client::getMutablePlayerFactory(void) const { static MutablePlayerFactory fac; return &fac; } MutableRoomFactory* Client::getMutableRoomFactory(void) const { static MutableRoomFactory fac; return &fac; } } }
38.4354
339
0.712426
h-iwata
b59135669105fd4a36aa4c9375d01013c66f8760
934
cpp
C++
Searching/Linear_search.cpp
calmesam01/Algorithms
c3b137b0c0bbd43cb542b12e0d8a6f91a3c06138
[ "MIT" ]
5
2017-05-19T12:21:19.000Z
2021-12-09T10:35:37.000Z
Searching/Linear_search.cpp
calmesam01/Algorithms
c3b137b0c0bbd43cb542b12e0d8a6f91a3c06138
[ "MIT" ]
null
null
null
Searching/Linear_search.cpp
calmesam01/Algorithms
c3b137b0c0bbd43cb542b12e0d8a6f91a3c06138
[ "MIT" ]
1
2017-06-25T14:16:00.000Z
2017-06-25T14:16:00.000Z
/*Linear search algo to search all the elements linearly Author = Satyam Complexity = O(n) */ //Adding Header files #include<iostream> //Setting std namespace using namespace std; //Main function started int main(){ //Declaring variables int n,arr[50],element; bool a=false; cout << "How many numbers do you want to enter = "; cin >> n; //Entering the elements in array cout << "\nEnter the numbers:"<<endl; for (int i=0;i<n;i++){ cout << i+1 << ".)\t"; cin >> arr[i]; cout << endl; } //Searching the elemets linearly cout << "Enter the element to search = "; cin >> element; for(int i=0;i<n;i++){ if(element == arr[i]){ cout << "\nElement found at location " << i+1 << endl ; a = true; } } //If element not found if(a == false){ cout << "\nElement not found"; } return 0; }
21.227273
67
0.542827
calmesam01
b592ac04d0c6e8556a31843c576619a0e3b4a3bb
8,404
cpp
C++
source/Library/Numeric/LongInt.cpp
dracc/VCMP-SqMod
d3e6adea147f5b2cae5119ddd6028833aa625c09
[ "MIT" ]
null
null
null
source/Library/Numeric/LongInt.cpp
dracc/VCMP-SqMod
d3e6adea147f5b2cae5119ddd6028833aa625c09
[ "MIT" ]
null
null
null
source/Library/Numeric/LongInt.cpp
dracc/VCMP-SqMod
d3e6adea147f5b2cae5119ddd6028833aa625c09
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------------------------------------ #include "Library/Numeric/LongInt.hpp" #include "Library/Numeric/Random.hpp" #include "Base/Shared.hpp" #include "Base/DynArg.hpp" // ------------------------------------------------------------------------------------------------ #include <cstdio> #include <cerrno> #include <cstdlib> // ------------------------------------------------------------------------------------------------ namespace SqMod { // ------------------------------------------------------------------------------------------------ SQMODE_DECL_TYPENAME(TypenameS, _SC("SLongInt")) SQMODE_DECL_TYPENAME(TypenameU, _SC("ULongInt")) // ------------------------------------------------------------------------------------------------ LongInt< Int64 >::LongInt(CSStr text) : m_Data(0), m_Text() { m_Data = std::strtoll(text, nullptr, 10); } // ------------------------------------------------------------------------------------------------ LongInt< Int64 >::LongInt(CSStr text, Uint32 base) : m_Data(0), m_Text() { m_Data = std::strtoll(text, nullptr, base); } // ------------------------------------------------------------------------------------------------ LongInt< Int64 > & LongInt< Int64 >::operator = (CSStr text) { m_Data = std::strtoll(text, nullptr, 10); return *this; } // ------------------------------------------------------------------------------------------------ CSStr LongInt< Int64 >::ToString() { if (std::snprintf(m_Text, sizeof(m_Text), "%llu", m_Data) < 0) { m_Text[0] = 0; } return m_Text; } // ------------------------------------------------------------------------------------------------ void LongInt< Int64 >::Random() { m_Data = GetRandomInt64(); } // ------------------------------------------------------------------------------------------------ void LongInt< Int64 >::Random(Type n) { m_Data = GetRandomInt64(n); } // ------------------------------------------------------------------------------------------------ void LongInt< Int64 >::Random(Type m, Type n) { m_Data = GetRandomInt64(m, n); } // ------------------------------------------------------------------------------------------------ LongInt< Uint64 >::LongInt(CSStr text) : m_Data(0), m_Text() { m_Data = std::strtoull(text, nullptr, 10); } // ------------------------------------------------------------------------------------------------ LongInt< Uint64 >::LongInt(CSStr text, Uint32 base) : m_Data(0), m_Text() { m_Data = std::strtoull(text, nullptr, base); } // ------------------------------------------------------------------------------------------------ LongInt< Uint64 > & LongInt< Uint64 >::operator = (CSStr text) { m_Data = std::strtoull(text, nullptr, 10); return *this; } // ------------------------------------------------------------------------------------------------ CSStr LongInt< Uint64 >::ToString() { if (std::snprintf(m_Text, sizeof(m_Text), "%llu", m_Data) < 0) { m_Text[0] = 0; } return m_Text; } // ------------------------------------------------------------------------------------------------ void LongInt< Uint64 >::Random() { m_Data = GetRandomUint64(); } // ------------------------------------------------------------------------------------------------ void LongInt< Uint64 >::Random(Type n) { m_Data = GetRandomUint64(n); } // ------------------------------------------------------------------------------------------------ void LongInt< Uint64 >::Random(Type m, Type n) { m_Data = GetRandomUint64(m, n); } // ================================================================================================ void Register_LongInt(HSQUIRRELVM vm) { RootTable(vm).Bind(TypenameS::Str, Class< SLongInt >(vm, TypenameS::Str) // Constructors .Ctor() .Ctor< SLongInt::Type >() .template Ctor< CCStr, SQInteger >() // Properties .Prop(_SC("Str"), &SLongInt::GetCStr, &SLongInt::SetStr) .Prop(_SC("Num"), &SLongInt::GetSNum, &SLongInt::SetNum) // Core Meta-methods .SquirrelFunc(_SC("cmp"), &SqDynArgFwd< SqDynArgCmpFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >) .SquirrelFunc(_SC("_typename"), &TypenameS::Fn) .Func(_SC("_tostring"), &SLongInt::ToString) // Core Functions .Func(_SC("tointeger"), &SLongInt::ToSqInteger) .Func(_SC("tofloat"), &SLongInt::ToSqFloat) .Func(_SC("tostring"), &SLongInt::ToSqString) .Func(_SC("tobool"), &SLongInt::ToSqBool) .Func(_SC("tochar"), &SLongInt::ToSqChar) // Meta-methods .SquirrelFunc(_SC("_add"), &SqDynArgFwd< SqDynArgAddFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >) .SquirrelFunc(_SC("_sub"), &SqDynArgFwd< SqDynArgSubFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >) .SquirrelFunc(_SC("_mul"), &SqDynArgFwd< SqDynArgMulFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >) .SquirrelFunc(_SC("_div"), &SqDynArgFwd< SqDynArgDivFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >) .SquirrelFunc(_SC("_modulo"), &SqDynArgFwd< SqDynArgModFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >) .Func< SLongInt (SLongInt::*)(void) const >(_SC("_unm"), &SLongInt::operator -) // Functions .Func(_SC("GetStr"), &SLongInt::GetCStr) .Func(_SC("SetStr"), &SLongInt::SetStr) .Func(_SC("GetNum"), &SLongInt::GetSNum) .Func(_SC("SetNum"), &SLongInt::SetNum) // Overloads .Overload< void (SLongInt::*)(void) >(_SC("Random"), &SLongInt::Random) .Overload< void (SLongInt::*)(SLongInt::Type) >(_SC("Random"), &SLongInt::Random) .Overload< void (SLongInt::*)(SLongInt::Type, SLongInt::Type) >(_SC("Random"), &SLongInt::Random) ); RootTable(vm).Bind(TypenameU::Str, Class< ULongInt >(vm, TypenameU::Str) // Constructors .Ctor() .Ctor< ULongInt::Type >() .Ctor< CCStr, SQInteger >() // Properties .Prop(_SC("Str"), &ULongInt::GetCStr, &ULongInt::SetStr) .Prop(_SC("Num"), &ULongInt::GetSNum, &ULongInt::SetNum) // Core Meta-methods .SquirrelFunc(_SC("cmp"), &SqDynArgFwd< SqDynArgCmpFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >) .SquirrelFunc(_SC("_typename"), &TypenameU::Fn) .Func(_SC("_tostring"), &ULongInt::ToString) // Core Functions .Func(_SC("tointeger"), &ULongInt::ToSqInteger) .Func(_SC("tofloat"), &ULongInt::ToSqFloat) .Func(_SC("tostring"), &ULongInt::ToSqString) .Func(_SC("tobool"), &ULongInt::ToSqBool) .Func(_SC("tochar"), &ULongInt::ToSqChar) // Meta-methods .SquirrelFunc(_SC("_add"), &SqDynArgFwd< SqDynArgAddFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >) .SquirrelFunc(_SC("_sub"), &SqDynArgFwd< SqDynArgSubFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >) .SquirrelFunc(_SC("_mul"), &SqDynArgFwd< SqDynArgMulFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >) .SquirrelFunc(_SC("_div"), &SqDynArgFwd< SqDynArgDivFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >) .SquirrelFunc(_SC("_modulo"), &SqDynArgFwd< SqDynArgModFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >) .Func< ULongInt (ULongInt::*)(void) const >(_SC("_unm"), &ULongInt::operator -) // Functions .Func(_SC("GetStr"), &ULongInt::GetCStr) .Func(_SC("SetStr"), &ULongInt::SetStr) .Func(_SC("GetNum"), &ULongInt::GetSNum) .Func(_SC("SetNum"), &ULongInt::SetNum) // Overloads .Overload< void (ULongInt::*)(void) >(_SC("Random"), &ULongInt::Random) .Overload< void (ULongInt::*)(ULongInt::Type) >(_SC("Random"), &ULongInt::Random) .Overload< void (ULongInt::*)(ULongInt::Type, ULongInt::Type) >(_SC("Random"), &ULongInt::Random) ); } } // Namespace:: SqMod
42.444444
149
0.486435
dracc
b5976e5b63e16087f73c50ef909cff93f019e8ee
3,604
cpp
C++
160. Intersection of Two Linked Lists.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
160. Intersection of Two Linked Lists.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
160. Intersection of Two Linked Lists.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
/* Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to intersect at node c1. Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 Output: Reference of the node with value = 8 Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. Example 2: Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Reference of the node with value = 2 Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: null Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. Solution one is an intutive solution, solution is interesting */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *curA = headA; ListNode *curB = headB; int ct1 = 0; int ct2 = 0; while ( curA ) { ct1++; curA = curA->next; } while ( curB ) { ct2++; curB = curB->next; } curA = headA; curB = headB; if ( ct1 > ct2 ) { for ( int i = 0; i < ct1 - ct2; i++ ) { curA = curA->next; } } else if ( ct1 < ct2 ) { for ( int i = 0; i < ct2 - ct1; i++ ) { curB = curB->next; } } while ( curA && curB ) { if ( curA == curB ) return curA; curA = curA->next; curB = curB->next; } return nullptr; } }; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *curA = headA; ListNode *res; while ( curA ) { curA->val = -curA->val; curA = curA->next; } curA = headB; while ( curA ) { if ( curA->val < 0 ) { res = curA; break; } curA = curA->next; } curA = headA; while ( curA ) { curA->val = -curA->val; curA = curA->next; } return res; } };
27.937984
307
0.549945
NeoYY
b598a37351cc6a8f1b27572dc377a2b943fccdec
702
cpp
C++
src/Main.cpp
PetokLorand/ETL
9aebbd4044a1604813163b1104aa5d4d017befa9
[ "MIT" ]
null
null
null
src/Main.cpp
PetokLorand/ETL
9aebbd4044a1604813163b1104aa5d4d017befa9
[ "MIT" ]
null
null
null
src/Main.cpp
PetokLorand/ETL
9aebbd4044a1604813163b1104aa5d4d017befa9
[ "MIT" ]
null
null
null
#include <iostream> #include "ExpressionTemplates.hpp" #include "Argument.hpp" class Scalar : public et::BaseExpression<Scalar> , public et::AdditionExpressionGenerator<Scalar> { public: Scalar(int value) : m_value(value) {} et::Int32Expression operator()(auto&&) { return m_value; } private: int m_value; }; int main() { using namespace et::literals; { Argument x(10); Argument y(5); Argument z(2); auto result = (x * y - x / z)[3_u64]; std::cout << result() << std::endl; } // auto result = (Argument{2} + Argument{3})[1_u64]; // std::cout << result() << std::endl; Argument::print(); return 0; }
18.972973
62
0.579772
PetokLorand
b59d061bdf40f8b2cf48f1fd6efb78107245da4a
6,542
cc
C++
modules/drivers/apriltags/april_tags.cc
positionering/apollo
53d961f054f8a1c2e647337d5b0108985e289d38
[ "Apache-2.0" ]
1
2019-05-14T18:36:40.000Z
2019-05-14T18:36:40.000Z
modules/drivers/apriltags/april_tags.cc
positionering/apollo
53d961f054f8a1c2e647337d5b0108985e289d38
[ "Apache-2.0" ]
null
null
null
modules/drivers/apriltags/april_tags.cc
positionering/apollo
53d961f054f8a1c2e647337d5b0108985e289d38
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/drivers/apriltags/april_tags.h" #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <iterator> #include <vector> #include "cyber/cyber.h" #include <fcntl.h> #include <sys/ioctl.h> #include <termios.h> #include <cstdlib> #include <iostream> #include <errno.h> #include "cyber/time/rate.h" #include "cyber/time/time.h" #include "modules/drivers/apriltags/proto/aprilTags.pb.h" #include <memory> #include <vector> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> #include "modules/drivers/proto/sensor_image.pb.h" using apollo::cyber::Rate; using apollo::cyber::Time; using apollo::drivers::Image; using apollo::modules::drivers::apriltags::proto::apriltags; extern "C" { #include <apriltag/apriltag.h> #include <apriltag/apriltag_pose.h> #include <apriltag/common/getopt.h> #include <apriltag/tag16h5.h> #include <apriltag/tag25h9.h> #include <apriltag/tag36h11.h> #include <apriltag/tagCircle21h7.h> #include <apriltag/tagCircle49h12.h> #include <apriltag/tagCustom48h12.h> #include <apriltag/tagStandard41h12.h> #include <apriltag/tagStandard52h13.h> } cv::Mat image; void MessageCallback( const std::shared_ptr<apollo::drivers::CompressedImage> &compressed_image) { std::vector<uint8_t> compressed_raw_data(compressed_image->data().begin(), compressed_image->data().end()); cv::Mat mat_image = cv::imdecode(compressed_raw_data, CV_LOAD_IMAGE_COLOR); cv::cvtColor(mat_image, mat_image, CV_BGR2RGB); image = mat_image; } bool aprilTags::Init() { // AERROR << "Commontest component init"; auto listener_node = apollo::cyber::CreateNode("listener_cam"); // create listener auto listener = listener_node->CreateReader<apollo::drivers::CompressedImage>( "/apollo/sensor/camera/front_6mm/image/compressed", MessageCallback); auto talker_node_apriltags = apollo::cyber::CreateNode("apriltags_node"); // create talker auto talker_apriltags = talker_node_apriltags->CreateWriter<apriltags>("channel/apriltags"); apriltag_detector_t *td = apriltag_detector_create(); apriltag_family_t *tf = tag36h11_create(); apriltag_pose_t pose; apriltag_detector_add_family(td, tf); td->quad_decimate = 2.0; td->quad_sigma = 0; td->refine_edges = 1; td->decode_sharpening = 0.25; cv::Mat frame, gray; int tagId, detec; double x, y, z, x_old, y_old, z_old, x_filt, y_filt, z_filt, phi; double alpha = 0.1; bool first = true; while (apollo::cyber::OK()) { tagId = 0; detec = 0; if (image.data) { frame = image; cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); image_u8_t im = {.width = gray.cols, .height = gray.rows, .stride = gray.cols, .buf = gray.data}; zarray_t *detections = apriltag_detector_detect(td, &im); // Draw detection outlines for (int i = 0; i < zarray_size(detections); i++) { apriltag_detection_t *det; zarray_get(detections, i, &det); tagId = det->id; // First create an apriltag_detection_info_t struct using your known // parameters. apriltag_detection_info_t info; info.det = det; info.tagsize = 0.1615; // size april tag (88 mm liten, 185 mm stor) (0.1615 stor?) info.fx = 1660.70; // 1394.33; // 1983.97376; info.fy = 1668.19; // 1394.95; // 1981.62916; info.cx = 886.07; // 964.117; // 998.341216; info.cy = 522.40; // 537.659; // 621.618227; // Then call estimate_tag_pose. double err = estimate_tag_pose(&info, &pose); if (err < 5e0) { detec = 1; x = pose.t->data[0]; y = pose.t->data[1]; z = pose.t->data[2]; // phi = // atan2(-pose.R->data[6],sqrt(pose.R->data[7]*pose.R->data[7]+pose.R->data[8]*pose.R->data[8])); // x = cos(phi)*x-sin(phi)*z; // z = sin(phi)*x+cos(phi)*z; // complementary filter if (first) { first = false; x_old = x; y_old = y; z_old = z; } else { x_filt = x * alpha + (1 - alpha) * x_old; x_old = x_filt; y_filt = y * alpha + (1 - alpha) * y_old; y_old = y_filt; z_filt = z * alpha + (1 - alpha) * z_old; z_old = z_filt; } // AERROR << "ERROR is this ---> " << err; // AERROR << "X is this ---> " << x; // AERROR << "Y is this ---> " << y; // AERROR << "Z is this ---> " << z; } // AERROR << "Z: " << z << " Z_filt: " << z_filt << " X: " << x // << " X_filt: " << x_filt << " Phi " << phi // << " Time: " << Time::Now().ToNanosecond(); } zarray_destroy(detections); } auto msg = std::make_shared<apriltags>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_detec(detec); msg->set_tag_id(tagId); msg->set_x(x); msg->set_y(y); msg->set_z(z); msg->set_angle_offset(phi); if (detec) { msg->mutable_rots()->Reserve(9); for (int i = 0; i < 9; i++) { msg->add_rots(pose.R->data[i]); } } talker_apriltags->Write(msg); } apriltag_detector_destroy(td); tag36h11_destroy(tf); return true; } bool aprilTags::Proc(const std::shared_ptr<Driver> &msg0, const std::shared_ptr<Driver> &msg1) { // AINFO << "Start common component Proc [" << msg0->msg_id() << "] [" // << msg1->msg_id() << "]"; return true; }
30.427907
108
0.594314
positionering
b5a06157c1baed2af9b30832f44c7454a5951ec9
403
cpp
C++
duration.cpp
kuldeep3/C-Programming-
86db928902c752434cce417eae846d6a6384ae31
[ "MIT" ]
1
2019-09-14T17:59:11.000Z
2019-09-14T17:59:11.000Z
duration.cpp
kuldeep3/C-Programming-
86db928902c752434cce417eae846d6a6384ae31
[ "MIT" ]
null
null
null
duration.cpp
kuldeep3/C-Programming-
86db928902c752434cce417eae846d6a6384ae31
[ "MIT" ]
3
2019-10-01T15:51:17.000Z
2019-10-02T16:31:08.000Z
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while (n--) { int sh,sm,eh,em,min,hr; cin>>sh>>sm>>eh>>em; if (em<sm) { em = em+60; min = em-sm; eh = eh - 1; } else { min = em-sm; } hr = eh-sh; cout<<hr<<" "<<min<<endl; } }
16.12
33
0.334988
kuldeep3
b5a0d7048547191ff3f7eeabb7147f26ef9b0c1b
5,403
cpp
C++
libs/unicode/src/utf/utf32_codecvt.cpp
cordarei/boost-unicode
edfe39ff623c286cb157c7495ffeeee4dfd2d319
[ "BSL-1.0" ]
1
2019-02-26T07:46:39.000Z
2019-02-26T07:46:39.000Z
libs/unicode/src/utf/utf32_codecvt.cpp
cordarei/boost-unicode
edfe39ff623c286cb157c7495ffeeee4dfd2d319
[ "BSL-1.0" ]
null
null
null
libs/unicode/src/utf/utf32_codecvt.cpp
cordarei/boost-unicode
edfe39ff623c286cb157c7495ffeeee4dfd2d319
[ "BSL-1.0" ]
null
null
null
// Define a UTF-32 codecvt fact. // Though this file is under the Boost license, it is NOT (or not yet) part of // Boost! // Copyright Graham Barnett, Rogier van Dalen 2005. // Use, modification, and distribution are subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <cassert> #include <boost/unicode/codecvt.hpp> #include <boost/unicode/detail/utf_limits.hpp> namespace boost { namespace unicode { /** Turn a byte sequence in a UTF-32 scheme into codepoints. An ill-formed sequence should result in an error. \todo What about noncharacters? Noncharacters are "U+nFFFE and U+nFFFF (where n is from 0x0 to 0x10) and the values U+FDD0..U+FDEF." These may be deleted, ignored, or signal an error. They are not for external use. */ std::codecvt_base::result utf32be_codecvt::do_in (utf_mbstate & state, const char * from, const char * from_end, const char * & from_next, codepoint * to, codepoint * to_end, codepoint *& to_next) const { // to and from are used to iterate over the buffers // The input buffer must contain at least 4 bytes. while (from + 4 <= from_end && to != to_end) { char32_t ch = char32_t ((unsigned char)(*from)) << 24; ++ from; ch |= char32_t ((unsigned char)(*from)) << 16; ++ from; ch |= char32_t ((unsigned char)(*from)) << 8; ++ from; ch |= char32_t ((unsigned char)(*from)); ++ from; if ((ch >= detail::first_surrogate && ch <= detail::last_surrogate) || ch > max_codepoint) { from_next = from - 4; to_next = to; return std::codecvt_base::error; } *to = ch; ++ to; } from_next = from; to_next = to; if (from == from_end) return std::codecvt_base::ok; else return std::codecvt_base::partial; } std::codecvt_base::result utf32le_codecvt::do_in (utf_mbstate & state, const char * from, const char * from_end, const char * & from_next, codepoint * to, codepoint * to_end, codepoint *& to_next) const { // to and from are used to iterate over the buffers // The input buffer must contain at least 4 bytes. while (from + 4 <= from_end && to != to_end) { char32_t ch = char32_t ((unsigned char)(*from)); ++ from; ch |= char32_t ((unsigned char)(*from)) << 8; ++ from; ch |= char32_t ((unsigned char)(*from)) << 16; ++ from; ch |= char32_t ((unsigned char)(*from)) << 24; ++ from; if ((ch >= detail::first_surrogate && ch <= detail::last_surrogate) || ch > max_codepoint) { from_next = from - 4; to_next = to; return std::codecvt_base::error; } *to = ch; ++ to; } from_next = from; to_next = to; if (from == from_end) return std::codecvt_base::ok; else return std::codecvt_base::partial; } /** Convert a sequence of UTF-32 encoded characters to UTF-16. An error is returned when the input is outside the range of Unicode scalar values: 0x0..0xd7ff, 0xe000..0x10ffff. */ std::codecvt_base::result utf32be_codecvt::do_out (utf_mbstate & state, const codepoint * from, const codepoint * from_end, const codepoint * & from_next, char * to, char * to_end, char * & to_next) const { // to and from are used to iterate over the buffers // The output buffer must contain at least 4 bytes. while (from < from_end && to + 4 <= to_end) { if ((*from >= detail::first_surrogate && *from < detail::last_surrogate) || *from > max_codepoint) { // Invalid codepoint. from_next = from; to_next = to; return std::codecvt_base::error; } *to = char (*from >> 24); ++ to; *to = char (*from >> 16); ++ to; *to = char (*from >> 8); ++ to; *to = char (*from); ++ to; ++ from; } from_next = from; to_next = to; if (from == from_end) return std::codecvt_base::ok; else return std::codecvt_base::partial; } std::codecvt_base::result utf32le_codecvt::do_out (utf_mbstate & state, const codepoint * from, const codepoint * from_end, const codepoint * & from_next, char * to, char * to_end, char * & to_next) const { // to and from are used to iterate over the buffers // The output buffer must contain at least 4 bytes. while (from < from_end && to + 4 <= to_end) { if ((*from >= detail::first_surrogate && *from < detail::last_surrogate) || *from > max_codepoint) { // Invalid codepoint. from_next = from; to_next = to; return std::codecvt_base::error; } *to = char (*from); ++ to; *to = char (*from >> 8); ++ to; *to = char (*from >> 16); ++ to; *to = char (*from >> 24); ++ to; ++ from; } from_next = from; to_next = to; if (from == from_end) return std::codecvt_base::ok; else return std::codecvt_base::partial; } /** Get the number of chars in [from, from_end) that convert to max codepoints. No UTF error checking is done. UTF-32 is a fixed encoding, so this is pretty easy. */ int utf32be_codecvt::do_length (const utf_mbstate & state, const char * from, const char * from_end, std::size_t max) const { if (std::size_t ((from_end - from) / 4) < max) return ((from_end - from) / 4) * 4; else return max * 4; } int utf32le_codecvt::do_length (const utf_mbstate & state, const char * from, const char * from_end, std::size_t max) const { if (std::size_t ((from_end - from) / 4) < max) return ((from_end - from) / 4) * 4; else return max * 4; } } // namespace unicode } // namespace boost
23.38961
78
0.646863
cordarei
b5a286fc25c9eeb226960bc335240f45d42b2bf0
16,543
cc
C++
cpp/tests/test-config-load.cc
peurpdapeurp/ndnrtc
59552bff9398ee2e49636f32cac020cc8027ae04
[ "BSD-2-Clause" ]
null
null
null
cpp/tests/test-config-load.cc
peurpdapeurp/ndnrtc
59552bff9398ee2e49636f32cac020cc8027ae04
[ "BSD-2-Clause" ]
null
null
null
cpp/tests/test-config-load.cc
peurpdapeurp/ndnrtc
59552bff9398ee2e49636f32cac020cc8027ae04
[ "BSD-2-Clause" ]
null
null
null
// // test-config-load.cc // // Created by Peter Gusev on 02 March 2016. // Copyright 2013-2016 Regents of the University of California // #include <stdlib.h> #include "gtest/gtest.h" #include "client/src/config.hpp" #define TEST_CONFIG_FILE "tests/default.cfg" #define TEST_CONFIG_SAMPLE_CONSUMER_FILE "tests/sample-consumer.cfg" #define TEST_CONFIG_SAMPLE_PRODUCER_FILE "tests/sample-producer.cfg" #define TEST_CONFIG_FILE_BAD1 "tests/sample-bad1.cfg" #define TEST_CONFIG_FILE_CA "tests/consumer-audio.cfg" #define TEST_CONFIG_FILE_CV "tests/consumer-video.cfg" using namespace std; TEST(TestConfigLoad, LoadGeneral) { string fileName(TEST_CONFIG_FILE); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); EXPECT_EQ(params.getGeneralParameters().loggingLevel_, ndnlog::NdnLoggerDetailLevelDefault); EXPECT_EQ(params.getGeneralParameters().logFile_, "ndnrtc-client.log"); EXPECT_EQ(params.getGeneralParameters().logPath_, "/tmp"); EXPECT_TRUE(params.getGeneralParameters().useFec_); EXPECT_TRUE(params.getGeneralParameters().useAvSync_); EXPECT_EQ(params.getGeneralParameters().host_, "localhost"); EXPECT_EQ(params.getGeneralParameters().portNum_, 6363); } TEST(TestConfigLoad, LoadGeneralBad) { string fileName(TEST_CONFIG_FILE_BAD1); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_NE(0, loadParamsFromFile(fileName, params, identity)); } TEST(TestConfigLoad, LoadConsumerParams) { string fileName(TEST_CONFIG_FILE); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); EXPECT_EQ(2000, params.getConsumerParams().generalAudioParams_.interestLifetime_); EXPECT_EQ(150, params.getConsumerParams().generalAudioParams_.jitterSizeMs_); EXPECT_EQ(2000, params.getConsumerParams().generalVideoParams_.interestLifetime_); EXPECT_EQ(150, params.getConsumerParams().generalVideoParams_.jitterSizeMs_); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_.size()); EXPECT_EQ("buffer", params.getConsumerParams().statGatheringParams_[0].statFileName_); EXPECT_EQ("playback", params.getConsumerParams().statGatheringParams_[1].statFileName_); EXPECT_EQ("play", params.getConsumerParams().statGatheringParams_[2].statFileName_); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_[0].getStats().size()); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_[1].getStats().size()); EXPECT_EQ(4, params.getConsumerParams().statGatheringParams_[2].getStats().size()); EXPECT_EQ(4, params.getConsumerParams().fetchedStreams_.size()); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeVideo, params.getConsumerParams().fetchedStreams_[0].type_); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeVideo, params.getConsumerParams().fetchedStreams_[1].type_); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeAudio, params.getConsumerParams().fetchedStreams_[2].type_); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeAudio, params.getConsumerParams().fetchedStreams_[3].type_); EXPECT_EQ("/ndn/edu/ucla/remap/clientB", params.getConsumerParams().fetchedStreams_[0].sessionPrefix_); EXPECT_EQ("/ndn/edu/ucla/remap/clientC", params.getConsumerParams().fetchedStreams_[1].sessionPrefix_); EXPECT_EQ("/ndn/edu/ucla/remap/clientB", params.getConsumerParams().fetchedStreams_[2].sessionPrefix_); EXPECT_EQ("/ndn/edu/ucla/remap/clientC", params.getConsumerParams().fetchedStreams_[3].sessionPrefix_); EXPECT_EQ("clientB-camera", params.getConsumerParams().fetchedStreams_[0].sink_.name_); EXPECT_EQ("clientC-camera", params.getConsumerParams().fetchedStreams_[1].sink_.name_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[2].sink_.name_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[3].sink_.name_); EXPECT_EQ("low", params.getConsumerParams().fetchedStreams_[0].threadToFetch_); EXPECT_EQ("mid", params.getConsumerParams().fetchedStreams_[1].threadToFetch_); EXPECT_EQ("pcmu", params.getConsumerParams().fetchedStreams_[2].threadToFetch_); EXPECT_EQ("pcmu", params.getConsumerParams().fetchedStreams_[3].threadToFetch_); EXPECT_EQ(0, params.getConsumerParams().fetchedStreams_[0].getThreadNum()); EXPECT_EQ(0, params.getConsumerParams().fetchedStreams_[1].getThreadNum()); EXPECT_EQ(0, params.getConsumerParams().fetchedStreams_[2].getThreadNum()); EXPECT_EQ(0, params.getConsumerParams().fetchedStreams_[3].getThreadNum()); EXPECT_EQ("camera", params.getConsumerParams().fetchedStreams_[0].streamName_); EXPECT_EQ("camera", params.getConsumerParams().fetchedStreams_[1].streamName_); EXPECT_EQ("sound", params.getConsumerParams().fetchedStreams_[2].streamName_); EXPECT_EQ("sound", params.getConsumerParams().fetchedStreams_[3].streamName_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[0].synchronizedStreamName_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[1].synchronizedStreamName_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[2].synchronizedStreamName_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[3].synchronizedStreamName_); } TEST(TestConfigLoad, LoadProducerParams) { string fileName(TEST_CONFIG_FILE); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); EXPECT_EQ("/test/identity", params.getProducerParams().prefix_); EXPECT_EQ(3, params.getProducerParams().publishedStreams_.size()); EXPECT_EQ("camera.argb", params.getProducerParams().publishedStreams_[0].source_); EXPECT_EQ("desktop.argb", params.getProducerParams().publishedStreams_[1].source_); EXPECT_EQ("", params.getProducerParams().publishedStreams_[2].source_); EXPECT_EQ(2, params.getProducerParams().publishedStreams_[0].getThreadNum()); EXPECT_EQ(2, params.getProducerParams().publishedStreams_[1].getThreadNum()); EXPECT_EQ(1, params.getProducerParams().publishedStreams_[2].getThreadNum()); EXPECT_EQ("camera", params.getProducerParams().publishedStreams_[0].streamName_); EXPECT_EQ("desktop", params.getProducerParams().publishedStreams_[1].streamName_); EXPECT_EQ("sound", params.getProducerParams().publishedStreams_[2].streamName_); } TEST(TestConfigLoad, LoadAudioConsumerOnly) { // ndnlog::new_api::Logger::initAsyncLogging(); string fileName(TEST_CONFIG_FILE_CA); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); EXPECT_EQ(2000, params.getConsumerParams().generalAudioParams_.interestLifetime_); EXPECT_EQ(150, params.getConsumerParams().generalAudioParams_.jitterSizeMs_); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_.size()); EXPECT_EQ("buffer", params.getConsumerParams().statGatheringParams_[0].statFileName_); EXPECT_EQ("playback", params.getConsumerParams().statGatheringParams_[1].statFileName_); EXPECT_EQ("play", params.getConsumerParams().statGatheringParams_[2].statFileName_); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_[0].getStats().size()); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_[1].getStats().size()); EXPECT_EQ(4, params.getConsumerParams().statGatheringParams_[2].getStats().size()); EXPECT_EQ(2, params.getConsumerParams().fetchedStreams_.size()); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeAudio, params.getConsumerParams().fetchedStreams_[0].type_); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeAudio, params.getConsumerParams().fetchedStreams_[1].type_); EXPECT_EQ("/ndn/edu/ucla/remap/clientA", params.getConsumerParams().fetchedStreams_[0].sessionPrefix_); EXPECT_EQ("/ndn/edu/ucla/remap/clientA", params.getConsumerParams().fetchedStreams_[1].sessionPrefix_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[0].sink_.name_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[1].sink_.name_); EXPECT_EQ("pcmu", params.getConsumerParams().fetchedStreams_[0].threadToFetch_); EXPECT_EQ("pcmu", params.getConsumerParams().fetchedStreams_[1].threadToFetch_); EXPECT_EQ(0, params.getConsumerParams().fetchedStreams_[0].getThreadNum()); EXPECT_EQ(0, params.getConsumerParams().fetchedStreams_[1].getThreadNum()); EXPECT_EQ("sound", params.getConsumerParams().fetchedStreams_[0].streamName_); EXPECT_EQ("sound2", params.getConsumerParams().fetchedStreams_[1].streamName_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[0].synchronizedStreamName_); EXPECT_EQ("", params.getConsumerParams().fetchedStreams_[1].synchronizedStreamName_); } TEST(TestConfigLoad, LoadVideoConsumerOnly) { string fileName(TEST_CONFIG_FILE_CV); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); EXPECT_EQ(2000, params.getConsumerParams().generalVideoParams_.interestLifetime_); EXPECT_EQ(150, params.getConsumerParams().generalVideoParams_.jitterSizeMs_); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_.size()); EXPECT_EQ("buffer", params.getConsumerParams().statGatheringParams_[0].statFileName_); EXPECT_EQ("playback", params.getConsumerParams().statGatheringParams_[1].statFileName_); EXPECT_EQ("play", params.getConsumerParams().statGatheringParams_[2].statFileName_); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_[0].getStats().size()); EXPECT_EQ(3, params.getConsumerParams().statGatheringParams_[1].getStats().size()); EXPECT_EQ(4, params.getConsumerParams().statGatheringParams_[2].getStats().size()); EXPECT_EQ(2, params.getConsumerParams().fetchedStreams_.size()); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeVideo, params.getConsumerParams().fetchedStreams_[0].type_); EXPECT_EQ(ClientMediaStreamParams::MediaStreamTypeVideo, params.getConsumerParams().fetchedStreams_[1].type_); EXPECT_EQ("/ndn/edu/ucla/remap/clientB", params.getConsumerParams().fetchedStreams_[0].sessionPrefix_); EXPECT_EQ("/ndn/edu/ucla/remap/clientC", params.getConsumerParams().fetchedStreams_[1].sessionPrefix_); EXPECT_EQ("clientB-camera", params.getConsumerParams().fetchedStreams_[0].sink_.name_); EXPECT_EQ("/tmp/clientC-camera", params.getConsumerParams().fetchedStreams_[1].sink_.name_); EXPECT_STREQ("file", params.getConsumerParams().fetchedStreams_[0].sink_.type_.c_str()); EXPECT_STREQ("pipe", params.getConsumerParams().fetchedStreams_[1].sink_.type_.c_str()); EXPECT_EQ("low", params.getConsumerParams().fetchedStreams_[0].threadToFetch_); EXPECT_EQ("mid", params.getConsumerParams().fetchedStreams_[1].threadToFetch_); EXPECT_EQ("camera", params.getConsumerParams().fetchedStreams_[0].streamName_); EXPECT_EQ("camera", params.getConsumerParams().fetchedStreams_[1].streamName_); } // TBD: since output formatting changes frequently, these tests below need to be updated // since i'm not enjoying it, someone is welcome to volunteer #if 0 TEST(TestConfigLoad, LoadAndOutput) { string fileName(TEST_CONFIG_FILE); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); stringstream ss; ss << params; // std::cout << params << std::endl; #if 1 EXPECT_EQ( "-general:\n" "log level: INFO; log file: ndnrtc-client.log (at /tmp); FEC: ON; " "A/V Sync: ON; Host: localhost; Port #: 6363\n" "-consuming:\n" "general audio: interest lifetime: 2000 ms; jitter size: 150 ms\n" "general video: interest lifetime: 2000 ms; jitter size: 150 ms\n" "stat gathering:\n" "stat file: buffer.stat; stats: (jitterPlay, jitterTar, dArr)\n" "stat file: playback.stat; stats: (framesAcq, lambdaD, drdPrime)\n" "stat file: play.stat; stats: (lambdaD, drdPrime, jitterTar, dArr)\n" "fetching:\n" "[0: stream sink: clientB-camera; thread to fetch: low; session prefix: " "/ndn/edu/ucla/remap/clientB; name: camera (video); synced to: ;" " seg size: 0 bytes; freshness: 0 ms; no device; 0 threads:\n" "]\n" "[1: stream sink: clientC-camera; thread to fetch: mid; session prefix: " "/ndn/edu/ucla/remap/clientC; name: camera (video); " "synced to: ; seg size: 0 bytes; freshness: 0 ms; no device; 0 threads:\n" "]\n" "[2: stream sink: ; thread to fetch: pcmu; session prefix: " "/ndn/edu/ucla/remap/clientB; name: sound (audio); synced to:" " ; seg size: 0 bytes; freshness: 0 ms; no device; 0 threads:\n" "]\n" "[3: stream sink: ; thread to fetch: pcmu; session prefix: " "/ndn/edu/ucla/remap/clientC; name: sound (audio); synced to:" " ; seg size: 0 bytes; freshness: 0 ms; no device; 0 threads:\n" "]\n" "-producing:\n" "prefix: /test/identity;\n" "--0:\n" "stream source: camera.argb; session prefix: ; name: camera (video); " "synced to: sound; seg size: 1000 bytes; freshness: 2000 ms; no device; 2 threads:\n" "[0: name: low; 30FPS; GOP: 30; Start bitrate: 1000 Kbit/s; " "Max bitrate: 10000 Kbit/s; 720x405; Drop: YES]\n" "[1: name: hi; 30FPS; GOP: 30; Start bitrate: 3000 Kbit/s; " "Max bitrate: 10000 Kbit/s; 1920x1080; Drop: YES]\n" "--1:\n" "stream source: desktop.argb; session prefix: ; name: desktop (video); " "synced to: sound; seg size: 1000 bytes; freshness: 2000 ms; no device; 2 threads:\n" "[0: name: mid; 30FPS; GOP: 30; Start bitrate: 1000 Kbit/s; " "Max bitrate: 10000 Kbit/s; 1080x720; Drop: YES]\n" "[1: name: low; 30FPS; GOP: 30; Start bitrate: 300 Kbit/s; " "Max bitrate: 10000 Kbit/s; 352x288; Drop: YES]\n" "--2:\n" "stream source: ; session prefix: ; name: sound (audio); " "synced to: ; seg size: 1000 bytes; freshness: 2000 ms; " "capture device id: 0; 1 threads:\n" "[0: name: pcmu; codec: g722]\n", ss.str()); #endif } TEST(TestConfigLoad, TestSampleConsumerParams) { // ndnlog::new_api::Logger::initAsyncLogging(); string fileName(TEST_CONFIG_SAMPLE_CONSUMER_FILE); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); stringstream ss; ss << params; EXPECT_EQ( "-general:\n" "log level: INFO; log file: ndnrtc-client.log (at /tmp); FEC: ON; " "A/V Sync: ON; Host: localhost; Port #: 6363\n" "-consuming:\n" "general audio: interest lifetime: 2000 ms; jitter size: 150 ms\n" "general video: interest lifetime: 2000 ms; jitter size: 150 ms\n" "stat gathering:\n" "stat file: buffer.stat; stats: (jitterPlay, jitterTar, dArr)\n" "stat file: playback.stat; stats: (framesAcq, lambdaD, drdPrime)\n" "stat file: play.stat; stats: (lambdaD, drdPrime, jitterTar, dArr)\n" "fetching:\n" "[0: stream sink: ; thread to fetch: pcmu; session prefix: " "/ndn/edu/ucla/remap/clientA; name: sound (audio); synced to:" " ; seg size: 0 bytes; freshness: 0 ms; no device; 0 threads:\n" "]\n" "[1: stream sink: /tmp/clientA-camera; thread to fetch: tiny; session prefix: " "/ndn/edu/ucla/remap/clientA; name: camera (video); synced to:" " ; seg size: 0 bytes; freshness: 0 ms; no device; 0 threads:\n" "]\n", ss.str()); } TEST(TestConfigLoad, TestSampleProducerParams) { // ndnlog::new_api::Logger::initAsyncLogging(); string fileName(TEST_CONFIG_SAMPLE_PRODUCER_FILE); ASSERT_TRUE(std::ifstream(fileName.c_str()).good()); string identity = "/test/identity"; ClientParams params; ASSERT_EQ(0, loadParamsFromFile(fileName, params, identity)); stringstream ss; ss << params; EXPECT_EQ( "-general:\n" "log level: INFO; log file: ndnrtc-client.log (at /tmp); FEC: ON; A/V Sync: ON; " "Host: localhost; Port #: 6363\n" "-producing:\n" "prefix: /test/identity;\n" "--0:\n" "stream source: ../tests/test-source-320x240.argb; session prefix: ; " "name: camera (video); synced to: sound; seg size: 1000 bytes; freshness: 2000 ms; no device; 1 threads:\n" "[0: name: tiny; 30FPS; GOP: 30; Start bitrate: 100 Kbit/s; Max bitrate: 10000 Kbit/s; 320x240; Drop: YES]\n" "--1:\n" "stream source: ; session prefix: ; name: sound (audio); synced to: ;" " seg size: 1000 bytes; freshness: 2000 ms; capture device id: 0; 1 threads:\n" "[0: name: pcmu; codec: g722]\n", ss.str()); } #endif int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
47.950725
111
0.75603
peurpdapeurp
b5a3696b833329118c2f39e01cf650d0a845c223
13,853
cpp
C++
kinesis-video-producer/src/CachingEndpointOnlyCallbackProvider.cpp
nsharma098/amazon-kinesis-video-streams-producer-sdk-cpp
e3b63724494b16e00079027ccc232e8914731d66
[ "Apache-2.0" ]
null
null
null
kinesis-video-producer/src/CachingEndpointOnlyCallbackProvider.cpp
nsharma098/amazon-kinesis-video-streams-producer-sdk-cpp
e3b63724494b16e00079027ccc232e8914731d66
[ "Apache-2.0" ]
null
null
null
kinesis-video-producer/src/CachingEndpointOnlyCallbackProvider.cpp
nsharma098/amazon-kinesis-video-streams-producer-sdk-cpp
e3b63724494b16e00079027ccc232e8914731d66
[ "Apache-2.0" ]
null
null
null
/** Copyright 2019 Amazon.com. All rights reserved. */ #include "CachingEndpointOnlyCallbackProvider.h" #include "Version.h" #include "Logger.h" namespace com { namespace amazonaws { namespace kinesis { namespace video { LOGGER_TAG("com.amazonaws.kinesis.video"); using std::move; using std::unique_ptr; using std::make_unique; using std::shared_ptr; using std::string; using std::thread; using Json::FastWriter; STATUS CachingEndpointOnlyCallbackProvider::createStreamHandler( UINT64 custom_data, PCHAR device_name, PCHAR stream_name, PCHAR content_type, PCHAR kms_arn, UINT64 retention_period, PServiceCallContext service_call_ctx) { LOG_DEBUG("createStreamHandler invoked"); UNUSED_PARAM(device_name); UNUSED_PARAM(content_type); UNUSED_PARAM(kms_arn); UNUSED_PARAM(retention_period); string stream_name_str = string(stream_name); auto this_obj = reinterpret_cast<CachingEndpointOnlyCallbackProvider*>(custom_data); auto async_call = [](CachingEndpointOnlyCallbackProvider* this_obj, string stream_name_str, PServiceCallContext service_call_ctx) -> auto { uint64_t custom_data = service_call_ctx->customData; // Wait for the specified amount of time before calling auto call_after_time = std::chrono::nanoseconds(service_call_ctx->callAfter * DEFAULT_TIME_UNIT_IN_NANOS); auto time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> (call_after_time); sleepUntilWithTimeCallback(time_point); // We will return stream name as the arm STATUS status = createStreamResultEvent(custom_data, SERVICE_CALL_RESULT_OK, const_cast<PCHAR>(stream_name_str.c_str())); this_obj->notifyResult(status, custom_data); }; thread worker(async_call, this_obj, stream_name_str, service_call_ctx); worker.detach(); return STATUS_SUCCESS; } STATUS CachingEndpointOnlyCallbackProvider::tagResourceHandler( UINT64 custom_data, PCHAR stream_arn, UINT32 num_tags, PTag tags, PServiceCallContext service_call_ctx) { LOG_DEBUG("tagResourceHandler invoked for stream: " << stream_arn); UNUSED_PARAM(num_tags); UNUSED_PARAM(tags); string stream_arn_str = string(stream_arn); auto this_obj = reinterpret_cast<CachingEndpointOnlyCallbackProvider*>(custom_data); auto async_call = [](CachingEndpointOnlyCallbackProvider* this_obj, string stream_arn_str, PServiceCallContext service_call_ctx) -> auto { uint64_t custom_data = service_call_ctx->customData; // Wait for the specified amount of time before calling auto call_after_time = std::chrono::nanoseconds(service_call_ctx->callAfter * DEFAULT_TIME_UNIT_IN_NANOS); auto time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> (call_after_time); sleepUntilWithTimeCallback(time_point); STATUS status = tagResourceResultEvent(custom_data, SERVICE_CALL_RESULT_OK); this_obj->notifyResult(status, custom_data); }; thread worker(async_call, this_obj, stream_arn_str, service_call_ctx); worker.detach(); return STATUS_SUCCESS; } STATUS CachingEndpointOnlyCallbackProvider::describeStreamHandler( UINT64 custom_data, PCHAR stream_name, PServiceCallContext service_call_ctx) { LOG_DEBUG("describeStreamHandler invoked"); auto this_obj = reinterpret_cast<CachingEndpointOnlyCallbackProvider*>(custom_data); string stream_name_str = string(stream_name); auto async_call = [](CachingEndpointOnlyCallbackProvider* this_obj, string stream_name_str, PServiceCallContext service_call_ctx) -> auto { uint64_t custom_data = service_call_ctx->customData; // Wait for the specified amount of time before calling auto call_after_time = std::chrono::nanoseconds(service_call_ctx->callAfter * DEFAULT_TIME_UNIT_IN_NANOS); auto time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> (call_after_time); sleepUntilWithTimeCallback(time_point); StreamDescription stream_description; stream_description.version = STREAM_DESCRIPTION_CURRENT_VERSION; // set the device name string synth_str("DEVICE_NAME"); std::memcpy(&(stream_description.deviceName), synth_str.c_str(), synth_str.size()); stream_description.deviceName[synth_str.size()] = '\0'; // set the stream name std::memcpy(&(stream_description.streamName), stream_name_str.c_str(), stream_name_str.size()); stream_description.streamName[stream_name_str.size()] = '\0'; // Set the content type synth_str = "MIME_TYPE"; std::memcpy(&(stream_description.contentType), synth_str.c_str(), synth_str.size()); stream_description.contentType[synth_str.size()] = '\0'; // Set the update version synth_str = "Version"; std::memcpy(&(stream_description.updateVersion), synth_str.c_str(), synth_str.size()); stream_description.updateVersion[synth_str.size()] = '\0'; // Set the ARN LOG_INFO("Discovered existing Kinesis Video stream: " << stream_name_str); std::memcpy(&(stream_description.streamArn), stream_name_str.c_str(), stream_name_str.size()); stream_description.streamArn[stream_name_str.size()] = '\0'; stream_description.streamStatus = STREAM_STATUS_ACTIVE; // Set the creation time stream_description.creationTime = getCurrentTimeHandler(custom_data); STATUS status = describeStreamResultEvent(custom_data, SERVICE_CALL_RESULT_OK, &stream_description); this_obj->notifyResult(status, custom_data); }; thread worker(async_call, this_obj, stream_name_str, service_call_ctx); worker.detach(); return STATUS_SUCCESS; } STATUS CachingEndpointOnlyCallbackProvider::streamingEndpointHandler( UINT64 custom_data, PCHAR stream_name, PCHAR api_name, PServiceCallContext service_call_ctx) { LOG_DEBUG("streamingEndpointHandler invoked"); auto this_obj = reinterpret_cast<CachingEndpointOnlyCallbackProvider*>(custom_data); string stream_name_str = string(stream_name); // Check if we can return the cached value if (!this_obj->streaming_endpoint_.empty() && std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - this_obj->last_update_time_).count() < this_obj->cache_update_period_) { // return the cached data auto async_call = [](CachingEndpointOnlyCallbackProvider* this_obj, string stream_name_str, PServiceCallContext service_call_ctx) -> auto { uint64_t custom_data = service_call_ctx->customData; // Wait for the specified amount of time before calling auto call_after_time = std::chrono::nanoseconds(service_call_ctx->callAfter * DEFAULT_TIME_UNIT_IN_NANOS); auto time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> (call_after_time); sleepUntilWithTimeCallback(time_point); STATUS status = getStreamingEndpointResultEvent(custom_data, SERVICE_CALL_RESULT_OK, const_cast<PCHAR>(this_obj->streaming_endpoint_.c_str())); this_obj->notifyResult(status, custom_data); }; thread worker(async_call, this_obj, stream_name_str, service_call_ctx); worker.detach(); return STATUS_SUCCESS; } Json::Value args = Json::objectValue; args["StreamName"] = stream_name_str; args["APIName"] = api_name; FastWriter jsonWriter; string post_body(jsonWriter.write(args)); // De-serialize the credentials from the context Credentials credentials; SerializedCredentials::deSerialize(service_call_ctx->pAuthInfo->data, service_call_ctx->pAuthInfo->size, credentials); // New static credentials provider to go with the signer object auto staticCredentialProvider = make_unique<StaticCredentialProvider> (credentials); auto request_signer = AwsV4Signer::Create(this_obj->region_, this_obj->service_, move(staticCredentialProvider)); string endpoint = this_obj->getControlPlaneUri(); string url = endpoint + "/getDataEndpoint"; unique_ptr<Request> request = make_unique<Request>(Request::POST, url, (STREAM_HANDLE) service_call_ctx->customData); request->setConnectionTimeout(std::chrono::milliseconds(service_call_ctx->timeout / HUNDREDS_OF_NANOS_IN_A_MILLISECOND)); request->setHeader("host", endpoint); request->setHeader("user-agent", this_obj->user_agent_); request->setBody(post_body); auto async_call = [](CachingEndpointOnlyCallbackProvider* this_obj, std::unique_ptr<Request> request, std::unique_ptr<const RequestSigner> request_signer, string stream_name_str, PServiceCallContext service_call_ctx) -> auto { uint64_t custom_data = service_call_ctx->customData; // Wait for the specified amount of time before calling auto call_after_time = std::chrono::nanoseconds(service_call_ctx->callAfter * DEFAULT_TIME_UNIT_IN_NANOS); auto time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> (call_after_time); sleepUntilWithTimeCallback(time_point); // Perform a sync call shared_ptr<Response> response = this_obj->ccm_.call(move(request), move(request_signer), this_obj); // Remove the response from the active response map { std::unique_lock<std::recursive_mutex> lock(this_obj->ongoing_responses_mutex_); this_obj->ongoing_responses_.remove((STREAM_HANDLE) service_call_ctx->customData); } LOG_DEBUG("getStreamingEndpoint response: " << response->getData()); if (!response->terminated()) { string streaming_endpoint = ""; char streaming_endpoint_chars[MAX_URI_CHAR_LEN]; streaming_endpoint_chars[0] = '\0'; if (HTTP_OK == response->getStatusCode()) { Json::Reader reader; Json::Value json_response = Json::nullValue; if (!reader.parse(response->getData(), json_response)) { LOG_AND_THROW( "Unable to parse response from kinesis video get streaming endpoint call as json. Data: " + string(response->getData())); } // set the device name streaming_endpoint = json_response["DataEndpoint"].asString(); assert(MAX_URI_CHAR_LEN > streaming_endpoint.size()); strcpy(streaming_endpoint_chars, const_cast<PCHAR>(streaming_endpoint.c_str())); LOG_INFO("streaming to endpoint: " << string(reinterpret_cast<char *>(streaming_endpoint_chars))); } SERVICE_CALL_RESULT service_call_result = response->getServiceCallResult(); STATUS status = getStreamingEndpointResultEvent(custom_data, service_call_result, streaming_endpoint_chars); // Store the data on success if (STATUS_SUCCEEDED(status)) { this_obj->streaming_endpoint_ = streaming_endpoint; this_obj->last_update_time_ = std::chrono::system_clock::now(); } this_obj->notifyResult(status, custom_data); } }; thread worker(async_call, this_obj, move(request), move(request_signer), stream_name_str, service_call_ctx); worker.detach(); return STATUS_SUCCESS; } CachingEndpointOnlyCallbackProvider::CachingEndpointOnlyCallbackProvider( unique_ptr <ClientCallbackProvider> client_callback_provider, unique_ptr <StreamCallbackProvider> stream_callback_provider, unique_ptr <CredentialProvider> credentials_provider, const string& region, const string& control_plane_uri, const std::string &user_agent_name, const std::string &custom_user_agent, const std::string &cert_path, uint64_t cache_update_period) : DefaultCallbackProvider( move(client_callback_provider), move(stream_callback_provider), move(credentials_provider), region, control_plane_uri, user_agent_name, custom_user_agent, cert_path) { // Empty endpoint will invalidate the cache streaming_endpoint_ = ""; // Store the last update time last_update_time_ = std::chrono::system_clock::now(); // Store the update period cache_update_period_ = cache_update_period; } CachingEndpointOnlyCallbackProvider::~CachingEndpointOnlyCallbackProvider() { } CreateStreamFunc CachingEndpointOnlyCallbackProvider::getCreateStreamCallback() { return createStreamHandler; } DescribeStreamFunc CachingEndpointOnlyCallbackProvider::getDescribeStreamCallback() { return describeStreamHandler; } GetStreamingEndpointFunc CachingEndpointOnlyCallbackProvider::getStreamingEndpointCallback() { return streamingEndpointHandler; } TagResourceFunc CachingEndpointOnlyCallbackProvider::getTagResourceCallback() { return tagResourceHandler; } } // namespace video } // namespace kinesis } // namespace amazonaws } // namespace com
42.888545
129
0.687216
nsharma098
b286bf50a799ff50d525c2e34404edef583f241b
2,593
cpp
C++
Dx11/Rendering/MeshSDF.cpp
stoyannk/dx11-framework
1f1ce560d7c80f9e05f39479c316761f54c5cf12
[ "BSD-2-Clause" ]
18
2015-12-07T16:08:27.000Z
2020-02-11T12:30:36.000Z
Dx11/Rendering/MeshSDF.cpp
stoyannk/dx11-framework
1f1ce560d7c80f9e05f39479c316761f54c5cf12
[ "BSD-2-Clause" ]
null
null
null
Dx11/Rendering/MeshSDF.cpp
stoyannk/dx11-framework
1f1ce560d7c80f9e05f39479c316761f54c5cf12
[ "BSD-2-Clause" ]
8
2017-02-18T01:30:57.000Z
2022-01-03T22:41:11.000Z
// Copyright (c) 2011-2014, Stoyan Nikolov // All rights reserved. // This software is governed by a permissive BSD-style license. See LICENSE. #include "stdafx.h" #include "MeshSDF.h" #include "MathConv.h" #include <numeric> #include <utility> #include <ThirdParty/glm/glm/gtc/matrix_transform.hpp> using namespace DirectX; MeshSDF::MeshSDF(const glm::u32vec3& dims) : m_Dims(dims) , m_SDF(new char[dims.x * dims.y * dims.z]) {} MeshSDF::MeshSDF(MeshSDF&& other) : m_Dims(other.m_Dims) { m_SDF.swap(other.m_SDF); } MeshSDF& MeshSDF::operator=(MeshSDF&& other) { std::swap(m_SDF, other.m_SDF); std::swap(m_Dims, other.m_Dims); return *this; } void BruteForceSDFGen( const StandardVertex* vertices, const unsigned** indices, const unsigned* indexSizes, unsigned subsetCount, char* outSDF, const glm::u32vec3& dims) { const auto totalTriags = std::accumulate(indexSizes, indexSizes + subsetCount, 0u) / 3; std::unique_ptr<glm::mat4[]> matrices = std::make_unique<glm::mat4[]>(totalTriags); // Transform all triangles unsigned triagIndex = 0; for (auto subset = 0u; subset < subsetCount; ++subset) for (auto i = 0u; i < indexSizes[subset]; i += 3, ++triagIndex) { const auto i0 = indices[subset][i]; const auto i1 = indices[subset][i + 1]; const auto i2 = indices[subset][i + 2]; const auto v0v1 = glm::vec3(toVec3(vertices[i1].Position)) - glm::vec3(toVec3(vertices[i0].Position)); const auto v1v2 = glm::vec3(toVec3(vertices[i2].Position)) - glm::vec3(toVec3(vertices[i1].Position)); const auto normal = glm::normalize(glm::cross(v0v1, v1v2)); const glm::mat4 t1 = glm::translate(glm::mat4(1.0f), toVec3(vertices[i0].Position)); const auto cosa = -normal.x; const auto sina = sin(acos(-normal.x)); const glm::mat4 t2 = glm::mat4( cosa, -normal.y * sina, -normal.z*sina, 0, normal.y*sina, cosa + pow(normal.z, 2)*(1 - cosa), -normal.z*normal.y*(1-cosa), 0, normal.z*sina, -normal.y*normal.z*(1 - cosa), cosa + pow(normal.y, 2)*(1-cosa), 0, 0, 0, 0, 1 ); matrices[triagIndex] = t2*t1; } // Check distances w/ matrices for (auto z = 0u; z < dims.z; ++z) for (auto y = 0u; y < dims.y; ++y) for (auto x = 0u; x < dims.x; ++x) { } } void MeshSDF::Populate(const StandardVertex* vertices, const unsigned** indices, const unsigned* indexSizes, unsigned subsetCount, const glm::vec3& aabbMin, const glm::vec3& aabbMax) { BruteForceSDFGen(vertices, indices, indexSizes, subsetCount, m_SDF.get(), m_Dims); }
26.731959
105
0.651755
stoyannk
b286d01b53be9c52bfc2956d5a1f098dc9dfd065
3,167
hh
C++
src/Kernel/SphericalTableKernel.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Kernel/SphericalTableKernel.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Kernel/SphericalTableKernel.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // SphericalTableKernel // // Take a 3D Kernel and build a specialized 1D tabulated version appropriate // for use with the spherical SPH algorithm described in // Omang, M., Børve, S., & Trulsen, J. (2006). SPH in spherical and cylindrical coordinates. // Journal of Computational Physics, 213(1), 391412. https://doi.org/10.1016/j.jcp.2005.08.023 // // Created by JMO, Wed Dec 2 16:41:20 PST 2020 //----------------------------------------------------------------------------// #ifndef __Spheral_SphericalTableKernel_hh__ #define __Spheral_SphericalTableKernel_hh__ #include "Kernel.hh" #include "TableKernel.hh" #include "Utilities/BiQuadraticInterpolator.hh" #include "Geometry/Dimension.hh" namespace Spheral { class SphericalTableKernel { public: //--------------------------- Public Interface ---------------------------// using InterpolatorType = BiQuadraticInterpolator; using Scalar = Dim<1>::Scalar; using Vector = Dim<1>::Vector; using Tensor = Dim<1>::Tensor; using SymTensor = Dim<1>::SymTensor; // Constructor. // Takes a normal 3D TableKernel and constructs the integral form appropriate // for 1D spherical coordinates. SphericalTableKernel(const TableKernel<Dim<3>>& kernel); SphericalTableKernel(const SphericalTableKernel& rhs); // Destructor. virtual ~SphericalTableKernel(); // Assignment. SphericalTableKernel& operator=(const SphericalTableKernel& rhs); // These methods taking a Vector eta and Vector position are the special methods // allowing this kernel to implement the asymmetric sampling as a function of r. // Arguments: // etaj : Vector normalized coordinate: etaj = H*posj // etai : Vector normalized coordinate: etai = H*posi // Hdet : Determinant of the H tensor used to compute eta double operator()(const Vector& etaj, const Vector& etai, const Scalar Hdeti) const; Vector grad(const Vector& etaj, const Vector& etai, const Scalar Hdeti) const; std::pair<double, Vector> kernelAndGradValue(const Vector& etaj, const Vector& etai, const Scalar Hdeti) const; // Return the kernel weight for a given normalized distance or position. double kernelValue(const double etaMagnitude, const double Hdet) const; // Return the gradient value for a given normalized distance or position. double gradValue(const double etaMagnitude, const double Hdet) const; // Return the second derivative value for a given normalized distance or position. double grad2Value(const double etaMagnitude, const double Hdet) const; // Access our internal data. const InterpolatorType& Winterpolator() const; const TableKernel<Dim<3>>& kernel() const; Scalar etamax() const; // Test if the kernel is currently valid. virtual bool valid() const; private: //--------------------------- Private Interface ---------------------------// // Data for the kernel tabulation. InterpolatorType mInterp; TableKernel<Dim<3>> mKernel; Scalar metamax; }; } #include "SphericalTableKernelInline.hh" #else // Forward declaration. namespace Spheral { class SphericalTableKernel; } #endif
34.802198
113
0.688033
jmikeowen
b28953c094397a1814b6e0fd88971a0252e2e957
2,851
hpp
C++
thread/mrsw.hpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
thread/mrsw.hpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
thread/mrsw.hpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
#pragma once #include "semaphore.hpp" namespace so_thread { /// multi-reader single-writer class mrsw { so_this_typedefs( mrsw ) ; private: semaphore_t _reader ; semaphore_t _writer ; public: mrsw( void_t ) noexcept { } mrsw( this_rref_t rhv ) noexcept : _reader( std::move( rhv._reader ) ), _writer( std::move( rhv._writer ) ) {} mrsw( this_cref_t ) = delete ; ~mrsw( void_t ) noexcept {} public: /// writer access to mrsw object class writer_lock { so_this_typedefs( writer_lock ) ; private: mrsw& _l ; public: writer_lock( mrsw & r ) noexcept : _l(r) { r.writer_increment() ; } ~writer_lock( void_t ) noexcept { _l.writer_decrement() ; } writer_lock( this_cref_t ) = delete ; writer_lock( this_rref_t ) = delete ; }; so_typedef( writer_lock ) ; friend class writer_lock ; private: // writer void_t writer_increment( void_t ) noexcept { // ensure that only one writer is in critical section _writer.wait( so_thread::semaphore_static::is_zero_funk, so_thread::semaphore_static::increment_funk ) ; // ensure that no reader is in critical section _reader.wait( so_thread::semaphore_static::is_zero_funk, so_thread::semaphore_static::no_op_funk ) ; } void_t writer_decrement( void_t ) { _writer.decrement() ; } public: /// reader access to mrsw object class reader_lock { so_this_typedefs( reader_lock ) ; private: mrsw& _l ; public: reader_lock( mrsw& r ) noexcept : _l( r ) { r.reader_increment() ; } ~reader_lock( void_t ) noexcept { _l.reader_decrement() ; } reader_lock( this_cref_t ) = delete ; reader_lock( this_rref_t ) = delete ; }; so_typedef( reader_lock ) ; friend class reader_lock ; private: // reader void_t reader_increment( void_t ) noexcept { // just increment reader semaphore _reader.increment() ; // ensure that no writer is in critical section _writer.wait( so_thread::semaphore_static::is_zero_funk, so_thread::semaphore_static::no_op_funk ) ; } void_t reader_decrement( void_t ) { _reader.decrement() ; } }; so_typedef( mrsw ) ; }
22.100775
68
0.507892
aconstlink
b28dc718841c241ea9a019d26d8244e16ef3d074
13,133
cpp
C++
Code/Projects/Eldritch/src/Components/wbcompeldfrobbable.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
Code/Projects/Eldritch/src/Components/wbcompeldfrobbable.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
Code/Projects/Eldritch/src/Components/wbcompeldfrobbable.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
#include "core.h" #include "wbcompeldfrobbable.h" #include "aabb.h" #include "wbcompeldtransform.h" #include "wbcompeldcollision.h" #include "wbcompeldmesh.h" #include "wbentity.h" #include "eldritchframework.h" #include "irenderer.h" #include "configmanager.h" #include "wbeventmanager.h" #include "eldritchmesh.h" #include "idatastream.h" #include "inputsystem.h" #include "Common/uimanagercommon.h" WBCompEldFrobbable::WBCompEldFrobbable() : m_IsFrobbable(false), m_IsProbableFrobbable(false), m_HoldReleaseMode(false), m_HandleHoldRelease(false), m_UseCollisionExtents(false), m_UseMeshExtents(false), m_ExtentsFatten(0.0f), m_BoundOffset(), m_BoundExtents(), m_Highlight(), m_FriendlyName(), m_FrobVerb(), m_HoldVerb() {} WBCompEldFrobbable::~WBCompEldFrobbable() {} /*virtual*/ void WBCompEldFrobbable::InitializeFromDefinition( const SimpleString& DefinitionName) { Super::InitializeFromDefinition(DefinitionName); MAKEHASH(DefinitionName); STATICHASH(EldFrobbable); STATICHASH(IsFrobbable); m_IsFrobbable = ConfigManager::GetInheritedBool(sIsFrobbable, true, sDefinitionName); STATICHASH(HoldReleaseMode); m_HoldReleaseMode = ConfigManager::GetInheritedBool(sHoldReleaseMode, false, sDefinitionName); STATICHASH(UseCollisionExtents); m_UseCollisionExtents = ConfigManager::GetInheritedBool( sUseCollisionExtents, false, sDefinitionName); STATICHASH(UseMeshExtents); m_UseMeshExtents = ConfigManager::GetInheritedBool(sUseMeshExtents, false, sDefinitionName); STATICHASH(ExtentsFatten); m_ExtentsFatten = ConfigManager::GetInheritedFloat(sExtentsFatten, 0.0f, sDefinitionName); STATICHASH(ExtentsX); m_BoundExtents.x = ConfigManager::GetInheritedFloat(sExtentsX, 0.0f, sDefinitionName); STATICHASH(ExtentsY); m_BoundExtents.y = ConfigManager::GetInheritedFloat(sExtentsY, 0.0f, sDefinitionName); STATICHASH(ExtentsZ); m_BoundExtents.z = ConfigManager::GetInheritedFloat(sExtentsZ, 0.0f, sDefinitionName); STATICHASH(OffsetZ); m_BoundOffset.z = ConfigManager::GetInheritedFloat(sOffsetZ, 0.0f, sDefinitionName); STATICHASH(HighlightR); const float DefaultHighlightR = ConfigManager::GetFloat(sHighlightR, 0.0f, sEldFrobbable); m_Highlight.r = ConfigManager::GetInheritedFloat( sHighlightR, DefaultHighlightR, sDefinitionName); STATICHASH(HighlightG); const float DefaultHighlightG = ConfigManager::GetFloat(sHighlightG, 0.0f, sEldFrobbable); m_Highlight.g = ConfigManager::GetInheritedFloat( sHighlightG, DefaultHighlightG, sDefinitionName); STATICHASH(HighlightB); const float DefaultHighlightB = ConfigManager::GetFloat(sHighlightB, 0.0f, sEldFrobbable); m_Highlight.b = ConfigManager::GetInheritedFloat( sHighlightB, DefaultHighlightB, sDefinitionName); STATICHASH(FriendlyName); m_FriendlyName = ConfigManager::GetInheritedString( sFriendlyName, GetEntity()->GetName().CStr(), sDefinitionName); STATICHASH(FrobVerb); m_FrobVerb = ConfigManager::GetInheritedString(sFrobVerb, "", sDefinitionName); STATICHASH(HoldVerb); m_HoldVerb = ConfigManager::GetInheritedString(sHoldVerb, "", sDefinitionName); } /*virtual*/ void WBCompEldFrobbable::HandleEvent(const WBEvent& Event) { XTRACE_FUNCTION; Super::HandleEvent(Event); STATIC_HASHED_STRING(MarshalFrob); STATIC_HASHED_STRING(OnInitialized); STATIC_HASHED_STRING(OnDestroyed); STATIC_HASHED_STRING(OnMeshUpdated); STATIC_HASHED_STRING(SetIsFrobbable); STATIC_HASHED_STRING(BecomeFrobbable); STATIC_HASHED_STRING(BecomeNonFrobbable); STATIC_HASHED_STRING(SetHoldReleaseMode); STATIC_HASHED_STRING(SetFriendlyName); STATIC_HASHED_STRING(SetFrobVerb); STATIC_HASHED_STRING(SetBoundExtents); STATIC_HASHED_STRING(SetBoundOffsetZ); const HashedString EventName = Event.GetEventName(); if (EventName == sMarshalFrob) { STATIC_HASHED_STRING(Frobber); WBEntity* const pFrobber = Event.GetEntity(sFrobber); STATIC_HASHED_STRING(InputEdge); const int InputEdge = Event.GetInt(sInputEdge); MarshalFrob(pFrobber, InputEdge); } else if (EventName == sOnInitialized) { if (m_UseCollisionExtents) { WBCompEldCollision* const pCollision = GET_WBCOMP(GetEntity(), EldCollision); if (pCollision) { m_BoundExtents = pCollision->GetExtents() + Vector(m_ExtentsFatten, m_ExtentsFatten, m_ExtentsFatten); } } } else if (EventName == sOnDestroyed) { if (m_IsProbableFrobbable) { SetHUDHidden(true); } } else if (EventName == sOnMeshUpdated) { ASSERT(m_UseMeshExtents); WBCompEldTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompEldTransform>(); DEVASSERT(pTransform); WBCompEldMesh* const pMeshComponent = GET_WBCOMP(GetEntity(), EldMesh); ASSERT(pMeshComponent); EldritchMesh* const pMesh = pMeshComponent->GetMesh(); ASSERT(pMesh); m_BoundExtents = pMesh->m_AABB.GetExtents() + Vector(m_ExtentsFatten, m_ExtentsFatten, m_ExtentsFatten); m_BoundOffset = pMesh->m_AABB.GetCenter() - pTransform->GetLocation(); } else if (EventName == sSetIsFrobbable) { STATIC_HASHED_STRING(IsFrobbable); m_IsFrobbable = Event.GetBool(sIsFrobbable); } else if (EventName == sBecomeFrobbable) { m_IsFrobbable = true; } else if (EventName == sBecomeNonFrobbable) { m_IsFrobbable = false; } else if (EventName == sSetHoldReleaseMode) { const bool WasHoldReleaseMode = m_HoldReleaseMode; STATIC_HASHED_STRING(HoldReleaseMode); m_HoldReleaseMode = Event.GetBool(sHoldReleaseMode); if (m_HoldReleaseMode && !WasHoldReleaseMode) { m_HandleHoldRelease = false; } if (GetIsFrobTarget()) { PublishToHUD(); } } else if (EventName == sSetFriendlyName) { STATIC_HASHED_STRING(FriendlyName); m_FriendlyName = Event.GetString(sFriendlyName); if (GetIsFrobTarget()) { PublishToHUD(); } } else if (EventName == sSetFrobVerb) { STATIC_HASHED_STRING(FrobVerb); m_FrobVerb = Event.GetString(sFrobVerb); if (GetIsFrobTarget()) { PublishToHUD(); } } else if (EventName == sSetBoundExtents) { STATIC_HASHED_STRING(BoundExtents); m_BoundExtents = Event.GetVector(sBoundExtents); } else if (EventName == sSetBoundOffsetZ) { STATIC_HASHED_STRING(BoundOffsetZ); m_BoundOffset.z = Event.GetFloat(sBoundOffsetZ); } } /*virtual*/ void WBCompEldFrobbable::AddContextToEvent(WBEvent& Event) const { Super::AddContextToEvent(Event); WB_SET_CONTEXT(Event, Bool, IsFrobbable, m_IsFrobbable); } AABB WBCompEldFrobbable::GetBound() const { WBCompEldTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompEldTransform>(); DEVASSERT(pTransform); return AABB::CreateFromCenterAndExtents( pTransform->GetLocation() + m_BoundOffset, m_BoundExtents); } #if BUILD_DEV /*virtual*/ void WBCompEldFrobbable::DebugRender() const { WBCompEldTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompEldTransform>(); DEVASSERT(pTransform); const Vector Location = pTransform->GetLocation() + m_BoundOffset; GetFramework()->GetRenderer()->DEBUGDrawBox(Location - m_BoundExtents, Location + m_BoundExtents, ARGB_TO_COLOR(255, 255, 128, 0)); } #endif void WBCompEldFrobbable::SetIsFrobTarget(const bool IsFrobTarget, WBEntity* const pFrobber) { m_IsProbableFrobbable = IsFrobTarget; WB_MAKE_EVENT(OnBecameFrobTarget, GetEntity()); WB_SET_AUTO(OnBecameFrobTarget, Bool, IsFrobTarget, m_IsProbableFrobbable); WB_SET_AUTO(OnBecameFrobTarget, Entity, Frobber, pFrobber); WB_SET_AUTO(OnBecameFrobTarget, Vector, Highlight, m_Highlight); WB_DISPATCH_EVENT(GetEventManager(), OnBecameFrobTarget, GetEntity()); if (IsFrobTarget) { PublishToHUD(); } else { SetHUDHidden(true); } } void WBCompEldFrobbable::PublishToHUD() const { STATICHASH(HUD); STATICHASH(FrobName); ConfigManager::SetString(sFrobName, m_FriendlyName.CStr(), sHUD); STATICHASH(FrobVerb); ConfigManager::SetString(sFrobVerb, m_FrobVerb.CStr(), sHUD); STATICHASH(HoldVerb); ConfigManager::SetString(sHoldVerb, m_HoldVerb.CStr(), sHUD); SetHUDHidden(false); } void WBCompEldFrobbable::SetHUDHidden(const bool Hidden) const { UIManager* const pUIManager = GetFramework()->GetUIManager(); ASSERT(pUIManager); STATIC_HASHED_STRING(HUD); STATIC_HASHED_STRING(FrobName); STATIC_HASHED_STRING(FrobVerb); STATIC_HASHED_STRING(FrobHold); { WB_MAKE_EVENT(SetWidgetHidden, GetEntity()); WB_SET_AUTO(SetWidgetHidden, Hash, Screen, sHUD); WB_SET_AUTO(SetWidgetHidden, Hash, Widget, sFrobName); WB_SET_AUTO(SetWidgetHidden, Bool, Hidden, Hidden); WB_DISPATCH_EVENT(GetEventManager(), SetWidgetHidden, pUIManager); } { WB_MAKE_EVENT(SetWidgetHidden, GetEntity()); WB_SET_AUTO(SetWidgetHidden, Hash, Screen, sHUD); WB_SET_AUTO(SetWidgetHidden, Hash, Widget, sFrobVerb); WB_SET_AUTO(SetWidgetHidden, Bool, Hidden, Hidden); WB_DISPATCH_EVENT(GetEventManager(), SetWidgetHidden, pUIManager); } { WB_MAKE_EVENT(SetWidgetHidden, GetEntity()); WB_SET_AUTO(SetWidgetHidden, Hash, Screen, sHUD); WB_SET_AUTO(SetWidgetHidden, Hash, Widget, sFrobHold); WB_SET_AUTO(SetWidgetHidden, Bool, Hidden, Hidden || !m_HoldReleaseMode); WB_DISPATCH_EVENT(GetEventManager(), SetWidgetHidden, pUIManager); } } void WBCompEldFrobbable::MarshalFrob(WBEntity* const pFrobber, const int InputEdge) { if (m_HoldReleaseMode) { if (InputEdge == InputSystem::EIE_OnRise) { m_HandleHoldRelease = true; } else if (InputEdge == InputSystem::EIE_OnHold && m_HandleHoldRelease) { SendOnFrobbedHeldEvent(pFrobber); m_HandleHoldRelease = false; // NOTE: This means we won't get the OnRelease event for this // input! That's what I want currently, but maybe not always. } else if (InputEdge == InputSystem::EIE_OnFall && m_HandleHoldRelease) { SendOnFrobbedEvent(pFrobber); m_HandleHoldRelease = false; } } else { if (InputEdge == InputSystem::EIE_OnRise) { SendOnFrobbedEvent(pFrobber); } } } void WBCompEldFrobbable::SendOnFrobbedEvent(WBEntity* const pFrobber) const { WB_MAKE_EVENT(OnFrobbed, GetEntity()); WB_SET_AUTO(OnFrobbed, Entity, Frobber, pFrobber); WB_DISPATCH_EVENT(GetEventManager(), OnFrobbed, GetEntity()); } void WBCompEldFrobbable::SendOnFrobbedHeldEvent( WBEntity* const pFrobber) const { WB_MAKE_EVENT(OnFrobbedHeld, GetEntity()); WB_SET_AUTO(OnFrobbedHeld, Entity, Frobber, pFrobber); WB_DISPATCH_EVENT(GetEventManager(), OnFrobbedHeld, GetEntity()); } #define VERSION_EMPTY 0 #define VERSION_ISFROBBABLE 1 #define VERSION_HOLDRELEASEMODE 2 #define VERSION_FRIENDLYNAME 3 #define VERSION_FROBVERB 4 #define VERSION_BOUNDS 5 #define VERSION_CURRENT 5 uint WBCompEldFrobbable::GetSerializationSize() { uint Size = 0; Size += 4; // Version Size += 1; // m_IsFrobbable Size += 1; // m_HoldReleaseMode Size += IDataStream::SizeForWriteString(m_FriendlyName); Size += IDataStream::SizeForWriteString(m_FrobVerb); Size += sizeof(Vector); // m_BoundOffset Size += sizeof(Vector); // m_BoundExtents return Size; } void WBCompEldFrobbable::Save(const IDataStream& Stream) { Stream.WriteUInt32(VERSION_CURRENT); Stream.WriteBool(m_IsFrobbable); Stream.WriteBool(m_HoldReleaseMode); Stream.WriteString(m_FriendlyName); Stream.WriteString(m_FrobVerb); #ifdef __amigaos4__ Vector tmp = m_BoundOffset; littleBigEndian(&tmp.x); littleBigEndian(&tmp.y); littleBigEndian(&tmp.z); Stream.Write(sizeof(Vector), &tmp); tmp = m_BoundExtents; littleBigEndian(&tmp.x); littleBigEndian(&tmp.y); littleBigEndian(&tmp.z); Stream.Write(sizeof(Vector), &tmp); #else Stream.Write(sizeof(Vector), &m_BoundOffset); Stream.Write(sizeof(Vector), &m_BoundExtents); #endif } void WBCompEldFrobbable::Load(const IDataStream& Stream) { XTRACE_FUNCTION; const uint Version = Stream.ReadUInt32(); if (Version >= VERSION_ISFROBBABLE) { m_IsFrobbable = Stream.ReadBool(); } if (Version >= VERSION_HOLDRELEASEMODE) { m_HoldReleaseMode = Stream.ReadBool(); } if (Version >= VERSION_FRIENDLYNAME) { m_FriendlyName = Stream.ReadString(); } if (Version >= VERSION_FROBVERB) { m_FrobVerb = Stream.ReadString(); } if (Version >= VERSION_BOUNDS) { Stream.Read(sizeof(Vector), &m_BoundOffset); Stream.Read(sizeof(Vector), &m_BoundExtents); #ifdef __amigaos4__ littleBigEndian(&m_BoundOffset.x); littleBigEndian(&m_BoundOffset.y); littleBigEndian(&m_BoundOffset.z); littleBigEndian(&m_BoundExtents.x); littleBigEndian(&m_BoundExtents.y); littleBigEndian(&m_BoundExtents.z); #endif } }
31.120853
80
0.727404
kas1e
b29103fbb0fe79d08cd96b498067621f8d948f9a
987
cpp
C++
Sort strings based on position value.cpp
dishanp/Coding-In-C-and-Cpp
bb615c8c524920f1b0bcbadf1c8b9328aa83616a
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Sort strings based on position value.cpp
dishanp/Coding-In-C-and-Cpp
bb615c8c524920f1b0bcbadf1c8b9328aa83616a
[ "BSD-2-Clause" ]
null
null
null
Sort strings based on position value.cpp
dishanp/Coding-In-C-and-Cpp
bb615c8c524920f1b0bcbadf1c8b9328aa83616a
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
/* Write a function sortStringByValue() which takes in a list of strings and sort them according to the sum of the positional value of the alphabets where position of a is 1, b is 2, c is 3.....etc. till z=26. Alphabets are not ----- character other than alphabets (upper and lower case) should not be considered for positive value. Input Format: The first integer ‘n’ denotes the size of the array and the next n lines of input denote the n strings. Output: Print strings in sorted manner. Sample Input: 3 beast fox cat Sample Output: cat fox beast Explanation: beast= 2+5+1+19+20 =47, fox= 6+15+24=45, cat= 3+1+20=24 */ using namespace std; #include<bits/stdc++.h> static bool comp(string &a,string &b){ int va=0; int vb=0; for(char ch:a) va+=(int)ch; for(int ch:b) vb+=(int)ch; return va<vb; } int main(){ vector<string>s={"beast","fox","cat"}; sort(s.begin(),s.end(),&comp); for(int i=0;i<s.size();i++) cout<<s[i]<<" "; return 0; }
24.073171
101
0.666667
dishanp
b291e943f232b65823824b1c3d221b10af839b94
6,169
hpp
C++
octotiger/radiation/kernel_interface.hpp
srinivasyadav18/octotiger
4d93c50fe345a081b7985ecb4cb698d16c121565
[ "BSL-1.0" ]
35
2016-11-17T22:35:11.000Z
2022-01-24T19:07:36.000Z
octotiger/radiation/kernel_interface.hpp
srinivasyadav18/octotiger
4d93c50fe345a081b7985ecb4cb698d16c121565
[ "BSL-1.0" ]
123
2016-11-17T21:29:25.000Z
2022-03-03T21:40:04.000Z
octotiger/radiation/kernel_interface.hpp
srinivasyadav18/octotiger
4d93c50fe345a081b7985ecb4cb698d16c121565
[ "BSL-1.0" ]
10
2018-11-28T18:17:42.000Z
2022-01-25T12:52:37.000Z
// Copyright (c) 2019 AUTHORS // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "octotiger/defs.hpp" #include "octotiger/radiation/cpu_kernel.hpp" #include "octotiger/radiation/cuda_kernel.hpp" #include "octotiger/real.hpp" #include <hpx/include/run_as.hpp> #include <array> #include <vector> namespace octotiger { namespace radiation { #if defined(OCTOTIGER_DUMP_RADIATION_CASES) namespace dumper { constexpr char const* basepath = OCTOTIGER_DUMP_DIR "/octotiger-radiation-"; void save_v(std::ostream& os, std::vector<double> const& v) { std::size_t size = v.size(); os.write(reinterpret_cast<char*>(&size), sizeof(std::size_t)); os.write( reinterpret_cast<char const*>(&v[0]), size * sizeof(double)); } void save_a( std::ostream& os, std::array<std::vector<double>, NRF> const& a) { std::size_t size = a.size(); os.write(reinterpret_cast<char*>(&size), sizeof(std::size_t)); for (auto const& e : a) { save_v(os, e); } } void save_i(std::ostream& os, std::int64_t const i) { os.write(reinterpret_cast<char const*>(&i), sizeof(std::int64_t)); } void save_d(std::ostream& os, double const d) { os.write(reinterpret_cast<char const*>(&d), sizeof(double)); } void save_case_args(std::size_t const index, std::int64_t const& opts_eos, std::int64_t const& opts_problem, double const& opts_dual_energy_sw1, double const& opts_dual_energy_sw2, double const& physcon_A, double const& physcon_B, double const& physcon_c, double const& fgamma, double const& dt, double const& clightinv, std::int64_t const& er_i, std::int64_t const& fx_i, std::int64_t const& fy_i, std::int64_t const& fz_i, std::int64_t const& d, std::vector<double> const& sx, std::vector<double> const& sy, std::vector<double> const& sz, std::vector<double> const& egas, std::vector<double> const& tau, std::array<std::vector<double>, NRF> const& U, std::vector<double> const& rho, std::vector<double> const& X_spc, std::vector<double> const& Z_spc, std::vector<double> const& mmw) { std::string const args_fn = std::string{basepath} + std::to_string(index) + std::string{".args"}; std::ofstream os{args_fn, std::ios::binary}; if (!os) { throw std::runtime_error(hpx::util::format( "error: cannot open args file \"{}\".", args_fn)); } save_i(os, opts_eos); save_i(os, opts_problem); save_d(os, opts_dual_energy_sw1); save_d(os, opts_dual_energy_sw2); save_d(os, physcon_A); save_d(os, physcon_B); save_d(os, physcon_c); save_d(os, fgamma); save_d(os, dt); save_d(os, clightinv); save_i(os, er_i); save_i(os, fx_i); save_i(os, fy_i); save_i(os, fz_i); save_i(os, d); save_v(os, sx); save_v(os, sy); save_v(os, sz); save_v(os, egas); save_v(os, tau); save_a(os, U); save_v(os, rho); save_v(os, X_spc); save_v(os, Z_spc); save_v(os, mmw); } void save_case_outs(std::size_t const index, std::vector<double> const& sx, std::vector<double> const& sy, std::vector<double> const& sz, std::vector<double> const& egas, std::vector<double> const& tau, std::array<std::vector<double>, NRF> const& U) { std::string const outs_fn = std::string{basepath} + std::to_string(index) + std::string{".outs"}; std::ofstream os{outs_fn, std::ios::binary}; if (!os) { throw std::runtime_error(hpx::util::format( "error: cannot open outs file \"{}\".", outs_fn)); } save_v(os, sx); save_v(os, sy); save_v(os, sz); save_v(os, egas); save_v(os, tau); save_a(os, U); } } #endif template <integer er_i, integer fx_i, integer fy_i, integer fz_i> void radiation_kernel(integer const d, std::vector<real> const& rho, std::vector<real>& sx, std::vector<real>& sy, std::vector<real>& sz, std::vector<real>& egas, std::vector<real>& tau, real const fgamma, std::vector<std::vector<real>>& U, std::vector<real> const& mmw, std::vector<real> const& X_spc, std::vector<real> const& Z_spc, real dt, real const clightinv) { #if defined(OCTOTIGER_DUMP_RADIATION_CASES) static std::atomic_size_t next_index(0); std::size_t index = next_index++; hpx::threads::run_as_os_thread([&]() { dumper::save_case_args(index, opts().eos, opts().problem, opts().dual_energy_sw1, opts().dual_energy_sw2, physcon().A, physcon().B, physcon().c, fgamma, dt, clightinv, er_i, fx_i, fy_i, fz_i, d, sx, sy, sz, egas, tau, U, rho, X_spc, Z_spc, mmw); }).get(); #endif radiation_cpu_kernel<er_i, fx_i, fy_i, fz_i>(d, rho, sx, sy, sz, egas, tau, fgamma, U, mmw, X_spc, Z_spc, dt, clightinv); #if defined(OCTOTIGER_DUMP_RADIATION_CASES) hpx::threads::run_as_os_thread([&]() { dumper::save_case_outs(index, sx, sy, sz, egas, tau, U); }).get(); #endif } }}
33.166667
84
0.53088
srinivasyadav18
b29334f1c72da4be6685f83f50a5d08dc8779faa
441
cpp
C++
acmicpc.net/2261.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
4
2016-04-15T07:54:39.000Z
2021-01-11T09:02:16.000Z
acmicpc.net/2261.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
acmicpc.net/2261.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> using namespace std; struct point { int x, y; bool operator<(const point& p) { return x < p.x || (x == p.x && y < p.y); } }; set<point> xy; int main() { int N; scanf("%d", &N); for (int i = 0; i < N; i++) { int X, Y; scanf("%d %d", &X, &Y); X += 10000, Y += 10000; xy.insert({ X, Y }); } int result = 1e9; return 0; }
17.64
42
0.548753
kbu1564
b294f1c719412818a41f1d4c65ded55c38105469
1,982
cpp
C++
source/Texture.cpp
Xaer033/Torque
55ed32b5269e0058121b38e95be19b67e325db6d
[ "MIT" ]
null
null
null
source/Texture.cpp
Xaer033/Torque
55ed32b5269e0058121b38e95be19b67e325db6d
[ "MIT" ]
null
null
null
source/Texture.cpp
Xaer033/Torque
55ed32b5269e0058121b38e95be19b67e325db6d
[ "MIT" ]
null
null
null
#include "Texture.h" #include "IwGL.h" #include "IwImage.h" namespace GG { Texture::Texture() { _image = NULL; _handle = 0; } Texture::Texture( CIwImage & image ) { _handle = 0; setImage( image ); } Texture::~Texture() { //we dont own image, so dont free _image = NULL; if( _handle ) glDeleteTextures( 1, &_handle ); } void Texture::setImage( CIwImage & image ) { _image = &image; _createVRAMTexture(); } bool Texture::loadFromFile( const char * location ) { if( !_image ) _image = new CIwImage(); _image->LoadFromFile( location ); _createVRAMTexture(); return true; } uint Texture::getWidth() const { if( _image ) return _image->GetWidth(); return 0; } uint Texture::getHeight() const { if( _image ) return _image->GetHeight(); return 0; } void Texture::setHandle( const uint handle ) { //if( _handle ) // glDeleteTextures( 1, &_handle ); _handle = handle; } uint Texture::getHandle() const { return _handle; } bool Texture::_createVRAMTexture() { if( _image == NULL ) return false; int interalFormat = ( _image->HasAlpha() > 0 ) ? GL_RGBA : GL_RGB; if( !_handle ) glGenTextures( 1, &_handle ); glBindTexture( GL_TEXTURE_2D, _handle ); //gluBuild2DMipmaps( GL_TEXTURE_2D, 4, texture.getSize().x, texture.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, texture.getPixelsPtr() ); glTexImage2D( GL_TEXTURE_2D, 0, interalFormat, _image->GetWidth(), _image->GetHeight(), 0, interalFormat, GL_UNSIGNED_BYTE, _image->GetTexels() ); glGenerateMipmap( GL_TEXTURE_2D ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); return true; } }
16.79661
148
0.655399
Xaer033
b29735647e323dce1479ed96703f40a43197e0fc
1,335
cpp
C++
Cracking coding Interview/Array and String/URLify.cpp
jv640/Coding
19bda40200ee1fdcc16bb3dc174fe14c7090b58d
[ "MIT" ]
null
null
null
Cracking coding Interview/Array and String/URLify.cpp
jv640/Coding
19bda40200ee1fdcc16bb3dc174fe14c7090b58d
[ "MIT" ]
null
null
null
Cracking coding Interview/Array and String/URLify.cpp
jv640/Coding
19bda40200ee1fdcc16bb3dc174fe14c7090b58d
[ "MIT" ]
null
null
null
/* Description : Write a method to replace all spaces in a string with '%20: You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string/ */ int replaceSpaces(char str[]) { // count spaces and find current length int space_count = 0, i; for (i = 0; str[i]; i++) if (str[i] == ' ') space_count++; // Remove trailing spaces while (str[i-1] == ' ') { space_count--; i--; } // Find new length. int new_length = i + space_count * 2 + 1; // New length must be smaller than length // of string provided. if (new_length > MAX) return -1; // Start filling character from end int index = new_length - 1; // Fill string termination. str[index--] = '\0'; // Fill rest of the string from end for (int j=i-1; j>=0; j--) { // inserts %20 in place of space if (str[j] == ' ') { str[index] = '0'; str[index - 1] = '2'; str[index - 2] = '%'; index = index - 3; } else { str[index] = str[j]; index--; } } return new_length; }
24.722222
174
0.484644
jv640
b29cf73236e924e5609aa88ce9dba0bb6ca75816
5,744
cpp
C++
src/losses.cpp
AvocadoML/ReferenceBackend
391644beb6eacc1982c23aab6ca5104acae4131e
[ "Apache-2.0" ]
null
null
null
src/losses.cpp
AvocadoML/ReferenceBackend
391644beb6eacc1982c23aab6ca5104acae4131e
[ "Apache-2.0" ]
null
null
null
src/losses.cpp
AvocadoML/ReferenceBackend
391644beb6eacc1982c23aab6ca5104acae4131e
[ "Apache-2.0" ]
null
null
null
/* * losses.cpp * * Created on: Nov 25, 2021 * Author: Maciej Kozarzewski */ #include <Avocado/reference_backend.h> #include <Avocado/backend_descriptors.hpp> #include "utils.hpp" namespace { using namespace avocado::backend; template<typename T> T kernel_MSE_loss(const T *output, const T *target, av_int64 elements) noexcept { T result = zero<T>(); for (av_int64 i = 0; i < elements; i++) result += square(output[i] - target[i]); return static_cast<T>(0.5) * result; } template<typename T> void kernel_MSE_gradient(T *gradient, const T *output, const T *target, av_int64 elements, T alpha, T beta) noexcept { if (beta == zero<T>()) clear(gradient, elements); for (av_int64 i = 0; i < elements; i++) gradient[i] = alpha * (output[i] - target[i]) + beta * gradient[i]; } template<typename T> T kernel_CE_loss(const T *output, const T *target, av_int64 elements) noexcept { T result = zero<T>(); for (av_int64 i = 0; i < elements; i++) result += target[i] * safe_log(output[i]) + (one<T>() - target[i]) * safe_log(one<T>() - output[i]); return -result; } template<typename T> void kernel_CE_gradient(T *gradient, const T *output, const T *target, av_int64 elements, T alpha, T beta, bool fused) noexcept { if (beta == zero<T>()) clear(gradient, elements); if (fused) { for (av_int64 i = 0; i < elements; i++) gradient[i] = alpha * (output[i] - target[i]) + beta * gradient[i]; } else { for (av_int64 i = 0; i < elements; i++) gradient[i] = alpha * (output[i] - target[i]) / (eps<T>() + output[i] * (one<T>() - output[i])) + beta * gradient[i]; } } template<typename T> T kernel_KL_loss(const T *output, const T *target, av_int64 elements) noexcept { T result = zero<T>(); for (av_int64 i = 0; i < elements; i++) result += target[i] * safe_log(output[i]) + (one<T>() - target[i]) * safe_log(one<T>() - output[i]) - target[i] * safe_log(target[i]) - (one<T>() - target[i]) * safe_log(one<T>() - target[i]); return -result; } template<typename T> void kernel_KL_gradient(T *gradient, const T *output, const T *target, av_int64 elements, T alpha, T beta, bool fused) noexcept { if (beta == zero<T>()) clear(gradient, elements); if (fused) { for (av_int64 i = 0; i < elements; i++) gradient[i] = alpha * (output[i] - target[i]) + beta * gradient[i]; } else { for (av_int64 i = 0; i < elements; i++) gradient[i] = alpha * (output[i] - target[i]) / (eps<T>() + output[i] * (one<T>() - output[i])) + beta * gradient[i]; } } template<typename T> T loss_helper(avLossType_t lossType, const T *output, const T *target, av_int64 elements) noexcept { switch (lossType) { case AVOCADO_MEAN_SQUARE_LOSS: return kernel_MSE_loss(output, target, elements); case AVOCADO_CROSS_ENTROPY_LOSS: return kernel_CE_loss(output, target, elements); case AVOCADO_KL_DIVERGENCE_LOSS: return kernel_KL_loss(output, target, elements); default: return zero<T>(); } } template<typename T> void gradient_helper(avLossType_t lossType, T *gradient, const T *output, const T *target, av_int64 elements, T alpha, T beta, bool fused) noexcept { switch (lossType) { case AVOCADO_MEAN_SQUARE_LOSS: kernel_MSE_gradient(gradient, output, target, elements, alpha, beta); break; case AVOCADO_CROSS_ENTROPY_LOSS: kernel_CE_gradient(gradient, output, target, elements, alpha, beta, fused); break; case AVOCADO_KL_DIVERGENCE_LOSS: kernel_KL_gradient(gradient, output, target, elements, alpha, beta, fused); break; } } } namespace avocado { namespace backend { using namespace BACKEND_NAMESPACE; avStatus_t refLossFunction(avContextDescriptor_t context, avLossType_t lossType, const avTensorDescriptor_t outputDesc, const avMemoryDescriptor_t outputMem, const avTensorDescriptor_t targetDesc, const avMemoryDescriptor_t targetMem, void *result) { const av_int64 elements = getTensor(outputDesc).volume(); switch (getTensor(outputDesc).dtype()) { case AVOCADO_DTYPE_FLOAT32: { float loss = loss_helper(lossType, getPointer<float>(outputMem), getPointer<float>(targetMem), elements); std::memcpy(result, &loss, sizeof(float)); break; } case AVOCADO_DTYPE_FLOAT64: { double loss = loss_helper(lossType, getPointer<double>(outputMem), getPointer<double>(targetMem), elements); std::memcpy(result, &loss, sizeof(double)); break; } default: return AVOCADO_STATUS_UNSUPPORTED_DATATYPE; } return AVOCADO_STATUS_SUCCESS; } avStatus_t refLossGradient(avContextDescriptor_t context, avLossType_t lossType, const void *alpha, const avTensorDescriptor_t outputDesc, const avMemoryDescriptor_t outputMem, const avTensorDescriptor_t targetDesc, const avMemoryDescriptor_t targetMem, const void *beta, const avTensorDescriptor_t gradientDesc, avMemoryDescriptor_t gradientMem, bool isFused) { const av_int64 elements = getTensor(outputDesc).volume(); switch (getTensor(outputDesc).dtype()) { case AVOCADO_DTYPE_FLOAT32: { gradient_helper(lossType, getPointer<float>(gradientMem), getPointer<float>(outputMem), getPointer<float>(targetMem), elements, getAlphaValue(alpha), getBetaValue(beta), isFused); break; } case AVOCADO_DTYPE_FLOAT64: { gradient_helper(lossType, getPointer<double>(gradientMem), getPointer<double>(outputMem), getPointer<double>(targetMem), elements, getAlphaValue<double>(alpha), getBetaValue<double>(beta), isFused); break; } default: return AVOCADO_STATUS_UNSUPPORTED_DATATYPE; } return AVOCADO_STATUS_SUCCESS; } } /* namespace backend */ } /* namespace avocado */
33.011494
140
0.686281
AvocadoML
b2a44270c5ac741c456296b45b733c5670016c8f
3,458
h++
C++
include/ogonek/segmentation/graphemes.h++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
25
2016-10-21T12:37:23.000Z
2021-02-22T05:46:46.000Z
include/ogonek/segmentation/graphemes.h++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
null
null
null
include/ogonek/segmentation/graphemes.h++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
4
2016-09-05T10:23:18.000Z
2020-07-09T19:37:37.000Z
// Ogonek // // Written in 2012-2013 by Martinho Fernandes <martinho.fernandes@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Grapheme segmentation #ifndef OGONEK_SEGMENTATION_GRAPHEMES_HPP #define OGONEK_SEGMENTATION_GRAPHEMES_HPP #include <ogonek/error/assume_valid.h++> #include <ogonek/segmentation/detail/grapheme_iterator.h++> // TODO uncrapify this one #include <taussig/primitives.h++> #include <wheels/meta.h++> #include <utility> namespace ogonek { namespace detail { template <typename Sequence> struct grapheme_sequence_impl : detail::ogonek_sequence_old<> { public: template <typename SequenceF, wheels::meta::DisableIf<wheels::meta::is_related<grapheme_sequence_impl<Sequence>, SequenceF>>...> explicit grapheme_sequence_impl(SequenceF&& s) : s(std::forward<SequenceF>(s)) {} using value_type = Sequence; using reference = value_type; bool empty() const { return seq::empty(s); } reference front() const { //return seq::before(s, skip_grapheme()); // TODO fix throw ""; } void pop_front() { s = skip_grapheme(); } grapheme_sequence_impl save() const { return *this; } grapheme_sequence_impl before(grapheme_sequence_impl const& that) const { return { s.before(that.s) }; } private: Sequence s; Sequence skip_grapheme() const { auto remaining = s; auto before = seq::front(remaining); seq::pop_front(remaining); do { auto after = seq::front(remaining); if(detail::is_grapheme_boundary(before, after)) break; seq::pop_front(remaining); before = after; } while(!seq::empty(remaining)); return remaining; } }; static_assert(seq::is_true_sequence<grapheme_sequence_impl<std::pair<char const*, char const*>>>(), ""); } // namespace detail template <typename Sequence> using grapheme_sequence = detail::grapheme_sequence_impl<wheels::meta::Decay<Sequence>>; template <typename Sequence, wheels::meta::EnableIf<detail::is_well_formed<Sequence>>...> grapheme_sequence<Sequence> graphemes_ex(Sequence&& s) { return grapheme_sequence<Sequence>(std::forward<Sequence>(s)); } } // namespace ogonek // ---- CRAP BELOW THIS LINE #include <ogonek/detail/ranges.h++> #include <boost/range/iterator_range.hpp> namespace ogonek { template <typename UnicodeSequence, // TODO use UnicodeSequenceIterator typename Iterator = detail::grapheme_iterator<detail::RangeConstIterator<UnicodeSequence>>> boost::iterator_range<Iterator> graphemes(UnicodeSequence const& sequence) { return detail::wrap_range<Iterator>(detail::as_code_point_range(sequence, assume_valid)); } } // namespace ogonek #endif // OGONEK_SEGMENTATION_GRAPHEMES_HPP
37.182796
120
0.643436
libogonek
b2abaced5f1b57ccd0a666a432bb5287208d68b7
4,346
hpp
C++
include/Matrix3.hpp
CCColda/calcda
0d30d2d7c0d8c4abdbf7642e8df2879b9ef7b7a0
[ "MIT" ]
null
null
null
include/Matrix3.hpp
CCColda/calcda
0d30d2d7c0d8c4abdbf7642e8df2879b9ef7b7a0
[ "MIT" ]
null
null
null
include/Matrix3.hpp
CCColda/calcda
0d30d2d7c0d8c4abdbf7642e8df2879b9ef7b7a0
[ "MIT" ]
null
null
null
#ifndef CALCDA_MATRIX3_H #define CALCDA_MATRIX3_H #include <initializer_list> // std::initializer_list #include "Intrinsic.hpp" #include "Rotation.hpp" // Calcda::Rotation #include "Vector2.hpp" // Calcda::Vector2 #include "Vector3.hpp" // Calcda::Vector3 #include <string> namespace Calcda { //! @brief Class for handling 3x3 matrices class Matrix3 { public: //! @brief Containing union type union container_t { //! @brief Per-item layout struct { float m00; float m01; float m02; float m10; float m11; float m12; float m20; float m21; float m22; }; //! @brief 3 by 3 layout float matrix[3][3]; //! @brief row matrix layout float data[9]; } value; public: Matrix3(); Matrix3(const std::initializer_list<float> &List); Matrix3(const Matrix3 &Other); ~Matrix3(); //! @brief Requests the 1st row Vector3 r01() const; //! @brief Requests the 2nd row Vector3 r02() const; //! @brief Requests the 3rd row Vector3 r03() const; //! @brief Requests the 1st column Vector3 c01() const; //! @brief Requests the 2nd column Vector3 c02() const; //! @brief Requests the 3rd column Vector3 c03() const; //! @brief Returns a pointer to the beginning of the data float *getData(); //! @brief Returns a const pointer to the beginning of the data const float *getData() const; //! @brief Multiplies the matrix by @c Other Matrix3 &selfMultiply(const Matrix3 &Other); //! @brief Divides the matrix by @c Other (multiplies by the inverse of @c //! Other) Matrix3 &selfDivide(const Matrix3 &Other); //! @brief Calculates the adjugate of the current matrix Matrix3 calculateAdjugate() const; //! @brief Calculates the determinant for the current matrix double calculateDeterminant() const; /** * @brief Calculates the inverse of the current matrix * @param adjugate Optional; adjugate of the matrix * @param determinant Optional; determinant of the matrix */ Matrix3 inverse(Matrix3 *adjugate = nullptr, double *determinant = nullptr) const; //! @brief Returns the current matrix divided by @c Other Matrix3 divide(const Matrix3 &Other) const; //! @brief Returns the current matrix multiplied by @c Other Matrix3 multiply(const Matrix3 &Other) const; //! @brief Multiplies the current matrix with the vector @c Other, then //! returns the vector result Vector3 multiply(const Vector3 &Other) const; //! @brief Transposes the current matrix (flips it along its top-left to //! bottom-right diagonal) Matrix3 transpose() const; //! @brief Negates every value in the matrix Matrix3 negate() const; Matrix3 operator*(const Matrix3 &Other) const; Vector3 operator*(const Vector3 &Other) const; Matrix3 operator/(const Matrix3 &Other) const; Matrix3 operator-() const; Matrix3 &operator*=(const Matrix3 &Other); Matrix3 &operator/=(const Matrix3 &Other); Matrix3 &operator=(const Matrix3 &Other); bool operator==(const Matrix3 &Other) const; bool operator!=(const Matrix3 &Other) const; /** * @brief Calculates a rotation on @c RotateAxis * @param RotateAxis X, Y, or Z axis, for the rotation to be calculated on * @param Amount Amount of rotation, in radians */ static Matrix3 rotation(Axis RotateAxis, double Amount); //! @brief Transforms the matrix with @c X, @c Y static Matrix3 translation(float X, float Y); //! @brief Transforms the matrix with @c Point.x, @c Point.y static Matrix3 translation(Vector2 Point); //! @brief Scales the matrix with @c X, @c Y static Matrix3 scale(float X, float Y); //! @brief Scales the matrix with @c Point.x, @c Point.y static Matrix3 scale(Vector2 Point); std::string toString() const; std::string toStringO(unsigned int Padding = 0, unsigned int Precision = 2) const; //! @brief Identity matrix, 0 everywhere, except the top-left to //! bottom-right diagonal, where it is 1 static const Matrix3 Identity; }; } // namespace Calcda #endif // !CALCDA_MATRIX4_H
28.973333
78
0.645651
CCColda
b2b3634ccfd0f8cf7b428301b2b6bcc576370662
5,716
hpp
C++
include/smooth/c1.hpp
tgurriet/smooth
c19e35e23c8e0084314726729d0cf6729192240f
[ "MIT" ]
31
2021-07-06T21:05:05.000Z
2022-02-09T13:26:44.000Z
include/smooth/c1.hpp
tgurriet/smooth
c19e35e23c8e0084314726729d0cf6729192240f
[ "MIT" ]
23
2021-07-07T21:13:49.000Z
2022-03-19T04:40:37.000Z
include/smooth/c1.hpp
tgurriet/smooth
c19e35e23c8e0084314726729d0cf6729192240f
[ "MIT" ]
6
2021-07-09T07:16:08.000Z
2022-01-12T14:29:44.000Z
// smooth: Lie Theory for Robotics // https://github.com/pettni/smooth // // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // // Copyright (c) 2021 Petter Nilsson // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef SMOOTH__C1_HPP_ #define SMOOTH__C1_HPP_ #include <Eigen/Core> #include <complex> #include "internal/c1.hpp" #include "internal/lie_group_base.hpp" #include "internal/macro.hpp" #include "lie_group.hpp" #include "map.hpp" #include "so2.hpp" namespace smooth { // \cond template<typename Scalar> class SO2; // \endcond /** * @brief Base class for C1 Lie group types. * * Memory layout * ------------- * * - Group: \f$ \mathbf{x} = [a, b] \f$ * - Tangent: \f$ \mathbf{a} = [s, \omega_z] \f$ * * Constraints * ----------- * * - Group: \f$ a^2 + b^2 > 0 \f$ * - Tangent: \f$ -\pi < \omega_z \leq \pi \f$ * * Lie group matrix form * --------------------- * * \f[ * \mathbf{X} = * \begin{bmatrix} * b & -a \\ * a & b * \end{bmatrix} \in \mathbb{R}^{2 \times 2} * \f] * * * Lie algebra matrix form * ----------------------- * * \f[ * \mathbf{a}^\wedge = * \begin{bmatrix} * s & -\omega_z \\ * \omega_z & s \\ * \end{bmatrix} \in \mathbb{R}^{2 \times 2} * \f] */ template<typename _Derived> class C1Base : public LieGroupBase<_Derived> { using Base = LieGroupBase<_Derived>; protected: C1Base() = default; public: SMOOTH_INHERIT_TYPEDEFS; /** * @brief Rotation angle. */ Scalar angle() const { using std::atan2; return atan2( static_cast<const _Derived &>(*this).coeffs().x(), static_cast<const _Derived &>(*this).coeffs().y()); } /** * @brief Scaling. */ Scalar scaling() const { using std::sqrt; return sqrt( static_cast<const _Derived &>(*this).coeffs().x() * static_cast<const _Derived &>(*this).coeffs().x() + static_cast<const _Derived &>(*this).coeffs().y() * static_cast<const _Derived &>(*this).coeffs().y()); } /** * @brief Rotation. */ SO2<Scalar> so2() const { return SO2<Scalar>(c1()); // it's normalized inside SO2 } /** * @brief Complex number representation. */ std::complex<Scalar> c1() const { return std::complex<Scalar>( static_cast<const _Derived &>(*this).coeffs().y(), static_cast<const _Derived &>(*this).coeffs().x()); } /** * @brief Rotation and scaling action on 2D vector. */ template<typename EigenDerived> Eigen::Matrix<Scalar, 2, 1> operator*(const Eigen::MatrixBase<EigenDerived> & v) const { return Base::matrix() * v; } }; // \cond template<typename _Scalar> class C1; // \endcond // \cond template<typename _Scalar> struct liebase_info<C1<_Scalar>> { static constexpr bool is_mutable = true; using Impl = C1Impl<_Scalar>; using Scalar = _Scalar; template<typename NewScalar> using PlainObject = C1<NewScalar>; }; // \endcond /** * @brief Storage implementation of C1 Lie group. * * @see C1Base for memory layout. */ template<typename _Scalar> class C1 : public C1Base<C1<_Scalar>> { using Base = C1Base<C1<_Scalar>>; SMOOTH_GROUP_API(C1); public: /** * @brief Construct from scaling and angle. * * @param scaling strictly greater than zero. * @param angle angle of rotation (radians). */ C1(const Scalar & scaling, const Scalar & angle) { using std::cos, std::sin; coeffs_.x() = scaling * sin(angle); coeffs_.y() = scaling * cos(angle); } /** * @brief Construct from complex number. * * @param c complex number. */ C1(const std::complex<Scalar> & c) { coeffs_.x() = c.imag(); coeffs_.y() = c.real(); } }; // \cond template<typename _Scalar> struct liebase_info<Map<C1<_Scalar>>> : public liebase_info<C1<_Scalar>> {}; // \endcond /** * @brief Memory mapping of C1 Lie group. * * @see C1Base for memory layout. */ template<typename _Scalar> class Map<C1<_Scalar>> : public C1Base<Map<C1<_Scalar>>> { using Base = C1Base<Map<C1<_Scalar>>>; SMOOTH_MAP_API(); }; // \cond template<typename _Scalar> struct liebase_info<Map<const C1<_Scalar>>> : public liebase_info<C1<_Scalar>> { static constexpr bool is_mutable = false; }; // \endcond /** * @brief Const memory mapping of C1 Lie group. * * @see C1Base for memory layout. */ template<typename _Scalar> class Map<const C1<_Scalar>> : public C1Base<Map<const C1<_Scalar>>> { using Base = C1Base<Map<const C1<_Scalar>>>; SMOOTH_CONST_MAP_API(); }; using C1f = C1<float>; ///< C1 with float scalar representation using C1d = C1<double>; ///< C1 with double scalar representation } // namespace smooth #endif // SMOOTH__C1_HPP_
22.592885
88
0.647481
tgurriet
b2b448081e570f152ecb5186ac7edce3b04d01ba
3,526
hpp
C++
include/edlib/EDP/LocalHamiltonian.hpp
cecri/ExactDiagonalization
a168ed2f60149b1c3e5bd9ae46a5d169aea76773
[ "MIT" ]
null
null
null
include/edlib/EDP/LocalHamiltonian.hpp
cecri/ExactDiagonalization
a168ed2f60149b1c3e5bd9ae46a5d169aea76773
[ "MIT" ]
null
null
null
include/edlib/EDP/LocalHamiltonian.hpp
cecri/ExactDiagonalization
a168ed2f60149b1c3e5bd9ae46a5d169aea76773
[ "MIT" ]
null
null
null
#pragma once #include <Eigen/Sparse> namespace edp { namespace internal { inline uint32_t ipow(uint32_t base, uint32_t exp) { uint32_t result = 1U; while(exp != 0) { if((exp & 1U) != 0) { result *= base; } exp >>= 1U; base *= base; } return result; } } template<typename T> struct TwoSiteTerm { std::pair<uint32_t, uint32_t> sites; Eigen::SparseMatrix<T> m; TwoSiteTerm(std::pair<uint32_t, uint32_t> p1, const Eigen::SparseMatrix<T>& p2) : sites(std::move(p1)), m(p2) { } TwoSiteTerm(std::pair<uint32_t, uint32_t>&& p1, Eigen::SparseMatrix<T>&& p2) : sites(p1), m(p2) { } }; template<typename T> struct OneSiteTerm { uint32_t site; Eigen::SparseMatrix<T> m; OneSiteTerm(uint32_t p1, const Eigen::SparseMatrix<T>& p2) : site(p1), m(p2) { } OneSiteTerm(uint32_t p1, Eigen::SparseMatrix<T>&& p2) : site(p1), m(p2) { } }; template<typename T> class LocalHamiltonian { private: uint32_t numSites_; uint64_t d_; // local Hibert dimension std::vector<TwoSiteTerm<T>> twoSiteTerms_; std::vector<OneSiteTerm<T>> oneSiteTerms_; [[nodiscard]] uint32_t swapBaseD(uint32_t idx, uint32_t pos, uint32_t val) const { uint32_t b = internal::ipow(d_, pos); uint32_t upper = (idx / (b * d_)) * d_ + val; return upper * b + (idx % b); } public: LocalHamiltonian(uint32_t numSites, uint32_t d) : numSites_{numSites}, d_{d} { } void clearTerms() { std::vector<TwoSiteTerm<T>>().swap(twoSiteTerms_); std::vector<OneSiteTerm<T>>().swap(oneSiteTerms_); } [[nodiscard]] uint32_t getNumSites() const { return numSites_; } [[nodiscard]] std::map<uint32_t, T> getCol(uint32_t n) const; [[nodiscard]] inline std::map<uint32_t, T> operator()(uint32_t n) const { return getCol(n); } void addTwoSiteTerm(const std::pair<int, int>& site, Eigen::SparseMatrix<T> m) { m.makeCompressed(); twoSiteTerms_.emplace_back(site, std::move(m)); } void addOneSiteTerm(uint32_t site, Eigen::SparseMatrix<T> m) { m.makeCompressed(); oneSiteTerms_.emplace_back(site, std::move(m)); } }; } // namespace edp template<typename T> std::map<uint32_t, T> edp::LocalHamiltonian<T>::getCol(uint32_t n) const { using Eigen::SparseMatrix; using internal::ipow; std::map<uint32_t, T> m; for(auto& twoSiteTerm : twoSiteTerms_) { auto a = (n / ipow(d_, twoSiteTerm.sites.first)) % d_; auto b = (n / ipow(d_, twoSiteTerm.sites.second)) % d_; // auto col = twoSiteTerm.m.col(a*d_ + b); auto col = b * d_ + a; for(typename SparseMatrix<T>::InnerIterator it(twoSiteTerm.m, col); it; ++it) { uint32_t r = it.row(); uint32_t t = n; t = swapBaseD(t, twoSiteTerm.sites.first, r % d_); t = swapBaseD(t, twoSiteTerm.sites.second, r / d_); m[t] += it.value(); } } for(auto& oneSiteTerm : oneSiteTerms_) { uint32_t a = (n / ipow(d_, oneSiteTerm.site)) % d_; // auto col = oneSiteTerm.m.col(a); auto col = a; for(typename SparseMatrix<T>::InnerIterator it(oneSiteTerm.m, col); it; ++it) { uint32_t r = it.row(); uint32_t t = n; t = swapBaseD(t, oneSiteTerm.site, r); m[t] += it.value(); } } return m; }
27.76378
99
0.577708
cecri
b2b58a468617610f26a94ce21af9b0d8c5a552ee
7,484
cpp
C++
Implementations/content/strings (14)/Heavy/SuffixArrayTest.cpp
wanglawrence9990/USACO
45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2
[ "CC0-1.0" ]
null
null
null
Implementations/content/strings (14)/Heavy/SuffixArrayTest.cpp
wanglawrence9990/USACO
45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2
[ "CC0-1.0" ]
null
null
null
Implementations/content/strings (14)/Heavy/SuffixArrayTest.cpp
wanglawrence9990/USACO
45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2
[ "CC0-1.0" ]
1
2021-07-04T02:36:09.000Z
2021-07-04T02:36:09.000Z
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef double db; typedef string str; typedef pair<int, int> pi; typedef pair<ll,ll> pl; typedef pair<ld,ld> pd; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<ld> vd; typedef vector<str> vs; typedef vector<pi> vpi; typedef vector<pl> vpl; #define FOR(i,a,b) for (int i = (a); i < (b); ++i) #define F0R(i,a) FOR(i,0,a) #define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i) #define R0F(i,a) ROF(i,0,a) #define trav(a,x) for (auto& a: x) #define sz(x) (int)x.size() #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) #define rsz resize #define ins insert #define mp make_pair #define pb push_back #define eb emplace_back #define f first #define s second #define lb lower_bound #define ub upper_bound const int MOD = 1e9+7; // 998244353; // = (119<<23)+1 const int MX = 2e5+5; const ll INF = 1e18; const ld PI = 4*atan((ld)1); template<class T> bool ckmin(T& a, const T& b) { return a > b ? a = b, 1 : 0; } template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); namespace input { template<class T> void re(complex<T>& x); template<class T1, class T2> void re(pair<T1,T2>& p); template<class T> void re(vector<T>& a); template<class T, size_t SZ> void re(array<T,SZ>& a); template<class T> void re(T& x) { cin >> x; } void re(double& x) { string t; re(t); x = stod(t); } void re(ld& x) { string t; re(t); x = stold(t); } template<class T, class... Ts> void re(T& t, Ts&... ts) { re(t); re(ts...); } template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = cd(a,b); } template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); } template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); } template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); } } using namespace input; namespace output { void pr(int x) { cout << x; } void pr(long x) { cout << x; } void pr(ll x) { cout << x; } void pr(unsigned x) { cout << x; } void pr(unsigned long x) { cout << x; } void pr(unsigned long long x) { cout << x; } void pr(float x) { cout << x; } void pr(double x) { cout << x; } void pr(ld x) { cout << x; } void pr(char x) { cout << x; } void pr(const char* x) { cout << x; } void pr(const string& x) { cout << x; } void pr(bool x) { pr(x ? "true" : "false"); } template<class T> void pr(const complex<T>& x) { cout << x; } template<class T1, class T2> void pr(const pair<T1,T2>& x); template<class T> void pr(const T& x); template<class T, class... Ts> void pr(const T& t, const Ts&... ts) { pr(t); pr(ts...); } template<class T1, class T2> void pr(const pair<T1,T2>& x) { pr("{",x.f,", ",x.s,"}"); } template<class T> void pr(const T& x) { pr("{"); // const iterator needed for vector<bool> bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0; pr("}"); } void ps() { pr("\n"); } // print w/ spaces template<class T, class... Ts> void ps(const T& t, const Ts&... ts) { pr(t); if (sizeof...(ts)) pr(" "); ps(ts...); } void pc() { pr("]\n"); } // debug w/ commas template<class T, class... Ts> void pc(const T& t, const Ts&... ts) { pr(t); if (sizeof...(ts)) pr(", "); pc(ts...); } #define dbg(x...) pr("[",#x,"] = ["), pc(x); } using namespace output; namespace io { void setIn(string s) { freopen(s.c_str(),"r",stdin); } void setOut(string s) { freopen(s.c_str(),"w",stdout); } void setIO(string s = "") { cin.sync_with_stdio(0); cin.tie(0); // fast I/O // cin.exceptions(cin.failbit); // ex. throws exception when you try to read letter into int if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO } } using namespace io; typedef decay<decltype(MOD)>::type T; struct mi { T val; explicit operator T() const { return val; } mi() { val = 0; } mi(const ll& v) { val = (-MOD <= v && v <= MOD) ? v : v % MOD; if (val < 0) val += MOD; } // friend ostream& operator<<(ostream& os, const mi& a) { // return os << a.val; } friend void pr(const mi& a) { pr(a.val); } friend void re(mi& a) { ll x; re(x); a = mi(x); } friend bool operator==(const mi& a, const mi& b) { return a.val == b.val; } friend bool operator!=(const mi& a, const mi& b) { return !(a == b); } friend bool operator<(const mi& a, const mi& b) { return a.val < b.val; } mi operator-() const { return mi(-val); } mi& operator+=(const mi& m) { if ((val += m.val) >= MOD) val -= MOD; return *this; } mi& operator-=(const mi& m) { if ((val -= m.val) < 0) val += MOD; return *this; } mi& operator*=(const mi& m) { val = (ll)val*m.val%MOD; return *this; } friend mi pow(mi a, ll p) { mi ans = 1; assert(p >= 0); for (; p; p /= 2, a *= a) if (p&1) ans *= a; return ans; } friend mi inv(const mi& a) { assert(a != 0); return pow(a,MOD-2); } mi& operator/=(const mi& m) { return (*this) *= inv(m); } friend mi operator+(mi a, const mi& b) { return a += b; } friend mi operator-(mi a, const mi& b) { return a -= b; } friend mi operator*(mi a, const mi& b) { return a *= b; } friend mi operator/(mi a, const mi& b) { return a /= b; } }; typedef pair<mi,mi> pmi; typedef vector<mi> vmi; typedef vector<pmi> vpmi; struct SuffixArray { string S; int N; void init(const string& _S) { S = _S; N = sz(S); genSa(); genLcp(); // R.init(lcp); } vi sa, isa; void genSa() { sa.rsz(N), isa.rsz(N); iota(all(sa),0); sort(all(sa),[&](int a, int b) { return S[a] < S[b]; }); F0R(i,N) { bool same = i && S[sa[i]] == S[sa[i-1]]; isa[sa[i]] = same ? isa[sa[i-1]] : i; } for (int len = 1; len < N; len *= 2) { // sufs currently sorted by first len chars vi is(isa), s(sa), nex(N); iota(all(nex),0); FOR(i,-1,N) { // rearrange sufs by 2*len int s1 = (i == -1 ? N : s[i])-len; if (s1 >= 0) sa[nex[isa[s1]]++] = s1; } F0R(i,N) { // update isa for 2*len bool same = i && sa[i-1]+len < N && is[sa[i]] == is[sa[i-1]] && is[sa[i]+len] == is[sa[i-1]+len]; isa[sa[i]] = same ? isa[sa[i-1]] : i; } } } vi lcp; void genLcp() { // Kasai's Algo lcp = vi(N-1); int h = 0; F0R(i,N) if (isa[i]) { for (int j=sa[isa[i]-1]; j+h<N && S[i+h]==S[j+h]; h++); lcp[isa[i]-1] = h; if (h) h--; } // if we cut off first chars of two strings with lcp h // then remaining portions still have lcp h-1 } /*RMQ<int> R; int getLCP(int a, int b) { // lcp of suffixes starting at a,b if (max(a,b) >= N) return 0; if (a == b) return N-a; int t0 = isa[a], t1 = isa[b]; if (t0 > t1) swap(t0,t1); return R.query(t0,t1-1); }*/ }; pair<vi,vi> smart(str s) { SuffixArray S; S.init(s); return {S.sa,S.isa}; } pair<vi,vi> dumb(str s) { vi sa(sz(s)); iota(all(sa),0); sort(all(sa),[&](int a, int b) { return s.substr(a,sz(s)-a) < s.substr(b,sz(s)-b); }); vi isa(sz(s)); F0R(i,sz(sa)) isa[sa[i]] = i; return {sa,isa}; } void dfs(str s = "") { if (sz(s)) { auto a = smart(s); auto b = dumb(s); if (a != b) { ps("BAD",s,a,b); exit(0); } } if (sz(s) == 10) return; F0R(i,3) dfs(s+char('a'+i)); } int main() { cin.sync_with_stdio(0); cin.tie(0); dfs(); // you should actually read the stuff at the bottom } /* stuff you should look for * int overflow, array bounds * special cases (n=1?), slow multiset operations * do smth instead of nothing and stay organized */
28.241509
94
0.563201
wanglawrence9990
b2c369a20d23a70445a99c42cc27e5bd2b1168d8
1,193
cpp
C++
cpp/src/exercise/e0900/e0892.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0900/e0892.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0900/e0892.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/surface-area-of-3d-shapes/ #include "extern.h" class S0892 { public: int surfaceArea(vector<vector<int>>& grid) { if (grid.empty() || grid.front().empty()) return 0; int r_size = grid.size(), c_size = grid.front().size(); int result = 0; for (int r = 0; r < r_size; ++r) { for (int c = 0; c < c_size; ++c) { result += (grid[r][c] == 0) ? 0 : 4 * grid[r][c] + 2; if (r > 0) result -= 2 * min(grid[r][c], grid[r - 1][c]); if (c > 0) result -= 2 * min(grid[r][c], grid[r][c - 1]); } } return result; } }; TEST(e0900, e0892) { vector<vector<int>> grid; grid = str_to_mat<int>("[[2]]"); ASSERT_EQ(S0892().surfaceArea(grid), 10); grid = str_to_mat<int>("[[1,2],[3,4]]"); ASSERT_EQ(S0892().surfaceArea(grid), 34); grid = str_to_mat<int>("[[1,0],[0,2]]"); ASSERT_EQ(S0892().surfaceArea(grid), 16); grid = str_to_mat<int>("[[1,1,1],[1,0,1],[1,1,1]]"); ASSERT_EQ(S0892().surfaceArea(grid), 32); grid = str_to_mat<int>("[[2,2,2],[2,1,2],[2,2,2]]"); ASSERT_EQ(S0892().surfaceArea(grid), 46); }
34.085714
73
0.50964
ajz34
b2c76d68c287040000c84c2c6f878d977b19a5af
1,897
cpp
C++
SortingAndSearching/SlidingMedian/m2.cpp
0x5eba/CSES-solutions
c18b66262f5dbef44b58d793f5185c3d0cf3a77c
[ "MIT" ]
27
2019-12-23T21:20:00.000Z
2022-02-06T04:28:27.000Z
SortingAndSearching/SlidingMedian/m2.cpp
0x5eba/CSES-solutions
c18b66262f5dbef44b58d793f5185c3d0cf3a77c
[ "MIT" ]
2
2020-04-14T21:40:43.000Z
2020-09-06T11:15:42.000Z
SortingAndSearching/SlidingMedian/m2.cpp
0x5eba/CSES-solutions
c18b66262f5dbef44b58d793f5185c3d0cf3a77c
[ "MIT" ]
9
2020-05-22T08:00:29.000Z
2021-09-14T09:01:58.000Z
#include<bits/stdc++.h> using namespace std; typedef pair<int,int> ii; typedef long long ll; bool mysort(ii &a, ii &b) { return (a.first < b.first); } template<typename T> T getint() { T val=0; char c; bool neg=false; while((c=getchar()) && !(c>='0' && c<='9')) { neg|=c=='-'; } do { val=(val*10)+c-'0'; } while((c=getchar()) && (c>='0' && c<='9')); return val*(neg?-1:1); } int main() { ios::sync_with_stdio(0); cin.tie(0); int N = getint<int>(); int K = getint<int>(); bool pari = false; int middle = (int)(K/2)+1; if(K%2 == 0){ pari = true; middle = (int)(K/2); } middle--; vector<int> v; queue<int> first_k_elm; for(int a = 0; a < K; ++a){ int val = getint<int>(); first_k_elm.push(val); v.push_back(val); } sort(v.begin(), v.end()); // if(pari){ // cout << min(v[middle], v[middle+1]) << " "; // } else { // cout << v[middle] << " "; // } auto pos = lower_bound(v.begin(), v.end(), first_k_elm.front()) - v.begin(); v.erase(v.begin() + pos); first_k_elm.pop(); // cout << endl; // for(auto a : v){ // cout << a << endl; // } // return 0; for(int a = K; a < N; ++a){ int val = getint<int>(); v.push_back(val); first_k_elm.push(val); int middleone = v[middle]; cout << middleone << endl; if(val > middleone){ middle--; } else { middle++; } // sort(v.begin(), v.end()); // if(pari){ // cout << min(v[middle], v[middle+1]) << " "; // } else { // cout << v[middle] << " "; // } auto pos = lower_bound(v.begin(), v.end(), first_k_elm.front()) - v.begin(); v.erase(v.begin() + pos); first_k_elm.pop(); } return 0; }
20.180851
84
0.448603
0x5eba
b2c8aeded0904b0b2479c8225e17385703a8f9ec
511
hpp
C++
src/acceleration/bbox.hpp
gosteponlegopls/inferno
b007277be1c0500403bd46c93b279c02615fbb17
[ "MIT" ]
13
2019-09-09T09:29:27.000Z
2019-10-26T00:04:29.000Z
src/acceleration/bbox.hpp
gosteponlegopls/inferno
b007277be1c0500403bd46c93b279c02615fbb17
[ "MIT" ]
null
null
null
src/acceleration/bbox.hpp
gosteponlegopls/inferno
b007277be1c0500403bd46c93b279c02615fbb17
[ "MIT" ]
1
2019-10-07T15:44:23.000Z
2019-10-07T15:44:23.000Z
#ifndef INFERNO_ACCELERATION_BBOX_H_ #define INFERNO_ACCELERATION_BBOX_H_ #include "../maths.hpp" class Ray; class Triangle; class BBox { public: glm::vec3 vmin, vmax; BBox(); void MakeEmpty(); void Add(glm::vec3 vec); bool Inside(glm::vec3 v); bool TestIntersect(Ray& ray); float ClosestIntersection(Ray& ray); bool IntersectTriangle(Triangle& triangle); void Split(Axis axis, float where, BBox& left, BBox& right); bool IntersectWall(Axis axis, float where, const Ray& ray); }; #endif
20.44
64
0.726027
gosteponlegopls
b2cd318fd9d56335f1794610ba1da280fd11d400
2,298
cpp
C++
GenericExpressInstanceParserTests/BenchmarkTestCase.cpp
quinte17/GenericExpressInstanceParser
cfa5736e73fb34cc1fa86f87f7dcd1e74218c42f
[ "Zlib" ]
null
null
null
GenericExpressInstanceParserTests/BenchmarkTestCase.cpp
quinte17/GenericExpressInstanceParser
cfa5736e73fb34cc1fa86f87f7dcd1e74218c42f
[ "Zlib" ]
6
2015-02-15T13:35:19.000Z
2015-02-15T14:41:05.000Z
GenericExpressInstanceParserTests/BenchmarkTestCase.cpp
quinte17/GenericExpressInstanceParser
cfa5736e73fb34cc1fa86f87f7dcd1e74218c42f
[ "Zlib" ]
null
null
null
#include "BenchmarkTestCase.h" //qt inlcudes #include <QTest> //stl includes #include <sstream> //generic express instance parser (geip) inclues #include <GenericExpressInstanceParser.h> BenchmarkTestCase::BenchmarkTestCase(QObject *parent) : QObject(parent) { } BenchmarkTestCase::~BenchmarkTestCase() { } /*****************************/ //init and cleanup functions /*****************************/ void BenchmarkTestCase::initTestCase() { } void BenchmarkTestCase::cleanupTestCase() { } void BenchmarkTestCase::init() { m_parser.reset(new geip::GenericExpressInstanceParser()); } void BenchmarkTestCase::cleanup() { } /*****************************/ //benchmark functions /*****************************/ void BenchmarkTestCase::benchmark_parsing_data() { QTest::addColumn<int>("loopCount"); QTest::newRow(".") << 1; QTest::newRow("..") << 10; QTest::newRow("...") << 100; QTest::newRow("....") << 1000; } void BenchmarkTestCase::benchmark_parsing() { QFETCH(int, loopCount); //init test data set std::stringstream instances; for(int i = 0; i < loopCount; ++i){ instances << "Entity()"; instances << "Entity ( ) Entity()"; instances << "EnumType(type := USER)"; instances << "EnumType(type:=\"USER\")"; instances << "EnumType(type1 := USER, type2 := SYSTEM)"; instances << "EnumType(type1 := USER, type2 := Entity())"; instances << "ListType(emptyList := [])"; instances << "ListType(elements:= [Entity1(), Entity2()])"; instances << "Pair(key:=\"591\",value:=\"1900\")"; instances << "Error (number:=24973)"; instances << "Error (number:=+24973)"; instances << "Error (number:=-24973)"; instances << "Error (number:=24973.44)"; instances << "Error (number:=-123.45)"; instances << "Error (number:=+123.45)"; instances << "Min (min:=3.45)"; instances << "StringList (elements:= [\"element 1\",\"element 2\"])"; instances << "User(name:=\"aaä\")"; } QBENCHMARK { std::list<geip::EntityInstance*> entities = m_parser->parse(instances.str()); foreach (geip::EntityInstance* entity, entities) { delete entity; } entities.clear(); } }
23.44898
85
0.568755
quinte17
b2ceff915f080f48571331a4f045f1088351e225
1,166
cpp
C++
utils/print_stats.cpp
ndvbd/tongrams
a301022cd01a21f542757c22b6738ff647887e00
[ "Apache-2.0" ]
null
null
null
utils/print_stats.cpp
ndvbd/tongrams
a301022cd01a21f542757c22b6738ff647887e00
[ "Apache-2.0" ]
null
null
null
utils/print_stats.cpp
ndvbd/tongrams
a301022cd01a21f542757c22b6738ff647887e00
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "../lm_types.hpp" #include "util.hpp" #include "stats.cpp" using namespace tongrams; template<typename T> void print_stats(const char* binary_filename) { T model; util::logger("Loading data structure"); size_t bytes = util::load(model, binary_filename); model.print_stats(bytes); } int main(int argc, char** argv) { if (argc < 2 || building_util::request_help(argc, argv)) { building_util::display_legend(); std::cerr << "Usage " << argv[0] << ":\n" << "\t" << style::bold << style::underline << "binary_filename" << style::off << std::endl; return 1; } const char* binary_filename = argv[1]; auto model_string_type = util::get_model_type(binary_filename); if (false) { #define LOOP_BODY(R, DATA, T) \ } else if (model_string_type == BOOST_PP_STRINGIZE(T)) { \ print_stats<T>(binary_filename); \ BOOST_PP_SEQ_FOR_EACH(LOOP_BODY, _, SXLM_TYPES); #undef LOOP_BODY } else { building_util::unknown_type(model_string_type); } return 0; }
27.116279
95
0.593482
ndvbd
b2d37ae701bdb5a596446000a15e667c0b88cee3
588
cpp
C++
Source/SA/Logger/Streams/ALogStream.cpp
SapphireSuite/Logger
c922f1b0899274cc586df66b18572da55f4a3e2a
[ "MIT" ]
null
null
null
Source/SA/Logger/Streams/ALogStream.cpp
SapphireSuite/Logger
c922f1b0899274cc586df66b18572da55f4a3e2a
[ "MIT" ]
1
2022-02-08T18:52:56.000Z
2022-02-08T18:52:56.000Z
Source/SA/Logger/Streams/ALogStream.cpp
SapphireSuite/Logger
c922f1b0899274cc586df66b18572da55f4a3e2a
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Sapphire's Suite. All Rights Reserved. #include <Streams/ALogStream.hpp> namespace Sa { void ALogStream::ProcessLog(const Log& _log, bool _bForce) { if (_bForce) { Output(_log); return; } const bool bLevelEnabled = levelFlags & _log.level; const bool bChannelEnabled = channelFilter.IsChannelEnabled(_log.chanName); if (bLevelEnabled && bChannelEnabled) Output(_log); } void ALogStream::Flush() { /* Implementation in children */ } ALogStream& ALogStream::operator<<(const Log& _log) { ProcessLog(_log); return *this; } }
16.8
77
0.693878
SapphireSuite
b2d9e93db99c1ec59c85467669589c93523066b3
4,349
hpp
C++
test/data_sampler.hpp
youruncleda/relative_pose
cb613f210a812e03754fbfc9c2e93d1f6fe4a265
[ "BSD-3-Clause" ]
21
2020-07-08T17:58:17.000Z
2022-02-28T03:58:37.000Z
test/data_sampler.hpp
taogashi/relative_pose
cb613f210a812e03754fbfc9c2e93d1f6fe4a265
[ "BSD-3-Clause" ]
null
null
null
test/data_sampler.hpp
taogashi/relative_pose
cb613f210a812e03754fbfc9c2e93d1f6fe4a265
[ "BSD-3-Clause" ]
5
2020-07-24T01:26:28.000Z
2020-10-13T13:32:48.000Z
#include <opencv2/opencv.hpp> double ANGLE_EPSILON = 1e-5; struct DataSampler { bool zero_screw_transl; double angle_bound, nearest_dist, baseline_turb, depth, focal, half_size, noise, outlier_rate; cv::Vec3d baseline; cv::RNG rng; DataSampler(); void sampleRays(int num_points, cv::OutputArray _rvec, cv::OutputArray _tvec, cv::OutputArray _image_rays1, cv::OutputArray _image_rays2); cv::Mat1d cameraMatrix() const; void samplePoints(int num_points, cv::OutputArray _rvec, cv::OutputArray _tvec, cv::OutputArray _image_points1, cv::OutputArray _image_points2); }; DataSampler::DataSampler() { rng = cv::RNG(211); angle_bound = CV_PI / 18; nearest_dist = 10; baseline_turb = 0.05; baseline = {0, 0, -1}; depth = 10; focal = 300; half_size = 175; noise = 0; outlier_rate = 0; zero_screw_transl = true; } cv::Mat1d DataSampler::cameraMatrix() const { cv::Mat1d camera_matrix(3, 3); camera_matrix << focal, 0, 0, 0, focal, 0, 0, 0, 1; return camera_matrix; } void assignOutputArray(cv::Mat mat, cv::OutputArray output) { if (output.fixedType()) { mat = mat.reshape(output.channels()); mat.convertTo(mat, output.type()); } output.create(mat.size(), mat.type()); // FIXME(libo): Work-around for https://github.com/opencv/opencv/issues/5350 if (output.kind() == cv::_InputArray::STD_VECTOR) mat = mat.t(); mat.copyTo(output.getMat()); } void DataSampler::sampleRays(int num_rays, cv::OutputArray _rvec, cv::OutputArray _tvec, cv::OutputArray _image_rays1, cv::OutputArray _image_rays2) { using namespace cv; Mat2d image_points1, image_points2; samplePoints(num_rays, _rvec, _tvec, image_points1, image_points2); Mat3d image_rays1, image_rays2; convertPointsToHomogeneous(image_points1.reshape(1) / focal, image_rays1); convertPointsToHomogeneous(image_points2.reshape(1) / focal, image_rays2); assignOutputArray(image_rays1, _image_rays1); assignOutputArray(image_rays2, _image_rays2); } void DataSampler::samplePoints(int num_points, cv::OutputArray _rvec, cv::OutputArray _tvec, cv::OutputArray _image_points1, cv::OutputArray _image_points2) { using namespace cv; Vec3d rvec, tvec, cvec; rng.fill(rvec, RNG::UNIFORM, -angle_bound, angle_bound); rng.fill(cvec, RNG::UNIFORM, -baseline_turb, baseline_turb); cvec += baseline; double angle = norm(rvec); Matx33d rmat; Rodrigues(rvec, rmat); tvec = -rmat * cvec; if (zero_screw_transl && angle > ANGLE_EPSILON) tvec -= (rvec / angle) * (tvec.dot(rvec) / angle); auto camera_matrix = cameraMatrix(); Mat1d object_points(num_points, 3); rng.fill(object_points, RNG::UNIFORM, -half_size, half_size); object_points.col(2) = 1; object_points = camera_matrix.inv() * object_points.t(); object_points = object_points.t(); Mat1d ds(num_points, 1); rng.fill(ds, RNG::UNIFORM, nearest_dist, nearest_dist + depth); multiply(object_points, repeat(ds, 1, 3), object_points); Mat image_points1, image_points2; projectPoints(object_points, Matx13d::zeros(), Matx13d::zeros(), camera_matrix, noArray(), image_points1); projectPoints(object_points, rvec, tvec, camera_matrix, noArray(), image_points2); int num_outliers = std::floor(num_points * outlier_rate); if (num_outliers > 0) { rng.fill(image_points1.rowRange(0, num_outliers), RNG::UNIFORM, -half_size, half_size); rng.fill(image_points2.rowRange(0, num_outliers), RNG::UNIFORM, -half_size, half_size); } if (_image_points1.fixedType()) { assert(_image_points2.fixedType() && image_points1.type() == image_points2.type()); image_points1 = image_points1.reshape(_image_points1.channels()); image_points1.convertTo(image_points1, _image_points1.type()); image_points2 = image_points2.reshape(_image_points2.channels()); image_points2.convertTo(image_points2, _image_points2.type()); } assignOutputArray(image_points1, _image_points1); assignOutputArray(image_points2, _image_points2); _rvec.assign(Mat(rvec)); _tvec.assign(Mat(tvec)); }
31.28777
83
0.675328
youruncleda
b2dbd22913caabe1dd52abe4ff37accd261dd658
1,528
cpp
C++
src/body_interact_game/body_analizer.cpp
forno/body_interact_game
8668c45fbe4c0d91aa1345b6c833d3b507920669
[ "BSD-3-Clause" ]
1
2021-04-26T04:44:19.000Z
2021-04-26T04:44:19.000Z
src/body_interact_game/body_analizer.cpp
forno/body_interact_game
8668c45fbe4c0d91aa1345b6c833d3b507920669
[ "BSD-3-Clause" ]
null
null
null
src/body_interact_game/body_analizer.cpp
forno/body_interact_game
8668c45fbe4c0d91aa1345b6c833d3b507920669
[ "BSD-3-Clause" ]
null
null
null
#include <body_interact_game/body_analizer.hpp> #include <Eigen/SVD> namespace { constexpr auto pi {3.141592653589793}; inline Eigen::AngleAxisd get_yaw_inverse_matrix(Eigen::Affine3d pos) noexcept { const auto ypr {pos.rotation().eulerAngles(2, 0, 1)}; const auto yaw_angle {ypr(0) < pi / 2 ? ypr(2) : ypr(2) - pi}; return {-yaw_angle, Eigen::Vector3d::UnitY()}; } } body_analizer::body_analizer(std::string root, std::size_t target_number) : root_ {root}, target_number_ {std::to_string(target_number)}, base_name_ {"torso_" + target_number_}, right_hand_name_ {"right_hand_" + target_number_}, left_hand_name_ {"left_hand_" + target_number_}, right_knee_name_ {"right_knee_" + target_number_}, left_knee_name_ {"left_knee_" + target_number_} { } void body_analizer::update() { const auto current_time {ros::Time{0}}; const auto base_pos {get_position(base_name_, current_time)}; const auto yaw_canceller {get_yaw_inverse_matrix(base_pos)}; head_ = yaw_canceller * base_pos.rotation() * Eigen::Vector3d::UnitY(); const auto base_vec {base_pos.translation()}; right_hand_ = yaw_canceller * (get_position(right_hand_name_, current_time).translation() - base_vec); left_hand_ = yaw_canceller * (get_position(left_hand_name_, current_time).translation() - base_vec); right_knee_ = yaw_canceller * (get_position(right_knee_name_, current_time).translation() - base_vec); left_knee_ = yaw_canceller * (get_position(left_knee_name_, current_time).translation() - base_vec); }
36.380952
104
0.744764
forno
b2e414c4c122c0d20494e7a124f7f019fee0a649
4,709
cpp
C++
src/io.cpp
cmourglia/cpp_utils
ae7ea1521ac68edced2dbe0f0d00d760028cc2d2
[ "MIT" ]
null
null
null
src/io.cpp
cmourglia/cpp_utils
ae7ea1521ac68edced2dbe0f0d00d760028cc2d2
[ "MIT" ]
null
null
null
src/io.cpp
cmourglia/cpp_utils
ae7ea1521ac68edced2dbe0f0d00d760028cc2d2
[ "MIT" ]
null
null
null
#include <beard/io/io.h> #include <beard/core/macros.h> #include <codecvt> #if BEARD_PLATFORM_WINDOWS START_EXTERNAL_INCLUDE # include <Windows.h> END_EXTERNAL_INCLUDE #elif # error TODO #endif namespace beard::io { i64 get_file_write_time(const char* filename) { #if BEARD_PLATFORM_WINDOWS HANDLE fileHandle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); defer(CloseHandle(fileHandle)); if (fileHandle == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error != ERROR_SHARING_VIOLATION) { ASSERT(false, "File error %d\n", error); } return 0; } FILE_BASIC_INFO infos; bool ok = GetFileInformationByHandleEx(fileHandle, FileBasicInfo, &infos, sizeof(infos)); if (!ok) { DWORD error = GetLastError(); ASSERT(false, "File error %d\n", error); return 0; } return infos.LastWriteTime.QuadPart; #else static_assert(false, "TODO"); #endif } std::string read_whole_file(const char* filename) { std::string result; #if BEARD_PLATFORM_WINDOWS HANDLE fileHandle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); defer(CloseHandle(fileHandle)); if (fileHandle == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error != ERROR_SHARING_VIOLATION) { ASSERT(false, "File error %d\n", error); } return result; } FILE_STANDARD_INFO infos; bool ok = GetFileInformationByHandleEx(fileHandle, FileStandardInfo, &infos, sizeof(infos)); if (!ok) { DWORD error = GetLastError(); ASSERT(false, "File error %d\n", error); return result; } result.resize(infos.EndOfFile.QuadPart); DWORD bytesRead = 0; ReadFile(fileHandle, result.data(), static_cast<DWORD>(infos.EndOfFile.QuadPart), &bytesRead, nullptr); #else static_assert(false, "TODO"); #endif return result; } beard::optional<std::string> read_while_file_if_newer(const char* filename, i64 lastWrite, i64* newLastWrite) { beard::optional<std::string> result; #if BEARD_PLATFORM_WINDOWS HANDLE fileHandle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); defer(CloseHandle(fileHandle)); if (fileHandle == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error != ERROR_SHARING_VIOLATION) { ASSERT(false, "File error %d\n", error); } return result; } bool ok = true; FILE_BASIC_INFO basicInfos; ok = GetFileInformationByHandleEx(fileHandle, FileBasicInfo, &basicInfos, sizeof(basicInfos)); if (!ok) { DWORD error = GetLastError(); ASSERT(false, "File error %d\n", error); return result; } if (lastWrite >= basicInfos.LastWriteTime.QuadPart) { return result; } FILE_STANDARD_INFO standardInfos; ok = GetFileInformationByHandleEx(fileHandle, FileStandardInfo, &standardInfos, sizeof(standardInfos)); if (!ok) { DWORD error = GetLastError(); ASSERT(false, "File error %d\n", error); return result; } if (standardInfos.EndOfFile.QuadPart == 0) { return result; } std::string contentTmp; DWORD bytesRead = 0; contentTmp.resize(standardInfos.EndOfFile.QuadPart); ok = ReadFile(fileHandle, contentTmp.data(), static_cast<DWORD>(standardInfos.EndOfFile.QuadPart), &bytesRead, nullptr); if (!ok) { DWORD error = GetLastError(); ASSERT(false, "File error %d\n", error); return result; } *newLastWrite = basicInfos.LastWriteTime.QuadPart; result = std::move(contentTmp); #else static_assert(false, "TODO"); #endif return result; } std::u32string to_utf8(const std::string& str) { std::wstring_convert<std::codecvt_utf8<i32>, i32> converter; auto asInt = converter.from_bytes(str); return std::u32string(reinterpret_cast<char32_t const*>(asInt.data()), asInt.length()); } std::string from_utf8(const std::u32string& str) { std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter; auto asChar = converter.to_bytes(str); return std::string(reinterpret_cast<char const*>(asChar.data(), asChar.length()); } }
24.148718
109
0.635804
cmourglia
b2e714af274683b9767415360dea70f91b29b6c6
278
hpp
C++
include/o80_example/joint.hpp
intelligent-soft-robots/o80_example
bd72eca61e0ddd0c3318ac3aabdba163e77c5ba2
[ "BSD-3-Clause" ]
1
2021-04-08T09:03:43.000Z
2021-04-08T09:03:43.000Z
include/o80_example/joint.hpp
intelligent-soft-robots/o80_example
bd72eca61e0ddd0c3318ac3aabdba163e77c5ba2
[ "BSD-3-Clause" ]
1
2020-12-22T16:44:38.000Z
2020-12-22T16:44:38.000Z
include/o80_example/joint.hpp
intelligent-soft-robots/o80_example
bd72eca61e0ddd0c3318ac3aabdba163e77c5ba2
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "o80/state.hpp" namespace o80_example { class Joint : public o80::State<double, Joint> { public: Joint() : o80::State<double, Joint>(0) { } Joint(double value) : o80::State<double, Joint>(value) { } }; } // namespace o80_example
15.444444
58
0.625899
intelligent-soft-robots
b2e827a6d1cd26afc8fe25b85bef4d70d035f9c0
8,556
cpp
C++
Engine/Preview_Lightning.cpp
AutoSync/LightningEngine
0c3b0daba4399aa71d56327254caca59cb5f4858
[ "Apache-2.0" ]
null
null
null
Engine/Preview_Lightning.cpp
AutoSync/LightningEngine
0c3b0daba4399aa71d56327254caca59cb5f4858
[ "Apache-2.0" ]
null
null
null
Engine/Preview_Lightning.cpp
AutoSync/LightningEngine
0c3b0daba4399aa71d56327254caca59cb5f4858
[ "Apache-2.0" ]
null
null
null
//// 2018 - 2022 AutoSync Lightning Engine | Erick Andrade - All Rights Reserved // ///* nuklear - 1.32.0 - public domain */ //#include <stdio.h> //#include <stdlib.h> //#include <stdint.h> //#include <stdarg.h> //#include <string.h> //#include <math.h> //#include <assert.h> //#include <limits.h> //#include <time.h> // //#include <GLEW/glew.h> //#include <GLFW/glfw3.h> // //#define NK_INCLUDE_FIXED_TYPES //#define NK_INCLUDE_STANDARD_IO //#define NK_INCLUDE_STANDARD_VARARGS //#define NK_INCLUDE_DEFAULT_ALLOCATOR //#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT //#define NK_INCLUDE_FONT_BAKING //#define NK_INCLUDE_DEFAULT_FONT //#define NK_IMPLEMENTATION //#define NK_GLFW_GL4_IMPLEMENTATION //#define NK_KEYSTATE_BASED_INPUT //#include "nuklear.h" //#include "nuklear_glfw_gl4.h" // //#define WINDOW_WIDTH 1200 //#define WINDOW_HEIGHT 800 // //#define MAX_VERTEX_BUFFER 512 * 1024 //#define MAX_ELEMENT_BUFFER 128 * 1024 // ///* =============================================================== // * // * EXAMPLE // * // * ===============================================================*/ // /* This are some code examples to provide a small overview of what can be // * done with this library. To try out an example uncomment the defines */ // /*#define INCLUDE_ALL */ // /*#define INCLUDE_STYLE */ // /*#define INCLUDE_CALCULATOR */ // /*#define INCLUDE_CANVAS */ //#define INCLUDE_OVERVIEW ///*#define INCLUDE_NODE_EDITOR */ // //#ifdef INCLUDE_ALL //#define INCLUDE_STYLE //#define INCLUDE_CALCULATOR //#define INCLUDE_CANVAS //#define INCLUDE_OVERVIEW //#define INCLUDE_NODE_EDITOR //#endif // //#ifdef INCLUDE_STYLE //#include "source/Nuklear/common/style.c" //#endif //#ifdef INCLUDE_CALCULATOR //#include "source/Nuklear/common/calculator.c" //#endif //#ifdef INCLUDE_CANVAS //#include "source/Nuklear//common/canvas.c" //#endif //#ifdef INCLUDE_OVERVIEW //#include "source/Nuklear/common/overview.c" //#endif //#ifdef INCLUDE_NODE_EDITOR //#include "source/Nuklear/common/node_editor.c" //#endif // ///* =============================================================== // * // * DEMO // * // * ===============================================================*/ //static void error_callback(int e, const char* d) //{ // printf("Error %d: %s\n", e, d); //} // //int main(void) //{ // /* Platform */ // static GLFWwindow* win; // int width = 0, height = 0; // struct nk_context* ctx; // struct nk_colorf bg; // struct nk_image img; // // /* GLFW */ // glfwSetErrorCallback(error_callback); // if (!glfwInit()) { // fprintf(stdout, "[GFLW] failed to init!\n"); // exit(1); // } // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //#ifdef __APPLE__ // glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //#endif // win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL); // glfwMakeContextCurrent(win); // glfwGetWindowSize(win, &width, &height); // // /* OpenGL */ // glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // glewExperimental = 1; // if (glewInit() != GLEW_OK) { // fprintf(stderr, "Failed to setup GLEW\n"); // exit(1); // } // // ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); // /* Load Fonts: if none of these are loaded a default font will be used */ // /* Load Cursor: if you uncomment cursor loading please hide the cursor */ // {struct nk_font_atlas* atlas; // nk_glfw3_font_stash_begin(&atlas); // /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/ // /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/ // /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/ // /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/ // /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/ // /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/ // nk_glfw3_font_stash_end(); // /*nk_style_load_all_cursors(ctx, atlas->cursors);*/ // /*nk_style_set_font(ctx, &droid->handle);*/} // //#ifdef INCLUDE_STYLE // /*set_style(ctx, THEME_WHITE);*/ // /*set_style(ctx, THEME_RED);*/ // /*set_style(ctx, THEME_BLUE);*/ // /*set_style(ctx, THEME_DARK);*/ //#endif // ///* Create bindless texture. // * The index returned is not the opengl resource id. // * IF you need the GL resource id use: nk_glfw3_get_tex_ogl_id() */ // {int tex_index = 0; // enum { tex_width = 256, tex_height = 256 }; // char pixels[tex_width * tex_height * 4]; // memset(pixels, 128, sizeof(pixels)); // tex_index = nk_glfw3_create_texture(pixels, tex_width, tex_height); // img = nk_image_id(tex_index); } // // bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; // while (!glfwWindowShouldClose(win)) // { // /* Input */ // glfwPollEvents(); // nk_glfw3_new_frame(); // // /* GUI */ // if (nk_begin(ctx, "Demo", nk_rect(50, 50, 230, 250), // NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE | // NK_WINDOW_MINIMIZABLE | NK_WINDOW_TITLE)) // { // enum { EASY, HARD }; // static int op = EASY; // static int property = 20; // nk_layout_row_static(ctx, 30, 80, 1); // if (nk_button_label(ctx, "button")) // fprintf(stdout, "button pressed\n"); // // nk_layout_row_dynamic(ctx, 30, 2); // if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; // if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; // // nk_layout_row_dynamic(ctx, 25, 1); // nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); // // nk_layout_row_dynamic(ctx, 20, 1); // nk_label(ctx, "background:", NK_TEXT_LEFT); // nk_layout_row_dynamic(ctx, 25, 1); // if (nk_combo_begin_color(ctx, nk_rgb_cf(bg), nk_vec2(nk_widget_width(ctx), 400))) { // nk_layout_row_dynamic(ctx, 120, 1); // bg = nk_color_picker(ctx, bg, NK_RGBA); // nk_layout_row_dynamic(ctx, 25, 1); // bg.r = nk_propertyf(ctx, "#R:", 0, bg.r, 1.0f, 0.01f, 0.005f); // bg.g = nk_propertyf(ctx, "#G:", 0, bg.g, 1.0f, 0.01f, 0.005f); // bg.b = nk_propertyf(ctx, "#B:", 0, bg.b, 1.0f, 0.01f, 0.005f); // bg.a = nk_propertyf(ctx, "#A:", 0, bg.a, 1.0f, 0.01f, 0.005f); // nk_combo_end(ctx); // } // } // nk_end(ctx); // // /* Bindless Texture */ // if (nk_begin(ctx, "Texture", nk_rect(250, 150, 230, 250), // NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE | // NK_WINDOW_MINIMIZABLE | NK_WINDOW_TITLE)) // { // struct nk_command_buffer* canvas = nk_window_get_canvas(ctx); // struct nk_rect total_space = nk_window_get_content_region(ctx); // nk_draw_image(canvas, total_space, &img, nk_white); // } // nk_end(ctx); // // /* -------------- EXAMPLES ---------------- */ //#ifdef INCLUDE_CALCULATOR // calculator(ctx); //#endif //#ifdef INCLUDE_CANVAS // canvas(ctx); //#endif //#ifdef INCLUDE_OVERVIEW // overview(ctx); //#endif //#ifdef INCLUDE_NODE_EDITOR // node_editor(ctx); //#endif // /* ----------------------------------------- */ // // /* Draw */ // glfwGetWindowSize(win, &width, &height); // glViewport(0, 0, width, height); // glClear(GL_COLOR_BUFFER_BIT); // glClearColor(bg.r, bg.g, bg.b, bg.a); // /* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state // * with blending, scissor, face culling, depth test and viewport and // * defaults everything back into a default state. // * Make sure to either a.) save and restore or b.) reset your own state after // * rendering the UI. */ // nk_glfw3_render(NK_ANTI_ALIASING_ON); // glfwSwapBuffers(win); // } // nk_glfw3_shutdown(); // glfwTerminate(); // return 0; //}
36.564103
126
0.589177
AutoSync
b2e941fecd4d3f3e6b267317035a2a83f01e782f
1,145
cpp
C++
src/ui/AsyncMessage.cpp
jnmeurisse/FortiRDP
53f48413c8a292304de27468b271847534353c61
[ "Apache-2.0" ]
null
null
null
src/ui/AsyncMessage.cpp
jnmeurisse/FortiRDP
53f48413c8a292304de27468b271847534353c61
[ "Apache-2.0" ]
null
null
null
src/ui/AsyncMessage.cpp
jnmeurisse/FortiRDP
53f48413c8a292304de27468b271847534353c61
[ "Apache-2.0" ]
1
2022-02-19T19:47:43.000Z
2022-02-19T19:47:43.000Z
/*! * This file is part of FortiRDP * * Copyright (C) 2022 Jean-Noel Meurisse * SPDX-License-Identifier: Apache-2.0 * */ #include "AsyncMessage.h" AsyncMessage::AsyncMessage(UINT eventNumber): _id(eventNumber) { } AsyncMessage::~AsyncMessage() { } LRESULT AsyncMessage::send(HWND hWnd, void* lParam) const { return ::SendMessage(hWnd, AsyncMessage::_registrationId, _id, (LPARAM) lParam); } BOOL AsyncMessage::post(HWND hWnd, void* lParam) const { return ::PostMessage(hWnd, AsyncMessage::_registrationId, _id, (LPARAM)lParam); } UINT AsyncMessage::_registrationId = ::RegisterWindowMessage(L"fortirdp$message"); AsyncMessage AsyncMessage::OutputInfoMessageRequest(1); AsyncMessage AsyncMessage::ShowErrorMessageDialogRequest(2); AsyncMessage AsyncMessage::ShowInvalidCertificateDialogRequest(3); AsyncMessage AsyncMessage::ShowAskCredentialDialogRequest(4); AsyncMessage AsyncMessage::ShowAskCodeDialogRequest(5); AsyncMessage AsyncMessage::DisconnectFromFirewallRequest(6); AsyncMessage AsyncMessage::ConnectedEvent(100); AsyncMessage AsyncMessage::DisconnectedEvent(101); AsyncMessage AsyncMessage::TunnelListeningEvent(102);
24.361702
82
0.8
jnmeurisse
b2ed90e1ec93d49c26bdf4abf6e6eb746fb82ebc
508
cpp
C++
1000-1100/1003. Check If Word Is Valid After Substitutions.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1000-1100/1003. Check If Word Is Valid After Substitutions.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1000-1100/1003. Check If Word Is Valid After Substitutions.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
class Solution { public: bool isValid(string s) { stack<char> stk; for (auto &c : s) { if (c == 'c') { string tmp; for (int i = 0; i < 2 && !stk.empty(); i++) { tmp.push_back(stk.top()); stk.pop(); } if (tmp.size() == 2 && tmp[0] == 'b' && tmp[1] == 'a') { continue; } tmp.push_back(tmp[1]); tmp.push_back(tmp[0]); } stk.push(c); } return stk.empty(); } };
18.142857
62
0.385827
erichuang1994
b2f02d92f43bcf33b03806283c1ec89cf100506e
2,806
hpp
C++
MACAO/ORAM.hpp
thanghoang/MACAO
b1614ca7311f3555ca492b1088ca031089c1099e
[ "MIT" ]
4
2020-02-25T22:55:35.000Z
2021-06-17T22:10:34.000Z
MACAO/ORAM.hpp
thanghoang/MACAO
b1614ca7311f3555ca492b1088ca031089c1099e
[ "MIT" ]
null
null
null
MACAO/ORAM.hpp
thanghoang/MACAO
b1614ca7311f3555ca492b1088ca031089c1099e
[ "MIT" ]
5
2020-03-04T21:37:54.000Z
2022-01-07T19:27:15.000Z
/* * ORAM.hpp * * Author: thanghoang */ #ifndef SSORAM_HPP #define SSORAM_HPP #include "config.h" class ORAM { public: ORAM(); ~ORAM(); static int build(TYPE_POS_MAP *pos_map, TYPE_INDEX **metaData); static int getEvictIdx(TYPE_INDEX *srcIdx, TYPE_INDEX *destIdx, TYPE_INDEX *siblIdx, string evict_str); static string getEvictString(TYPE_INDEX n_evict); static int getFullPathIdx(TYPE_INDEX *fullPath, TYPE_INDEX pathID); //Circuit-ORAM layout static int getFullEvictPathIdx(TYPE_INDEX *fullPathIdx, string str_evict); static int getDeepestLevel(TYPE_INDEX PathID, TYPE_INDEX blockPathID); static void getDeepestBucketIdx(TYPE_INDEX *meta_stash, TYPE_INDEX *meta_path, TYPE_INDEX evictPathID, int *output); static int prepareDeepest(TYPE_INDEX *meta_stash, TYPE_INDEX *meta_path, TYPE_INDEX PathID, int *deepest); static int getEmptySlot(TYPE_INDEX *meta_path, int level); static int prepareTarget(TYPE_INDEX *meta_path, TYPE_INDEX pathID, int *deepest, int *target); static int createShares(TYPE_DATA secret, TYPE_DATA *secret_shares, TYPE_DATA *mac_shares); static int createShares(TYPE_DATA secret, TYPE_DATA *secret_shares, TYPE_DATA *mac_shares, prng_state *pseudo_state, int secretShareIdx); static int recoverSecret(zz_p **secret_shares, zz_p **mac_shares, zz_p *secret, zz_p *mac); static int recoverSecret(unsigned char **retrieval_in, zz_p *secret); static int recoverSecret(unsigned char **retrieval_in, zz_p *secret, zz_p *mac); static int xor_reconstruct(unsigned char **input, zz_p *output, zz_p *output_mac); static int xor_retrieve(unsigned char *query, zz_p **db, zz_p **db_mac, int start_db_idx, int end_db_idx, unsigned char *output, unsigned char *output_mac); static int xor_createQuery(TYPE_INDEX idx, unsigned int db_size, unsigned char **output); static int checkRandLinComb(zz_p *input, zz_p *input_mac); static int sss_createQuery(TYPE_INDEX idx, unsigned int DB_SIZE, unsigned char **output); static int sss_createQuery(TYPE_INDEX idx, unsigned int DB_SIZE, unsigned char **output, prng_state *prng); static int createRetrievalTriplets(int n); static int createEvictionTriplets(int n); static int perform_dot_product(zz_p **A, zz_p *B, zz_p *C, int row, int input_length); static int perform_cross_product(zz_p **A, zz_p **B, zz_p **C, int row, int input_length, int output_length); static int writeTriplets(zz_p ****data, int n, int row, int col, string file_name); static int writeTriplets(zz_p ***data, int n, int row, string file_name); static int clearMemory(zz_p **data, int m); static int clearMemory(zz_p ***data, int m, int n); static int clearMemory(zz_p ****data, int m, int n, int p); }; #endif // SSORAM_HPP
43.84375
160
0.743051
thanghoang
b2f0a5db171fc333c3dde0a8f6200150cdfbde7d
1,847
cpp
C++
usaco_practice/gold/gold_practice/radio.cpp
juneharold/USACO
a96b54f68e7247c61044f3c0d9e7260952c508e2
[ "MIT" ]
null
null
null
usaco_practice/gold/gold_practice/radio.cpp
juneharold/USACO
a96b54f68e7247c61044f3c0d9e7260952c508e2
[ "MIT" ]
null
null
null
usaco_practice/gold/gold_practice/radio.cpp
juneharold/USACO
a96b54f68e7247c61044f3c0d9e7260952c508e2
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> using namespace std; #define f first #define s second const int MAX=1005; int N, M, dp[MAX][MAX]={}; pair<int, int> fj[MAX], bs[MAX]; string fjpath, bspath; int solve(int a, int b) { if (a<0 || b<0) return 1e9; if (dp[a][b]!=1e9) return dp[a][b]; int cost=(fj[a].f-bs[b].f)*(fj[a].f-bs[b].f)+(fj[a].s-bs[b].s)*(fj[a].s-bs[b].s); dp[a][b]=min(dp[a][b], solve(a-1, b-1)+cost); dp[a][b]=min(dp[a][b], solve(a, b-1)+cost); dp[a][b]=min(dp[a][b], solve(a-1, b)+cost); return dp[a][b]; } void make_path() { for (int i=0; i<N; i++) { if (fjpath[i]=='N') { fj[i+1].f=fj[i].f; fj[i+1].s=fj[i].s+1; } if (fjpath[i]=='E') { fj[i+1].f=fj[i].f+1; fj[i+1].s=fj[i].s; } if (fjpath[i]=='W') { fj[i+1].f=fj[i].f-1; fj[i+1].s=fj[i].s; } if (fjpath[i]=='S') { fj[i+1].f=fj[i].f; fj[i+1].s=fj[i].s-1; } } for (int i=0; i<M; i++) { if (bspath[i]=='N') { bs[i+1].f=bs[i].f; bs[i+1].s=bs[i].s+1; } if (bspath[i]=='E') { bs[i+1].f=bs[i].f+1; bs[i+1].s=bs[i].s; } if (bspath[i]=='W') { bs[i+1].f=bs[i].f-1; bs[i+1].s=bs[i].s; } if (bspath[i]=='S') { bs[i+1].f=bs[i].f; bs[i+1].s=bs[i].s-1; } } } int main() { freopen("radio.in", "r", stdin); freopen("radio.out", "w", stdout); ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> N >> M >> fj[0].f >> fj[0].s >> bs[0].f >> bs[0].s; cin >> fjpath >> bspath; make_path(); fill(&dp[0][0], &dp[1004][1004], 1e9); dp[0][0]=0; cout << solve(N, M); }
22.253012
85
0.409854
juneharold
b2f19468a25729f55ddfba3f5415c1ade12e5fa3
502
cpp
C++
Lista5/exe3.cpp
nathalyoliveira/LG1-IFSP
b072c916f71a8b5924a766d8b6fa4e0a481faa64
[ "MIT" ]
null
null
null
Lista5/exe3.cpp
nathalyoliveira/LG1-IFSP
b072c916f71a8b5924a766d8b6fa4e0a481faa64
[ "MIT" ]
null
null
null
Lista5/exe3.cpp
nathalyoliveira/LG1-IFSP
b072c916f71a8b5924a766d8b6fa4e0a481faa64
[ "MIT" ]
null
null
null
#include<stdio.h> #include<conio.h> int main() { int a[15], b[15],i, j,x, y; for (i=0;i<15;++i) {puts("DIGITE OS VALORES DO VETOR A:"); scanf("%d", &a[i]);} for(i=0;i<15;++i) { b[i]=1; for(y=a[i]; y>=1; y--) {b[i]=b[i]*y;} } for(i=0;i<15;++i) for(j=i+1;j<15;++j) if(b[i]>b[j]) {x=b[i]; b[i]=b[j]; b[j]=x;} for(i=0;i<15;++i) { printf("FATORIAL MATRIZ B: %d\n", b[i]);} getch (); return 0; }
14.764706
46
0.39243
nathalyoliveira
b2f381a8a283377e0c47afcc4b39f4069dd274d2
797
cpp
C++
src/TCPClient.cpp
mjssw/crux-net
6dd2e2b36e9e6211b959f21cb34e3c7fb4845788
[ "BSD-3-Clause" ]
1
2016-07-04T16:07:57.000Z
2016-07-04T16:07:57.000Z
src/TCPClient.cpp
mjssw/crux-net
6dd2e2b36e9e6211b959f21cb34e3c7fb4845788
[ "BSD-3-Clause" ]
null
null
null
src/TCPClient.cpp
mjssw/crux-net
6dd2e2b36e9e6211b959f21cb34e3c7fb4845788
[ "BSD-3-Clause" ]
null
null
null
#include "TCPClient.h" #include "Session.h" namespace Crux { TCPClient::TCPClient() : m_Connected(false), m_pSession( NULL ) { } TCPClient::~TCPClient() { } void TCPClient::Disconnect() { m_Connected = false; m_pSession->Disconnect(); } bool TCPClient::Connected() const { return m_Connected; } void TCPClient::SetConnected( bool connected ) { m_Connected = connected; } void TCPClient::SetSession( Session* pSession ) { m_pSession = pSession; } bool TCPClient::SendMsg( int sessionID, void* pData, size_t size ) { return m_pSession->SendMsg( sessionID, pData, size ); } size_t TCPClient::GetSendDataSizeTotal() const { return m_pSession->GetSendDataSizeTotal(); } size_t TCPClient::GetRecvDataSizeTotal() const { return m_pSession->GetRecvDataSizeTotal(); } } //namespace Crux
15.037736
66
0.734003
mjssw
b2ffe4331f29fb6e3bcbc7f7f79bd88ccf42a2f3
706
cpp
C++
Algorithms/Implementation/counting-valleys.cpp
CodeLogist/hackerrank-solutions
faecc4c9563a017eb61e83f0025aa9eb78fd33a1
[ "MIT" ]
73
2016-09-14T18:20:41.000Z
2022-02-05T14:58:04.000Z
Algorithms/Implementation/counting-valleys.cpp
A-STAR0/hackerrank-solutions-1
518cdd9049477d70c499ba4f51f06ac99178f0ab
[ "MIT" ]
3
2017-03-03T01:12:31.000Z
2020-04-18T16:51:59.000Z
Algorithms/Implementation/counting-valleys.cpp
A-STAR0/hackerrank-solutions-1
518cdd9049477d70c499ba4f51f06ac99178f0ab
[ "MIT" ]
69
2017-03-02T19:03:54.000Z
2022-03-29T12:35:38.000Z
#include <vector> #include <iostream> #include <algorithm> int main() { int n; std::cin >> n; std::vector<int> heights(n+2,0); std::string steps; std::cin >> steps; for (int i = 1; i < n+1; i++) { heights[i] = heights[i-1] + (steps[i-1] == 'U' ? 1 : -1); } int valley_count = 0; std::vector<int>::iterator a,b; for (a = std::find(heights.begin(),heights.end(), 0); a != heights.end(); a = b) { b = std::find(a+1,heights.end(), 0); for (; a != b; a++) { if (*a < 0) { valley_count++; break; } } } std::cout << valley_count << std::endl; return 0; }
22.774194
86
0.444759
CodeLogist
6507a43c497b8fa11b5b99747952df588ab4ff6d
1,638
cpp
C++
gameObjects/Shot.cpp
streusselhirni/HF-ICT_GUI_Game-Pokemon
a260fd8088b3c1ef69a7d197d8de3448459341ba
[ "MIT" ]
null
null
null
gameObjects/Shot.cpp
streusselhirni/HF-ICT_GUI_Game-Pokemon
a260fd8088b3c1ef69a7d197d8de3448459341ba
[ "MIT" ]
null
null
null
gameObjects/Shot.cpp
streusselhirni/HF-ICT_GUI_Game-Pokemon
a260fd8088b3c1ef69a7d197d8de3448459341ba
[ "MIT" ]
null
null
null
#include <QString> #include <cmath> #include "Shot.h" #include <QPainter> Shot::Shot(int x, int y, int speed, int angle) : GameObject(x, y, 50, new QMovie("img/pokeball.gif"), 50), speed(speed), angle(angle), rotation(0), t(0) { this->fired = false; } void Shot::move(uint64_t delta) { if (!this->fired) { return; } double rad = 3.1415926 / 180 * this->angle; auto dx = (int) this->speed / 3 * cos(rad) * this->t; auto dy = (int) this->speed / 3 * sin(rad) * this->t - (this->g / 2) * pow(this->t, 2); this->t += .1; this->x = this->x + dx / 2; this->y = this->y - dy / 2; this->rotation += 20; } short Shot::getBodyType() const { return GameObject::KINEMATIC_BODY; } void Shot::paint(QPainter *painter) { if (this->fired) { QTransform transform; transform.translate(this->x + this->getWidth()/2, this->y + this->getHeight()/2); transform.rotate(this->rotation); transform.translate(-(this->x + this->getWidth()/2), -(this->y + this->getHeight()/2)); painter->setTransform(transform); if (this->movie != nullptr) { this->img = movie->currentImage(); } painter->drawImage(this->x, this->y, this->img.scaledToWidth(this->getWidth())); painter->resetTransform(); } } void Shot::onOutOfBound() { this->fired = false; } void Shot::init(int x, int y, int s, int a, double time) { this->x = x; this->y = y; this->speed = s; this->angle = a; this->t = time; this->fired = true; } bool Shot::getFired() { return this->fired; }
26.419355
95
0.559829
streusselhirni
650e168120823187ed7ae46f661159a7f19274dc
963
cpp
C++
Friendship/Main.cpp
rastabrandy02/Programming2
8dba0e75c01dc884df09f19bcacf1140ca9ca501
[ "MIT" ]
null
null
null
Friendship/Main.cpp
rastabrandy02/Programming2
8dba0e75c01dc884df09f19bcacf1140ca9ca501
[ "MIT" ]
null
null
null
Friendship/Main.cpp
rastabrandy02/Programming2
8dba0e75c01dc884df09f19bcacf1140ca9ca501
[ "MIT" ]
1
2021-02-22T08:43:48.000Z
2021-02-22T08:43:48.000Z
#include <iostream> #include "Friendship.cpp" using namespace std; void StarTouched(Player* p) { p->invincible = true; } int main() { string name; string itemName; bool playing = true; cout << "Introduce your name: " << endl; cin >> name; Player player(name); while (playing) { cout << "---STATS---" << endl; cout << "Name: " << player.GetName() << endl; player.PrintNumLifes(); player.PrintInvincible(); player.PrintCapabilities(); player.PrintWeapon(); cout << "Introduce the name of the item: " << endl; cin >> itemName; Item item(itemName); if ((itemName == "One_Up") || (itemName == "Mini_Mario") || (itemName == "Super_Mario") || (itemName == "Fire_Flower") || (itemName == "Ice_Flower") || (itemName == "Golden_Flower")) player.UseItem(&item); if (itemName == "Quit") { cout << "Goodbye " << player.GetName() << endl; playing = false; } if (itemName == "Star") StarTouched(&player); } }
20.0625
64
0.608515
rastabrandy02
651025462d34c381134cf849b531b7444cfdf6e3
2,486
cpp
C++
Practice/2018/2018.9.25/BZOJ3428.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.9.25/BZOJ3428.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.9.25/BZOJ3428.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=50100; const int inf=2147483647; class Point { public: int x,y; }; int n; Point B[maxN],W[maxN],Up[maxN],Down[maxN]; int Calc(); bool cmp(Point A,Point B); Point operator + (Point A,Point B); Point operator - (Point A,Point B); ll cross(Point A,Point B); ostream & operator << (ostream &os,Point A); int main(){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d%d",&B[i].x,&B[i].y); for (int i=1;i<=n;i++) scanf("%d%d",&W[i].x,&W[i].y); sort(&B[1],&B[n+1],cmp);sort(&W[1],&W[n+1],cmp); printf("%d ",Calc()); swap(B,W); printf("%d\n",Calc()); return 0; } int Calc(){ int top1=0,top2=0; //cout<<"after sorter:"<<endl; //for (int i=1;i<=n;i++) cout<<B[i]<<" ";cout<<endl; for (int i=1;i<=n;i++){ while ((top1>=2)&&(cross(B[i]-Up[top1-1],Up[top1]-Up[top1-1])<=0)) top1--; Up[++top1]=B[i]; } for (int i=n;i>=1;i--){ while ((top2>=2)&&(cross(B[i]-Down[top2],B[i]-Down[top2-1])<=0)) top2--; Down[++top2]=B[i]; } reverse(&Down[1],&Down[top2+1]); if (Up[1].x==Up[top1].x){ int ret=0; for (int i=1;i<=n;i++) if ((W[i].x==Up[1].x)&&(W[i].y>=Up[1].y)&&(W[i].y<=Up[top1].y)) ret++; return ret; } //for (int i=1;i<=top1;i++) cout<<Up[i]<<" ";cout<<endl; //for (int i=1;i<=top2;i++) cout<<Down[i]<<" ";cout<<endl; int p1=0,p2=0,ret=0; for (int i=1;i<=n;i++){ while ((p1!=top1)&&(Up[p1+1].x<=W[i].x)) p1++; while ((p2!=top2)&&(Down[p2+1].x<=W[i].x)) p2++; //cout<<i<<" "<<p1<<" "<<p2<<endl; if ((p1==0)&&(p2==0)) continue; if ((p1==top1)&&(p2==top2)&&(W[i].x!=Up[top1].x)&&(W[i].x!=Down[top2].x)) break; bool flag=1; if (Up[p1].x==W[i].x){ if (W[i].y>Up[p1].y) flag=0; } else if (cross(W[i]-Up[p1],Up[p1+1]-Up[p1])<0) flag=0; if (Down[p2].x==W[i].x){ if (W[i].y<Down[p2].y) flag=0; } else if (cross(Down[p2+1]-Down[p2],W[i]-Down[p2])<0) flag=0; if (flag) ret++; } return ret; } bool cmp(Point A,Point B){ if (A.x!=B.x) return A.x<B.x; return A.y<B.y; } Point operator + (Point A,Point B){ return ((Point){A.x+B.x,A.y+B.y}); } Point operator - (Point A,Point B){ return ((Point){A.x-B.x,A.y-B.y}); } ll cross(Point A,Point B){ return 1ll*A.x*B.y-1ll*A.y*B.x; } ostream & operator << (ostream & os,Point A){ os<<"("<<A.x<<","<<A.y<<")";return os; } /* 7 0 3 1 1 3 0 5 0 2 4 4 3 6 6 1 0 3 6 1 3 4 1 2 1 6 1 6 6 //*/
19.888
95
0.542639
SYCstudio
651039cda528f0b5c29d952f73704ceab04ddcba
103
cpp
C++
src/my_app.cpp
mahilab/mahi-template
022d0aa27b69abc71b7c6df610a65149069d62ad
[ "MIT" ]
6
2018-09-14T05:07:03.000Z
2021-09-30T17:15:11.000Z
template/src/my_app.cpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
1
2020-10-15T13:46:27.000Z
2020-10-15T13:46:27.000Z
src/my_app.cpp
mahilab/mahi-template
022d0aa27b69abc71b7c6df610a65149069d62ad
[ "MIT" ]
3
2018-09-20T00:58:31.000Z
2022-02-09T06:02:56.000Z
#include "MyClass.hpp" int main() { MyClass my_class; my_class.hello_world(); return 0; }
12.875
27
0.631068
mahilab