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
6b78f2bbe172f47b2f3292a5fc446c833d8d57c0
1,250
hpp
C++
src/main/cpp/pistis/json/util/Utf8CharEncoder.hpp
tomault/pistis-json
db39580d3e905dc4fbdbb22b06f4670cc3d76b04
[ "Apache-2.0" ]
null
null
null
src/main/cpp/pistis/json/util/Utf8CharEncoder.hpp
tomault/pistis-json
db39580d3e905dc4fbdbb22b06f4670cc3d76b04
[ "Apache-2.0" ]
null
null
null
src/main/cpp/pistis/json/util/Utf8CharEncoder.hpp
tomault/pistis-json
db39580d3e905dc4fbdbb22b06f4670cc3d76b04
[ "Apache-2.0" ]
null
null
null
#ifndef __PISTIS__JSON__UTIL__UTF8CHARENCODER_HPP__ #define __PISTIS__JSON__UTIL__UTF8CHARENCODER_HPP__ #include <pistis/exceptions/IllegalValueError.hpp> #include <iomanip> #include <sstream> namespace pistis { namespace json { namespace util { class Utf8CharEncoder { public: template <typename Buffer> void encodeChar(Buffer& buffer, uint32_t c) const { if (c < 0x80) { buffer.write((char)c); } else if (c < 0x800) { buffer.write((char)(0xC0 | (c >> 6))); buffer.write((char)(0x80 | (c & 0x3F))); } else if (c < 0x10000) { buffer.write((char)(0xE0 | (c >> 12))); buffer.write((char)(0x80 | ((c >> 6) & 0x3F))); buffer.write((char)(0x80 | (c & 0x3F))); } else if (c < 0x200000) { buffer.write((char)(0xF0 | (c >> 18))); buffer.write((char)(0x80 | ((c >> 12) & 0x3F))); buffer.write((char)(0x80 | ((c >> 6) & 0x3F))); buffer.write((char)(0x80 | (c & 0x3F))); } else { std::ostringstream msg; msg << "Cannot encode character 0x" << std::width(4) << std::fill('0') << std::hex << c << ", which has more than 21 bits"; throw pistis::exceptions::IllegalValueError(msg.str(), PISTIS_EX_HERE); } } }; } } } #endif
26.041667
59
0.5864
tomault
6b7b4f0f7e85896b28c57915ef7f051fa7a6da73
4,979
cpp
C++
entity_manager.cpp
jasonhutchens/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
4
2016-06-05T04:36:12.000Z
2016-08-21T20:11:49.000Z
entity_manager.cpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
entity_manager.cpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
//============================================================================== #include <entity_manager.hpp> #include <entity.hpp> #include <engine.hpp> #include <hgeResource.h> #include <sstream> #include <cstdarg> //------------------------------------------------------------------------------ EntityManager::EntityManager() : m_registry(), m_entities(), m_sprites(), m_names(), m_new_entities() { } //------------------------------------------------------------------------------ EntityManager::~EntityManager() { fini(); } //------------------------------------------------------------------------------ void EntityManager::init() { } //------------------------------------------------------------------------------ void EntityManager::update( float dt ) { std::vector< Entity * >::iterator i( m_entities.begin() ); while ( i != m_entities.end() ) { ( * i )->update( dt ); if ( ( * i )->isGone() ) { delete ( * i ); i = m_entities.erase( i ); } else { ++i; } } while ( m_new_entities.size() > 0 ) { m_entities.push_back( m_new_entities.back() ); m_new_entities.pop_back(); } } //------------------------------------------------------------------------------ void EntityManager::fini() { while ( m_entities.size() > 0 ) { delete m_entities.back(); m_entities.pop_back(); } while ( m_new_entities.size() > 0 ) { delete m_new_entities.back(); m_new_entities.pop_back(); } m_registry.clear(); m_sprites.clear(); m_names.clear(); } //------------------------------------------------------------------------------ void EntityManager::registerEntity( unsigned int type, Entity * ( * factory )(), const char * table, const char * query ) { std::map< unsigned int, EntityData >::iterator i( m_registry.find( type ) ); if ( i != m_registry.end() ) { Engine::hge()->System_Log( "Cannot register same entity twice." ); return; } EntityData data; data.m_factory = factory; data.m_table = table; data.m_query = query; m_registry.insert( std::pair< unsigned int, EntityData >( type, data ) ); } //------------------------------------------------------------------------------ sqlite_int64 EntityManager::registerSprite( const char * cname ) { std::string name( cname ); std::map< std::string, sqlite_int64 >::iterator i( m_names.find( name ) ); if ( i != m_names.end() ) { return m_names[name]; } sqlite_int64 id( 0 ); for ( id = 0; m_sprites.find( id ) != m_sprites.end(); ++id ); m_names[name] = id; m_sprites[id] = Engine::rm()->GetSprite( cname ); return id; } //------------------------------------------------------------------------------ Entity * EntityManager::factory( unsigned int type, bool add ) { std::map< unsigned int, EntityData >::iterator i( m_registry.find( type ) ); if ( i == m_registry.end() ) { Engine::hge()->System_Log( "Tried to create unregistered entity." ); return 0; } Entity * entity( i->second.m_factory() ); entity->setType( type ); if ( add ) { m_new_entities.push_back( entity ); } return entity; } //------------------------------------------------------------------------------ std::vector< Entity * > EntityManager::databaseFactory( unsigned int type ) { std::vector< Entity * > retval; return retval; } //------------------------------------------------------------------------------ sqlite_int64 EntityManager::persistToDatabase( Entity * entity, char * rows[], ... ) { return 0; } //------------------------------------------------------------------------------ void EntityManager::deleteFromDatabase( Entity * entity ) { } //------------------------------------------------------------------------------ hgeSprite * EntityManager::getSprite( sqlite_int64 sprite_id ) { std::map< sqlite_int64,hgeSprite * >::iterator i(m_sprites.find(sprite_id)); if ( i == m_sprites.end() ) { Engine::hge()->System_Log( "Cannot find referenced sprite." ); return 0; } return m_sprites[sprite_id]; } //------------------------------------------------------------------------------ std::vector<Entity*> EntityManager::getEntities(unsigned int type) { std::vector< Entity * > entities; std::vector< Entity * >::iterator i; for ( i = m_entities.begin(); i != m_entities.end(); ++i ) { Entity* ent = (*i); if (ent->getType() == type) { entities.push_back(ent); } } return entities; } //==============================================================================
26.625668
81
0.420165
jasonhutchens
6b7c08973280db624a523f6c53e5003ed6ac2865
3,957
cpp
C++
Spark/ShapeCreator.cpp
MickAlmighty/SparkRenderer
0e30e342c7cf4003da54e9ce191fead647a868eb
[ "MIT" ]
1
2022-02-15T19:50:01.000Z
2022-02-15T19:50:01.000Z
Spark/ShapeCreator.cpp
MickAlmighty/SparkRenderer
0e30e342c7cf4003da54e9ce191fead647a868eb
[ "MIT" ]
null
null
null
Spark/ShapeCreator.cpp
MickAlmighty/SparkRenderer
0e30e342c7cf4003da54e9ce191fead647a868eb
[ "MIT" ]
null
null
null
#include "ShapeCreator.h" #include <cstring> #include <glm/gtx/rotate_vector.hpp> constexpr double pi = 3.14159265358979323846; namespace spark { std::vector<glm::vec3> ShapeCreator::createSphere(float radius, int precision, glm::vec3 centerPoint) { if(radius < 0.0f) return {}; if(precision < 3) return {}; std::vector<glm::vec3> vertices; const float radStep = 2.0f * static_cast<float>(pi) / static_cast<float>(precision); float angle = 0.0f; for(int i = 0; i < precision; ++i) { createSphereSegment(&vertices, angle, i == precision - 1 ? 2.0f * static_cast<float>(pi) - angle : radStep, radius, precision, centerPoint); angle += radStep; } return vertices; } void ShapeCreator::createSphereSegment(std::vector<glm::vec3>* vertices, float angle, float radStep, float radius, int precision, glm::vec3 centerPoint) { std::vector<glm::vec3> circle(precision); float circleAngle = -pi / 2.0f; const float vertRadStep = pi / (static_cast<float>(precision) - 1.0f); for(int i = 0; i < precision; ++i) { if(i == precision - 1) { circle[i].x = 0.0f; circle[i].y = radius; } else if(i == 0) { circle[i].x = 0.0f; circle[i].y = -radius; } else { circle[i].x = radius * cos(circleAngle); circle[i].y = radius * sin(circleAngle); } circle[i].z = 0.0f; circleAngle += vertRadStep; } const glm::vec3 rotateAxis(0.0f, 1.0f, 0.0f); for(int i = 0; i < precision; i++) { circle[i] = rotate(circle[i], angle, rotateAxis); } std::vector<glm::vec3> circle2(precision); std::memcpy(circle2.data(), circle.data(), precision * sizeof(glm::vec3)); for(int i = 0; i < precision; ++i) { circle2[i] = rotate(circle2[i], radStep, rotateAxis); } for(int i = 0; i < precision - 1; ++i) { if(i == 0) { createTriangle(vertices, circle[i], circle[i + 1], circle2[i + 1], centerPoint); } else if(i == precision - 2) { createTriangle(vertices, circle[i + 1], circle2[i], circle[i], centerPoint); } else { createRectangle(vertices, circle[i], circle2[i], circle2[i + 1], circle[i + 1], centerPoint); } } } void ShapeCreator::createRectangle(std::vector<glm::vec3>* vertices, const glm::vec3& tL, const glm::vec3& tR, const glm::vec3& dR, const glm::vec3& dL, glm::vec3 centerPoint) { const glm::vec3 horizontal = dR - dL; const glm::vec3 vertical = tL - dL; // glm::vec3 normal = cross(vertical, horizontal); glm::vec3 output[4]; /*for (int i = 0; i < 4; i++) { output[i].Normal = normal; }*/ output[0] = tL + centerPoint; output[1] = tR + centerPoint; output[2] = dR + centerPoint; output[3] = dL + centerPoint; vertices->push_back(output[0]); vertices->push_back(output[2]); vertices->push_back(output[3]); vertices->push_back(output[0]); vertices->push_back(output[1]); vertices->push_back(output[2]); } void ShapeCreator::createTriangle(std::vector<glm::vec3>* vertices, const glm::vec3& up, const glm::vec3& right, const glm::vec3& left, glm::vec3 centerPoint) { const glm::vec3 horizontal = right - left; const glm::vec3 vertical = up - left; // const glm::vec3 normal = cross(horizontal, vertical); glm::vec3 output[3]; /*for (int i = 0; i < 3; i++) { output[i].Normal = normal; }*/ output[0] = up + centerPoint; output[1] = right + centerPoint; output[2] = left + centerPoint; vertices->push_back(output[0]); vertices->push_back(output[2]); vertices->push_back(output[1]); } } // namespace spark
28.06383
148
0.564064
MickAlmighty
6b7f7e2fe5c718d23ef535be5580e276a4f357bc
1,951
cpp
C++
packages/ogdf.js/src/module/src/InitialPlacer.cpp
ZJUVAI/ogdf.js
6670d20b6c630a46593ac380d1edf91d2c9aabe8
[ "MIT" ]
3
2021-09-14T08:11:37.000Z
2022-03-04T15:42:07.000Z
packages/ogdf.js/src/module/src/InitialPlacer.cpp
JackieAnxis/ogdf.js
6670d20b6c630a46593ac380d1edf91d2c9aabe8
[ "MIT" ]
2
2021-12-04T17:09:53.000Z
2021-12-16T08:57:25.000Z
packages/ogdf.js/src/module/src/InitialPlacer.cpp
ZJUVAI/ogdf.js
6670d20b6c630a46593ac380d1edf91d2c9aabe8
[ "MIT" ]
2
2021-06-22T08:21:54.000Z
2021-07-07T06:57:22.000Z
#include "../main.h" #include <ogdf/energybased/multilevel_mixer/BarycenterPlacer.h> #include <ogdf/energybased/multilevel_mixer/CirclePlacer.h> #include <ogdf/energybased/multilevel_mixer/MedianPlacer.h> #include <ogdf/energybased/multilevel_mixer/RandomPlacer.h> #include <ogdf/energybased/multilevel_mixer/SolarPlacer.h> #include <ogdf/energybased/multilevel_mixer/ZeroPlacer.h> EM_PORT_API(BarycenterPlacer *) InitialPlacer_BarycenterPlacer(bool randomOffset, bool weightedPositionPriority) { BarycenterPlacer *placer = new BarycenterPlacer(); placer->setRandomOffset(randomOffset); placer->weightedPositionPriority(weightedPositionPriority); return placer; } EM_PORT_API(CirclePlacer *) InitialPlacer_CirclePlacer(float circleSize, int nodeSelection, bool radiusFixed, bool randomOffset) { CirclePlacer *placer = new CirclePlacer(); placer->setCircleSize(circleSize); placer->setNodeSelection(static_cast<CirclePlacer::NodeSelection>(nodeSelection)); placer->setRadiusFixed(radiusFixed); placer->setRandomOffset(randomOffset); return placer; } EM_PORT_API(MedianPlacer *) InitialPlacer_MedianPlacer(bool randomOffset) { MedianPlacer *placer = new MedianPlacer(); placer->setRandomOffset(randomOffset); return placer; } EM_PORT_API(RandomPlacer *) InitialPlacer_RandomPlacer(bool randomOffset, double circleSize) { RandomPlacer *placer = new RandomPlacer(); placer->setRandomOffset(randomOffset); placer->setCircleSize(circleSize); return placer; } EM_PORT_API(SolarPlacer *) InitialPlacer_SolarPlacer(bool randomOffset) { SolarPlacer *placer = new SolarPlacer(); placer->setRandomOffset(randomOffset); return placer; } EM_PORT_API(ZeroPlacer *) InitialPlacer_ZeroPlacer(double randomRange, bool randomOffset) { ZeroPlacer *placer = new ZeroPlacer(); placer->setRandomRange(randomRange); placer->setRandomOffset(randomOffset); return placer; }
30.968254
100
0.785751
ZJUVAI
6b87577d459e6ac851f43a6e95106c6b94b68af4
25
cpp
C++
Source/Utility/TextureLoader.cpp
reo-prg/TurnZ_code
f079c27921e2597bb824eba416b8b9a31258580c
[ "Unlicense" ]
null
null
null
Source/Utility/TextureLoader.cpp
reo-prg/TurnZ_code
f079c27921e2597bb824eba416b8b9a31258580c
[ "Unlicense" ]
null
null
null
Source/Utility/TextureLoader.cpp
reo-prg/TurnZ_code
f079c27921e2597bb824eba416b8b9a31258580c
[ "Unlicense" ]
null
null
null
#include <DirectXTex.h>
8.333333
23
0.72
reo-prg
6b897acf6092080c0e6a1ce1abe3cc23b2c68296
2,191
cpp
C++
Scene.cpp
KosukeTakahashi/CoSDL
9e7ae8e2f9f2434eca2236e25c6bcf54d5af716e
[ "MIT" ]
null
null
null
Scene.cpp
KosukeTakahashi/CoSDL
9e7ae8e2f9f2434eca2236e25c6bcf54d5af716e
[ "MIT" ]
null
null
null
Scene.cpp
KosukeTakahashi/CoSDL
9e7ae8e2f9f2434eca2236e25c6bcf54d5af716e
[ "MIT" ]
null
null
null
#include <SDL.h> #include "./Scene.hpp" #include "evcodes.hpp" #include "logger.hpp" Scene::Scene() { } Scene::~Scene() { } bool Scene::run(int fps, SDL_Renderer *renderer) { auto intervalMs = fps <= 0 ? 0 : 1000 / fps; SDL_Event ev; while (true) { auto start = SDL_GetTicks(); while (SDL_PollEvent(&ev)) { if (ev.type == SDL_QUIT) return true; if (ev.type == SDL_USEREVENT) { if (ev.user.code == static_cast<int>(EventCodes::QUIT)) return true; else if (ev.user.code == static_cast<int>(EventCodes::EXIT_SCENE)) return false; } } for (const auto &obj : this->objects) { obj->update(); } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); for (const auto &obj : this->objects) { obj->render(renderer); } SDL_RenderPresent(renderer); auto end = SDL_GetTicks(); auto elapsed = end - start; if (elapsed < intervalMs) { SDL_Delay(intervalMs - elapsed); } } } std::shared_ptr<GameObject> Scene::addGameObject(std::string label) { // Check if a object of the same label exists for (auto obj : this->objects) { if (obj->label == label) { Logger::warn("Scene#addGameObject", "A object of the same label found. Abort."); return nullptr; } } auto obj = std::make_shared<GameObject>(); obj->label = label; obj->parent = this; obj->start(); this->objects.push_back(obj); return obj; } std::shared_ptr<GameObject> Scene::getGameObject(std::string label) { for (auto obj : this->objects) { if (obj->label == label) { return obj; } } return nullptr; } bool Scene::removeGameObject(std::string label) { auto targetIter = this->objects.begin(); for (; targetIter != this->objects.end(); targetIter++) { if ((*targetIter)->label == label) { this->objects.erase(targetIter); return true; } } return false; }
25.776471
92
0.545413
KosukeTakahashi
6b951db2f0edf984e31abad90d864157ad8bb550
568
cpp
C++
template/specialization.cpp
0iui0/Cpp-Primer
ff8530a202ac0340a3e8de6bb9726cf0516c50fc
[ "CC0-1.0" ]
null
null
null
template/specialization.cpp
0iui0/Cpp-Primer
ff8530a202ac0340a3e8de6bb9726cf0516c50fc
[ "CC0-1.0" ]
null
null
null
template/specialization.cpp
0iui0/Cpp-Primer
ff8530a202ac0340a3e8de6bb9726cf0516c50fc
[ "CC0-1.0" ]
null
null
null
// // Created by iouoi on 2021/5/29. // //1.full specialization //指定任意类型会走这里 template<class Key> struct hash { }; //指定以下类型会走这里 template<> struct hash<int> { size_t operator( int x){ return x; }; } template<> //cout<<hash<long>()(1000)<<endl; struct hash<long> { size_t operator( long x){ return x; }; } //2.partial specialization 个数偏 template<typename T, typename Alloc= ...> class vector { }; template<typename Alloc= ...> class vector<bool, Alloc> { }; //范围偏 任意类型-->指针类型 template<typename T> class C { }; template<typename U> class C<U *> { };
13.853659
41
0.646127
0iui0
6b96be766f6f9d3cd5fba220af39669fa1a5ab3b
4,369
hpp
C++
PCL SAC + Boost/SampleConsensusProblem.hpp
erfannoury/sac
7e4c183a91bf16803bc78536476bba594bfba109
[ "MIT" ]
7
2016-10-19T12:35:06.000Z
2019-06-26T08:19:24.000Z
PCL SAC + Boost/SampleConsensusProblem.hpp
erfannoury/sac
7e4c183a91bf16803bc78536476bba594bfba109
[ "MIT" ]
null
null
null
PCL SAC + Boost/SampleConsensusProblem.hpp
erfannoury/sac
7e4c183a91bf16803bc78536476bba594bfba109
[ "MIT" ]
null
null
null
#ifndef ASLAM_SAMPLE_CONSENSUS_PROBLEM_HPP #define ASLAM_SAMPLE_CONSENSUS_PROBLEM_HPP #include <boost/random.hpp> #include <boost/shared_ptr.hpp> #include <ctime> namespace aslam { template<typename MODEL_T> class SampleConsensusProblem { public: typedef MODEL_T model_t; SampleConsensusProblem(bool randomSeed = true); virtual ~SampleConsensusProblem(); virtual void getSamples(int &iterations, std::vector<int> &samples); virtual bool isSampleGood(const std::vector<int> & sample) const; /** \brief Get a pointer to the vector of indices used. */ boost::shared_ptr <std::vector<int> > getIndices() const; void drawIndexSample (std::vector<int> & sample); virtual int getSampleSize() const = 0; virtual bool computeModelCoefficients( const std::vector<int> & indices, model_t & outModel) const = 0; /** \brief Recompute the model coefficients using the given inlier set * and return them to the user. Pure virtual. * * @note: these are the coefficients of the model after refinement * (e.g., after a least-squares optimization) * * \param[in] inliers the data inliers supporting the model * \param[in] model_coefficients the initial guess for the model coefficients * \param[out] optimized_coefficients the resultant recomputed coefficients after non-linear optimization */ virtual void optimizeModelCoefficients (const std::vector<int> & inliers, const model_t & model_coefficients, model_t & optimized_coefficients) = 0; /// \brief evaluate the score for the elements at indices based on this model. /// low scores mean a good fit. virtual void getSelectedDistancesToModel( const model_t & model, const std::vector<int> & indices, std::vector<double> & scores) const = 0; /** \brief Compute all distances from the cloud data to a given model. Pure virtual. * * \param[in] model_coefficients the coefficients of a model that we need to compute distances to * \param[out] distances the resultant estimated distances */ virtual void getDistancesToModel (const model_t & model_coefficients, std::vector<double> &distances); /** \brief Select all the points which respect the given model * coefficients as inliers. Pure virtual. * * \param[in] model_coefficients the coefficients of a model that we need to compute distances to * \param[in] threshold a maximum admissible distance threshold for determining the inliers from * the outliers * \param[out] inliers the resultant model inliers */ virtual void selectWithinDistance (const model_t &model_coefficients, const double threshold, std::vector<int> &inliers); /** \brief Count all the points which respect the given model * coefficients as inliers. Pure virtual. * * \param[in] model_coefficients the coefficients of a model that we need to * compute distances to * \param[in] threshold a maximum admissible distance threshold for * determining the inliers from the outliers * \return the resultant number of inliers */ virtual int countWithinDistance (const model_t &model_coefficients, const double threshold); void setIndices(const std::vector<int> & indices); void setUniformIndices(int N); int rnd(); int max_sample_checks_; boost::shared_ptr< std::vector<int> > indices_; std::vector<int> shuffled_indices_; /** \brief Boost-based random number generator algorithm. */ boost::mt19937 rng_alg_; /** \brief Boost-based random number generator distribution. */ boost::shared_ptr<boost::uniform_int<> > rng_dist_; /** \brief Boost-based random number generator. */ boost::shared_ptr<boost::variate_generator< boost::mt19937&, boost::uniform_int<> > > rng_gen_; }; } // namespace aslam #include "implementation/SampleConsensusProblem.hpp" #endif /* ASLAM_SAMPLE_CONSENSUS_PROBLEM_HPP */
37.025424
109
0.650721
erfannoury
6b9786f5b54b7a2bd3419b0ce0f4ab580f992559
1,074
cpp
C++
Backtracking/Graph Coloring.cpp
Sakshi14-code/CompetitiveCodingQuestions
2b23bb743106df2178f2832d5b4c8d7601127c91
[ "MIT" ]
null
null
null
Backtracking/Graph Coloring.cpp
Sakshi14-code/CompetitiveCodingQuestions
2b23bb743106df2178f2832d5b4c8d7601127c91
[ "MIT" ]
null
null
null
Backtracking/Graph Coloring.cpp
Sakshi14-code/CompetitiveCodingQuestions
2b23bb743106df2178f2832d5b4c8d7601127c91
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> #define n 4 #define m 3 int *node; int adj[4][4]={{0, 1, 1, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 0, 1, 0}, }; void printSoln() { int i; for(i=0;i<n;i++) { printf("Node %d is colored with color %d.\n",(i+1),node[i]); } printf("\n"); } int canicolor(int k, int color ) // checking whether kth node can be colored with a particular color. { int j; for(j=0;j<n;j++) if(adj[k][j]==1 && color==node[j]) return 0; return 1; } void ncoloring(int k) { if(k==n) { printSoln(); return; } int i; for(i=1;i<=m;i++) //running through all the colors as i was running through all columns in nqueens. { if(canicolor(k,i)) { node[k]=i; ncoloring(k+1); } } } int main() { int i; node= (int*)calloc(n,sizeof(int)); // all nodes filled with 0 color i.e invalid color or no colour. // adj=(int**)malloc(n*sizeof(int*)); // for(i=0;i<n;i++) // adj[i]=(int*)malloc(n*sizeof(int)); ncoloring(0); return 0; }
17.047619
103
0.522346
Sakshi14-code
6ba30af97637070ff4419988180d966e19938234
3,949
cpp
C++
src/CopyConstructors.cpp
jonathan-santos/learning-cpp
321208f8e7064c0efd86ce060b41bdb97f9ede7f
[ "MIT" ]
null
null
null
src/CopyConstructors.cpp
jonathan-santos/learning-cpp
321208f8e7064c0efd86ce060b41bdb97f9ede7f
[ "MIT" ]
null
null
null
src/CopyConstructors.cpp
jonathan-santos/learning-cpp
321208f8e7064c0efd86ce060b41bdb97f9ede7f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> void ValuesDoCopy() { int a = 1; int b = a; b++; std::cout << "Value do not copy[a]: " << a << std::endl; // 1 std::cout << "Value do not copy[b]: " << b << std::endl; // 2 } struct VectorCopy { float x, y; }; void ClassesAndStructsDoCopy() { VectorCopy a = { 1, 3 }; VectorCopy b = a; b.x = 10; b.y = 30; std::cout << "Classes and structs do not copy[Vector a]: (x): " << a.x << ", (y): " << a.y << std::endl; std::cout << "Classes and structs do not copy[Vector b]: (x): " << b.x << ", (y): " << b.y << std::endl; } void PointersCopyThePointerNotTheValue() { int* a = new int(1); int* b = a; (*b)++; std::cout << "Pointers copy the pointer, not the value[a]: " << *a << std::endl; // 2 std::cout << "Pointers copy the pointer, not the value[b]: " << *b << std::endl; // 2 delete a; VectorCopy* c = new VectorCopy(); (*c).x = 1; (*c).y = 3; VectorCopy* d = c; (*d).x = 10; (*d).y = 30; std::cout << "Pointers copy the pointer, not the value[Vector c]: (x): " << c->x << ", (y): " << c->y << std::endl; std::cout << "Pointers copy the pointer, not the value[Vector d]: (x): " << d->x << ", (y): " << d->y << std::endl; delete c; } class BasicString { private: char* m_Buffer; unsigned int m_Size; public: BasicString(const char* string) { m_Size = strlen(string); m_Buffer = new char[m_Size + 1]; memcpy(m_Buffer, string, m_Size); m_Buffer[m_Size] = 0; } ~BasicString() { delete[] m_Buffer; } //BasicString(const BasicString& other); // Copy constructor //BasicString(const BasicString& other) = delete; // Disable Copy constructor BasicString(const BasicString& other) // Deep copy. As in it guarantees that when being copied, BasicString will not copy m_Buffer as a pointer, but it will copy the value inside m_Buffer from the copied object to the new, while them both having different memory locations : m_Size(other.m_Size) { std::cout << "Copied BasicString" << std::endl; m_Buffer = new char[m_Size + 1]; memcpy(m_Buffer, other.m_Buffer, m_Size + 1); } char& operator[](unsigned int index) { return m_Buffer[index]; } friend std::ostream& operator<<(std::ostream& stream, const BasicString& string); }; std::ostream& operator<<(std::ostream& stream, const BasicString& string) { stream << string.m_Buffer; return stream; } void CopyOperator() { BasicString string = "Jhow"; BasicString secondString = string; secondString[0] = 'j'; std::cout << "string: " << string << std::endl; std::cout << "secondString: " << secondString << std::endl; } void PrintByValue(BasicString e) { std::cout << "By Value: " << e << std::endl; } void PrintByPointer(BasicString* e) { std::cout << "By pointer: " << *e << std::endl; } void PrintByReference(BasicString& e) { std::cout << "By reference: " << e << std::endl; } // When passing a object as a parameter to a function, you gotta be careful as how it is defined in the function. In the example bellow, when we pass the variable string to function PrintByValue, the variable string is actually being copied in memory to the function. The other two don't have the same behavior, saving memory and processing void FunctionCopy() { BasicString string = "Jhow"; PrintByValue(string); // Will appear "Copied BasicString" in console, because the Copy constructor was called PrintByPointer(&string); // No duplication PrintByReference(string); // No duplication } void ExecuteCopyConstructors() { ValuesDoCopy(); std::cout << std::endl; ClassesAndStructsDoCopy(); std::cout << std::endl; PointersCopyThePointerNotTheValue(); std::cout << std::endl; CopyOperator(); std::cout << std::endl; FunctionCopy(); }
28.615942
340
0.610028
jonathan-santos
6baa8aaebc87835c39186149cca16792ca3e6c4f
15,081
cpp
C++
source/backend/cpu/compute/DenseConvolutionTiledExecutor.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
source/backend/cpu/compute/DenseConvolutionTiledExecutor.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
source/backend/cpu/compute/DenseConvolutionTiledExecutor.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
// // DenseConvolutionTiledExecutor.cpp // MNN // // Created by MNN on 2018/07/16. // Copyright © 2018, Alibaba Group Holding Limited // #include "DenseConvolutionTiledExecutor.hpp" #include <MNN/AutoTime.hpp> #include "backend/cpu/CPUBackend.hpp" #include "CommonOptFunction.h" #include "core/Concurrency.h" #include "ConvOpt.h" #include "core/Macro.h" #include "core/TensorUtils.hpp" #include "math/Vec.hpp" #include "core/BufferAllocator.hpp" #include "core/MemoryFormater.h" using Vec4 = MNN::Math::Vec<float, 4>; namespace MNN { void DenseConvolutionTiledExecutor::initWeight(float *dest, const float *source, float* cache, int depth, int outputCount, int kernelSize, const CoreFunctions* function) { ConvolutionTiledExecutor::initWeight(source, cache, depth, outputCount, kernelSize, function); function->MNNPackForMatMul_B(dest, cache, outputCount, kernelSize * depth, true); /*MNN_PRINT("dense weight matrix tile:"); formatMatrix(dest, {UP_DIV(outputCount, 4), kernelSize * depth, 4});*/ } DenseConvolutionTiledExecutor::DenseConvolutionTiledExecutor(const Convolution2DCommon* common, Backend* b, const float* originWeight, size_t originWeightSize, const float* bias, size_t biasSize) : ConvolutionTiledExecutor(b, bias, biasSize) { auto outputCount = (int)biasSize; int eP, lP, hP; auto core = static_cast<CPUBackend*>(b)->functions(); int bytes = core->bytes; core->MNNGetMatMulPackMode(&eP, &lP, &hP); // Don't use common->inputCount for old model common->inputCount is zero auto srcCount = (int)originWeightSize / outputCount / common->kernelX() / common->kernelY(); auto lSize = srcCount * common->kernelX() * common->kernelY(); mResource->mWeight.reset(Tensor::createDevice<uint8_t>( {UP_DIV(outputCount, hP) * UP_DIV(lSize, lP) * hP * lP * bytes})); std::shared_ptr<Tensor> cache(Tensor::createDevice<uint8_t>({outputCount * srcCount * common->kernelX() * common->kernelY() * (int)sizeof(float)})); // cache must be float mValid = mValid && backend()->onAcquireBuffer(mResource->mWeight.get(), Backend::STATIC); mValid = mValid && backend()->onAcquireBuffer(cache.get(), Backend::STATIC); if (!mValid) { return; } initWeight(mResource->mWeight->host<float>(), originWeight, cache->host<float>(), srcCount, outputCount, common->kernelX() * common->kernelY(), core); backend()->onReleaseBuffer(cache.get(), Backend::STATIC); mProxy.reset(new DenseConvolutionTiledImpl(common, b)); } DenseConvolutionTiledExecutor::DenseConvolutionTiledExecutor(std::shared_ptr<CPUConvolution::Resource> res, const Convolution2DCommon* common, Backend* b) : ConvolutionTiledExecutor(res, b) { mProxy.reset(new DenseConvolutionTiledImpl(common, b)); } DenseConvolutionTiledExecutor::~DenseConvolutionTiledExecutor() { // Do nothing } bool DenseConvolutionTiledExecutor::onClone(Backend* bn, const Op* op, Execution** dst) { if (!mValid) { return false; } if (nullptr == dst) { return true; } *dst = new DenseConvolutionTiledExecutor(mResource, op->main_as_Convolution2D()->common(), bn); return true; } ErrorCode ConvolutionTiledExecutorMultiInput::onExecute(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs) { int depth = inputs[1]->channel(); int outputCount = inputs[1]->batch(); auto function = static_cast<CPUBackend*>(backend())->functions(); if (nullptr != mTempBias) { ::memset(mTempBias->host<float>(), 0, mTempBias->elementSize() * function->bytes); if (inputs.size() > 2) { ::memcpy(mTempBias->host<float>(), inputs[2]->host<float>(), inputs[2]->elementSize() * function->bytes); } } auto cache = mTempWeightCache->host<float>(); auto source = inputs[1]->host<float>(); auto kernelSize = inputs[1]->stride(1); // Swap k, ic int dims[4] = { depth, kernelSize, kernelSize, depth }; if (function->bytes < 4) { // TODO: Opt it // Lowp source = mTempWeightCache->host<float>() + mTempWeightCache->stride(0); function->MNNLowpToFp32(inputs[1]->host<int16_t>(), source, inputs[1]->elementSize()); for (int o=0; o<outputCount; ++o) { auto dO = cache + o * depth * kernelSize; auto sO = source + o * depth * kernelSize; MNNTranspose32Bit((int32_t*)dO, (const int32_t*)sO, &dims[0]); } function->MNNFp32ToLowp(cache, (int16_t*)cache, inputs[1]->elementSize()); } else { for (int o=0; o<outputCount; ++o) { auto dO = cache + o * depth * kernelSize; auto sO = source + o * depth * kernelSize; MNNTranspose32Bit((int32_t*)dO, (const int32_t*)sO, &dims[0]); } } function->MNNPackForMatMul_B(mTempWeight->host<float>(), mTempWeightCache->host<float>(), outputCount, kernelSize * depth, true); return mProxy->onExecute(mInputs, outputs); } ErrorCode ConvolutionTiledExecutorMultiInput::onResize(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs) { int depth = inputs[1]->channel(); int outputCount = outputs[0]->channel(); auto function = static_cast<CPUBackend*>(backend())->functions(); int eP, lP, hP; function->MNNGetMatMulPackMode(&eP, &lP, &hP); auto kernelSize = depth * inputs[1]->stride(1); mTempWeight.reset(Tensor::createDevice<float>( {UP_DIV(outputCount, hP), UP_DIV(kernelSize, lP), lP * hP})); if (function->bytes < 4) { mTempWeightCache.reset(Tensor::createDevice<int32_t>({2, outputCount * kernelSize})); } else { mTempWeightCache.reset(Tensor::createDevice<float>({outputCount * kernelSize})); } auto res = backend()->onAcquireBuffer(mTempWeight.get(), Backend::DYNAMIC); res = res && backend()->onAcquireBuffer(mTempWeightCache.get(), Backend::DYNAMIC); mTempBias.reset(); if (!res) { return OUT_OF_MEMORY; } if (inputs.size() > 2 && inputs[2]->elementSize() % function->pack == 0) { mInputs = {inputs[0], mTempWeight.get(), inputs[2]}; } else { mTempBias.reset(Tensor::createDevice<float>({UP_DIV(outputCount, function->pack) * function->pack})); backend()->onAcquireBuffer(mTempBias.get(), Backend::DYNAMIC); mInputs = {inputs[0], mTempWeight.get(), mTempBias.get()}; } backend()->onReleaseBuffer(mTempWeightCache.get(), Backend::DYNAMIC); auto errorCode = mProxy->onResize(mInputs, outputs); backend()->onReleaseBuffer(mTempWeight.get(), Backend::DYNAMIC); if (nullptr != mTempBias) { backend()->onReleaseBuffer(mTempBias.get(), Backend::DYNAMIC); } return errorCode; } void DenseConvolutionTiledImpl::getPackParameter(int* eP, int* lP, int* hP, const CoreFunctions* core) { core->MNNGetMatMulPackMode(eP, lP, hP); return; } ErrorCode DenseConvolutionTiledImpl::onResize(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs) { CPUConvolution::onResize(inputs, outputs); auto input = inputs[0]; auto weight = inputs[1]; Tensor *bias = nullptr; auto core = static_cast<CPUBackend *>(backend())->functions(); int bytes = core->bytes; int unit = core->pack; auto packA = core->MNNPackC4ForMatMul_A; int eP, lP, hP; getPackParameter(&eP, &lP, &hP, core); auto matmulUnit = core->MNNPackedMatMul; auto matmulRemain = core->MNNPackedMatMulRemain; auto strideX = mCommon->strideX(); auto strideY = mCommon->strideY(); auto dilateX = mCommon->dilateX(); auto dilateY = mCommon->dilateY(); auto padY = mPadY; auto padX = mPadX; auto kernel_width = mCommon->kernelX(); auto kernel_height = mCommon->kernelY(); auto output = outputs[0]; auto batch = output->batch(); auto width = output->width(); auto height = output->height(); int threadNumber = ((CPUBackend *)backend())->threadNumber(); auto weightPtr = weight->host<float>(); auto src_width = input->width(); auto src_height = input->height(); auto icC4 = UP_DIV(input->channel(), unit); auto ic = input->channel(); auto L = ic * mCommon->kernelY() * mCommon->kernelX(); if (src_width == 1 && width == 1 && height > 1) { /* Swap x, y*/ width = height; height = 1; padX = mPadY; padY = mPadX; strideX = strideY; strideY = 1; /* Don't need stride */ src_width = src_height; src_height = 1; dilateX = dilateY; dilateY = 1; kernel_width = kernel_height; kernel_height = 1; } const float *biasPtr = nullptr; if (inputs.size() > 2) { bias = inputs[2]; biasPtr = bias->host<float>(); } auto kernelSize = mCommon->kernelX() * mCommon->kernelY(); mTempBufferTranspose.buffer().type = halide_type_of<uint8_t>(); mTempBufferTranspose.buffer().dimensions = 2; mTempBufferTranspose.buffer().dim[0].extent = threadNumber; mTempBufferTranspose.buffer().dim[1].extent = UP_DIV(L, lP) * lP * eP * bytes; TensorUtils::setLinearLayout(&mTempBufferTranspose); auto plane = width * height * batch; int tileCount = UP_DIV(plane, eP); bool success = backend()->onAcquireBuffer(&mTempBufferTranspose, Backend::DYNAMIC); if (!success) { return OUT_OF_MEMORY; } auto outputChannel = output->channel(); auto oC4 = UP_DIV(outputChannel, unit); auto bufferAlloc = static_cast<CPUBackend *>(backend())->getBufferAllocator(); auto maxLine = UP_DIV(eP, width) + 1; auto tempPtr = bufferAlloc->alloc(kernelSize * maxLine * threadNumber * (4 * sizeof(int32_t) + sizeof(float *))); if (nullptr == tempPtr.first) { return OUT_OF_MEMORY; } backend()->onReleaseBuffer(&mTempBufferTranspose, Backend::DYNAMIC); bufferAlloc->free(tempPtr); auto threadNumberFirst = std::min(threadNumber, tileCount); auto postParameters = getPostParameters(); mFunction.first = threadNumberFirst; mFunction.second = [=](int tId) { auto gemmBuffer = mTempBufferTranspose.host<uint8_t>() + mTempBufferTranspose.stride(0) * tId; auto srcPtr = (float const **)((uint8_t *)tempPtr.first + tempPtr.second + tId * kernelSize * maxLine * (4 * sizeof(int32_t) + sizeof(float *))); auto el = (int32_t *)(srcPtr + kernelSize * maxLine); int32_t info[4]; info[1] = src_width * src_height * batch; info[2] = eP; info[3] = strideX; size_t parameters[6]; parameters[0] = eP * bytes; parameters[1] = L; parameters[2] = outputChannel; parameters[3] = plane * unit * bytes; parameters[4] = 0; parameters[5] = 0; auto dstOrigin = output->host<uint8_t>(); auto srcOrigin = input->host<uint8_t>(); for (int x = (int)tId; x < tileCount; x += threadNumberFirst) { int start = (int)x * eP; int remain = plane - start; int xC = remain > eP ? eP : remain; /* Compute Pack position */ int oyBegin = start / width; int oxBegin = start % width; int oyEnd = (start + xC - 1) / width; remain = xC; int number = 0; bool needZero = false; int eStart = 0; for (int oyb = oyBegin; oyb <= oyEnd; ++oyb) { int step = std::min(width - oxBegin, remain); int oy = oyb % height; int ob = oyb / height; int sySta = oy * strideY - padY; int kyStart = std::max(0, UP_DIV(-sySta, dilateY)); int kyEnd = std::min(kernel_height, UP_DIV(src_height - sySta, dilateY)); if (kyEnd - kyStart < kernel_height) { needZero = true; } auto srcStart = srcOrigin + ((ob * src_height + sySta) * src_width) * bytes * unit; for (int ky = kyStart; ky < kyEnd; ++ky) { auto lKYOffset = ky * kernel_width * ic; auto srcKy = srcStart + ky * dilateY * src_width * bytes * unit; for (int kx = 0; kx < kernel_width; ++kx) { /* Compute x range:*/ /* 0 <= (oxBegin + x) * strideX - padX + dilateX * kx < src_width*/ /* 0 <= x <= step*/ int end = std::min( step, (src_width - oxBegin * strideX - dilateX * kx + padX + strideX - 1) / strideX); int sta = std::max(0, UP_DIV((padX - oxBegin * strideX - dilateX * kx), strideX)); if (end - sta < step) { needZero = true; } if (end > sta) { auto lOffset = lKYOffset + (kx * ic); auto srcKx = srcKy + ((oxBegin + sta) * strideX + dilateX * kx - padX) * bytes * unit; srcPtr[number] = (const float *)srcKx; el[4 * number + 0] = end - sta; el[4 * number + 1] = ic; el[4 * number + 2] = eStart + sta; el[4 * number + 3] = lOffset; number++; } } } oxBegin = 0; remain -= step; eStart += step; } info[0] = number; if (needZero || lP != 1) { ::memset(gemmBuffer, 0, mTempBufferTranspose.stride(0)); } if (number > 0) { packA((float *)gemmBuffer, srcPtr, info, el); } if (xC == eP) { matmulUnit((float*)(dstOrigin + start * unit * bytes), (float*)gemmBuffer, weightPtr, parameters,postParameters.data(), biasPtr); } else { matmulRemain((float*)(dstOrigin + start * unit * bytes), (float*)gemmBuffer, weightPtr, xC, parameters,postParameters.data(), biasPtr); } } }; return NO_ERROR; } } // namespace MNN
45.561934
191
0.562496
foreverlms
6baac81394bddd9d2004eed038e8f2c76543a91d
5,054
cpp
C++
src/SortVisualizer.cpp
NFWSA/SortVisualizer
32ce9b42d0c50b5ebca47169b5a9cc6eecec292b
[ "MIT" ]
null
null
null
src/SortVisualizer.cpp
NFWSA/SortVisualizer
32ce9b42d0c50b5ebca47169b5a9cc6eecec292b
[ "MIT" ]
null
null
null
src/SortVisualizer.cpp
NFWSA/SortVisualizer
32ce9b42d0c50b5ebca47169b5a9cc6eecec292b
[ "MIT" ]
null
null
null
#include "DataLine.h" #include "SortView.h" #include <ege.h> #include <string> #include <algorithm> #include <map> #include <exception> using namespace ege; using namespace SurgeNight; class sort_break : std::logic_error { public: sort_break(const std::string &msg) : std::logic_error(msg) {} }; void countSort(DataLine *beg, DataLine *end, SortView *view = nullptr) { unsigned int max = view->getMax(); auto count = new unsigned int[max + 1](); std::fill(count, count + max + 1, 0); try { for (auto i = beg; i < end; ++i) { i->setAccessed(); ++count[i->getKey()]; } for (auto i = 1u; i <= max; ++i) { count[i] += count[i-1]; view->paint(static_cast<float>(i) / max * 100.0f); } } catch (const sort_break &e) { delete[] count; throw; } auto ndata = new DataLine[end - beg]; view->setData(ndata); try { for (auto i = beg; i < end; ++i) { ndata[--count[i->getKey()]] = *i; } } catch (const sort_break &e) { view->setData(nullptr); delete[] ndata; delete[] count; throw; } view->setData(nullptr); delete[] ndata; delete[] count; } void selectSort(DataLine *beg, DataLine *end, SortView *view = nullptr) { for (auto i = beg; i < end; ++i) { auto key = i; for (auto j = i + 1; j < end; ++j) { if (*j < *key) key = j; } std::swap(*key, *i); } } void bubbleSort(DataLine *beg, DataLine *end, SortView *view = nullptr) { for (auto i = beg; i < end; ++i) { for (auto j = end - 1; j > i; --j) { if (*(j - 1) > *j) { std::swap(*(j - 1), *j); } } } } void quickSort(DataLine *beg, DataLine *end, SortView *view = nullptr) { if (end <= beg) return; auto t = end - 1; auto i = beg; for (auto j = beg; j < end - 1; ++j) { if (*j <= *t) std::swap(*i++, *j); } std::swap(*i, *t); quickSort(beg, i); quickSort(i + 1, end); } void insertSort(DataLine *beg, DataLine *end, SortView *view = nullptr) { DataLine t; for (auto i = beg; i < end; ++i) { t = *i; auto j = i; for (; j > beg; --j) { if (*(j - 1) > t) *j = *(j - 1); else break; } std::swap(*j, t); } } void stdSort(DataLine *beg, DataLine *end, SortView *view = nullptr) { std::sort(beg, end); } void show(const std::string &name, std::function<void(DataLine*, DataLine*, SortView*)> &func) { cleardevice(); SortView view(name, "in.txt", 0, 0, getwidth(), getheight()); try { DataLine::setDrawFunc([&]() { cleardevice(); view.paint(); if (ege::kbhit() && ege::getch() == ege::key_esc) { sort_break a("Sort Break"); throw a; } }); func(view.begin(), view.end(), &view); xyprintf(20, 20, "Sort finish, press any key to continue..."); } catch (const sort_break &e) { xyprintf(20, 20, "Sort break, press any key to continue..."); } DataLine::setDrawFunc(nullptr); getch(); } int main() { setinitmode( INIT_NOFORCEEXIT | INIT_RENDERMANUAL ); //setinitmode( INIT_RENDERMANUAL | INIT_NOBORDER | INIT_NOFORCEEXIT ); initgraph(1300, 320); setcaption("Sort Visualizer by SurgeNight"); std::string str[] = { "bubble sort", "insert sort", "select sort", "quick sort", "count sort", "std sort", "exit" }; typedef std::pair< std::string, std::function<void(DataLine*, DataLine*, SortView*)> > Algo; typedef std::map< int, Algo > AlgoTab; AlgoTab algo = { { key_1, { "Bubble", bubbleSort } }, { key_2, { "Insert", insertSort } }, { key_3, { "Select", selectSort } }, { key_4, { "Quick", quickSort } }, { key_5, { "Count", countSort } }, { key_6, { "Std", stdSort } } }; setfont(30, 0, "Arial"); setcolor(LIGHTGREEN); while (is_run()) { cleardevice(); xyprintf(20, 20, "Please press key to start to sort:"); auto menuNum = sizeof(str) / sizeof(std::string); for(auto i = 0u; i < menuNum; ++i) xyprintf(20, 50 + i * 30, "\t%d. %s", (i + 1) % menuNum, str[i].c_str()); int key = getch(); if (key_0 == key) break; auto it = algo.find(key); if (it != algo.end()){ show((*it).second.first, (*it).second.second); } else { xyprintf(20, 20, "Select error! Press any key to continue..."); getch(); continue; } } closegraph(); return 0; }
27.318919
97
0.475069
NFWSA
6bab921d21ad76d971808fd81abb4f1875381fa3
11,206
cpp
C++
src/qt/qtbase/src/widgets/dialogs/qerrormessage.cpp
chihlee/phantomjs
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/widgets/dialogs/qerrormessage.cpp
chihlee/phantomjs
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/widgets/dialogs/qerrormessage.cpp
chihlee/phantomjs
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWidgets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qerrormessage.h" #ifndef QT_NO_ERRORMESSAGE #include "qapplication.h" #include "qcheckbox.h" #include "qlabel.h" #include "qlayout.h" #include "qmessagebox.h" #include "qpushbutton.h" #include "qstringlist.h" #include "qtextedit.h" #include "qdialog_p.h" #include "qpixmap.h" #include "qmetaobject.h" #include "qthread.h" #include "qqueue.h" #include "qset.h" #include <stdio.h> #include <stdlib.h> #ifdef Q_OS_WINCE extern bool qt_wince_is_mobile(); //defined in qguifunctions_wince.cpp extern bool qt_wince_is_high_dpi(); //defined in qguifunctions_wince.cpp #endif QT_BEGIN_NAMESPACE class QErrorMessagePrivate : public QDialogPrivate { Q_DECLARE_PUBLIC(QErrorMessage) public: QPushButton * ok; QCheckBox * again; QTextEdit * errors; QLabel * icon; QQueue<QPair<QString, QString> > pending; QSet<QString> doNotShow; QSet<QString> doNotShowType; QString currentMessage; QString currentType; bool nextPending(); void retranslateStrings(); }; class QErrorMessageTextView : public QTextEdit { public: QErrorMessageTextView(QWidget *parent) : QTextEdit(parent) { setReadOnly(true); } virtual QSize minimumSizeHint() const; virtual QSize sizeHint() const; }; QSize QErrorMessageTextView::minimumSizeHint() const { #ifdef Q_OS_WINCE if (qt_wince_is_mobile()) if (qt_wince_is_high_dpi()) return QSize(200, 200); else return QSize(100, 100); else return QSize(70, 70); #else return QSize(50, 50); #endif } QSize QErrorMessageTextView::sizeHint() const { #ifdef Q_OS_WINCE if (qt_wince_is_mobile()) if (qt_wince_is_high_dpi()) return QSize(400, 200); else return QSize(320, 120); else return QSize(300, 100); #else return QSize(250, 75); #endif //Q_OS_WINCE } /*! \class QErrorMessage \brief The QErrorMessage class provides an error message display dialog. \ingroup standard-dialog \inmodule QtWidgets An error message widget consists of a text label and a checkbox. The checkbox lets the user control whether the same error message will be displayed again in the future, typically displaying the text, "Show this message again" translated into the appropriate local language. For production applications, the class can be used to display messages which the user only needs to see once. To use QErrorMessage like this, you create the dialog in the usual way, and show it by calling the showMessage() slot or connecting signals to it. The static qtHandler() function installs a message handler using qInstallMessageHandler() and creates a QErrorMessage that displays qDebug(), qWarning() and qFatal() messages. This is most useful in environments where no console is available to display warnings and error messages. In both cases QErrorMessage will queue pending messages and display them in order, with each new message being shown as soon as the user has accepted the previous message. Once the user has specified that a message is not to be shown again it is automatically skipped, and the dialog will show the next appropriate message in the queue. The \l{dialogs/standarddialogs}{Standard Dialogs} example shows how to use QErrorMessage as well as other built-in Qt dialogs. \image qerrormessage.png \sa QMessageBox, QStatusBar::showMessage(), {Standard Dialogs Example} */ static QErrorMessage * qtMessageHandler = 0; static void deleteStaticcQErrorMessage() // post-routine { if (qtMessageHandler) { delete qtMessageHandler; qtMessageHandler = 0; } } static bool metFatal = false; static void jump(QtMsgType t, const QMessageLogContext & /*context*/, const QString &m) { if (!qtMessageHandler) return; QString rich; switch (t) { case QtDebugMsg: default: rich = QErrorMessage::tr("Debug Message:"); break; case QtWarningMsg: rich = QErrorMessage::tr("Warning:"); break; case QtFatalMsg: rich = QErrorMessage::tr("Fatal Error:"); } rich = QString::fromLatin1("<p><b>%1</b></p>").arg(rich); rich += Qt::convertFromPlainText(m, Qt::WhiteSpaceNormal); // ### work around text engine quirk if (rich.endsWith(QLatin1String("</p>"))) rich.chop(4); if (!metFatal) { if (QThread::currentThread() == qApp->thread()) { qtMessageHandler->showMessage(rich); } else { QMetaObject::invokeMethod(qtMessageHandler, "showMessage", Qt::QueuedConnection, Q_ARG(QString, rich)); } metFatal = (t == QtFatalMsg); } } /*! Constructs and installs an error handler window with the given \a parent. */ QErrorMessage::QErrorMessage(QWidget * parent) : QDialog(*new QErrorMessagePrivate, parent) { Q_D(QErrorMessage); QGridLayout * grid = new QGridLayout(this); d->icon = new QLabel(this); #ifndef QT_NO_MESSAGEBOX d->icon->setPixmap(QMessageBox::standardIcon(QMessageBox::Information)); d->icon->setAlignment(Qt::AlignHCenter | Qt::AlignTop); #endif grid->addWidget(d->icon, 0, 0, Qt::AlignTop); d->errors = new QErrorMessageTextView(this); grid->addWidget(d->errors, 0, 1); d->again = new QCheckBox(this); d->again->setChecked(true); grid->addWidget(d->again, 1, 1, Qt::AlignTop); d->ok = new QPushButton(this); #if defined(Q_OS_WINCE) d->ok->setFixedSize(0,0); #endif connect(d->ok, SIGNAL(clicked()), this, SLOT(accept())); d->ok->setFocus(); grid->addWidget(d->ok, 2, 0, 1, 2, Qt::AlignCenter); grid->setColumnStretch(1, 42); grid->setRowStretch(0, 42); d->retranslateStrings(); } /*! Destroys the error message dialog. */ QErrorMessage::~QErrorMessage() { if (this == qtMessageHandler) { qtMessageHandler = 0; QtMessageHandler tmp = qInstallMessageHandler(0); // in case someone else has later stuck in another... if (tmp != jump) qInstallMessageHandler(tmp); } } /*! \reimp */ void QErrorMessage::done(int a) { Q_D(QErrorMessage); if (!d->again->isChecked() && !d->currentMessage.isEmpty() && d->currentType.isEmpty()) { d->doNotShow.insert(d->currentMessage); } if (!d->again->isChecked() && !d->currentType.isEmpty()) { d->doNotShowType.insert(d->currentType); } d->currentMessage.clear(); d->currentType.clear(); if (!d->nextPending()) { QDialog::done(a); if (this == qtMessageHandler && metFatal) exit(1); } } /*! Returns a pointer to a QErrorMessage object that outputs the default Qt messages. This function creates such an object, if there isn't one already. */ QErrorMessage * QErrorMessage::qtHandler() { if (!qtMessageHandler) { qtMessageHandler = new QErrorMessage(0); qAddPostRoutine(deleteStaticcQErrorMessage); // clean up qtMessageHandler->setWindowTitle(QApplication::applicationName()); qInstallMessageHandler(jump); } return qtMessageHandler; } /*! \internal */ bool QErrorMessagePrivate::nextPending() { while (!pending.isEmpty()) { QPair<QString,QString> pendingMessage = pending.dequeue(); QString message = pendingMessage.first; QString type = pendingMessage.second; if (!message.isEmpty() && ((type.isEmpty() && !doNotShow.contains(message)) || (!type.isEmpty() && !doNotShowType.contains(type)))) { #ifndef QT_NO_TEXTHTMLPARSER errors->setHtml(message); #else errors->setPlainText(message); #endif currentMessage = message; currentType = type; return true; } } return false; } /*! Shows the given message, \a message, and returns immediately. If the user has requested for the message not to be shown again, this function does nothing. Normally, the message is displayed immediately. However, if there are pending messages, it will be queued to be displayed later. */ void QErrorMessage::showMessage(const QString &message) { Q_D(QErrorMessage); if (d->doNotShow.contains(message)) return; d->pending.enqueue(qMakePair(message,QString())); if (!isVisible() && d->nextPending()) show(); } /*! \since 4.5 \overload Shows the given message, \a message, and returns immediately. If the user has requested for messages of type, \a type, not to be shown again, this function does nothing. Normally, the message is displayed immediately. However, if there are pending messages, it will be queued to be displayed later. \sa showMessage() */ void QErrorMessage::showMessage(const QString &message, const QString &type) { Q_D(QErrorMessage); if (d->doNotShow.contains(message) && d->doNotShowType.contains(type)) return; d->pending.push_back(qMakePair(message,type)); if (!isVisible() && d->nextPending()) show(); } /*! \reimp */ void QErrorMessage::changeEvent(QEvent *e) { Q_D(QErrorMessage); if (e->type() == QEvent::LanguageChange) { d->retranslateStrings(); } QDialog::changeEvent(e); } void QErrorMessagePrivate::retranslateStrings() { again->setText(QErrorMessage::tr("&Show this message again")); ok->setText(QErrorMessage::tr("&OK")); } QT_END_NAMESPACE #endif // QT_NO_ERRORMESSAGE
28.807198
141
0.664465
chihlee
6babe9b2516f92e9e3db90d77a034a4747cd90b5
14,283
cpp
C++
DeepSkyDad.AF2.ESP32/src/Motor_AF2.cpp
DeepSkyDad/AF2
126bb3e09c76fd83932dd60cf9df8ba7ddc1df7e
[ "MIT" ]
null
null
null
DeepSkyDad.AF2.ESP32/src/Motor_AF2.cpp
DeepSkyDad/AF2
126bb3e09c76fd83932dd60cf9df8ba7ddc1df7e
[ "MIT" ]
1
2019-09-09T23:56:16.000Z
2019-09-22T08:15:27.000Z
DeepSkyDad.AF2.ESP32/src/Motor_AF2.cpp
DeepSkyDad/AF2
126bb3e09c76fd83932dd60cf9df8ba7ddc1df7e
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "Motor_AF2.h" void Motor_AF2::_writeCoilsMode() { //Serial.println(_eeprom->getIsManualControl()); if (isMoving()) return; unsigned short coilsMode = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsMode() : _eeprom->getCoilsMode(); unsigned int holdCurrent = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsCurrentHold() : _eeprom->getCoilsCurrentHold(); unsigned int timeoutMs = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsIdleTimeoutMs() : _eeprom->getCoilsIdleTimeoutMs(); if (coilsMode == (unsigned short)COILS_MODE::IDLE_OFF) { //Serial.println("off"); digitalWrite(MP6500_PIN_SLP, LOW); _coilsOn = false; } //Always on else if (coilsMode == (unsigned short)COILS_MODE::ALWAYS_ON) { //Serial.println("Always on"); digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, holdCurrent); _coilsOn = true; } //Idle - coils timeout (ms) else if (coilsMode == (unsigned short)COILS_MODE::IDLE_TIMEOUT_OFF) { //Serial.println("Timeout"); if ((millis() - _lastStopMs) <= timeoutMs) { digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, holdCurrent); _coilsOn = true; } else { digitalWrite(MP6500_PIN_SLP, LOW); _coilsOn = false; } } } void Motor_AF2::_writeStepMode(unsigned short stepMode) { switch (stepMode) { case (unsigned short)STEP_MODE::FULL: digitalWrite(MP6500_PIN_MS1, 0); digitalWrite(MP6500_PIN_MS2, 0); break; case (unsigned short)STEP_MODE::HALF: digitalWrite(MP6500_PIN_MS1, 1); digitalWrite(MP6500_PIN_MS2, 0); break; case (unsigned short)STEP_MODE::QUARTER: digitalWrite(MP6500_PIN_MS1, 0); digitalWrite(MP6500_PIN_MS2, 1); break; case (unsigned short)STEP_MODE::EIGHT: digitalWrite(MP6500_PIN_MS1, 1); digitalWrite(MP6500_PIN_MS2, 1); break; default: // half step by default digitalWrite(MP6500_PIN_MS1, 1); digitalWrite(MP6500_PIN_MS2, 0); break; } } void Motor_AF2::init(EEPROM_AF2 &eeprom) { pinMode(MP6500_PIN_DIR, OUTPUT); pinMode(MP6500_PIN_STEP, OUTPUT); pinMode(MP6500_PIN_MS1, OUTPUT); pinMode(MP6500_PIN_MS2, OUTPUT); pinMode(MP6500_PIN_SLP, OUTPUT); pinMode(MP6500_PIN_EN, OUTPUT); digitalWrite(MP6500_PIN_EN, LOW); ledcAttachPin(MP6500_PIN_I1, 1); // Initialize channels // channels 0-15, resolution 1-16 bits, freq limits depend on resolution // ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits); ledcSetup(1, 64000, 12); // 12 kHz PWM, 12-bit resolution // set direction and step to low digitalWrite(MP6500_PIN_DIR, LOW); digitalWrite(MP6500_PIN_STEP, LOW); digitalWrite(MP6500_PIN_SLP, LOW); _eeprom = &eeprom; _writeStepMode(_eeprom->getStepMode()); _writeCoilsMode(); } //GENERAL void Motor_AF2::handleMove() { if (_movementStatus != MOVEMENT_STATUS::STOP) { digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getIsManualControl() ? _eeprom->getManualCoilsCurrentMove() : _eeprom->getCoilsCurrentMove()); unsigned short sm = _eeprom->getIsManualControl() ? _eeprom->getManualStepMode() : _eeprom->getStepMode(); bool reverseDirection = _eeprom->getIsManualControl() ? _eeprom->getManualReverseDirection() : _eeprom->getReverseDirection(); unsigned int speedFactor = 1; switch (_eeprom->getIsManualControl() ? _eeprom->getManualSpeedMode() : _eeprom->getSpeedMode()) { case (unsigned short)SPEED_MODE::SLOW: speedFactor = 30; break; case (unsigned short)SPEED_MODE::MEDIUM: speedFactor = 12; break; case (unsigned short)SPEED_MODE::FAST: speedFactor = 1; break; } if (_eeprom->getTargetPosition() < _eeprom->getPosition()) { digitalWrite(MP6500_PIN_DIR, reverseDirection ? LOW : HIGH); while (_eeprom->getPosition() > _eeprom->getTargetPosition()) { digitalWrite(MP6500_PIN_STEP, 1); delayMicroseconds(1); digitalWrite(MP6500_PIN_STEP, 0); _eeprom->setPosition(_eeprom->getPosition() - 1); delayMicroseconds(speedFactor * (1600 / sm)); if (_movementStatus == MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS) _eeprom->setTargetPosition(_eeprom->getTargetPosition() - 2); } } else if (_eeprom->getTargetPosition() > _eeprom->getPosition()) { digitalWrite(MP6500_PIN_DIR, reverseDirection ? HIGH : LOW); while (_eeprom->getPosition() < _eeprom->getTargetPosition()) { digitalWrite(MP6500_PIN_STEP, 1); delayMicroseconds(1); digitalWrite(MP6500_PIN_STEP, 0); _eeprom->setPosition(_eeprom->getPosition() + 1); delayMicroseconds(speedFactor * (1600 / sm)); if (_movementStatus == MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS) _eeprom->setTargetPosition(_eeprom->getTargetPosition() + 2); } } stop(); } else { unsigned short coilsMode = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsMode() : _eeprom->getCoilsMode(); if (_coilsOn && coilsMode == (unsigned short)COILS_MODE::IDLE_TIMEOUT_OFF) { //auto-off coils after timeout unsigned int timeoutMs = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsIdleTimeoutMs() : _eeprom->getCoilsIdleTimeoutMs(); if ((millis() - _lastStopMs) > timeoutMs) { _writeCoilsMode(); } } } } void Motor_AF2::stop() { if (_movementStatus != MOVEMENT_STATUS::STOP) { _movementStatus = MOVEMENT_STATUS::STOP; _eeprom->setTargetPosition(_eeprom->getPosition()); _lastStopMs = millis(); _settled = _eeprom->getSettleBufferMs() == 0; _writeCoilsMode(); } } bool Motor_AF2::isMoving() { if (_movementStatus != MOVEMENT_STATUS::STOP) { return true; } else { /* if your focuser has any play, this can affect the autofocuser performance. SGP for example goes aways from current position and than starts traversing back. When it changes focus direction (traverse back), focuser play can cause FOV to wiggle just a bit, which causes enlongated stars on the next exposure. Settle buffer option returns IsMoving as TRUE after focuser reaches target position, letting it to settle a bit. Advices by Jared Wellman of SGP. */ if (!_settled) { if ((millis() - _lastStopMs) > _eeprom->getSettleBufferMs()) { _settled = true; return false; } else { return true; } } else { return false; } } } MOVEMENT_STATUS Motor_AF2::getMovementStatus() { return _movementStatus; } void Motor_AF2::resetToDefaults() { _writeStepMode(_eeprom->getStepMode()); _writeCoilsMode(); } //EXTERNAL (ASCOM or INDI via Serial/Wifi) void Motor_AF2::move() { if (_eeprom->getTargetPosition() == _eeprom->getPosition()) return; _writeStepMode(_eeprom->getStepMode()); digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getCoilsCurrentMove()); /* When waking up from sleep mode, approximately 1ms of time must pass before a STEP command can be issued to allow the internal circuitry to stabilize. */ delayMicroseconds(1000); _movementStatus = MOVEMENT_STATUS::MOVING; _eeprom->setIsManualControl(false); _eeprom->delayEepromWrite(); } void Motor_AF2::setCoilsMode(unsigned short mode) { _eeprom->setIsManualControl(false); _eeprom->setCoilsMode(mode); _writeCoilsMode(); } int Motor_AF2::getMoveCurrentPercent() { return (int)((float)MP6500_PIN_I1_MOVE_MAX - (float)_eeprom->getCoilsCurrentMove()) / (float)MP6500_PIN_I1_MOVE_RANGE * 100; } void Motor_AF2::setMoveCurrentPercent(float percent) { percent = percent / 100.0; _eeprom->setCoilsCurrentMove((unsigned short)MP6500_PIN_I1_MOVE_MAX - MP6500_PIN_I1_MOVE_RANGE * percent); } void Motor_AF2::setMoveCurrent(unsigned int value) { _eeprom->setIsManualControl(false); if (value > MP6500_PIN_I1_MOVE_MAX) value = MP6500_PIN_I1_MOVE_MAX; else if (value < MP6500_PIN_I1_MOVE_MIN) value = MP6500_PIN_I1_MOVE_MIN; _eeprom->setCoilsCurrentMove(value); _writeCoilsMode(); } int Motor_AF2::getHoldCurrentPercent() { return (int)((float)MP6500_PIN_I1_HOLD_MAX - (float)_eeprom->getCoilsCurrentHold()) / (float)MP6500_PIN_I1_HOLD_RANGE * 100; } void Motor_AF2::setHoldCurrentPercent(float percent) { percent = percent / 100.0; _eeprom->setCoilsCurrentHold((unsigned short)(MP6500_PIN_I1_HOLD_MAX - MP6500_PIN_I1_HOLD_RANGE * percent)); _writeCoilsMode(); } void Motor_AF2::setHoldCurrent(unsigned int value) { _eeprom->setIsManualControl(false); if (value > MP6500_PIN_I1_HOLD_MAX) value = MP6500_PIN_I1_HOLD_MAX; else if (value < MP6500_PIN_I1_HOLD_MIN) value = MP6500_PIN_I1_HOLD_MIN; _eeprom->setCoilsCurrentHold(value); _writeCoilsMode(); } //MANUAL MOVEMENT void Motor_AF2::moveManual() { if (_eeprom->getTargetPosition() == _eeprom->getPosition()) return; _writeStepMode(_eeprom->getManualStepMode()); digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getManualCoilsCurrentMove()); /* When waking up from sleep mode, approximately 1ms of time must pass before a STEP command can be issued to allow the internal circuitry to stabilize. */ delayMicroseconds(1000); _movementStatus = MOVEMENT_STATUS::MOVING_MANUAL; _eeprom->setIsManualControl(true); _eeprom->delayEepromWrite(); } void Motor_AF2::moveManual(MOVEMENT_MANUAL_DIR dir) { _eeprom->setIsManualControl(true); int diff = _eeprom->getManualFineMoveSteps(); if (_eeprom->getManualStepSize() == (unsigned short)MANUAL_STEP_SIZE::COARSE) { diff = _eeprom->getManualCoarseMoveSteps(); } if (dir == MOVEMENT_MANUAL_DIR::CW) _eeprom->setTargetPosition(_eeprom->getPosition() + diff); else { if (diff > _eeprom->getPosition()) _eeprom->setTargetPosition(0); else _eeprom->setTargetPosition(_eeprom->getPosition() - diff); } if (_eeprom->getTargetPosition() == _eeprom->getPosition()) return; //Serial.println(_eeprom->getPosition()); //Serial.println(_eeprom->getTargetPosition()); _writeStepMode(_eeprom->getManualStepMode()); digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getManualCoilsCurrentMove()); /* When waking up from sleep mode, approximately 1ms of time must pass before a STEP command can be issued to allow the internal circuitry to stabilize. */ delayMicroseconds(1000); _movementStatus = MOVEMENT_STATUS::MOVING_MANUAL; _eeprom->delayEepromWrite(); } void Motor_AF2::moveManualContinuous(MOVEMENT_MANUAL_DIR dir) { _eeprom->setIsManualControl(true); _writeStepMode(_eeprom->getManualStepMode()); digitalWrite(MP6500_PIN_SLP, HIGH); ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getManualCoilsCurrentMove()); /* When waking up from sleep mode, approximately 1ms of time must pass before a STEP command can be issued to allow the internal circuitry to stabilize. */ delayMicroseconds(1000); if (dir == MOVEMENT_MANUAL_DIR::CW) { _eeprom->setTargetPosition(_eeprom->getTargetPosition() + 1); _movementStatus = MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS; } else { _eeprom->setTargetPosition(_eeprom->getTargetPosition() - 1); _movementStatus = MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS; } _eeprom->delayEepromWrite(); } void Motor_AF2::setManualCoilsMode(unsigned short mode) { _eeprom->setIsManualControl(true); _eeprom->setManualCoilsMode(mode); _writeCoilsMode(); } int Motor_AF2::getManualMoveCurrentPercent() { return (int)((float)MP6500_PIN_I1_MOVE_MAX - (float)_eeprom->getManualCoilsCurrentMove()) / (float)MP6500_PIN_I1_MOVE_RANGE * 100; } void Motor_AF2::setManualMoveCurrentPercent(float percent) { percent = percent / 100.0; _eeprom->setManualCoilsCurrentMove((unsigned short)MP6500_PIN_I1_MOVE_MAX - MP6500_PIN_I1_MOVE_RANGE * percent); } void Motor_AF2::setManualMoveCurrent(unsigned int value) { _eeprom->setIsManualControl(true); if (value > MP6500_PIN_I1_MOVE_MAX) value = MP6500_PIN_I1_MOVE_MAX; else if (value < MP6500_PIN_I1_MOVE_MIN) value = MP6500_PIN_I1_MOVE_MIN; _eeprom->setManualCoilsCurrentMove(value); _writeCoilsMode(); } int Motor_AF2::getManualHoldCurrentPercent() { return (int)((float)MP6500_PIN_I1_HOLD_MAX - (float)_eeprom->getManualCoilsCurrentHold()) / (float)MP6500_PIN_I1_HOLD_RANGE * 100; } void Motor_AF2::setManualHoldCurrentPercent(float percent) { percent = percent / 100.0; _eeprom->setManualCoilsCurrentHold((unsigned short)MP6500_PIN_I1_HOLD_MAX - MP6500_PIN_I1_HOLD_RANGE * percent); _writeCoilsMode(); } void Motor_AF2::setManualHoldCurrent(unsigned int value) { _eeprom->setIsManualControl(true); if (value > MP6500_PIN_I1_HOLD_MAX) value = MP6500_PIN_I1_HOLD_MAX; else if (value < MP6500_PIN_I1_HOLD_MIN) value = MP6500_PIN_I1_HOLD_MIN; _eeprom->setManualCoilsCurrentHold(value); _writeCoilsMode(); }
31.669623
148
0.660505
DeepSkyDad
6bb0458ab4e21e879de84213c10e3435ea28d335
1,394
cc
C++
dyn/src/main.cc
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
14
2020-07-31T09:35:23.000Z
2021-11-15T11:18:35.000Z
dyn/src/main.cc
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
dyn/src/main.cc
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
#include <iostream> #include <getopt.h> #include "utils/fs.hh" #include "dyn/emu.hh" #include "dyn/unicorn-emu.hh" #include "fmt/format.h" #include <string> #include <optional> struct options { std::optional<std::string> coverage_file; std::string binary; bool help; bool singlestep; }; options parse_options(int argc, char **argv) { int opt = 0; options ret{}; while ((opt = getopt(argc, argv, "shc:")) != -1 && !ret.help) { if (opt == 'c') ret.coverage_file = optarg; else if (opt == 'h') ret.help = true; else if (opt == 's') ret.singlestep = true; else { fmt::print("option '{}' not recognized\n", (char)opt); ret.help = true; } } if (optind == argc) ret.help = true; else ret.binary = argv[optind]; return ret; } int main(int argc, char *argv[]) { auto opts = parse_options(argc, argv); if (opts.help) { fmt::print("{} [-c coverage_output] [-s] [-h] binary\n", argv[0]); return 1; } utils::mapped_file file(opts.binary); dyn::emu emu(file, dyn::emu_params(opts.singlestep)); std::ofstream coverage_file; if (opts.coverage_file) { coverage_file.open(*opts.coverage_file); emu.add_on_entry_callback([&](uint64_t pc, uint64_t end) { for (uint64_t i = pc; i <= end; i += 4) coverage_file << fmt::format("{:#x}\n", i); }); } emu.init(); emu.setup(); emu.run(); fmt::print("Exited: {}\n", emu.exit_code()); }
19.633803
64
0.621951
balayette
6bb2533d765f7526f977de70830165c431947c14
9,305
cpp
C++
core/fileManager.cpp
n3on/revisy
f69f778563776ae463505baf9835820704e72bd4
[ "MIT" ]
1
2020-02-18T22:59:20.000Z
2020-02-18T22:59:20.000Z
core/fileManager.cpp
n3on/revisy
f69f778563776ae463505baf9835820704e72bd4
[ "MIT" ]
null
null
null
core/fileManager.cpp
n3on/revisy
f69f778563776ae463505baf9835820704e72bd4
[ "MIT" ]
null
null
null
/*************************************************************************** * This file is part of the ReViSy project * Copyright (C) 2007 by Neon ***************************************************************************/ #include "fileManager.h" FileManager* FileManager::m_instance = NULL; FileManager::FileManager() { //this->m_fileModel.loadFile(); this->m_list = 0; this->m_initFolder = false; this->m_hdc = GetDC(Config->getHWND()); m_font = new OutFont(this->m_hdc); } FileManager::~FileManager() { ReleaseDC(Config->getHWND(),this->m_hdc); } FileManager* FileManager::getInstance() { if(FileManager::m_instance==NULL) FileManager::m_instance = new FileManager(); return FileManager::m_instance; } void FileManager::renderFiles() { //glPushMatrix(); //if(!this->m_list) //{ // this->m_list = glGenLists(1); // glNewList(this->m_list, GL_COMPILE); //glScalef(this->m_files[0].width,this->m_files[0].height,this->m_files[0].depth); //this->m_file.render(); //printf("pos: x = %f, y = %f, z = %f\n",camera->getPosition().x, camera->getPosition().y,camera->getPosition().z); for(int i=0; i<this->m_files.size(); i++) { //glPushMatrix(); //glRotatef(180.0f,0.0f,1.0f,0.0f); if(frustum->boxCheck(this->m_files[i].getPosition().x, this->m_files[i].getPosition().y, this->m_files[i].getPosition().z, this->m_files[i].width, this->m_files[i].height, this->m_files[i].depth)) { glPushMatrix(); /* printf("pos: x = %f, y = %f, z = %f\n",camera->getPosition().x, camera->getPosition().y,camera->getPosition().z); printf("render: i = %d, x1 = %f, y2 = %f, z3 = %f\n",i,this->m_files[i].getPosition().x, this->m_files[i].getPosition().y, this->m_files[i].getPosition().z);*/ //glPopMatrix(); //glPushMatrix(); this->m_files[i].render(); glColor3f(0.0f,1.0f,0.0f); this->m_font->setBody(this->m_files[i].width, this->m_files[i].height, this->m_files[i].depth); this->m_font->print(this->m_files[i].getPosition().x, this->m_files[i].getPosition().y+this->m_files[i].height+1, this->m_files[i].getPosition().z, this->m_files[i].getFileName()); /*if(((abs(camera->getPosition().x-this->m_files[i].getPosition().x))<=this->m_files[i].width) && ((abs(camera->getPosition().y-this->m_files[i].getPosition().y))<=this->m_files[i].height) && ((abs(camera->getPosition().z-this->m_files[i].getPosition().z))<=this->m_files[i].depth)) {*/ if(this->m_files[i].objectCollision(camera->getPosition())) { if(this->m_files[i].getFileType()==FILE_TYPE_DIR) { this->m_initFolder = false; //MessageBox(NULL,Config->getValue("StartPath"),"BeforePath",MB_OK); char *newPath; newPath = new char[1024]; //char *oldPath; //memset(newPath,0,sizeof(newPath)); //oldPath = new char[1024]; strncpy(newPath, Config->getValue("StartPath"),strlen(Config->getValue("StartPath"))); newPath[strlen(Config->getValue("StartPath"))-1] = '\0'; //MessageBox(NULL,newPath,"NewPath",MB_OK); sprintf(newPath,"%s%s\\*",newPath,this->m_files[i].getFileName()); //Config->makeEntry("StartPath",newPath); Config->makeEntry("StartPath",newPath); //MessageBox(NULL,Config->getValue("StartPath"),"StartPath",MB_OK); camera->SetCamera(0, 0, 0, 1, 0, -1); this->m_files.clear(); } else { if(GetKeyState('W') & 0x80) camera->Move(DIR_DOWN, fps->getSpeedFactor(60)); if(GetKeyState('S') & 0x80) camera->Move(DIR_UP, fps->getSpeedFactor(60)); if(GetKeyState('D') & 0x80) camera->RotateY(DIR_LEFT, fps->getSpeedFactor(60)); if(GetKeyState('A') & 0x80) camera->RotateY(DIR_RIGHT, fps->getSpeedFactor(60)); } } // printf("pos: x = %f, y = %f, z = %f\n",camera->getPosition().x, camera->getPosition().y,camera->getPosition().z); glPopMatrix(); } else { //this->m_files[i].moveObject(this->m_files[i].getPosition().x, // this->m_files[i].getPosition().y+30.0f, // this->m_files[i].getPosition().z); /*glPushMatrix(); glColor3f(1.0f,0.0f,0.0f); this->m_files[i].render(); glPopMatrix();*/ } } //glPopMatrix(); // glEndList(); //} //else // glCallList(this->m_list); } bool FileManager::isInitialized() { return this->m_initFolder; } void FileManager::GetFilesInFolder(const char *path) { //File fileModel; WIN32_FIND_DATA fileData; //glPushMatrix(); //if(!this->m_list) //{ // glPushMatrix(); // this->m_list = glGenLists(1); // glNewList(this->m_list, GL_COMPILE); this->m_fileHandle = FindFirstFile(path, &fileData); //fileModel.setPosition(0.0f,0.0f,0.0f); //glTranslatef(0.0f,0.0f,0.0f); float x = 160.0f; float y = 130.0f; float z = -100.0f; float posX = 0; float posY = 0; float posZ = 0; int numRowX = 0; int numRowZ = 0; do { File fileModel; fileModel.setFileName(fileData.cFileName); switch(fileData.dwFileAttributes) { case FILE_ATTRIBUTE_SYSTEM: case FILE_ATTRIBUTE_READONLY: case FILE_ATTRIBUTE_ARCHIVE: case FILE_ATTRIBUTE_NORMAL: case FILE_ATTRIBUTE_COMPRESSED: case FILE_ATTRIBUTE_TEMPORARY: case FILE_ATTRIBUTE_SPARSE_FILE: case FILE_ATTRIBUTE_REPARSE_POINT: case FILE_ATTRIBUTE_OFFLINE: case FILE_ATTRIBUTE_HIDDEN: case FILE_ATTRIBUTE_ENCRYPTED: case FILE_ATTRIBUTE_DIRECTORY: { fileModel.width = 8; fileModel.height = 16; fileModel.depth = 8; fileModel.setFileType(FILE_TYPE_DIR); }break; default: { fileModel.width = 16; fileModel.height = 16; fileModel.depth = 16; fileModel.setFileType(FILE_TYPE_NON); }break; } //if (!(((m_fileData.cFileName[0]=='.') && (m_fileData.cFileName[1]=='.')||(m_fileData.cFileName[1]==0)))) //{ if(numRowX<10) { /* if(numRowZ>=10) { this->m_file.moveObject(0.0f,20.0f,0.0f); //glTranslatef(0.0f,100.0f,0.0f); z = -z; numRowZ = 0; } else*/ posX += x; fileModel.moveObject(posX,posY,posZ); //glTranslatef(x,0.0f,0.0f); } else { //glTranslatef(0.0f,0.0f,z); //x = -10*x; numRowZ++; numRowX = 0; //z = 20.0f; posX = x; posZ += z; fileModel.moveObject(posX,posY,posZ); } if(numRowZ>=10) { numRowZ = 0; posZ = z; posY += y; } //MessageBox(NULL,"File Found","Info",MB_OK); //glTranslatef(x,0.0f,z); //this->renderFiles(); //i+=0.5; numRowX++; //this->m_file.moveObject(x,0.0f,0.0f); //this->m_file.moveObject(200.0f,0.0f,0.0f); this->m_files.push_back(fileModel); //this->renderFiles(); //} }while(FindNextFile(this->m_fileHandle,&fileData)); //i=0.0f; // glPopMatrix(); FindClose(this->m_fileHandle); //glEndList(); //} //else // glCallList(this->m_list); this->m_initFolder = true; }
32.309028
138
0.450188
n3on
6bb89fe1087399aa9b253295809e2906d107c237
4,558
cpp
C++
src/appleseed/renderer/modeling/project/regexrenderlayerrule.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
1
2021-04-02T10:51:57.000Z
2021-04-02T10:51:57.000Z
src/appleseed/renderer/modeling/project/regexrenderlayerrule.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
null
null
null
src/appleseed/renderer/modeling/project/regexrenderlayerrule.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "regexrenderlayerrule.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/modeling/project/renderlayerrule.h" #include "renderer/utility/messagecontext.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/utility/api/apistring.h" #include "foundation/utility/api/specializedapiarrays.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/filter/regexfilter.h" // Standard headers. #include <string> using namespace foundation; using namespace std; namespace renderer { namespace { // // Render layer rule based on regular expressions. // const char* Model = "regex"; class RegExRenderLayerRule : public RenderLayerRule { public: RegExRenderLayerRule( const char* name, const ParamArray& params) : RenderLayerRule(name, params) { const EntityDefMessageContext context("render layer rule", this); const string pattern = params.get_required<string>("pattern", "", context); m_filter.set_pattern(pattern.c_str()); if (!m_filter.is_valid()) RENDERER_LOG_ERROR("%s: invalid regular expression pattern: %s", context.get(), pattern.c_str()); } virtual void release() APPLESEED_OVERRIDE { delete this; } virtual const char* get_model() const APPLESEED_OVERRIDE { return Model; } virtual bool applies(const Entity& entity) const APPLESEED_OVERRIDE { return m_filter.is_valid() ? m_filter.accepts(entity.get_path().c_str()) : false; } private: RegExFilter m_filter; }; } // // RegExRenderLayerRuleFactory class implementation. // const char* RegExRenderLayerRuleFactory::get_model() const { return Model; } Dictionary RegExRenderLayerRuleFactory::get_model_metadata() const { return Dictionary() .insert("name", Model) .insert("label", "Regular Expression") .insert("default_model", "true"); } DictionaryArray RegExRenderLayerRuleFactory::get_input_metadata() const { DictionaryArray metadata = RenderLayerRuleFactory::get_input_metadata(); metadata.push_back( Dictionary() .insert("name", "pattern") .insert("label", "Pattern") .insert("type", "text") .insert("use", "required")); return metadata; } auto_release_ptr<RenderLayerRule> RegExRenderLayerRuleFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<RenderLayerRule>( new RegExRenderLayerRule(name, params)); } auto_release_ptr<RenderLayerRule> RegExRenderLayerRuleFactory::static_create( const char* name, const ParamArray& params) { return auto_release_ptr<RenderLayerRule>( new RegExRenderLayerRule(name, params)); } } // namespace renderer
29.217949
113
0.679026
istemi-bahceci
6bb8d53f360caca99c16992039093cd54edb784f
7,103
cpp
C++
object_analytics_nodelet/src/segmenter/organized_multi_plane_segmenter.cpp
Zippen-Huang/ros_object_analytics
eb0208edbb6da67e5d5c4092fd2964a2c8d9838e
[ "Apache-2.0" ]
186
2017-11-30T14:08:54.000Z
2022-02-24T19:17:20.000Z
object_analytics_nodelet/src/segmenter/organized_multi_plane_segmenter.cpp
Zippen-Huang/ros_object_analytics
eb0208edbb6da67e5d5c4092fd2964a2c8d9838e
[ "Apache-2.0" ]
38
2017-12-06T12:03:22.000Z
2021-10-18T13:38:10.000Z
object_analytics_nodelet/src/segmenter/organized_multi_plane_segmenter.cpp
Zippen-Huang/ros_object_analytics
eb0208edbb6da67e5d5c4092fd2964a2c8d9838e
[ "Apache-2.0" ]
58
2017-11-30T07:37:35.000Z
2022-02-04T20:45:59.000Z
/* * Copyright (c) 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> #include <pcl/common/time.h> #include <pcl/filters/impl/conditional_removal.hpp> #include <pcl/filters/impl/filter.hpp> #include <pcl/search/impl/organized.hpp> #include <pcl/segmentation/impl/organized_connected_component_segmentation.hpp> #include "object_analytics_nodelet/const.h" #include "object_analytics_nodelet/segmenter/organized_multi_plane_segmenter.h" namespace object_analytics_nodelet { namespace segmenter { using pcl::Label; using pcl::Normal; using pcl::PointCloud; using pcl::PointIndices; using pcl::PlanarRegion; OrganizedMultiPlaneSegmenter::OrganizedMultiPlaneSegmenter(ros::NodeHandle& nh) : plane_comparator_(new pcl::PlaneCoefficientComparator<PointT, Normal>) , euclidean_comparator_(new pcl::EuclideanPlaneCoefficientComparator<PointT, Normal>) , rgb_comparator_(new pcl::RGBPlaneCoefficientComparator<PointT, Normal>) , edge_aware_comparator_(new pcl::EdgeAwarePlaneComparator<PointT, Normal>) , euclidean_cluster_comparator_(new pcl::EuclideanClusterComparator<PointT, Normal, Label>) , conf_(nh, "OrganizedMultiPlaneSegmenter") { } void OrganizedMultiPlaneSegmenter::segment(const PointCloudT::ConstPtr& cloud, PointCloudT::Ptr& cloud_segment, std::vector<PointIndices>& cluster_indices) { double start = pcl::getTime(); ROS_DEBUG_STREAM("Total original point size = " << cloud->size()); pcl::copyPointCloud(*cloud, *cloud_segment); // cloud_segment is same as cloud for this algorithm applyConfig(); PointCloud<Normal>::Ptr normal_cloud(new PointCloud<Normal>); estimateNormal(cloud, normal_cloud); std::vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>> regions; PointCloud<Label>::Ptr labels(new PointCloud<Label>); std::vector<PointIndices> label_indices; segmentPlanes(cloud, normal_cloud, regions, labels, label_indices); segmentObjects(cloud, regions, labels, label_indices, cluster_indices); double end = pcl::getTime(); ROS_DEBUG_STREAM("Segmentation : " << double(end - start)); } void OrganizedMultiPlaneSegmenter::estimateNormal(const PointCloudT::ConstPtr& cloud, PointCloud<Normal>::Ptr& normal_cloud) { double start = pcl::getTime(); normal_estimation_.setInputCloud(cloud); normal_estimation_.compute(*normal_cloud); float* distance_map = normal_estimation_.getDistanceMap(); boost::shared_ptr<pcl::EdgeAwarePlaneComparator<PointT, Normal>> eapc = boost::dynamic_pointer_cast<pcl::EdgeAwarePlaneComparator<PointT, Normal>>(edge_aware_comparator_); eapc->setDistanceMap(distance_map); eapc->setDistanceThreshold(0.01f, false); double end = pcl::getTime(); ROS_DEBUG_STREAM("Calc normal : " << double(end - start)); } void OrganizedMultiPlaneSegmenter::segmentPlanes( const PointCloudT::ConstPtr& cloud, const pcl::PointCloud<Normal>::Ptr& normal_cloud, std::vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>>& regions, pcl::PointCloud<Label>::Ptr labels, std::vector<PointIndices>& label_indices) { double start = pcl::getTime(); std::vector<pcl::ModelCoefficients> model_coefficients; std::vector<PointIndices> inlier_indices; std::vector<PointIndices> boundary_indices; plane_segmentation_.setInputNormals(normal_cloud); plane_segmentation_.setInputCloud(cloud); plane_segmentation_.segmentAndRefine(regions, model_coefficients, inlier_indices, labels, label_indices, boundary_indices); double end = pcl::getTime(); ROS_DEBUG_STREAM("Plane detection : " << double(end - start)); } void OrganizedMultiPlaneSegmenter::segmentObjects( const PointCloudT::ConstPtr& cloud, std::vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>>& regions, PointCloud<Label>::Ptr labels, std::vector<PointIndices>& label_indices, std::vector<PointIndices>& cluster_indices) { double start = pcl::getTime(); std::vector<bool> plane_labels; plane_labels.resize(label_indices.size(), false); for (size_t i = 0; i < label_indices.size(); i++) { if (label_indices[i].indices.size() > plane_minimum_points_) { plane_labels[i] = true; } } euclidean_cluster_comparator_->setInputCloud(cloud); euclidean_cluster_comparator_->setLabels(labels); euclidean_cluster_comparator_->setExcludeLabels(plane_labels); PointCloud<Label> euclidean_labels; pcl::OrganizedConnectedComponentSegmentation<PointT, Label> euclidean_segmentation(euclidean_cluster_comparator_); euclidean_segmentation.setInputCloud(cloud); euclidean_segmentation.segment(euclidean_labels, cluster_indices); auto func = [this](PointIndices indices) { return indices.indices.size() < this->object_minimum_points_; }; cluster_indices.erase(std::remove_if(cluster_indices.begin(), cluster_indices.end(), func), cluster_indices.end()); double end = pcl::getTime(); ROS_DEBUG_STREAM("Cluster : " << double(end - start)); } void OrganizedMultiPlaneSegmenter::applyConfig() { OrganizedMultiPlaneSegmentationConfig conf = conf_.getConfig(); plane_minimum_points_ = static_cast<size_t>(conf.plane_minimum_points); object_minimum_points_ = static_cast<size_t>(conf.object_minimum_points); normal_estimation_.setNormalEstimationMethod(normal_estimation_.SIMPLE_3D_GRADIENT); normal_estimation_.setNormalEstimationMethod(normal_estimation_.COVARIANCE_MATRIX); normal_estimation_.setMaxDepthChangeFactor(conf.normal_max_depth_change); normal_estimation_.setNormalSmoothingSize(conf.normal_smooth_size); euclidean_cluster_comparator_->setDistanceThreshold(conf.euclidean_distance_threshold, false); plane_segmentation_.setMinInliers(conf.min_plane_inliers); plane_segmentation_.setAngularThreshold(pcl::deg2rad(conf.normal_angle_threshold)); plane_segmentation_.setDistanceThreshold(conf.normal_distance_threshold); if (conf.comparator == kPlaneCoefficientComparator) { plane_segmentation_.setComparator(plane_comparator_); } else if (conf.comparator == kEuclideanPlaneCoefficientComparator) { plane_segmentation_.setComparator(euclidean_comparator_); } else if (conf.comparator == kRGBPlaneCoefficientComparator) { plane_segmentation_.setComparator(rgb_comparator_); } else if (conf.comparator == kEdgeAwarePlaneComaprator) { plane_segmentation_.setComparator(edge_aware_comparator_); } } } // namespace segmenter } // namespace object_analytics_nodelet
40.129944
120
0.770801
Zippen-Huang
6bba5c3ae4bcc603f36e8c0bdceaec11b201d83d
1,231
cpp
C++
src/controllerNode.cpp
amrish1222/intelli_bot
8bfa25296d942c9b79a828788a19ff8f0d0dac34
[ "MIT" ]
null
null
null
src/controllerNode.cpp
amrish1222/intelli_bot
8bfa25296d942c9b79a828788a19ff8f0d0dac34
[ "MIT" ]
null
null
null
src/controllerNode.cpp
amrish1222/intelli_bot
8bfa25296d942c9b79a828788a19ff8f0d0dac34
[ "MIT" ]
1
2018-12-05T01:07:40.000Z
2018-12-05T01:07:40.000Z
#include "ros/ros.h" #include "std_msgs/String.h" #include "geometry_msgs/Twist.h" #include "nav_msgs/Odometry.h" #include "../include/Control.h" #include "std_msgs/Empty.h" #include <sstream> int main(int argc, char **argv) { ros::init(argc, argv, "intelli_bot"); ros::NodeHandle n; Control _control; _control.setPathPts(); ros::Subscriber sub = n.subscribe("/ground_truth/state", 1000, &Control::navMessageReceived, &_control); ros::Publisher takeOff_msg = n.advertise<std_msgs::Empty>("/ardrone/takeoff", 1, true); std_msgs::Empty emptyMsg; takeOff_msg.publish(emptyMsg); ros::Publisher vel_pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1); ros::Rate loop_rate(10); int count = 0; while (ros::ok()) { geometry_msgs::Twist new_vel; // get Twist msg from control class algorithm new_vel = _control.getVelocityPose(); ROS_INFO_STREAM( "vel_pub = " << new_vel.linear.x << "," << new_vel.linear.y << ","<< new_vel.linear.z); // Publish the computed velocity vel_pub.publish(new_vel); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; }
23.226415
95
0.618197
amrish1222
6bbad17aeb39418aa1dac2e26916013680bd97dd
9,527
cpp
C++
src/textfile.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
null
null
null
src/textfile.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
2
2016-11-25T19:52:09.000Z
2017-04-15T14:49:52.000Z
src/textfile.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
null
null
null
// Copyright (c) 2013 Alexandre Grigorovitch (alexezh@gmail.com). // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "stdafx.h" #include "traceapp.h" #include "textfile.h" #include "log.h" /////////////////////////////////////////////////////////////////////////////// // CTextTraceFile::CTextTraceFile() { LineInfoDesc::Reset(m_Desc); SYSTEM_INFO si; GetSystemInfo(&si); m_PageSize = si.dwPageSize; } CTextTraceFile::~CTextTraceFile() { } void WINAPI CTextTraceFile::LoadThreadInit(void * pCtx) { CTextTraceFile * pFile = (CTextTraceFile*) pCtx; pFile->LoadThread(); } HRESULT CTextTraceFile::Open(LPCWSTR pszFile, CTraceFileLoadCallback * pCallback, bool bReverse) { HRESULT hr = S_OK; LOG("@%p open $S", this, pszFile); m_pCallback = pCallback; m_bReverse = bReverse; m_hFile = CreateFile(pszFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL); if (m_hFile == INVALID_HANDLE_VALUE) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Cleanup; } if (!GetFileSizeEx(m_hFile, &m_FileSize)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Cleanup; } Cleanup: return hr; } HRESULT CTextTraceFile::Close() { if (m_hFile != INVALID_HANDLE_VALUE) { CloseHandle(m_hFile); } return S_OK; } void CTextTraceFile::Load(uint64_t nStop) { if (m_bLoading) { return; } if (m_bReverse) { ATLASSERT(false); } else { if (nStop > m_FileSize.QuadPart) { nStop = (QWORD) m_FileSize.QuadPart; } if (m_nStop > nStop) { return; } } m_nStop = nStop; m_bLoading = true; QueueUserWorkItem((LPTHREAD_START_ROUTINE) LoadThreadInit, this, 0); } /////////////////////////////////////////////////////////////////////////////// // void CTextTraceFile::LoadThread() { HRESULT hr = S_OK; DWORD cbRead; DWORD cbToRead; LARGE_INTEGER liPos; m_pCallback->OnLoadBegin(); for (;; ) { LoadBlock * pNew = nullptr; if (m_bReverse) { ATLASSERT(false); } else { DWORD cbRollover = 0; if (m_Blocks.size() > 0) { LoadBlock * pEnd = m_Blocks.back(); if (pEnd->nFileStop > m_nStop) { break; } // copy end of line from previous buffer // we have to copy page aligned block and record the start of next data assert(pEnd->cbBuf >= pEnd->cbLastFullLineEnd); cbRollover = pEnd->cbBuf - pEnd->cbLastFullLineEnd; DWORD cbRolloverRounded = (cbRollover + m_PageSize - 1) & (~(m_PageSize - 1)); IFC(AllocBlock(cbRolloverRounded + m_BlockSize, &pNew)); pNew->cbFirstFullLineStart = cbRolloverRounded - cbRollover; memcpy(pNew->pbBuf + pNew->cbFirstFullLineStart, pEnd->pbBuf + pEnd->cbLastFullLineEnd, cbRollover); // at this point we can decommit unnecessary pages for unicode // this will waste address space but keep memory usage low // nFileStart is in file offset // cbLastFullLineEnd is in buffer pNew->nFileStart = pEnd->nFileStop; pNew->cbWriteStart = cbRolloverRounded; // if we are in unicode mode, trim previous block if (m_bUnicode) TrimBlock(pEnd); } else { IFC(AllocBlock(m_BlockSize, &pNew)); // we are going forward so start pos is null pNew->cbWriteStart = 0; } pNew->nFileStop = pNew->nFileStart + m_BlockSize; // we actually have data in the buffer, so set cbData pNew->cbData = cbRollover; } liPos.QuadPart = (__int64) pNew->nFileStart; SetFilePointerEx(m_hFile, liPos, NULL, FILE_BEGIN); cbToRead = m_BlockSize; if (m_bReverse) { ATLASSERT(false); } else { // append data after rollover string if (!ReadFile(m_hFile, pNew->pbBuf + pNew->cbWriteStart, cbToRead, &cbRead, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Cleanup; } } pNew->cbData = cbRead + pNew->cbData; // parse data IFC(ParseBlock(pNew, pNew->cbFirstFullLineStart, pNew->cbData, &pNew->cbDataEnd, &pNew->cbLastFullLineEnd)); { LockGuard guard(m_Lock); // append block m_Blocks.push_back(pNew); } m_pCallback->OnLoadBlock(); if (cbRead != m_BlockSize) { break; } } Cleanup: m_pCallback->OnLoadEnd(hr); } HRESULT CTextTraceFile::AllocBlock(DWORD cbSize, LoadBlock ** ppBlock) { LoadBlock * b = new LoadBlock; b->cbBuf = cbSize; b->pbBuf = (BYTE*) VirtualAlloc(NULL, cbSize, MEM_COMMIT, PAGE_READWRITE); if (b->pbBuf == NULL) { return HRESULT_FROM_WIN32(GetLastError()); } m_cbTotalAlloc += cbSize; *ppBlock = b; return S_OK; } void CTextTraceFile::TrimBlock(LoadBlock* pBlock) { if (pBlock->isTrimmed) return; // unmap unnecessary space DWORD cbUsedAligned = ((pBlock->cbDataEnd) / m_PageSize + 1) * m_PageSize; if (cbUsedAligned < pBlock->cbBuf) { VirtualFree(pBlock->pbBuf + cbUsedAligned, pBlock->cbBuf - cbUsedAligned, MEM_DECOMMIT); m_cbTotalAlloc -= (pBlock->cbBuf - cbUsedAligned); } pBlock->isTrimmed = true; } HRESULT CTextTraceFile::ParseBlock(LoadBlock * pBlock, DWORD nStart, DWORD nStop, DWORD * pnStop, DWORD * pnLineEnd) { HRESULT hr = S_OK; char * pszCur; char * pszEnd; char * pszLine = NULL; WORD crcn = 0; BOOL fSkipSpace = FALSE; DWORD nVal = 0; LockGuard guard(m_Lock); // test unicode file pszCur = (char*) (pBlock->pbBuf + nStart); pszEnd = (char*) (pBlock->pbBuf + nStop); if (pBlock->nFileStart == 0 && pBlock->cbData > 2) { if (pBlock->pbBuf[0] == 0xff && pBlock->pbBuf[1] == 0xfe) { LOG("@%p unicode mode"); m_bUnicode = true; pszCur += 2; } } if (m_bUnicode) { wchar_t c; wchar_t* pszCurW = reinterpret_cast<wchar_t*>(pszCur); wchar_t* pszEndW = reinterpret_cast<wchar_t*>(pszEnd); wchar_t* pszLineW = reinterpret_cast<wchar_t*>(pszCur); for (; pszCurW < pszEndW; pszCurW++) { c = *pszCurW; crcn <<= 8; crcn |= (char) c; if (crcn == 0x0d0a) { // for now just drop first bytes char* pszLine = pszCur; for (wchar_t* p = pszLineW; p <= pszCurW; p++, pszCur++) { *pszCur = (char) *p; } // pszCur points after pszCurW so we do not need +1 m_Lines.Add(LineInfo(CStringRef(pszLine, pszCur - pszLine), m_Lines.GetSize())); pszLineW = pszCurW + 1; } } (*pnStop) = ((BYTE*) pszCur - pBlock->pbBuf); (*pnLineEnd) = (pszLineW) ? ((BYTE*) pszLineW - pBlock->pbBuf) : ((BYTE*) pszEndW - pBlock->pbBuf); } else { pszLine = pszCur; char c; for (; pszCur < pszEnd; pszCur++) { c = *pszCur; crcn <<= 8; crcn |= c; if (crcn == 0x0d0a) { m_Lines.Add(LineInfo(CStringRef(pszLine, pszCur - pszLine + 1), m_Lines.GetSize())); pszLine = pszCur + 1; } } (*pnStop) = nStop; (*pnLineEnd) = (pszLine) ? ((BYTE*) pszLine - pBlock->pbBuf) : ((BYTE*) pszEnd - pBlock->pbBuf); } // we are parsing under lock; it is safe to adjust the size m_LineParsed.Resize(m_Lines.GetSize()); //Cleanup: return hr; } /////////////////////////////////////////////////////////////////////////////// // const LineInfo& CTextTraceFile::GetLine(DWORD nIndex) { LockGuard guard(m_Lock); if (nIndex >= m_Lines.GetSize()) { static LineInfo line; return line; } LineInfo& line = m_Lines.GetAt(nIndex); if (!m_LineParsed.GetBit(nIndex)) { m_LineParsed.SetBit(nIndex); if (m_Parser == nullptr || !m_Parser->ParseLine(line.Content.psz, line.Content.cch, line)) { // just set msg as content line.Msg = line.Content; } } return line; } bool CTextTraceFile::SetTraceFormat(const char * pszFormat, const char* pszSep) { LockGuard guard(m_Lock); LineInfoDesc::Reset(m_Desc); m_Parser.reset(new TraceLineParser()); try { std::vector<char> sep; if (pszSep == nullptr) { sep.push_back('\t'); } else { sep.assign(pszSep, pszSep + strlen(pszSep)); } m_Parser->SetFormat(pszFormat, 0, sep); } catch (std::invalid_argument&) { return false; } // check what we captured for (auto it = m_Parser->GetFields().begin(); it != m_Parser->GetFields().end(); ++it) { if (*it == TraceLineParser::FieldId::ThreadId) { m_Desc.Tid = true; } else if (*it == TraceLineParser::FieldId::Time) { m_Desc.Time = true; } else if (*it == TraceLineParser::FieldId::User1) { m_Desc.SetUser(0); } else if (*it == TraceLineParser::FieldId::User2) { m_Desc.SetUser(1); } else if (*it == TraceLineParser::FieldId::User3) { m_Desc.SetUser(2); } else if (*it == TraceLineParser::FieldId::User4) { m_Desc.SetUser(3); } } // reset all parsed bits m_LineParsed.Fill(false); return true; }
21.554299
116
0.651622
alexezh
6bbb18d6f4cb21042af6175e1c7804f23212f82c
11,366
cpp
C++
private/tst/debugFascadeTest/src/SmartXDebugFacadeTest.cpp
juimonen/SmartXbar
033f521a5dba5bce5e097df9c98af5b2cc2636dd
[ "BSD-3-Clause" ]
5
2018-11-05T07:37:58.000Z
2022-03-04T06:40:09.000Z
private/tst/debugFascadeTest/src/SmartXDebugFacadeTest.cpp
juimonen/SmartXbar
033f521a5dba5bce5e097df9c98af5b2cc2636dd
[ "BSD-3-Clause" ]
null
null
null
private/tst/debugFascadeTest/src/SmartXDebugFacadeTest.cpp
juimonen/SmartXbar
033f521a5dba5bce5e097df9c98af5b2cc2636dd
[ "BSD-3-Clause" ]
7
2018-12-04T07:32:19.000Z
2021-02-17T11:28:28.000Z
/* * Copyright (C) 2018 Intel Corporation.All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /* * @file SmartXDebugFascadeTest.cpp * @date 2017 * @brief */ #include <functional> #include <gtest/gtest.h> #include <dlt/dlt.h> #include "boost/filesystem.hpp" #include "audio/configparser/IasSmartXDebugFacade.hpp" #include "audio/configparser/IasSmartXconfigParser.hpp" #include "audio/smartx/IasProperties.hpp" #include "rtprocessingfwx/IasPluginEngine.hpp" #include "rtprocessingfwx/IasCmdDispatcher.hpp" #include "SmartXDebugFacadeTest.hpp" #include "rtprocessingfwx/IasAudioChain.hpp" #include "rtprocessingfwx/IasGenericAudioCompConfig.hpp" #include "gtest/gtest.h" #include <sndfile.h> #include <string.h> #include <iostream> #include "audio/testfwx/IasTestFramework.hpp" #include "audio/testfwx/IasTestFrameworkSetup.hpp" #include "audio/smartx/IasProperties.hpp" #include "audio/smartx/IasIProcessing.hpp" #include "audio/smartx/IasIDebug.hpp" #include "model/IasAudioPin.hpp" #include "volume/IasVolumeLoudnessCore.hpp" #include "audio/volumex/IasVolumeCmd.hpp" #include "mixer/IasMixerCore.hpp" #include "audio/mixerx/IasMixerCmd.hpp" #include "audio/smartx/IasSetupHelper.hpp" #include <libxml/encoding.h> #include <libxml/xmlwriter.h> #include <libxml/parser.h> using namespace std; using namespace IasAudio; namespace fs = boost::filesystem; static const Ias::String validXmlFilesPath = "/nfs/ka/disks/ias_organisation_disk001/teams/audio/TestXmlFiles/2017-12-01/valid/"; static const auto PARSER_SUCCESS = true; namespace IasAudio { std::vector<Ias::String> SmartXDebugFacadeTest::getValidXmlFiles() { return validXmlFiles; } std::vector<Ias::String> SmartXDebugFacadeTest::getFileList(const std::string& path) { std::vector<Ias::String> files; if (!path.empty()) { fs::path apk_path(path); fs::recursive_directory_iterator end; for (fs::recursive_directory_iterator i(apk_path); i != end; ++i) { const fs::path cp = (*i); files.emplace_back(cp.string()); } } return files; } void SmartXDebugFacadeTest::SetUp() { setenv("AUDIO_PLUGIN_DIR", "../../..", true); validXmlFiles = getFileList(validXmlFilesPath); } void SmartXDebugFacadeTest::TearDown() { } SmartXDebugFacadeTest::WrapperSmartX::WrapperSmartX() { mSmartx = IasAudio::IasSmartX::create(); if (mSmartx == nullptr) { EXPECT_TRUE(false) << "Create smartx error\n"; } if (mSmartx->isAtLeast(SMARTX_API_MAJOR, SMARTX_API_MINOR, SMARTX_API_PATCH) == false) { std::cerr << "SmartX API version does not match" << std::endl; IasAudio::IasSmartX::destroy(mSmartx); EXPECT_TRUE(false); } } IasSmartX* SmartXDebugFacadeTest::WrapperSmartX::getSmartX() { return mSmartx; } SmartXDebugFacadeTest::WrapperSmartX::~WrapperSmartX() { const IasSmartX::IasResult smres = mSmartx->stop(); EXPECT_EQ(IasSmartX::eIasOk, smres); IasSmartX::destroy(mSmartx); mSmartx = nullptr; } TEST_F(SmartXDebugFacadeTest, ValidTopologyXmlAllocationFails) { for(int i = 0; i < 4; i++) { const char* file = "/nfs/ka/disks/ias_organisation_disk001/teams/audio/TestXmlFiles/2017-12-01/valid/pipeline_sxb_topology_06.xml"; WrapperSmartX wrapperSmartX{}; auto smartx = wrapperSmartX.getSmartX(); EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file; EXPECT_NE(wrapperSmartX.getSmartX(), nullptr); IasSmartXDebugFacade debugFascade {smartx}; Ias::String topology; const auto result = debugFascade.getSmartxTopology(topology); EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasFailed, result); } } TEST_F(SmartXDebugFacadeTest, ValidTopology) { for(const auto& file : getValidXmlFiles()) { WrapperSmartX wrapperSmartX{}; auto smartx = wrapperSmartX.getSmartX(); EXPECT_EQ(parseConfig(smartx, file.c_str()), PARSER_SUCCESS) << "File : " << file; EXPECT_NE(wrapperSmartX.getSmartX(), nullptr); IasSmartXDebugFacade debugFascade {smartx}; Ias::String topology; const auto result = debugFascade.getSmartxTopology(topology); EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasOk, result); EXPECT_NE("",topology); } } TEST_F(SmartXDebugFacadeTest, getVersion) { WrapperSmartX wrapperSmartX{}; auto smartx = wrapperSmartX.getSmartX(); auto file = getValidXmlFiles()[0].c_str(); EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file; EXPECT_NE(wrapperSmartX.getSmartX(), nullptr); IasSmartXDebugFacade debugFascade {smartx}; const auto result = debugFascade.getVersion(); EXPECT_NE("", result); } TEST_F(SmartXDebugFacadeTest, setParameterFailed) { WrapperSmartX wrapperSmartX{}; auto smartx = wrapperSmartX.getSmartX(); auto file = getValidXmlFiles()[0].c_str(); EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file; EXPECT_NE(wrapperSmartX.getSmartX(), nullptr); IasSmartXDebugFacade debugFascade {smartx}; IasProperties properties; const auto result = debugFascade.setParameters("invalid", properties); EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasFailed, result); } TEST_F(SmartXDebugFacadeTest, getParameterFailed) { WrapperSmartX wrapperSmartX{}; auto smartx = wrapperSmartX.getSmartX(); auto file = getValidXmlFiles()[0].c_str(); EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file; EXPECT_NE(wrapperSmartX.getSmartX(), nullptr); IasSmartXDebugFacade debugFascade {smartx}; IasProperties properties; const auto result = debugFascade.getParameters("invalid", properties); EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasFailed, result); } TEST_F(SmartXDebugFacadeTest, setParameterOk) { WrapperSmartX wrapperSmartX{}; auto smartx = wrapperSmartX.getSmartX(); EXPECT_NE(wrapperSmartX.getSmartX(), nullptr); auto setup = smartx->setup(); IasSmartXDebugFacade debugFascade {smartx}; IasRoutingZonePtr rzn = nullptr; // create sink device IasAudioDeviceParams sinkParam; sinkParam.clockType = IasAudio::eIasClockProvided; sinkParam.dataFormat = IasAudio::eIasFormatInt16; sinkParam.name = "mono"; sinkParam.numChannels = 1; sinkParam.numPeriods = 4; sinkParam.periodSize = 192; sinkParam.samplerate = 48000; IasAudioSinkDevicePtr monoSink; auto setupRes = IasSetupHelper::createAudioSinkDevice(setup, sinkParam, 0, &monoSink,&rzn); EXPECT_EQ(setupRes, IasISetup::eIasOk) << "Error creating " << sinkParam.name << ": " << toString(setupRes) << "\n"; // Create the pipeline IasPipelineParams pipelineParams; pipelineParams.name ="ExamplePipeline"; pipelineParams.samplerate = sinkParam.samplerate; pipelineParams.periodSize = sinkParam.periodSize; IasPipelinePtr pipeline = nullptr; IasISetup::IasResult res = setup->createPipeline(pipelineParams, &pipeline); EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating example pipeline (please review DLT output for details)\n"; // create pin IasAudioPinPtr pipelineInputMonoPin = nullptr; IasAudioPinPtr monoPin = nullptr; IasAudioPinParams pipelineInputMonoParams; pipelineInputMonoParams.name = "pipeInputMono"; pipelineInputMonoParams.numChannels = 1; res = setup->createAudioPin(pipelineInputMonoParams, &pipelineInputMonoPin); EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating pipeline input mono pin\n"; /// create volume module IasProcessingModuleParams volumeModuleParams; volumeModuleParams.typeName = "ias.volume"; volumeModuleParams.instanceName = "VolumeLoudness"; IasProcessingModulePtr volume = nullptr; IasAudioPinPtr volumeMonoPin = nullptr; IasAudioPinParams volumeMonoPinParams; volumeMonoPinParams.name = "Volume_InOutMonoPin"; volumeMonoPinParams.numChannels = 1; res = setup->createProcessingModule(volumeModuleParams, &volume); EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating volume module\n"; //// create volume loundness IasProperties volumeProperties; volumeProperties.set<Ias::Int32>("numFilterBands",1); IasStringVector activePins; activePins.push_back("Volume_InOutMonoPin"); volumeProperties.set("activePinsForBand.0", activePins); Ias::Int32 tempVol = 0; Ias::Int32 tempGain = 0; IasInt32Vector ldGains; IasInt32Vector ldVolumes; for(Ias::UInt32 i=0; i< 8; i++) { ldVolumes.push_back(tempVol); ldGains.push_back(tempGain); tempVol-= 60; tempGain+= 30; } volumeProperties.set("ld.volumes.0", ldVolumes); volumeProperties.set("ld.gains.0", ldGains); volumeProperties.set("ld.volumes.1", ldVolumes); volumeProperties.set("ld.gains.1", ldGains); volumeProperties.set("ld.volumes.2", ldVolumes); volumeProperties.set("ld.gains.2", ldGains); IasInt32Vector freqOrderType; IasFloat32Vector gainQual; freqOrderType.resize(3); gainQual.resize(2); freqOrderType[0] = 100; freqOrderType[1] = 2; freqOrderType[2] = eIasFilterTypeLowShelving; gainQual[0] = 1.0f; // gain gainQual[1] = 2.0f; // quality volumeProperties.set("ld.freq_order_type.0", freqOrderType); volumeProperties.set("ld.gain_quality.0", gainQual); freqOrderType[0] = 8000; freqOrderType[1] = 2; freqOrderType[2] = eIasFilterTypeHighShelving; gainQual[0] = 1.0f; // gain gainQual[1] = 2.0f; // quality volumeProperties.set("ld.freq_order_type.1", freqOrderType); volumeProperties.set("ld.gain_quality.1", gainQual); setup->setProperties(volume,volumeProperties); res = setup->addProcessingModule(pipeline,volume); EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding volume module to pipeline\n"; res = setup->createAudioPin(volumeMonoPinParams,&volumeMonoPin); EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating volume mono pin\n"; res = setup->addAudioInOutPin(volume, volumeMonoPin); EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding volume mono pin\n"; res = setup->addAudioInputPin(pipeline,pipelineInputMonoPin); EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding pipeline input mono pin\n"; res = setup->link(pipelineInputMonoPin, volumeMonoPin, eIasAudioPinLinkTypeImmediate); EXPECT_EQ(res, IasISetup::eIasOk) << "Error linking pipe input to mono volume mono input\n"; res = setup->initPipelineAudioChain(pipeline); EXPECT_EQ(res, IasISetup::eIasOk) << "Error init pipeline chain - Please check DLT output for additional info\n"; res = setup->addPipeline(rzn, pipeline); EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding pipeline to zone\n"; IasProperties volCmdProperties; volCmdProperties.set("cmd",static_cast<Ias::Int32>(IasAudio::IasVolume::eIasSetVolume)); volCmdProperties.set<Ias::String>("pin","Volume_InOutMonoPin"); volCmdProperties.set("volume",0); IasAudio::IasInt32Vector ramp; ramp.push_back(100); ramp.push_back(0); volCmdProperties.set("ramp",ramp); Ias::Int32 minVol = 2; Ias::Int32 maxVol = 10; volCmdProperties.set<Ias::Int32>("cmd", 201); volCmdProperties.set("MinVol", minVol); volCmdProperties.set("MaxVol", maxVol); IasProperties returnProps; auto result = debugFascade.setParameters("VolumeLoudness", volCmdProperties); EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasOk, result); IasProperties cmdReturnProperties; cmdReturnProperties.set<Ias::Int32>("cmd", 200); result = debugFascade.getParameters("VolumeLoudness", cmdReturnProperties); EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasOk, result); } } /* namespace IasAudio */
32.381766
135
0.747668
juimonen
6bbe9daba875ff05d39bdab9508820e0a4c12542
9,837
cpp
C++
Modules/Core/test/mitkPropertyPersistenceTest.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Modules/Core/test/mitkPropertyPersistenceTest.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Modules/Core/test/mitkPropertyPersistenceTest.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPropertyPersistence.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include "mitkStringProperty.h" #include "mitkIOMimeTypes.h" #include <mitkNumericConstants.h> #include <mitkEqual.h> #include <algorithm> #include <limits> class mitkPropertyPersistenceTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPropertyPersistenceTestSuite); MITK_TEST(AddInfo); MITK_TEST(GetInfos); MITK_TEST(GetInfo); MITK_TEST(GetInfosByKey); MITK_TEST(HasInfos); MITK_TEST(RemoveAllInfos); MITK_TEST(RemoveInfos); MITK_TEST(RemoveInfos_withMime); CPPUNIT_TEST_SUITE_END(); private: mitk::PropertyPersistenceInfo::Pointer info1; mitk::PropertyPersistenceInfo::Pointer info2; mitk::PropertyPersistenceInfo::Pointer info3; mitk::PropertyPersistenceInfo::Pointer info4; mitk::PropertyPersistenceInfo::Pointer info5; mitk::PropertyPersistenceInfo::Pointer info6; std::string prop1; std::string prop2; std::string prop3; std::string prop4; std::string prop5; std::string prop6; mitk::IPropertyPersistence* service; static bool checkExistance(const mitk::PropertyPersistence::InfoMapType& infos, const std::string& name, const mitk::PropertyPersistenceInfo* info) { auto infoRange = infos.equal_range(name); auto predicate = [info](const std::pair<const std::string, mitk::PropertyPersistenceInfo::Pointer>& x){return infosAreEqual(info, x.second); }; auto finding = std::find_if(infoRange.first, infoRange.second, predicate); bool result = finding != infoRange.second; return result; } static bool infosAreEqual(const mitk::PropertyPersistenceInfo* ref, const mitk::PropertyPersistenceInfo* info) { bool result = true; if (!info || !ref) { return false; } result = result && ref->GetKey() == info->GetKey(); result = result && ref->GetMimeTypeName() == info->GetMimeTypeName(); return result; } public: void setUp() override { service = mitk::CreateTestInstancePropertyPersistence(); info1 = mitk::PropertyPersistenceInfo::New("key1"); info2 = mitk::PropertyPersistenceInfo::New("key2", "mime2"); info3 = mitk::PropertyPersistenceInfo::New("key3", "mime3"); info4 = mitk::PropertyPersistenceInfo::New("key2", "mime2"); info5 = mitk::PropertyPersistenceInfo::New("key5", "mime5"); prop1 = "prop1"; prop2 = "prop1"; prop3 = "prop1"; prop4 = "prop4"; prop5 = "prop5"; service->AddInfo(prop1, info1, false); service->AddInfo(prop2, info2, false); service->AddInfo(prop3, info3, false); service->AddInfo(prop4, info4, false); service->AddInfo(prop5, info5, false); } void tearDown() override { delete service; } void AddInfo() { mitk::PropertyPersistenceInfo::Pointer info2_new = mitk::PropertyPersistenceInfo::New("newKey", "otherMime"); mitk::PropertyPersistenceInfo::Pointer info2_otherKey = mitk::PropertyPersistenceInfo::New("otherKey", "mime2"); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding", !service->AddInfo(prop2, info2_otherKey, false)); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding -> key should not be changed.", service->GetInfo(prop2, "mime2", false)->GetKey() == "key2"); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (overwrite) -> adding", service->AddInfo(prop2, info2_otherKey, true)); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> adding -> key should be changed.", service->GetInfo(prop2, "mime2", false)->GetKey() == "otherKey"); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding", service->AddInfo(prop2, info2_new, false)); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding -> info exists.", service->GetInfo(prop2, "otherMime", false).IsNotNull()); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding", service->AddInfo("newProp", info2_new, false)); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding ->info exists.", service->GetInfo("newProp", "otherMime", false).IsNotNull()); } void GetInfos() { mitk::PropertyPersistence::InfoMapType infos = service->GetInfos(prop1); CPPUNIT_ASSERT(infos.size() == 3); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop1, info1)); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop2, info2)); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop3, info3)); infos = service->GetInfos(prop4); CPPUNIT_ASSERT(infos.size() == 1); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop4, info4)); infos = service->GetInfos("unkown"); CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown prop.", infos.empty()); } void GetInfosByKey() { mitk::PropertyPersistence::InfoMapType infos = service->GetInfosByKey("key2"); CPPUNIT_ASSERT(infos.size() == 2); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop2, info2)); CPPUNIT_ASSERT_MESSAGE("Check expected element 2.", checkExistance(infos, prop4, info4)); infos = service->GetInfosByKey("key5"); CPPUNIT_ASSERT(infos.size() == 1); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop5, info5)); infos = service->GetInfosByKey("unkownkey"); CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown key.", infos.empty()); } void GetInfo() { mitk::PropertyPersistenceInfo::Pointer foundInfo = service->GetInfo(prop1, "mime2", false); CPPUNIT_ASSERT_MESSAGE("Check GetInfo (existing element, no wildcard allowed, wildcard exists).", infosAreEqual(info2, foundInfo)); foundInfo = service->GetInfo(prop1, "mime2", true); CPPUNIT_ASSERT_MESSAGE("Check GetInfo (existing element, wildcard allowed, wildcard exists).", infosAreEqual(info2, foundInfo)); foundInfo = service->GetInfo(prop1, "unknownmime", false); CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, no wildcard allowed, wildcard exists).", foundInfo.IsNull()); foundInfo = service->GetInfo(prop1, "unknownmime", true); CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, wildcard allowed, wildcard exists).", infosAreEqual(info1, foundInfo)); foundInfo = service->GetInfo(prop4, "unknownmime", false); CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, no wildcard allowed).", foundInfo.IsNull()); foundInfo = service->GetInfo(prop4, "unknownmime", true); CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, wildcard allowed).", foundInfo.IsNull()); } void HasInfos() { CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", service->HasInfos(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfos(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (unkown prop)", !service->HasInfos("unkownProp")); } void RemoveAllInfos() { CPPUNIT_ASSERT_NO_THROW(service->RemoveAllInfos()); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfos(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfos(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfos(prop5)); } void RemoveInfos() { CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfos(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfos(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfos(prop5)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfos(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfos(prop5)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop5)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfos(prop5)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos("unknown_prop")); } void RemoveInfos_withMime() { CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop1, "mime2")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos if info was removed",service->GetInfo(prop1, "mime2", false).IsNull()); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of same property name still exists", service->GetInfo(prop1, "mime3", false).IsNotNull()); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of other property name but same mime still exists", service->GetInfo(prop4, "mime2", false).IsNotNull()); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop5, "wrongMime")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5 with wrong mime", service->HasInfos(prop5)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop5, "mime5")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5", !service->HasInfos(prop5)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos("unkown_prop", "mime2")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if unkown property name but exting mime was used", service->HasInfos(prop4)); } }; MITK_TEST_SUITE_REGISTRATION(mitkPropertyPersistence)
41.506329
190
0.723391
samsmu
6bbf6df0693d77d43c19578f830f171975dfd6d4
17,009
cpp
C++
settingsHelper/SettingsHelperLib/Payload.cpp
stegru/windows
6e113cb192fe8360a697657d0221c8b4e771e506
[ "BSD-3-Clause" ]
12
2015-06-03T18:30:06.000Z
2021-12-07T12:22:25.000Z
settingsHelper/SettingsHelperLib/Payload.cpp
GPII/windows
d5a5a66059c308729ca6f8099e06819f77fdddb9
[ "BSD-3-Clause" ]
271
2015-01-28T13:24:59.000Z
2020-11-23T13:46:43.000Z
settingsHelper/SettingsHelperLib/Payload.cpp
stegru/windows
6e113cb192fe8360a697657d0221c8b4e771e506
[ "BSD-3-Clause" ]
31
2015-04-16T20:09:12.000Z
2022-01-19T14:29:05.000Z
/** * Datatypes representing payload and functions. * * Copyright 2019 Raising the Floor - US * * Licensed under the New BSD license. You may not use this file except in * compliance with this License. * * You may obtain a copy of the License at * https://github.com/GPII/universal/blob/master/LICENSE.txt */ #include "stdafx.h" #include "Payload.h" #include "IPropertyValueUtils.h" #include <windows.foundation.h> #include <windows.foundation.collections.h> #include <windows.data.json.h> #include <atlbase.h> #include <utility> #include <iostream> using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Foundation::Collections; using namespace ABI::Windows::Data::Json; using std::pair; #pragma comment (lib, "WindowsApp.lib") // ----------------------------------------------------------------------------- // Parameter // ----------------------------------------------------------------------------- // --------------------------- Public --------------------------------------- Parameter::Parameter() {} Parameter::Parameter(pair<wstring, ATL::CComPtr<IPropertyValue>> _objIdVal) : oIdVal(_objIdVal), isObject(true), isEmpty(false) {} Parameter::Parameter(ATL::CComPtr<IPropertyValue> _iPropVal) : iPropVal(_iPropVal), isObject(false), isEmpty(false) {} // ----------------------------------------------------------------------------- // Action // ----------------------------------------------------------------------------- /// <summary> /// Check that the members with which an action is going to be constructed are /// valid. /// </summary> /// <param name="method">The method for the action.</param> /// <param name="params">The parameters for the action</param> /// <returns> /// ERROR_SUCCESS in case of success or E_INVALIDARG in case of invalid /// action members. /// </returns> HRESULT checkActionMembers(wstring method, vector<Parameter> params) { if (method != L"GetValue" && method != L"SetValue") { return E_INVALIDARG; } HRESULT errCode { ERROR_SUCCESS }; if (params.size() > 1) { for (const auto& param : params) { bool validParam = param.isEmpty == false && param.isObject == true && param.oIdVal.first.empty() == false; if (validParam == false) { errCode = E_INVALIDARG; break; } } } return errCode; } /// <summary> /// Helper function to create an action that ensure that it doens't contradict /// the expected payload format. /// </summary> /// <param name="sId">The action target setting id.</param> /// <param name="sMethod">The action target method.</param> /// <param name="params">The action parameters</param> /// <param name="rAction">A reference to the action to be filled.</param> /// <returns> /// ERROR_SUCCESS in case of success or E_INVALIDARG in case of parameters /// not passing format checking. /// </returns> HRESULT createAction(wstring sId, wstring sMethod, vector<Parameter> params, Action& rAction) { HRESULT errCode { checkActionMembers(sMethod, params) }; if (errCode == ERROR_SUCCESS) { rAction = Action { sId, sMethod, params }; } return errCode; } // ----------------------------------------------------------------------------- // Parsing & Serialization Functions // ----------------------------------------------------------------------------- // --------------------------- Parsing -------------------------------------- enum class OpType { Get, Set }; HRESULT getValueParam(ATL::CComPtr<IJsonValue> jValue, ATL::CComPtr<IPropertyValue>& jPropVal) { HRESULT res = ERROR_SUCCESS; ATL::CComPtr<IPropertyValueStatics> pValueFactory; HSTRING rTimeClass = NULL; JsonValueType jElemValueType = JsonValueType::JsonValueType_Null; res = WindowsCreateString( RuntimeClass_Windows_Foundation_PropertyValue, static_cast<UINT32>(wcslen(RuntimeClass_Windows_Foundation_PropertyValue)), &rTimeClass ); if (res != ERROR_SUCCESS) goto cleanup; res = GetActivationFactory(rTimeClass, &pValueFactory); if (res != ERROR_SUCCESS) goto cleanup; res = jValue->get_ValueType(&jElemValueType); if (res != ERROR_SUCCESS) goto cleanup; if (jElemValueType == JsonValueType::JsonValueType_Boolean) { boolean elemValue; ATL::CComPtr<IPropertyValue> value; res = jValue->GetBoolean(&elemValue); if (res == ERROR_SUCCESS) { res = pValueFactory->CreateBoolean(elemValue, reinterpret_cast<IInspectable**>(&value)); if (res == ERROR_SUCCESS) { jPropVal = value; } } } else if (jElemValueType == JsonValueType::JsonValueType_String) { HSTRING elemValue; ATL::CComPtr<IPropertyValue> value; res = jValue->GetString(&elemValue); if (res == ERROR_SUCCESS) { UINT32 bufSize { 0 }; PCWSTR bufWSTR { WindowsGetStringRawBuffer(elemValue, &bufSize) }; wstring elemValueStr { bufWSTR, bufSize }; VARIANT vElemVal; vElemVal.vt = VARENUM::VT_BSTR; vElemVal.bstrVal = const_cast<BSTR>( elemValueStr.c_str() ); res = createPropertyValue(vElemVal, value); if (res == ERROR_SUCCESS) { jPropVal = value; } } } else if (jElemValueType == JsonValueType::JsonValueType_Number) { DOUBLE elemValue; ATL::CComPtr<IPropertyValue> value; res = jValue->GetNumber(&elemValue); if (res == ERROR_SUCCESS) { res = pValueFactory->CreateDouble(elemValue, reinterpret_cast<IInspectable**>(&value)); if (res == ERROR_SUCCESS) { jPropVal = value; } } } else { res = E_INVALIDARG; } cleanup: return res; } HRESULT getObjectParam(OpType opType, ATL::CComPtr<IJsonObject> jObject, Parameter& param) { HRESULT res = ERROR_SUCCESS; // Tags HSTRING hElemIdTag = NULL; PCWSTR pElemIdTag = L"elemId"; HSTRING hElemValTag = NULL; PCWSTR pElemValTag = L"elemVal"; // Values UINT32 hElemIdSize = 0; HSTRING hElemId = NULL; ATL::CComPtr<IJsonValue> jElemVal; ATL::CComPtr<IPropertyValue> pElemVal; res = WindowsCreateString(pElemIdTag, static_cast<UINT32>(wcslen(pElemIdTag)), &hElemIdTag); if (res != ERROR_SUCCESS) goto cleanup; res = WindowsCreateString(pElemValTag, static_cast<UINT32>(wcslen(pElemValTag)), &hElemValTag); if (res != ERROR_SUCCESS) goto cleanup; res = jObject->GetNamedString(hElemIdTag, &hElemId); if (res != ERROR_SUCCESS) goto cleanup; if (opType == OpType::Get) { VARIANT emptyVar; emptyVar.vt = VARENUM::VT_EMPTY; res = createPropertyValue(emptyVar, pElemVal); } else { res = jObject->GetNamedValue(hElemValTag, &jElemVal); if (res == ERROR_SUCCESS) { res = getValueParam(jElemVal, pElemVal); } } if (res == ERROR_SUCCESS) { param = Parameter { pair<wstring, ATL::CComPtr<IPropertyValue>> { wstring { WindowsGetStringRawBuffer(hElemId, &hElemIdSize) }, pElemVal } }; } cleanup: if (hElemIdTag != NULL) WindowsDeleteString(hElemIdTag); if (hElemValTag != NULL) WindowsDeleteString(hElemValTag); if (hElemId != NULL) WindowsDeleteString(hElemId); return res; } HRESULT getMatchingType(OpType type, const ATL::CComPtr<IJsonArray> arrayObj, const UINT32 index, Parameter& param) { HRESULT res = ERROR_SUCCESS; ATL::CComPtr<IVector<IJsonValue*>> jVectorValue; ATL::CComPtr<IJsonValue> jValue; JsonValueType jElemValueType = JsonValueType::JsonValueType_Null; boolean isValueType = false; res = arrayObj->QueryInterface(__uuidof(__FIVector_1_Windows__CData__CJson__CIJsonValue_t), reinterpret_cast<void**>(&jVectorValue)); if (res != ERROR_SUCCESS) goto cleanup; res = jVectorValue->GetAt(index, &jValue); if (res != ERROR_SUCCESS) goto cleanup; res = jValue->get_ValueType(&jElemValueType); if (res != ERROR_SUCCESS) goto cleanup; isValueType = jElemValueType == JsonValueType::JsonValueType_Boolean || jElemValueType == JsonValueType::JsonValueType_Number || jElemValueType == JsonValueType::JsonValueType_String; if (isValueType) { ATL::CComPtr<IPropertyValue> jPropVal; res = getValueParam(jValue, jPropVal); if (res == ERROR_SUCCESS) { param = Parameter{ jPropVal }; } } else if (jElemValueType == JsonValueType::JsonValueType_Object) { ATL::CComPtr<IJsonObject> jObjVal; res = jValue->GetObject(&jObjVal); if (res == ERROR_SUCCESS) { res = getObjectParam(type, jObjVal, param); } } else { res = E_INVALIDARG; } cleanup: return res; } HRESULT parseParameters(OpType type, const ATL::CComPtr<IJsonArray> arrayObj, vector<Parameter>& params) { if (arrayObj == NULL) { return E_INVALIDARG; }; HRESULT res = ERROR_SUCCESS; HRESULT nextElemErr = ERROR_SUCCESS; UINT32 jElemIndex = 0; vector<Parameter> _params {}; while (nextElemErr == ERROR_SUCCESS) { Parameter curParam {}; nextElemErr = getMatchingType(type, arrayObj, jElemIndex, curParam); if (curParam.isEmpty == false && nextElemErr == ERROR_SUCCESS) { _params.push_back(curParam); } else if (nextElemErr != E_BOUNDS) { res = nextElemErr; } jElemIndex++; } if (res == ERROR_SUCCESS) { params = _params; } return res; } HRESULT parseAction(const ATL::CComPtr<IJsonObject> elemObj, Action& action) { if (elemObj == NULL) { return E_INVALIDARG; } HRESULT errCode = ERROR_SUCCESS; UINT32 bufLength = 0; // Required fields vars // ======================================================================== HSTRING hSettingId = NULL; PCWSTR pSettingId = L"settingID"; PCWSTR pSettingRawBuf = NULL; HSTRING hMethod = NULL; PCWSTR pMethod = L"method"; PCWSTR pMethodRawBuf = NULL; HSTRING hSettingIdVal = NULL; HSTRING hMethodVal = NULL; wstring sSettingId {}; wstring sMethod {}; vector<Parameter> params {}; // Optional fields vars // ======================================================================== HRESULT getArrayErr = ERROR_SUCCESS; HSTRING hParams = NULL; PCWSTR pParams = L"parameters"; ATL::CComPtr<IJsonArray> jParamsArray = NULL; // Extract required fields // ======================================================================== errCode = WindowsCreateString(pSettingId, static_cast<UINT32>(wcslen(pSettingId)), &hSettingId); if (errCode != ERROR_SUCCESS) goto cleanup; errCode = WindowsCreateString(pMethod, static_cast<UINT32>(wcslen(pMethod)), &hMethod); if (errCode != ERROR_SUCCESS) goto cleanup; errCode = elemObj->GetNamedString(hSettingId, &hSettingIdVal); if (errCode != ERROR_SUCCESS) goto cleanup; errCode = elemObj->GetNamedString(hMethod, &hMethodVal); if (errCode != ERROR_SUCCESS) goto cleanup; pSettingRawBuf = WindowsGetStringRawBuffer(hSettingIdVal, &bufLength); pMethodRawBuf = WindowsGetStringRawBuffer(hMethodVal, &bufLength); if (pSettingRawBuf != NULL && pMethodRawBuf != NULL) { sSettingId = wstring(pSettingRawBuf); sMethod = wstring(pMethodRawBuf); } else { errCode = E_INVALIDARG; goto cleanup; } // Extract optional fields // ======================================================================== errCode = WindowsCreateString(pParams, static_cast<UINT32>(wcslen(pParams)), &hParams); if (errCode != ERROR_SUCCESS) goto cleanup; getArrayErr = elemObj->GetNamedArray(hParams, &jParamsArray); // Check that the payload ins't of type "SetValue" if "parameters" isn't present. if (getArrayErr != ERROR_SUCCESS) { if (sMethod == L"SetValue") { errCode = WEB_E_JSON_VALUE_NOT_FOUND; goto cleanup; } else if (sMethod == L"GetValue") { action = Action { sSettingId, sMethod, params }; } else { // TODO: Change with a more meaningful message errCode = E_INVALIDARG; } } else { if (sMethod == L"SetValue") { errCode = parseParameters(OpType::Set, jParamsArray, params); if (errCode == ERROR_SUCCESS) { Action _action {}; errCode = createAction(sSettingId, sMethod, params, _action); if (errCode == ERROR_SUCCESS) { action = _action; } } } else { errCode = parseParameters(OpType::Get, jParamsArray, params); if (errCode == ERROR_SUCCESS) { Action _action {}; errCode = createAction(sSettingId, sMethod, params, _action); if (errCode == ERROR_SUCCESS) { action = _action; } } } } cleanup: if (hSettingId != NULL) { WindowsDeleteString(hSettingId); } if (hMethod != NULL) { WindowsDeleteString(hMethod); } if (hSettingIdVal != NULL) { WindowsDeleteString(hSettingIdVal); } if (hMethodVal != NULL ) { WindowsDeleteString(hMethodVal); } if (hParams != NULL) { WindowsDeleteString(hParams); } return errCode; } HRESULT parsePayload(const wstring & payload, vector<pair<Action, HRESULT>>& actions) { HRESULT res = ERROR_SUCCESS; vector<pair<Action, HRESULT>> _actions {}; ATL::CComPtr<IJsonArrayStatics> jsonArrayFactory = NULL; HSTRING rJSONClass = NULL; res = WindowsCreateString( RuntimeClass_Windows_Data_Json_JsonArray, static_cast<UINT32>(wcslen(RuntimeClass_Windows_Data_Json_JsonArray)), &rJSONClass ); GetActivationFactory(rJSONClass, &jsonArrayFactory); HSTRING hPayload = NULL; WindowsCreateString(payload.c_str(), static_cast<UINT32>(payload.size()), &hPayload); ATL::CComPtr<IJsonArray> jActionsArray = NULL; HRESULT nextElemErr = ERROR_SUCCESS; UINT32 jElemIndex = 0; res = jsonArrayFactory->Parse(hPayload, &jActionsArray); if (res != ERROR_SUCCESS) goto cleanup; while (nextElemErr == ERROR_SUCCESS) { IJsonObject* curElem = NULL; nextElemErr = jActionsArray->GetObjectAt(jElemIndex, &curElem); if (curElem != NULL && nextElemErr == ERROR_SUCCESS) { Action curAction {}; ATL::CComPtr<IJsonObject> cCurElem { curElem }; HRESULT errCode = parseAction(cCurElem, curAction); if (errCode == ERROR_SUCCESS) { _actions.push_back({ curAction, ERROR_SUCCESS }); } else { _actions.push_back({ Action {}, errCode }); } }; jElemIndex++; } for (const auto& action : _actions) { if (action.second != ERROR_SUCCESS) { res = E_INVALIDARG; break; } } actions = _actions; cleanup: if (rJSONClass) { WindowsDeleteString(rJSONClass); } if (hPayload) { WindowsDeleteString(hPayload); } return res; } // ------------------------ Serialization ---------------------------------- HRESULT serializeResult(const Result& result, std::wstring& str) { std::wstring resultStr {}; HRESULT res = ERROR_SUCCESS; try { // JSON object start resultStr.append(L"{"); // SettingId resultStr.append(L"\"settingID\": "); if (result.settingID.empty()) { resultStr.append(L"null"); } else { resultStr.append(L"\"" + result.settingID + L"\""); } resultStr.append(L", "); // IsError resultStr.append(L"\"isError\": "); if (result.isError) { resultStr.append(L"true"); } else { resultStr.append(L"false"); } resultStr.append(L", "); // ErrorMessage resultStr.append(L"\"errorMessage\": "); if (result.errorMessage.empty()) { resultStr.append(L"null"); } else { resultStr.append(L"\"" + result.errorMessage + L"\""); } resultStr.append(L", "); // ReturnValue resultStr.append(L"\"returnValue\": "); if (result.returnValue.empty()) { resultStr.append(L"null"); } else { resultStr.append(result.returnValue); } // JSON object end resultStr.append(L"}"); // Communicate back the result str = resultStr; } catch(std::bad_alloc&) { res = E_OUTOFMEMORY; } return res; }
31.324125
137
0.587454
stegru
6bc0b00fdb774b8a05fe9c9b6a2f1b72447027f5
10,897
hpp
C++
parser/ParseCaseExpressions.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
parser/ParseCaseExpressions.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
parser/ParseCaseExpressions.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #ifndef QUICKSTEP_PARSER_PARSE_CASE_EXPRESSIONS_HPP_ #define QUICKSTEP_PARSER_PARSE_CASE_EXPRESSIONS_HPP_ #include <memory> #include <string> #include <vector> #include "parser/ParseExpression.hpp" #include "parser/ParsePredicate.hpp" #include "parser/ParseTreeNode.hpp" #include "utility/Macros.hpp" #include "utility/PtrVector.hpp" namespace quickstep { /** \addtogroup Parser * @{ */ /** * @brief The parsed representation of a WHEN clause in a simple CASE * expression (WHEN <condition operand> THEN <result expression>). */ class ParseSimpleWhenClause : public ParseTreeNode { public: /** * @brief Constructor. Takes ownership of all pointers. * * @param line_number The line number of "WHEN" in the SQL statement. * @param column_number The column number of "WHEN" in the SQL statement. * @param check_operand The condition operand to be compared with the * CASE operand (not in this class) of the CASE * expression. * @param result_expression The result expression for this condition. */ ParseSimpleWhenClause(int line_number, int column_number, ParseExpression *condition_operand, ParseExpression *result_expression) : ParseTreeNode(line_number, column_number), condition_operand_(condition_operand), result_expression_(result_expression) { } std::string getName() const override { return "SimpleWhenClause"; } /** * @return The condition operand. */ const ParseExpression* condition_operand() const { return condition_operand_.get(); } /** * @return The result expression for this condition. */ const ParseExpression* result_expression() const { return result_expression_.get(); } protected: void getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<const ParseTreeNode*> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override; private: std::unique_ptr<ParseExpression> condition_operand_; std::unique_ptr<ParseExpression> result_expression_; DISALLOW_COPY_AND_ASSIGN(ParseSimpleWhenClause); }; /** * @brief The parsed representation of a WHEN clause in a searched CASE * expression (WHEN <condition predicate> THEN <result expression>). * */ class ParseSearchedWhenClause : public ParseTreeNode { public: /** * @brief Constructor. Takes ownership of all pointers. * * @param line_number The line number of "WHEN" in the SQL statement. * @param column_number The column number of "WHEN" in the SQL statement. * @param condition_predicate The condition predicate. * @param result_expression The result expression for this condition. */ ParseSearchedWhenClause(int line_number, int column_number, ParsePredicate *condition_predicate, ParseExpression *result_expression) : ParseTreeNode(line_number, column_number), condition_predicate_(condition_predicate), result_expression_(result_expression) { } std::string getName() const override { return "SearchedWhenClause"; } /** * @return The condition predicate. */ const ParsePredicate* condition_predicate() const { return condition_predicate_.get(); } /** * @return The result expression. */ const ParseExpression* result_expression() const { return result_expression_.get(); } protected: void getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<const ParseTreeNode*> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override; private: std::unique_ptr<ParsePredicate> condition_predicate_; std::unique_ptr<ParseExpression> result_expression_; DISALLOW_COPY_AND_ASSIGN(ParseSearchedWhenClause); }; /** * @brief The parsed representation of a simple CASE expression: * CASE <case operand> * WHEN <condition_operand> THEN <result_expression> * [...n] * [ELSE <else_result_expression>] * END * It returns the <result_expression> of the first <case operand> = <when_operand> * that evaluates to true; if none is found and <else_result_expression> exists, * returns <else_result_expression>; otherwise, returns NULL. **/ class ParseSimpleCaseExpression : public ParseExpression { public: /** * @brief Constructor. Takes ownership of all pointers. * * @param line_number The line number of "CASE" in the SQL statement. * @param column_number The column number of "CASE" in the SQL statement. * @param case_operand The CASE operand. * @param when_clauses A vector of WHEN clauses, each having a check operand to * be compared with the CASE operand and a result expression * to be evaluated if the condition is satisfied. * @param else_result_expression Optional ELSE result expression. */ ParseSimpleCaseExpression(int line_number, int column_number, ParseExpression *case_operand, PtrVector<ParseSimpleWhenClause> *when_clauses, ParseExpression *else_result_expression) : ParseExpression(line_number, column_number), case_operand_(case_operand), when_clauses_(when_clauses), else_result_expression_(else_result_expression) { } std::string getName() const override { return "SimpleCaseExpression"; } ExpressionType getExpressionType() const override { return kSimpleCaseExpression; } /** * @return The CASE operand. */ const ParseExpression* case_operand() const { return case_operand_.get(); } /** * @return The vector of WHEN clauses. */ const PtrVector<ParseSimpleWhenClause>* when_clauses() const { return when_clauses_.get(); } /** * @return The ELSE result expression. Can be NULL. */ const ParseExpression* else_result_expression() const { return else_result_expression_.get(); } std::string generateName() const override; protected: void getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<const ParseTreeNode*> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override; private: std::unique_ptr<ParseExpression> case_operand_; std::unique_ptr<PtrVector<ParseSimpleWhenClause>> when_clauses_; std::unique_ptr<ParseExpression> else_result_expression_; DISALLOW_COPY_AND_ASSIGN(ParseSimpleCaseExpression); }; /** * @brief The parsed representation of a searched CASE expression: * CASE * WHEN <condition_predicate> THEN <result_expression> * [...n] * [ELSE <else_result_expression>] * END * It returns the <result_expression> of the first <condition_predicate> * that evaluates to true; if none is found and <else_result_expression> exists, * returns <else_result_expression>; otherwise, returns NULL. */ class ParseSearchedCaseExpression : public ParseExpression { public: /** * @brief Constructor. Takes ownership of all pointers. * * @param line_number The line number of "CASE" in the SQL statement. * @param column_number The column number of "CASE" in the SQL statement. * @param when_clauses A vector of WHEN clauses, each having a predicate * and a result expression to be evaluate if * the predicate evaluates to true. * @param else_result_expression Optional ELSE result expression. */ ParseSearchedCaseExpression(int line_number, int column_number, PtrVector<ParseSearchedWhenClause> *when_clauses, ParseExpression *else_result_expression) : ParseExpression(line_number, column_number), when_clauses_(when_clauses), else_result_expression_(else_result_expression) { } std::string getName() const override { return "SearchedCaseExpression"; } ExpressionType getExpressionType() const override { return kSearchedCaseExpression; } /** * @return The vector of WHEN clauses. */ const PtrVector<ParseSearchedWhenClause>* when_clauses() const { return when_clauses_.get(); } /** * @return The ELSE result expression. Can be NULL. */ const ParseExpression* else_result_expression() const { return else_result_expression_.get(); } std::string generateName() const override; protected: void getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<const ParseTreeNode*> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override; private: std::unique_ptr<PtrVector<ParseSearchedWhenClause>> when_clauses_; std::unique_ptr<ParseExpression> else_result_expression_; DISALLOW_COPY_AND_ASSIGN(ParseSearchedCaseExpression); }; /** @} */ } // namespace quickstep #endif /* QUICKSTEP_PARSER_PARSE_CASE_EXPRESSIONS_HPP_ */
34.484177
93
0.696706
Hacker0912
6bc210a3465b5cd4ef962cb2b8e18d8913cbf87a
6,724
cpp
C++
Coin3D/src/Inventor/Xt/devices/SoXtMouse.cpp
pniaz20/inventor-utils
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
[ "MIT" ]
null
null
null
Coin3D/src/Inventor/Xt/devices/SoXtMouse.cpp
pniaz20/inventor-utils
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
[ "MIT" ]
null
null
null
Coin3D/src/Inventor/Xt/devices/SoXtMouse.cpp
pniaz20/inventor-utils
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ // Class documentation in common code file. // ************************************************************************* #ifdef HAVE_CONFIG_H #include <config.h> #endif // HAVE_CONFIG_H #include <X11/X.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/events/SoLocation2Event.h> #include <Inventor/events/SoMouseButtonEvent.h> #include <Inventor/Xt/devices/SoXtMouse.h> #include <Inventor/Xt/devices/SoGuiMouseP.h> #include <soxtdefs.h> #define PRIVATE(p) (p->pimpl) #define PUBLIC(p) (p->pub) // ************************************************************************* class SoXtMouseP : public SoGuiMouseP { public: SoXtMouseP(SoXtMouse * p) : SoGuiMouseP(p) { } SoLocation2Event * makeLocationEvent(XMotionEvent * event); SoMouseButtonEvent * makeButtonEvent(XButtonEvent * event, SoButtonEvent::State state); }; // ************************************************************************* // Doc in common code file. SoXtMouse::SoXtMouse(int events) { PRIVATE(this) = new SoXtMouseP(this); PRIVATE(this)->eventmask = events; } // Doc in common code file. SoXtMouse::~SoXtMouse() { delete PRIVATE(this); } // ************************************************************************* // Doc in superclass. void SoXtMouse::enable(Widget widget, SoXtEventHandler * handler, void * closure) { // FIXME: should explicitly convert eventmask to bitmask with X11/Xt // bitflag values, just in case either our or X11's enum values // should ever change (yeah, I know, slim chance, but still.. that'd // be better design). 20020625 mortene. XtAddEventHandler(widget, PRIVATE(this)->eventmask, FALSE, handler, closure); } // Doc in superclass. void SoXtMouse::disable(Widget widget, SoXtEventHandler * handler, void * closure) { XtRemoveEventHandler(widget, PRIVATE(this)->eventmask, FALSE, handler, closure); } // ************************************************************************* // Doc in common code file. const SoEvent * SoXtMouse::translateEvent(XAnyEvent * event) { SoEvent * soevent = (SoEvent *) NULL; SoButtonEvent::State state = SoButtonEvent::UNKNOWN; switch (event->type) { // events we should catch: case ButtonPress: if (! (PRIVATE(this)->eventmask & SoXtMouse::BUTTON_PRESS)) break; state = SoButtonEvent::DOWN; soevent = PRIVATE(this)->makeButtonEvent((XButtonEvent *) event, state); break; case ButtonRelease: if (! (PRIVATE(this)->eventmask & SoXtMouse::BUTTON_RELEASE)) break; state = SoButtonEvent::UP; soevent = PRIVATE(this)->makeButtonEvent((XButtonEvent *) event, state); break; case MotionNotify: if (! (PRIVATE(this)->eventmask & SoXtMouse::POINTER_MOTION)) break; soevent = PRIVATE(this)->makeLocationEvent((XMotionEvent *) event); break; // FIXME: implement BUTTON_MOTION filtering. larsa. case EnterNotify: case LeaveNotify: // should we make location-events for these? do { SOXT_STUB(); } while (FALSE); break; // events we should ignore: default: break; } return (SoEvent *) soevent; } // ************************************************************************* #ifndef DOXYGEN_SKIP_THIS // This method translates from X motion events to Open Inventor // SoLocation2Event events. SoLocation2Event * SoXtMouseP::makeLocationEvent(XMotionEvent * event) { #if SOXT_DEBUG && 0 SoDebugError::postInfo("SoXtMouse::makeLocationEvent", "pointer at (%d, %d)", event->x, PUBLIC(this)->getWindowSize()[1] - event->y); #endif // 0 was SOXT_DEBUG delete this->locationevent; this->locationevent = new SoLocation2Event; PUBLIC(this)->setEventPosition(this->locationevent, event->x, event->y); this->locationevent->setShiftDown((event->state & ShiftMask) ? TRUE : FALSE); this->locationevent->setCtrlDown((event->state & ControlMask) ? TRUE : FALSE); this->locationevent->setAltDown((event->state & Mod1Mask) ? TRUE : FALSE); SbTime stamp; stamp.setMsecValue(event->time); this->locationevent->setTime(stamp); return this->locationevent; } // This method translates from X button events (mouse/pointer) to // Open Inventor SoMouseButtonEvent events. SoMouseButtonEvent * SoXtMouseP::makeButtonEvent(XButtonEvent * event, SoButtonEvent::State state) { #if 0 // SOXT_DEBUG SoDebugError::postInfo("SoXtMouse::makeButtonEvent", "button %d, state %d", event->button, (int) state); #endif // 0 was SOXT_DEBUG delete this->buttonevent; this->buttonevent = new SoMouseButtonEvent; this->buttonevent->setState(state); SoMouseButtonEvent::Button button = SoMouseButtonEvent::ANY; switch (event->button) { case 1: button = SoMouseButtonEvent::BUTTON1; break; case 3: button = SoMouseButtonEvent::BUTTON2; break; case 2: button = SoMouseButtonEvent::BUTTON3; break; #ifdef HAVE_SOMOUSEBUTTONEVENT_BUTTON5 case 4: button = SoMouseButtonEvent::BUTTON4; break; case 5: button = SoMouseButtonEvent::BUTTON5; break; #endif // HAVE_SOMOUSEBUTTONEVENT_BUTTON5 default: break; } this->buttonevent->setButton(button); PUBLIC(this)->setEventPosition(this->buttonevent, event->x, event->y); this->buttonevent->setShiftDown((event->state & ShiftMask) ? TRUE : FALSE); this->buttonevent->setCtrlDown((event->state & ControlMask) ? TRUE : FALSE); this->buttonevent->setAltDown((event->state & Mod1Mask) ? TRUE : FALSE); SbTime stamp; stamp.setMsecValue(event->time); this->buttonevent->setTime(stamp); return this->buttonevent; } #endif // DOXYGEN_SKIP_THIS // ************************************************************************* #undef PRIVATE #undef PUBLIC
31.716981
103
0.644259
pniaz20
6bc2e5171220162347f5c4700c7a2e61d36db9f1
3,161
hpp
C++
libvast/vast/arrow_table_slice.hpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/arrow_table_slice.hpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/arrow_table_slice.hpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include "vast/fwd.hpp" #include "vast/table_slice.hpp" #include "vast/view.hpp" #include <caf/fwd.hpp> #include <caf/intrusive_cow_ptr.hpp> #include <arrow/api.h> #include <memory> namespace vast { /// A table slice that stores elements encoded in the /// [Arrow](https://arrow.org) format. The implementation stores data in /// column-major order. class arrow_table_slice final : public vast::table_slice { public: // -- friends ---------------------------------------------------------------- friend arrow_table_slice_builder; // -- constants -------------------------------------------------------------- static constexpr caf::atom_value class_id = caf::atom("arrow"); // -- member types ----------------------------------------------------------- /// Base type. using super = vast::table_slice; /// Unsigned integer type. using size_type = super::size_type; /// Smart pointer to an Arrow record batch. using record_batch_ptr = std::shared_ptr<arrow::RecordBatch>; // -- constructors, destructors, and assignment operators -------------------- /// @pre `batch != nullptr` arrow_table_slice(vast::table_slice_header header, record_batch_ptr batch); // -- factories -------------------------------------------------------------- static vast::table_slice_ptr make(vast::table_slice_header header); // -- properties ------------------------------------------------------------- arrow_table_slice* copy() const override; caf::error serialize(caf::serializer& sink) const override; caf::error deserialize(caf::deserializer& source) override; void append_column_to_index(size_type col, value_index& idx) const override; caf::atom_value implementation_id() const noexcept override; vast::data_view at(size_type row, size_type col) const override; record_batch_ptr batch() const { return batch_; } private: using table_slice::table_slice; caf::error serialize_impl(caf::binary_serializer& sink) const; /// The Arrow table containing all elements. record_batch_ptr batch_; }; /// @relates arrow_table_slice using arrow_table_slice_ptr = caf::intrusive_cow_ptr<arrow_table_slice>; } // namespace vast
33.989247
80
0.53211
frerich
6bc422c93e0de3c9491a71ed7ac33d3810efeee0
2,022
cpp
C++
src/Example/project_WhiteBoxStudio/code/ModelTest/ObjectSerDef/_tagDirectoryInfoSetSoap_StructInfo.cpp
yds086/HereticOS-ObjectSystem
bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49
[ "Apache-2.0" ]
5
2017-09-07T06:58:34.000Z
2021-07-21T08:41:26.000Z
src/Example/project_WhiteBoxStudio/code/ModelTest/ObjectSerDef/_tagDirectoryInfoSetSoap_StructInfo.cpp
yds086/HereticOS-ObjectSystem
bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49
[ "Apache-2.0" ]
null
null
null
src/Example/project_WhiteBoxStudio/code/ModelTest/ObjectSerDef/_tagDirectoryInfoSetSoap_StructInfo.cpp
yds086/HereticOS-ObjectSystem
bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49
[ "Apache-2.0" ]
2
2017-09-27T06:31:11.000Z
2020-05-13T12:29:58.000Z
#include "stdafx.h" #include "CommonTypeDef.h" #include "_tagDirectoryInfoSetSoap_StructInfo.h" Serialize__tagDirectoryInfoSetSoap::_Myt& Serialize__tagDirectoryInfoSetSoap::operator=(_tagDirectoryInfoSetSoap & _X) { SetData(_X); return *this; } void Serialize__tagDirectoryInfoSetSoap::GetData() { m_Val.ObjectName=ObjectName; m_Val.ObjectType=ObjectType; m_Val.OtherInfo=OtherInfo; } BOOL Serialize__tagDirectoryInfoSetSoap::Construct(StorageObjectInterface * pOutObject) { ObjectName.init(this,_T("ObjectName"),0,pOutObject); ObjectType.init(this,_T("ObjectType"),0,pOutObject); OtherInfo.init(this,_T("OtherInfo"),0,pOutObject); return TRUE; } void Serialize__tagDirectoryInfoSetSoap::SetData(_tagDirectoryInfoSetSoap & _X) { ObjectName=_X.ObjectName; ObjectType=_X.ObjectType; OtherInfo=_X.OtherInfo; } BOOL Serialize__tagDirectoryInfoSetSoap::LoadGetCurSerializeObject(FieldAddr & CurFieldAddr, SerializeLoadSaveInterface * * RetObj) { *RetObj=0; if(tstring(CurFieldAddr.pFieldName)==tstring(_T("ObjectName"))) { *RetObj=&ObjectName; } else if(tstring(CurFieldAddr.pFieldName)==tstring(_T("ObjectType"))) { *RetObj=&ObjectType; } else if(tstring(CurFieldAddr.pFieldName)==tstring(_T("OtherInfo"))) { *RetObj=&OtherInfo; } if(*RetObj) return TRUE; return FALSE; } BOOL Serialize__tagDirectoryInfoSetSoap::Save(StorageObjectInterface * pStorageObject) { pStorageObject->PushNodeCtlBegin(_T("_tagDirectoryInfoSetSoap"),this); ObjectName.Save(pStorageObject); ObjectType.Save(pStorageObject); OtherInfo.Save(pStorageObject); pStorageObject->PushNodeCtlEnd(_T("_tagDirectoryInfoSetSoap"),this); return TRUE; } BOOL Serialize__tagDirectoryInfoSetSoap::GetObjectMap(IN OUT vector<SerializeObjectInterface *> & ObjectInterfaceMap) { ObjectInterfaceMap.push_back((SerializeObjectInterface *)&ObjectName); ObjectInterfaceMap.push_back((SerializeObjectInterface *)&ObjectType); ObjectInterfaceMap.push_back((SerializeObjectInterface *)&OtherInfo); return TRUE; }
27.324324
131
0.794263
yds086
6bc4970846db1d0b632b6bcc7c103ab94da08e19
5,003
cpp
C++
client/dll/offset.cpp
Nullptr-Archives/CSNS-SoftON-Hack
d68ee3c577181ef3b2910b413203aa9fc36e7c70
[ "MIT" ]
13
2021-03-14T11:34:29.000Z
2021-04-13T03:20:19.000Z
client/dll/offset.cpp
Nullptr-Archives/CSNS-SoftON-Hack
d68ee3c577181ef3b2910b413203aa9fc36e7c70
[ "MIT" ]
1
2021-03-26T17:03:50.000Z
2021-03-26T17:03:50.000Z
client/dll/offset.cpp
Nullptr-Archives/CSNS-SoftON-Hack
d68ee3c577181ef3b2910b413203aa9fc36e7c70
[ "MIT" ]
9
2021-03-14T11:35:19.000Z
2021-04-21T08:12:47.000Z
#include "offset.h" #include <unordered_map> #include "globals.h" #include "utils.h" // universal representation for game modules struct GameModule { DWORD start, end; GameModule() = default; // construct module with its start and end address GameModule(DWORD start_, DWORD end_) : start(start_), end(end_) {} // construct module with its name GameModule(const std::string& name) { auto get_module_size = [](DWORD address) -> DWORD { return PIMAGE_NT_HEADERS(address + (DWORD)PIMAGE_DOS_HEADER(address)->e_lfanew)->OptionalHeader.SizeOfImage; }; start = (DWORD)GetModuleHandleA(std::string(name + ".dll").c_str()); if (start == NULL) utils::TerminateGame("Module", name, "isn't loaded"); end = start + get_module_size(start) - 1; } }; // GameModules is a wrapper-class to make // work with game modules more comfortable. // to get module by name overloaded 'operator[]' is used. // that operator also constructs module if there is no module with given name class GameModules { public: const GameModule& operator [] (const std::string& name) { auto el = this->modules.find(name); if (el != this->modules.end()) return el->second; this->modules[name] = { name }; return this->modules[name]; } private: std::unordered_map<std::string, GameModule> modules; }; #define CompareMemory(Buff1, Buff2, Size) __comparemem((const UCHAR *)Buff1, (const UCHAR *)Buff2, (UINT)Size) #define FindMemoryClone(Module, Clone, Size) __findmemoryclone((const ULONG)Module.start, (const ULONG)Module.end, (const ULONG)Clone, (UINT)Size) #define FindReference(Module, Address) __findreference((const ULONG)Module.start, (const ULONG)Module.end, (const ULONG)Address) BOOL __comparemem(const UCHAR* buff1, const UCHAR* buff2, UINT size) { for (UINT i = 0; i < size; i++, buff1++, buff2++) { if ((*buff1 != *buff2) && (*buff2 != 0xFF)) return FALSE; } return TRUE; } ULONG __findmemoryclone(const ULONG start, const ULONG end, const ULONG clone, UINT size) { for (ULONG ul = start; (ul + size) < end; ul++) { if (CompareMemory(ul, clone, size)) return ul; } return NULL; } ULONG __findreference(const ULONG start, const ULONG end, const ULONG address) { UCHAR Pattern[5]; Pattern[0] = 0x68; *(ULONG*)& Pattern[1] = address; GameModule tmp = { static_cast<DWORD>(start), static_cast<DWORD>(end) }; return FindMemoryClone(tmp, Pattern, sizeof(Pattern) - 1); } DWORD FindPattern(PCHAR pattern, PCHAR mask, const GameModule & mod) { size_t patternLength = strlen(pattern); bool found = false; for (DWORD i = mod.start; i < mod.end - patternLength; i++) { found = true; for (size_t idx = 0; idx < patternLength; idx++) { if (mask[idx] == 'x' && pattern[idx] != *(PCHAR)(i + idx)) { found = false; break; } } if (found) return i; } return 0; } // offsets by: Eugene Golubev, Hardee, Jusic namespace offset { GameModules modules; DWORD ClientTable() { DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "ScreenFade", strlen("ScreenFade")); return *(DWORD*)(FindReference(modules["hw"], addr) + 0x13); } DWORD EngineTable() { DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "ScreenFade", strlen("ScreenFade")); return *(DWORD*)(FindReference(modules["hw"], addr) + 0x0D); } DWORD StudioTable() { return *(DWORD*)((DWORD)g::pClient->HUD_GetStudioModelInterface + 0x34); } DWORD StudioAPITable() { return *(DWORD*)((DWORD)g::pClient->HUD_GetStudioModelInterface + 0x3A); } DWORD UserMsgBase() { DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "UserMsg: Not Present on Client %d", strlen("UserMsg: Not Present on Client %d")); return *(DWORD*)* (DWORD*)(FindReference(modules["hw"], addr) - 0x14); } DWORD EventBase() { return *(DWORD*)(*(DWORD*)((DWORD)g::pEngine->HookEvent + 0x77)); } DWORD Speed() { DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "Texture load: %6.1fms", strlen("Texture load: %6.1fms")); DWORD ptr = *(DWORD*)(FindReference(modules["hw"], addr) - 0x09); DWORD old_prot; VirtualProtect((void*)ptr, sizeof(double), PAGE_READWRITE, &old_prot); return ptr; } DWORD ButtonsBase() { return *(DWORD*)(FindPattern((PCHAR)"\x0F\x44\xCA\x8B\xD1\x83\xCA\x20\x24\x03\x0F\x44\xD1\x83\x3D\x00\x00\x00\x00\x00\x74", (PCHAR)"xxxxxxxxxxxxxxx?????x", modules["client"]) - 0x04) - 0x08; } DWORD PlayerMove() { DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "ScreenFade", strlen("ScreenFade")); return *(DWORD*)(FindReference(modules["hw"], addr) + 0x24); } DWORD ClientState() { return *(DWORD*)((DWORD)g::pEngine->SetScreenFade + 0x26) - 0x44C; } DWORD ClientStatic() { DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "WARNING: Connection Problem", strlen("WARNING: Connection Problem")); return *(DWORD*)(FindReference(modules["hw"], addr) + 0xDE) - 0x08; } }
30.693252
147
0.658605
Nullptr-Archives
6bc59a6e13328a2f0907c60638b45d5eb1a2b01c
1,773
hpp
C++
genfile/include/genfile/SNPDataSinkChain.hpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
3
2021-04-21T05:42:24.000Z
2022-01-26T14:59:43.000Z
genfile/include/genfile/SNPDataSinkChain.hpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
2
2020-04-09T16:11:04.000Z
2020-11-10T11:18:56.000Z
genfile/include/genfile/SNPDataSinkChain.hpp
gavinband/qctool
8d8adb45151c91f953fe4a9af00498073b1132ba
[ "BSL-1.0" ]
null
null
null
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SNPDATAsinkCHAIN_HPP #define SNPDATAsinkCHAIN_HPP #include <iostream> #include <string> #include "genfile/snp_data_utils.hpp" #include "genfile/SNPDataSink.hpp" namespace genfile { // class SNPDataSinkChain represents a SNPDataSink // which outputs its data sequentially to a collection of other SNPDataSinks class SNPDataSinkChain: public SNPDataSink { public: SNPDataSinkChain() ; ~SNPDataSinkChain() ; void add_sink( SNPDataSink::UniquePtr sink ) ; operator bool() const ; void move_to_next_sink() ; std::size_t number_of_sinks() const ; SNPDataSink const& sink( std::size_t i ) const ; std::size_t index_of_current_sink() const ; std::string get_spec() const ; SinkPos get_stream_pos() const ; private: void set_metadata_impl( Metadata const& metadata ) ; void set_sample_names_impl( std::size_t number_of_samples, SampleNameGetter name_getter ) ; void write_snp_impl( uint32_t number_of_samples, std::string SNPID, std::string RSID, Chromosome chromosome, uint32_t SNP_position, std::string first_allele, std::string second_allele, GenotypeProbabilityGetter const& get_AA_probability, GenotypeProbabilityGetter const& get_AB_probability, GenotypeProbabilityGetter const& get_BB_probability, Info const& info ) ; void write_variant_data_impl( VariantIdentifyingData const& id_data, VariantDataReader& data_reader, Info const& info ) ; void finalise_impl() ; private: std::vector< SNPDataSink* > m_sinks ; std::size_t m_current_sink ; } ; } #endif
26.462687
93
0.744501
gavinband
6bc60dd1c75c0af46927f6ff45b986130514f09c
544
cpp
C++
trace_server/dock/dock.cpp
mojmir-svoboda/DbgToolkit
590887987d0856032be906068a3103b6ce31d21c
[ "MIT" ]
null
null
null
trace_server/dock/dock.cpp
mojmir-svoboda/DbgToolkit
590887987d0856032be906068a3103b6ce31d21c
[ "MIT" ]
null
null
null
trace_server/dock/dock.cpp
mojmir-svoboda/DbgToolkit
590887987d0856032be906068a3103b6ce31d21c
[ "MIT" ]
null
null
null
#include "dock.h" #include <QCloseEvent> #include <QMainWindow> #include "mainwindow.h" #include "dockwidget.h" #include <QApplication> DockedWidgetBase::DockedWidgetBase (MainWindow * mw, QStringList const & path) : ActionAble(path) , m_main_window(mw) , m_dockwidget(0) { qDebug("%s this=0x%08x", __FUNCTION__, this); } DockedWidgetBase::~DockedWidgetBase () { qDebug("%s this=0x%08x", __FUNCTION__, this); m_main_window->dockManager().removeActionAble(*this); m_dockwidget->setWidget(0); delete m_dockwidget; m_dockwidget = 0; }
21.76
78
0.738971
mojmir-svoboda
6bceede515f48fe461a8df7ab13cfb97ee20f3eb
1,743
cpp
C++
src/cckVec3.cpp
frmr/cck
0528157c6439057077547418c22e7977927c29f7
[ "MIT" ]
1
2015-10-02T17:00:18.000Z
2015-10-02T17:00:18.000Z
src/cckVec3.cpp
frmr/cck
0528157c6439057077547418c22e7977927c29f7
[ "MIT" ]
null
null
null
src/cckVec3.cpp
frmr/cck
0528157c6439057077547418c22e7977927c29f7
[ "MIT" ]
null
null
null
#include "cckVec3.h" #include "cckMath.h" #include <cmath> cck::GeoCoord cck::Vec3::ToGeographic() const { double lonRadians = atan2( y, x ); if ( lonRadians < -cck::pi ) { lonRadians += cck::twoPi; } else if ( lonRadians > cck::pi ) { lonRadians -= cck::twoPi; } return cck::GeoCoord( atan2( z, sqrt( x * x + y * y ) ), lonRadians ); } cck::Vec3 cck::Vec3::Unit() const { const double length = sqrt( x * x + y * y + z * z ); return cck::Vec3( x / length, y / length, z / length ); } cck::Vec3 cck::Vec3::operator+( const Vec3& rhs ) const { return cck::Vec3( x + rhs.x, y + rhs.y, z + rhs.z ); } cck::Vec3 cck::Vec3::operator-( const Vec3& rhs ) const { return cck::Vec3( x - rhs.x, y - rhs.y, z - rhs.z ); } cck::Vec3 cck::Vec3::operator*( const double& rhs ) const { return cck::Vec3( x * rhs, y * rhs, z * rhs ); } cck::Vec3 cck::Vec3::operator/( const double& rhs ) const { return cck::Vec3( x / rhs, y / rhs, z / rhs ); } cck::Vec3& cck::Vec3::operator+=( const Vec3& rhs ) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } cck::Vec3& cck::Vec3::operator-=( const Vec3& rhs ) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } cck::Vec3& cck::Vec3::operator*=( const double& rhs ) { x *= rhs; y *= rhs; z *= rhs; return *this; } cck::Vec3& cck::Vec3::operator/=( const double& rhs ) { x /= rhs; y /= rhs; z /= rhs; return *this; } cck::Vec3::Vec3() : x( 0.0 ), y( 0.0 ), z( 0.0 ) { } cck::Vec3::Vec3( const double x, const double y, const double z ) : x( x ), y( y ), z( z ) { }
19.58427
75
0.500287
frmr
6bcfbac38550d8b76a7e14d1c84c7987cff6c711
7,372
cpp
C++
src/planner/insert_plan.cpp
vittvolt/15721-peloton
3394c745ce5f3d71d1d71a09c700d5e367345e2e
[ "Apache-2.0" ]
7
2017-03-12T01:57:48.000Z
2022-03-16T12:44:07.000Z
src/planner/insert_plan.cpp
vittvolt/15721-peloton
3394c745ce5f3d71d1d71a09c700d5e367345e2e
[ "Apache-2.0" ]
null
null
null
src/planner/insert_plan.cpp
vittvolt/15721-peloton
3394c745ce5f3d71d1d71a09c700d5e367345e2e
[ "Apache-2.0" ]
2
2017-03-30T00:43:50.000Z
2021-07-21T06:27:44.000Z
//===----------------------------------------------------------------------===// // // PelotonDB // // insert_plan.cpp // // Identification: /peloton/src/planner/insert_plan.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "planner/insert_plan.h" #include "catalog/catalog.h" #include "catalog/column.h" #include "type/value.h" #include "parser/insert_statement.h" #include "parser/select_statement.h" #include "planner/project_info.h" #include "storage/data_table.h" #include "storage/tuple.h" namespace peloton { namespace planner { InsertPlan::InsertPlan(storage::DataTable *table, oid_t bulk_insert_count) : target_table_(table), bulk_insert_count(bulk_insert_count) {} // This constructor takes in a project info InsertPlan::InsertPlan( storage::DataTable *table, std::unique_ptr<const planner::ProjectInfo> &&project_info, oid_t bulk_insert_count) : target_table_(table), project_info_(std::move(project_info)), bulk_insert_count(bulk_insert_count) {} // This constructor takes in a tuple InsertPlan::InsertPlan(storage::DataTable *table, std::unique_ptr<storage::Tuple> &&tuple, oid_t bulk_insert_count) : target_table_(table), bulk_insert_count(bulk_insert_count) { tuples_.push_back(std::move(tuple)); LOG_TRACE("Creating an Insert Plan"); } InsertPlan::InsertPlan( storage::DataTable *table, std::vector<char *> *columns, std::vector<std::vector<peloton::expression::AbstractExpression *> *> * insert_values) : bulk_insert_count(insert_values->size()) { parameter_vector_.reset(new std::vector<std::tuple<oid_t, oid_t, oid_t>>()); params_value_type_.reset(new std::vector<type::Type::TypeId>); target_table_ = table; if (target_table_) { const catalog::Schema *table_schema = target_table_->GetSchema(); // INSERT INTO table_name VALUES (val2, val2, ...) if (columns == NULL) { for (uint32_t tuple_idx = 0; tuple_idx < insert_values->size(); tuple_idx++) { auto values = (*insert_values)[tuple_idx]; PL_ASSERT(values->size() == table_schema->GetColumnCount()); std::unique_ptr<storage::Tuple> tuple( new storage::Tuple(table_schema, true)); int col_cntr = 0; int param_index = 0; for (expression::AbstractExpression *elem : *values) { if (elem->GetExpressionType() == ExpressionType::VALUE_PARAMETER) { std::tuple<oid_t, oid_t, oid_t> pair = std::make_tuple(tuple_idx, col_cntr, param_index++); parameter_vector_->push_back(pair); params_value_type_->push_back( table_schema->GetColumn(col_cntr).GetType()); } else { expression::ConstantValueExpression *const_expr_elem = dynamic_cast<expression::ConstantValueExpression *>(elem); type::Value const_expr_elem_val = (const_expr_elem->GetValue()); switch (const_expr_elem->GetValueType()) { case type::Type::VARCHAR: case type::Type::VARBINARY: tuple->SetValue(col_cntr, const_expr_elem_val, GetPlanPool()); break; default: { tuple->SetValue(col_cntr, const_expr_elem_val, nullptr); } } } ++col_cntr; } tuples_.push_back(std::move(tuple)); } } // INSERT INTO table_name (col1, col2, ...) VALUES (val1, val2, ...); else { // columns has to be less than or equal that of schema for (uint32_t tuple_idx = 0; tuple_idx < insert_values->size(); tuple_idx++) { auto values = (*insert_values)[tuple_idx]; PL_ASSERT(columns->size() <= table_schema->GetColumnCount()); std::unique_ptr<storage::Tuple> tuple( new storage::Tuple(table_schema, true)); int col_cntr = 0; int param_index = 0; auto &table_columns = table_schema->GetColumns(); auto query_columns = columns; for (catalog::Column const &elem : table_columns) { std::size_t pos = std::find(query_columns->begin(), query_columns->end(), elem.GetName()) - query_columns->begin(); // If the column does not exist, insert a null value if (pos >= query_columns->size()) { tuple->SetValue(col_cntr, type::ValueFactory::GetNullValueByType( elem.GetType()), nullptr); } else { // If it's varchar or varbinary then use data pool, otherwise // allocate // inline auto data_pool = GetPlanPool(); if (elem.GetType() != type::Type::VARCHAR && elem.GetType() != type::Type::VARBINARY) data_pool = nullptr; LOG_TRACE( "Column %d found in INSERT query, ExpressionType: %s", col_cntr, ExpressionTypeToString(values->at(pos)->GetExpressionType()) .c_str()); if (values->at(pos)->GetExpressionType() == ExpressionType::VALUE_PARAMETER) { std::tuple<oid_t, oid_t, oid_t> pair = std::make_tuple(tuple_idx, col_cntr, param_index); parameter_vector_->push_back(pair); params_value_type_->push_back( table_schema->GetColumn(col_cntr).GetType()); ++param_index; } else { expression::ConstantValueExpression *const_expr_elem = dynamic_cast<expression::ConstantValueExpression *>( values->at(pos)); type::Value val = (const_expr_elem->GetValue()); tuple->SetValue(col_cntr, val, data_pool); } } ++col_cntr; } LOG_TRACE("Tuple to be inserted: %s", tuple->GetInfo().c_str()); tuples_.push_back(std::move(tuple)); } } } else { LOG_TRACE("Table does not exist!"); } } type::AbstractPool *InsertPlan::GetPlanPool() { // construct pool if needed if (pool_.get() == nullptr) pool_.reset(new type::EphemeralPool()); // return pool return pool_.get(); } void InsertPlan::SetParameterValues(std::vector<type::Value> *values) { PL_ASSERT(values->size() == parameter_vector_->size()); LOG_TRACE("Set Parameter Values in Insert"); for (unsigned int i = 0; i < values->size(); ++i) { auto param_type = params_value_type_->at(i); auto &put_loc = parameter_vector_->at(i); auto value = values->at(std::get<2>(put_loc)); // LOG_TRACE("Setting value of type %s", // ValueTypeToString(param_type).c_str()); switch (param_type) { case type::Type::VARBINARY: case type::Type::VARCHAR: { type::Value val = (value.CastAs(param_type)); tuples_[std::get<0>(put_loc)] ->SetValue(std::get<1>(put_loc), val, GetPlanPool()); break; } default: { type::Value val = (value.CastAs(param_type)); tuples_[std::get<0>(put_loc)] ->SetValue(std::get<1>(put_loc), val, nullptr); } } } } } }
37.42132
80
0.582339
vittvolt
6bd1f664608392956ecb975849d95fe25a09be4b
144
cpp
C++
src/app.cpp
overworks/MhGameLib
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
[ "MIT" ]
null
null
null
src/app.cpp
overworks/MhGameLib
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
[ "MIT" ]
null
null
null
src/app.cpp
overworks/MhGameLib
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
[ "MIT" ]
null
null
null
#include <mh/app.hpp> namespace Mh { App::App() : m_client_width(0), m_client_height(0), m_current_renderer(nullptr) {} App::~App() {} }
13.090909
70
0.652778
overworks
6bd2150707a370bf4806990ee933594e166545c9
19,085
hpp
C++
include/asioex/async.hpp
madmongo1/asio_experiments
4ed09b5fc1e3fe2597346d87cdcccc11f70d7d7f
[ "BSL-1.0" ]
1
2022-01-25T04:10:59.000Z
2022-01-25T04:10:59.000Z
include/asioex/async.hpp
madmongo1/asio_experiments
4ed09b5fc1e3fe2597346d87cdcccc11f70d7d7f
[ "BSL-1.0" ]
null
null
null
include/asioex/async.hpp
madmongo1/asio_experiments
4ed09b5fc1e3fe2597346d87cdcccc11f70d7d7f
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2022 Klemens D. Morgenstern // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef ASIO_EXPERIMENTS_ASYNC_HPP #define ASIO_EXPERIMENTS_ASYNC_HPP #include <asio/compose.hpp> #include <asio/post.hpp> #include <asio/dispatch.hpp> #include <asio/experimental/deferred.hpp> #include <asio/use_awaitable.hpp> #include <asio/experimental/as_tuple.hpp> #include <asio/this_coro.hpp> #include <coroutine> #include <boost/mp11/algorithm.hpp> #include <boost/mp11/list.hpp> #include <boost/preprocessor/repeat.hpp> #include <boost/preprocessor/repeat_2nd.hpp> #include <optional> #include <variant> namespace asio { template<typename E> struct use_awaitable_t; namespace experimental { template<typename E> struct use_coro_t; } } namespace asioex { template < typename... Signatures > struct compose_tag { }; namespace detail { template < typename T > constexpr auto compose_token_impl(const T *) { return asio::experimental::deferred; } template < typename Executor > constexpr auto compose_token_impl(const asio::use_awaitable_t< Executor > *) { return asio::experimental::as_tuple(asio::use_awaitable_t< Executor >()); } template < typename T > constexpr auto compose_token_impl(const asio::experimental::use_coro_t< T > *) { return asio::experimental::as_tuple(asio::experimental::use_coro_t< T >()); } template < template < class Token, class... > class Modifier, class Token, class... Ts > constexpr auto compose_token_impl( const Modifier< Token, Ts... > *, typename asio::constraint< !std::is_void< Token >::value >::type = 0) { return compose_token_impl(static_cast< const Token * >(nullptr)); } } template < typename T > constexpr auto compose_token(const T & val) { return detail::compose_token_impl(&val); } namespace detail { template<typename T> auto foo(T&&); template<typename Token> auto pick_executor(Token && token) { return asio::get_associated_executor(token); } template<typename Token, typename First, typename ... IoObjectsOrExecutors> auto pick_executor(Token && token, const First & first, IoObjectsOrExecutors && ... io_objects_or_executors) -> typename std::enable_if< asio::is_executor<First>::value || asio::execution::is_executor<First>::value ,First >::type { return first; } template<typename Token, typename First, typename ... IoObjectsOrExecutors> auto pick_executor(Token && token, First & first, IoObjectsOrExecutors && ... io_objects_or_executors) -> typename First::executor_type { return first.get_executor(); } template<typename Token, typename First, typename ... IoObjectsOrExecutors> auto pick_executor(Token && token, First &&, IoObjectsOrExecutors && ... io_objects_or_executors) { return pick_executor(std::forward<Token>(token), std::forward<IoObjectsOrExecutors>(io_objects_or_executors)...); } template<typename Derived, typename Signature> struct compose_promise_base; template<typename Derived, typename ... Args> struct compose_promise_base<Derived, void(Args...)> { void return_value(std::tuple<Args...> args) { static_cast<Derived*>(this)->result_ = std::move(args); } using tuple_type = std::tuple<Args...>; }; template<typename Return, typename Tag, typename Token, typename ... Args> struct compose_promise; template<typename Allocator, typename Tag, typename Token, typename ... Args> struct compose_promise_alloc_base { using allocator_type = Allocator; void* operator new(const std::size_t size, Args & ... args, Token & tk, Tag) { using alloc_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<unsigned char>; alloc_type alloc{asio::get_associated_allocator(tk)}; const auto align_needed = size % alignof(alloc_type); const auto align_offset = align_needed != 0 ? alignof(alloc_type) - align_needed : 0ull; const auto alloc_size = size + sizeof(alloc_type) + align_offset; const auto raw = std::allocator_traits<alloc_type>::allocate(alloc, alloc_size); new (raw + size + align_offset) alloc_type(std::move(alloc)); return raw; } void operator delete(void * raw_, std::size_t size) { using alloc_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<unsigned char>; const auto raw = static_cast<unsigned char *>(raw_); const auto align_needed = size % alignof(alloc_type); const auto align_offset = align_needed != 0 ? alignof(alloc_type) - align_needed : 0ull; const auto alloc_size = size + sizeof(alloc_type) + align_offset; auto alloc_p = reinterpret_cast<alloc_type*>(raw + size + align_offset); auto alloc = std::move(*alloc_p); alloc_p->~alloc_type(); std::allocator_traits<alloc_type>::deallocate(alloc, raw, alloc_size); } }; template<typename Tag, typename Token, typename ... Args> struct compose_promise_alloc_base<std::allocator<void>, Tag, Token, Args...> { }; template<typename Return, typename ...Sigs, typename Token, typename ... Args> struct compose_promise<Return, compose_tag<Sigs...>, Token, Args...> : compose_promise_alloc_base< asio::associated_allocator_t<std::decay_t<Token>>, compose_tag<Sigs...>, Token, Args...>, compose_promise_base<compose_promise<Return, compose_tag<Sigs...>, Token, Args...>, Sigs> ... { using my_type = compose_promise<Return, compose_tag<Sigs...>, Token, Args...>; using compose_promise_base<my_type, Sigs> ::return_value ...; using result_type = std::variant<typename compose_promise_base<my_type, Sigs>::tuple_type ...>; using token_type = std::decay_t<Token>; std::optional<result_type> result_; token_type token; using allocator_type = asio::associated_allocator_t<token_type>; asio::cancellation_state state{ asio::get_associated_cancellation_slot(token), asio::enable_terminal_cancellation() }; using executor_type = typename asio::prefer_result< decltype(pick_executor(std::declval<Token>(), std::declval<Args>()...)), asio::execution::outstanding_work_t::tracked_t>::type; executor_type executor_; bool did_suspend = false; #if defined(__clang__) || defined(_MSC_FULL_VER) compose_promise(Args &... args, Token & tk, const compose_tag<Sigs...> &) : token(static_cast<Token>(tk)), executor_( asio::prefer( pick_executor(token, args...), asio::execution::outstanding_work.tracked)) { } #else compose_promise(Args &... args, Token && tk, const compose_tag<Sigs...> &) : token(static_cast<Token>(tk)), executor_( asio::prefer( pick_executor(token, args...), asio::execution::outstanding_work.tracked)) { } #endif ~compose_promise() { if (completion && result_) std::visit( [this](auto & tup) { auto cpl = [tup = std::move(tup), completion = std::move(*completion)]() mutable { std::apply(std::move(completion), std::move(tup)); }; if (did_suspend) asio::dispatch(executor_, std::move(cpl)); else asio::post(executor_, std::move(cpl)); }, *result_); } constexpr static std::suspend_never initial_suspend() noexcept { return {}; } constexpr static std::suspend_never final_suspend() noexcept { return {}; } template<typename ... Args_, typename ... Ts> auto await_transform(asio::experimental::deferred_async_operation<void(Args_...), Ts...> op) { struct result { asio::experimental::deferred_async_operation<void(Args_...), Ts...> op; compose_promise * self; std::tuple<Args_...> res; struct completion { compose_promise * self; std::tuple<Args_...> &result; std::unique_ptr<void, coro_delete> coro_handle; using cancellation_slot_type = asio::cancellation_slot; cancellation_slot_type get_cancellation_slot() const noexcept { return self->state.slot(); } using executor_type = typename compose_promise::executor_type; executor_type get_executor() const noexcept { return self->executor_; } using allocator_type = typename compose_promise::allocator_type; allocator_type get_allocator() const noexcept { return asio::get_associated_allocator(self->token); } void operator()(Args_ ... args) { self->did_suspend = true; result = {std::move(args)...}; std::coroutine_handle<compose_promise>::from_address(coro_handle.release()).resume(); } }; bool await_ready() { return false; } void await_suspend( std::coroutine_handle<compose_promise> h) { std::move(op)(completion{self, res, {h.address(), coro_delete{}}}); } std::tuple<Args_...> await_resume() { return std::move(res); } }; return result{std::move(op), this}; }; struct coro_delete { void operator()(void * c) { if (c != nullptr) std::coroutine_handle<compose_promise>::from_address(c).destroy(); } }; auto await_transform(asio::this_coro::executor_t) const { struct exec_helper { const executor_type& value; constexpr static bool await_ready() noexcept { return true; } constexpr static void await_suspend(std::coroutine_handle<>) noexcept { } executor_type await_resume() const noexcept { return value; } }; return exec_helper{executor_}; } auto await_transform(asio::this_coro::cancellation_state_t) const { struct exec_helper { const asio::cancellation_state& value; constexpr static bool await_ready() noexcept { return true; } constexpr static void await_suspend(std::coroutine_handle<>) noexcept { } asio::cancellation_state await_resume() const noexcept { return value; } }; return exec_helper{state}; } // This await transformation resets the associated cancellation state. auto await_transform(asio::this_coro::reset_cancellation_state_0_t) noexcept { struct result { asio::cancellation_state &state; token_type & token; bool await_ready() const noexcept { return true; } void await_suspend(std::coroutine_handle<void>) noexcept { } auto await_resume() const { state = asio::cancellation_state(asio::get_associated_cancellation_slot(token)); } }; return result{state, token}; } // This await transformation resets the associated cancellation state. template <typename Filter> auto await_transform( asio::this_coro::reset_cancellation_state_1_t<Filter> reset) noexcept { struct result { asio::cancellation_state & state; Filter filter_; token_type & token; bool await_ready() const noexcept { return true; } void await_suspend(std::coroutine_handle<void>) noexcept { } auto await_resume() { state = asio::cancellation_state( asio::get_associated_cancellation_slot(token), ASIO_MOVE_CAST(Filter)(filter_)); } }; return result{state, ASIO_MOVE_CAST(Filter)(reset.filter), token}; } // This await transformation resets the associated cancellation state. template <typename InFilter, typename OutFilter> auto await_transform( asio::this_coro::reset_cancellation_state_2_t<InFilter, OutFilter> reset) noexcept { struct result { asio::cancellation_state & state; InFilter in_filter_; OutFilter out_filter_; token_type & token; bool await_ready() const noexcept { return true; } void await_suspend(std::coroutine_handle<void>) noexcept { } auto await_resume() { state = asio::cancellation_state( asio::get_associated_cancellation_slot(token), ASIO_MOVE_CAST(InFilter)(in_filter_), ASIO_MOVE_CAST(OutFilter)(out_filter_)); } }; return result{state, ASIO_MOVE_CAST(InFilter)(reset.in_filter), ASIO_MOVE_CAST(OutFilter)(reset.out_filter), token}; } auto get_return_object() -> Return { return asio::async_initiate<Token, Sigs...>( [this](auto tk) { completion.emplace(std::move(tk)); }, token); } void unhandled_exception() { // mangle it onto the executor so the coro dies safely asio::post(executor_, [ex = std::current_exception()] { std::rethrow_exception(ex); }); } // TODO implement for overloads using completion_type = typename asio::async_completion<Token, Sigs...>::completion_handler_type; std::optional<completion_type> completion; }; template<typename Return, typename Executor, typename Tag, typename Token, typename ... Args> struct awaitable_compose_promise; template<typename Return, typename Executor, typename ... Args_, typename Token, typename ... Args> struct awaitable_compose_promise<Return, Executor, compose_tag<void(Args_...)>, Token, Args...> : std::coroutine_traits<asio::awaitable<Return, Executor>>::promise_type { using base_type = typename std::coroutine_traits<asio::awaitable<Return, Executor>>::promise_type; void return_value_impl(asio::error_code ec, Return && result) { if (ec) this->set_error(ec); else this->base_type::return_value(std::move(result)); } void return_value_impl(std::exception_ptr e, Return && result) { if (e) this->set_except(e); else this->base_type::return_value(std::move(result)); } auto return_value(std::tuple<Args_ ...> result) { if constexpr (std::is_same_v<Return, std::tuple<Args_...>>) this->base_type::return_value(std::forward<Return>(result)); else std::apply( [this](auto ... args) { return_value_impl(std::move(args)...); }, std::move(result)); } void unhandled_exception() { throw ; } }; struct void_t {}; template<typename Executor, typename ... Args_, typename Token, typename ... Args> struct awaitable_compose_promise<void, Executor, compose_tag<void(Args_...)>, Token, Args...> : std::coroutine_traits<asio::awaitable<void_t, Executor>>::promise_type { using base_type = typename std::coroutine_traits<asio::awaitable<void_t, Executor>>::promise_type; asio::awaitable<void, Executor> get_return_object() noexcept { co_await base_type::get_return_object(); }; void return_value_impl(asio::error_code ec) { if (ec) this->set_error(ec); else this->base_type::return_value(void_t{}); } template<typename = void> void return_value_impl(std::exception_ptr e) { if (e) this->set_except(e); else this->base_type::return_value(void_t{}); } auto return_value(std::tuple<Args_ ...> result) { if constexpr (sizeof...(Args_)) this->base_type::return_value(void_t{}); else std::apply( [this](auto ... args) { return_value_impl(std::move(args)...); }, std::move(result)); } void unhandled_exception() { throw ; } }; } } namespace std { // this is hack AF template<typename Return, typename Executor, typename Tag, typename Token, typename ... Args> struct coroutine_handle<asioex::detail::awaitable_compose_promise<Return, Executor, Tag, Token, Args...>> : coroutine_handle<typename std::coroutine_traits<asio::awaitable<Return, Executor>>::promise_type> { }; #define ASIOEX_TYPENAME(z, n, text) , typename T##n #define ASIOEX_SPEC(z, n, text) , T##n #define ASIOEX_TRAIT_DECL(z, n, text) \ template<typename Return BOOST_PP_REPEAT_2ND(n, ASIOEX_TYPENAME, ), typename Token, typename ... Sigs > \ struct coroutine_traits<Return BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, ), Token, asioex::compose_tag<Sigs...>> \ { \ using promise_type = asioex::detail::compose_promise< \ Return, asioex::compose_tag<Sigs...>, Token \ BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, )>; \ }; BOOST_PP_REPEAT(24, ASIOEX_TRAIT_DECL, ); #define ASIOEX_AW_TRAIT_DECL(z, n, text) \ template<typename Return, typename Executor BOOST_PP_REPEAT_2ND(n, ASIOEX_TYPENAME, ), typename Token, typename ... Sigs > \ struct coroutine_traits<asio::awaitable<Return, Executor> BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, ), Token, asioex::compose_tag<Sigs...>> \ { \ using promise_type = asioex::detail::awaitable_compose_promise< \ Return, Executor, asioex::compose_tag<Sigs...>, Token \ BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, )>; \ }; BOOST_PP_REPEAT(24, ASIOEX_AW_TRAIT_DECL, ); #undef ASIOEX_TYPENAME #undef ASIOEX_SPEC #undef ASIOEX_TRAIT_DECL } #endif // ASIO_EXPERIMENTS_ASYNC_HPP
29.316436
135
0.599266
madmongo1
6bd6b2d10da7b45da59bc08522f75daf082cae37
950
cpp
C++
src/rtcore/ICamera.cpp
potato3d/rtrt2
5c135c1aea0ded2898e16220cec5ed2860dcc9b3
[ "MIT" ]
1
2021-11-06T06:13:05.000Z
2021-11-06T06:13:05.000Z
src/rtcore/ICamera.cpp
potato3d/rtrt2
5c135c1aea0ded2898e16220cec5ed2860dcc9b3
[ "MIT" ]
null
null
null
src/rtcore/ICamera.cpp
potato3d/rtrt2
5c135c1aea0ded2898e16220cec5ed2860dcc9b3
[ "MIT" ]
null
null
null
#include <rti/ICamera.h> using namespace rti; void ICamera::translate( float x, float y, float z ) { // avoid warnings x;y;z; } void ICamera::rotate( float radians, uint32 axis ) { // avoid warnings radians;axis; } void ICamera::setLookAt( float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ ) { // avoid warnings eyeX;eyeY;eyeZ;centerX;centerY;centerZ;upX;upY;upZ; } void ICamera::setPerspective( float fovY, float zNear, float zFar ) { // avoid warnings fovY;zNear;zFar; } void ICamera::setViewport( uint32 width, uint32 height ) { // avoid warnings width;height; } void ICamera::getViewport( uint32& width, uint32& height ) { width = 0; height = 0; } void ICamera::getRayOrigin( vr::vec3f& origin, float x, float y ) { origin.set( 0, 0, 0 ); } void ICamera::getRayDirection( vr::vec3f& dir, float x, float y ) { dir.set( 0, 0, 0 ); }
18.269231
67
0.670526
potato3d
6bd7be057a7b8fc1ffa799e2aeb17f7b363b1d33
16,353
cpp
C++
src/ARIA/ArRangeBuffer.cpp
rzsavilla/Robot_PathPlanning
7ca805b917824ecaf8f12a950b1f77bd76ac5836
[ "MIT" ]
1
2018-10-13T02:50:25.000Z
2018-10-13T02:50:25.000Z
src/ARIA/ArRangeBuffer.cpp
rzsavilla/Robot_PathPlanning
7ca805b917824ecaf8f12a950b1f77bd76ac5836
[ "MIT" ]
null
null
null
src/ARIA/ArRangeBuffer.cpp
rzsavilla/Robot_PathPlanning
7ca805b917824ecaf8f12a950b1f77bd76ac5836
[ "MIT" ]
1
2018-10-13T02:50:26.000Z
2018-10-13T02:50:26.000Z
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ #include "ArExport.h" #include "ariaOSDef.h" #include "ArRangeBuffer.h" #include "ArLog.h" /** @param size The size of the buffer, in number of readings */ AREXPORT ArRangeBuffer::ArRangeBuffer(int size) { mySize = size; } AREXPORT ArRangeBuffer::~ArRangeBuffer() { ArUtil::deleteSet(myBuffer.begin(), myBuffer.end()); ArUtil::deleteSet(myInvalidBuffer.begin(), myInvalidBuffer.end()); } AREXPORT size_t ArRangeBuffer::getSize(void) const { return mySize; } AREXPORT ArPose ArRangeBuffer::getPoseTaken() const { return myBufferPose; } AREXPORT void ArRangeBuffer::setPoseTaken(ArPose p) { myBufferPose = p; } AREXPORT ArPose ArRangeBuffer::getEncoderPoseTaken() const { return myEncoderBufferPose; } AREXPORT void ArRangeBuffer::setEncoderPoseTaken(ArPose p) { myEncoderBufferPose = p; } /** If the new size is smaller than the current buffer it chops off the readings that are excess from the oldest readings... if the new size is larger then it just leaves room for the buffer to grow @param size number of readings to set the buffer to */ AREXPORT void ArRangeBuffer::setSize(size_t size) { mySize = size; // if its smaller then chop the lists down to size while (myInvalidBuffer.size() + myBuffer.size() > mySize) { if ((myRevIterator = myInvalidBuffer.rbegin()) != myInvalidBuffer.rend()) { myReading = (*myRevIterator); myInvalidBuffer.pop_back(); delete myReading; } else if ((myRevIterator = myBuffer.rbegin()) != myBuffer.rend()) { myReading = (*myRevIterator); myBuffer.pop_back(); delete myReading; } } } /** This function returns a pointer to a list that has all of the readings in it. This list is mostly for reference, ie for finding some particular value or for using the readings to draw them. Don't do any modification at all to the list unless you really know what you're doing... and if you do you'd better lock the rangeDevice this came from so nothing messes with the list while you are doing so. @return the list of positions this range buffer has */ AREXPORT const std::list<ArPoseWithTime *> *ArRangeBuffer::getBuffer(void) const { return &myBuffer; } /** This function returns a pointer to a list that has all of the readings in it. This list is mostly for reference, ie for finding some particular value or for using the readings to draw them. Don't do any modification at all to the list unless you really know what you're doing... and if you do you'd better lock the rangeDevice this came from so nothing messes with the list while you are doing so. @return the list of positions this range buffer has */ AREXPORT std::list<ArPoseWithTime *> *ArRangeBuffer::getBuffer(void) { return &myBuffer; } /** Gets the closest reading in a region defined by startAngle going to endAngle... going counterclockwise (neg degrees to poseitive... with how the robot is set up, thats counterclockwise)... from -180 to 180... this means if you want the slice between 0 and 10 degrees, you must enter it as 0, 10, if you do 10, 0 you'll get the 350 degrees between 10 and 0... be especially careful with negative... for example -30 to -60 is everything from -30, around through 0, 90, and 180 back to -60... since -60 is actually to clockwise of -30 @param startAngle where to start the slice @param endAngle where to end the slice, going clockwise from startAngle @param startPos the position to find the closest reading to (usually the robots position) @param maxRange the maximum range to return (and what to return if nothing found) @param angle a pointer return of the angle to the found reading @return if the return is >= 0 and <= maxRange then this is the distance to the closest reading, if it is >= maxRange, then there was no reading in the given section */ AREXPORT double ArRangeBuffer::getClosestPolar(double startAngle, double endAngle, ArPose startPos, unsigned int maxRange, double *angle) const { return getClosestPolarInList(startAngle, endAngle, startPos, maxRange, angle, &myBuffer); } AREXPORT double ArRangeBuffer::getClosestPolarInList( double startAngle, double endAngle, ArPose startPos, unsigned int maxRange, double *angle, const std::list<ArPoseWithTime *> *buffer) { double closest; bool foundOne = false; std::list<ArPoseWithTime *>::const_iterator it; ArPoseWithTime *reading; double th; double closeTh; double dist; double angle1, angle2; startAngle = ArMath::fixAngle(startAngle); endAngle = ArMath::fixAngle(endAngle); for (it = buffer->begin(); it != buffer->end(); ++it) { reading = (*it); angle1=startPos.findAngleTo(*reading); angle2=startPos.getTh(); th = ArMath::subAngle(angle1, angle2); if (ArMath::angleBetween(th, startAngle, endAngle)) { if (!foundOne || (dist = reading->findDistanceTo(startPos)) < closest) { closeTh = th; if (!foundOne) closest = reading->findDistanceTo(startPos); else closest = dist; foundOne = true; } } } if (!foundOne) return maxRange; if (angle != NULL) *angle = closeTh; if (closest > maxRange) return maxRange; else return closest; } /** Gets the closest reading in a region defined by two points (opposeite points of a rectangle). @param x1 the x coordinate of one of the rectangle points @param y1 the y coordinate of one of the rectangle points @param x2 the x coordinate of the other rectangle point @param y2 the y coordinate of the other rectangle point @param startPos the position to find the closest reading to (usually the robots position) @param maxRange the maximum range to return (and what to return if nothing found) @param readingPos a pointer to a position in which to store the location of the closest position @param targetPose the origin of the local coords for the definition of the coordinates, e.g. ArRobot::getPosition() to center the box on the robot @return if the return is >= 0 and <= maxRange then this is the distance to the closest reading, if it is >= maxRange, then there was no reading in the given section */ AREXPORT double ArRangeBuffer::getClosestBox(double x1, double y1, double x2, double y2, ArPose startPos, unsigned int maxRange, ArPose *readingPos, ArPose targetPose) const { return getClosestBoxInList(x1, y1, x2, y2, startPos, maxRange, readingPos, targetPose, &myBuffer); } /** Get closest reading in a region defined by two points (opposeite points of a rectangle) from a given list readings (rather than the readings stored in an ArRangeBuffer) @param x1 the x coordinate of one of the rectangle points @param y1 the y coordinate of one of the rectangle points @param x2 the x coordinate of the other rectangle point @param y2 the y coordinate of the other rectangle point @param startPos the position to find the closest reading to (usually the robots position) @param maxRange the maximum range to return (and what to return if nothing found) @param readingPos a pointer to a position in which to store the location of the closest position @param targetPose the origin of the local coords for the definition of the coordinates, normally just ArRobot::getPosition() @param buffer Use the reading positions from this list @param targetPose the pose to see if we're closest too (in local coordinates), this should nearly always be the default of 0 0 0 @return if the return is >= 0 and <= maxRange then this is the distance to the closest reading, if it is >= maxRange, then there was no reading in the given section */ AREXPORT double ArRangeBuffer::getClosestBoxInList( double x1, double y1, double x2, double y2, ArPose startPos, unsigned int maxRange, ArPose *readingPos, ArPose targetPose, const std::list<ArPoseWithTime *> *buffer) { double closest = maxRange; double dist; ArPose closestPos; std::list<ArPoseWithTime *>::const_iterator it; ArTransform trans; ArPoseWithTime pose; ArPose zeroPos; double temp; zeroPos.setPose(0, 0, 0); trans.setTransform(startPos, zeroPos); if (x1 >= x2) { temp = x1, x1 = x2; x2 = temp; } if (y1 >= y2) { temp = y1, y1 = y2; y2 = temp; } for (it = buffer->begin(); it != buffer->end(); ++it) { pose = trans.doTransform(*(*it)); // see if its in the box if (pose.getX() >= x1 && pose.getX() <= x2 && pose.getY() >= y1 && pose.getY() <= y2) { dist = pose.findDistanceTo(targetPose); //pose.log(); if (dist < closest) { closest = dist; closestPos = pose; } } } if (readingPos != NULL) *readingPos = closestPos; if (closest > maxRange) return maxRange; else return closest; } /** Applies a transform to the buffers.. this is mostly useful for translating to/from local/global coords, but may have other uses @param trans the transform to apply to the data */ AREXPORT void ArRangeBuffer::applyTransform(ArTransform trans) { trans.doTransform(&myBuffer); } AREXPORT void ArRangeBuffer::clear(void) { beginRedoBuffer(); endRedoBuffer(); } AREXPORT void ArRangeBuffer::reset(void) { clear(); } AREXPORT void ArRangeBuffer::clearOlderThan(int milliSeconds) { std::list<ArPoseWithTime *>::iterator it; beginInvalidationSweep(); for (it = myBuffer.begin(); it != myBuffer.end(); ++it) { if ((*it)->getTime().mSecSince() > milliSeconds) invalidateReading(it); } endInvalidationSweep(); } AREXPORT void ArRangeBuffer::clearOlderThanSeconds(int seconds) { clearOlderThan(seconds*1000); } /** To redo the buffer means that you want to replace all of the readings in the buffer with new pose values, and get rid of the readings that you didn't update with new values (invalidate them). The three functions beginRedoBuffer(), redoReading(), and endRedoBuffer() are all made to enable you to do this. First call beginRedoBuffer(). Then for each reading you want to update in the buffer, call redoReading(double x, double y), then when you are done, call endRedoBuffer(). **/ AREXPORT void ArRangeBuffer::beginRedoBuffer(void) { myRedoIt = myBuffer.begin(); myHitEnd = false; myNumRedone = 0; } /** For a description of how to use this, see beginRedoBuffer() @param x the x param of the coord to add to the buffer @param y the x param of the coord to add to the buffer */ AREXPORT void ArRangeBuffer::redoReading(double x, double y) { if (myRedoIt != myBuffer.end() && !myHitEnd) { (*myRedoIt)->setPose(x, y); myRedoIt++; } // if we don't, add more (its just moving from buffers here, //but let the class for this do the work else { addReading(x,y); myHitEnd = true; } myNumRedone++; } /** For a description of how to use this, see beginRedoBuffer() **/ AREXPORT void ArRangeBuffer::endRedoBuffer(void) { if (!myHitEnd) { // now we get rid of the extra readings on the end beginInvalidationSweep(); while (myRedoIt != myBuffer.end()) { invalidateReading(myRedoIt); myRedoIt++; } endInvalidationSweep(); } } /** @param x the x position of the reading @param y the y position of the reading @param closeDistSquared if the new reading is within closeDistSquared distanceSquared of an old point the old point is just updated for time */ AREXPORT void ArRangeBuffer::addReadingConditional(double x, double y, double closeDistSquared) { if (closeDistSquared >= 0) { std::list<ArPoseWithTime *>::iterator it; ArPoseWithTime *pose; for (it = myBuffer.begin(); it != myBuffer.end(); ++it) { pose = (*it); if (ArMath::squaredDistanceBetween(pose->getX(), pose->getX(), x, y) < closeDistSquared) { pose->setTimeToNow(); return; } } } addReading(x, y); } /** @param x the x position of the reading @param y the y position of the reading */ AREXPORT void ArRangeBuffer::addReading(double x, double y) { if (myBuffer.size() < mySize) { if ((myIterator = myInvalidBuffer.begin()) != myInvalidBuffer.end()) { myReading = (*myIterator); myReading->setPose(x, y); myReading->setTimeToNow(); myBuffer.push_front(myReading); myInvalidBuffer.pop_front(); } else myBuffer.push_front(new ArPoseWithTime(x, y)); } else if ((myRevIterator = myBuffer.rbegin()) != myBuffer.rend()) { myReading = (*myRevIterator); myReading->setPose(x, y); myReading->setTimeToNow(); myBuffer.pop_back(); myBuffer.push_front(myReading); } } /** This is a set of funkiness used to invalid readings in the buffer. It is fairly complicated. But what you need to do, is set up the invalid sweeping with beginInvalidationSweep, then walk through the list of readings, and pass the iterator to a reading you want to invalidate to invalidateReading, then after you are all through walking the list call endInvalidationSweep. Look at the description of getBuffer for additional warnings. @see invalidateReading @see endInvalidationSweep */ void ArRangeBuffer::beginInvalidationSweep(void) { myInvalidSweepList.clear(); } /** See the description of beginInvalidationSweep, it describes how to use this function. @param readingIt the ITERATOR to the reading you want to get rid of @see beginInvaladationSweep @see endInvalidationSweep */ AREXPORT void ArRangeBuffer::invalidateReading( std::list<ArPoseWithTime*>::iterator readingIt) { myInvalidSweepList.push_front(readingIt); } /** See the description of beginInvalidationSweep, it describes how to use this function. @see beginInvalidationSweep @see invalidateReading */ void ArRangeBuffer::endInvalidationSweep(void) { while ((myInvalidIt = myInvalidSweepList.begin()) != myInvalidSweepList.end()) { //printf("nuked one before %d %d\n", myBuffer.size(), myInvalidBuffer.size()); myReading = (*(*myInvalidIt)); myInvalidBuffer.push_front(myReading); myBuffer.erase((*myInvalidIt)); myInvalidSweepList.pop_front(); //printf("after %d %d\n", myBuffer.size(), myInvalidBuffer.size()); } } /** Copy the readings from this buffer to a vector stored within this object, and return a pointer to that vector. Note that the actual vector object is stored within ArRangeBuffer, be careful if accessing it from multiple threads. @return Pointer to reading vector. */ AREXPORT std::vector<ArPoseWithTime> *ArRangeBuffer::getBufferAsVector(void) { std::list<ArPoseWithTime *>::iterator it; myVector.reserve(myBuffer.size()); myVector.clear(); // start filling the array with the buffer until we run out of // readings or its full for (it = myBuffer.begin(); it != myBuffer.end(); it++) { myVector.insert(myVector.begin(), *(*it)); } return &myVector; }
30.395911
131
0.699077
rzsavilla
6bda31de544e5c9f02f100ab88930531faa26073
1,186
cpp
C++
Framework/ML/Src/Datasets.cpp
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
Framework/ML/Src/Datasets.cpp
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
Framework/ML/Src/Datasets.cpp
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include "Datasets.h" using namespace JimmyGod::ML; using namespace JimmyGod::Math; Dataset Datasets::MakeLinear(size_t samples, float b0, float b1, float minX, float maxX, float noise) { Dataset dataset; dataset.x0.reserve(samples); dataset.y.reserve(samples); for (size_t i = 0; i < samples; i++) { float x = RandomFloat(minX, maxX); float y = b0 + (b1 * x) + RandomNormal(0.0f, noise); dataset.x0.push_back(x); dataset.y.push_back(y); } return dataset; } Dataset Datasets::MakeLogistic(size_t samples, float b0, float b1, float b2, float minX, float maxX, float noise) { Dataset dataset; dataset.x0.reserve(samples); dataset.x1.reserve(samples); dataset.y.reserve(samples); const float m = -b1 / b2; const float b = -b0 / b2; for (size_t i = 0; i < samples; i++) { const float x0 = RandomFloat(minX, maxX); const float point = (m * x0) + b; const float delta = RandomNormal(0.0f, noise); const float x1 = point + delta; const float y = (delta > 0.0f) ? 1.0f : 0.0f; dataset.x0.push_back(x0); dataset.x1.push_back(x1); dataset.y.push_back(y); } return dataset; }
24.708333
114
0.652614
TheJimmyGod
6bdc38145a33e2bce6e327a72f86e72f4dbde44d
1,961
hpp
C++
examples/toy/bnsl_state.hpp
kp1181/scool
296cd49a0d62de609d681b3ec3d7019b3d2c7c30
[ "MIT" ]
1
2022-03-14T05:23:51.000Z
2022-03-14T05:23:51.000Z
examples/toy/bnsl_state.hpp
kp1181/scool
296cd49a0d62de609d681b3ec3d7019b3d2c7c30
[ "MIT" ]
null
null
null
examples/toy/bnsl_state.hpp
kp1181/scool
296cd49a0d62de609d681b3ec3d7019b3d2c7c30
[ "MIT" ]
null
null
null
/*** * $Id$ ** * File: bnsl_state.hpp * Created: Jan 13, 2022 * * Author: Jaroslaw Zola <jaroslaw.zola@hush.com> * Distributed under the MIT License. * See accompanying file LICENSE. * * This file is part of SCoOL. */ #ifndef BNSL_STATE_HPP #define BNSL_STATE_HPP #include <istream> #include <ostream> #include <vector> #include "bit_util.hpp" #include "limits.hpp" template <typename set_type> struct bnsl_state { bnsl_state() = default; void identity() { } void operator+=(const bnsl_state& st) { if (st.score < score) { score = st.score; path = st.path; } } // operator+= bool operator==(const bnsl_state& st) const { return (tid == st.tid); } void print(std::ostream& os) const { os << "score: " << score << ", order:"; for (int x : path) os << " " << x; os << std::endl; } // print set_type tid = set_empty<set_type>(); double score = SABNA_DBL_INFTY; std::vector<uint8_t> path; }; // struct bnsl_state template <typename set_type> inline std::ostream& operator<<(std::ostream& os, const bnsl_state<set_type>& st) { int n = st.path.size(); os.write(reinterpret_cast<const char*>(&st.tid), sizeof(st.tid)); os.write(reinterpret_cast<const char*>(&st.score), sizeof(st.score)); os.write(reinterpret_cast<const char*>(&n), sizeof(n)); os.write(reinterpret_cast<const char*>(st.path.data()), n * sizeof(uint8_t)); return os; } // operator<< template <typename set_type> inline std::istream& operator>>(std::istream& is, bnsl_state<set_type>& st) { int n = 0; is.read(reinterpret_cast<char*>(&st.tid), sizeof(st.tid)); is.read(reinterpret_cast<char*>(&st.score), sizeof(st.score)); is.read(reinterpret_cast<char*>(&n), sizeof(n)); st.path.resize(n); is.read(reinterpret_cast<char*>(st.path.data()), n * sizeof(uint8_t)); return is; } // operator>> #endif // BNSL_STATE_HPP
26.863014
83
0.627231
kp1181
6be3d1104b8a3558401ebea570dab62f6a9821fd
5,740
cpp
C++
nifti_user/ogre_tools_diamond_back/src/ogre_tools/fps_camera.cpp
talkingrobots/NIFTi_OCU
017a36cd98f4302ebcd0f024a6c0c517b044bac7
[ "BSD-3-Clause" ]
1
2019-08-14T09:59:21.000Z
2019-08-14T09:59:21.000Z
nifti_user/ogre_tools_diamond_back/src/ogre_tools/fps_camera.cpp
talkingrobots/NIFTi_OCU
017a36cd98f4302ebcd0f024a6c0c517b044bac7
[ "BSD-3-Clause" ]
null
null
null
nifti_user/ogre_tools_diamond_back/src/ogre_tools/fps_camera.cpp
talkingrobots/NIFTi_OCU
017a36cd98f4302ebcd0f024a6c0c517b044bac7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "fps_camera.h" #include <OGRE/OgreCamera.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreVector3.h> #include <OGRE/OgreQuaternion.h> #include <stdint.h> #include <sstream> namespace ogre_tools { static const float PITCH_LIMIT_LOW = -Ogre::Math::HALF_PI + 0.001; static const float PITCH_LIMIT_HIGH = Ogre::Math::HALF_PI - 0.001; FPSCamera::FPSCamera( Ogre::SceneManager* scene_manager ) : CameraBase( scene_manager ) , pitch_(0.0f) , yaw_(0.0f) { } FPSCamera::~FPSCamera() { } void FPSCamera::relativeNodeChanged() { if ( relative_node_ ) { relative_node_->attachObject( camera_ ); } } void FPSCamera::update() { Ogre::Matrix3 pitch, yaw; yaw.FromAxisAngle( Ogre::Vector3::UNIT_Y, Ogre::Radian( yaw_ ) ); pitch.FromAxisAngle( Ogre::Vector3::UNIT_X, Ogre::Radian( pitch_ ) ); camera_->setOrientation( yaw * pitch ); } void FPSCamera::normalizePitch() { if ( pitch_ < PITCH_LIMIT_LOW ) { pitch_ = PITCH_LIMIT_LOW; } else if ( pitch_ > PITCH_LIMIT_HIGH ) { pitch_ = PITCH_LIMIT_HIGH; } } void FPSCamera::normalizeYaw() { yaw_ = fmod( yaw_, Ogre::Math::TWO_PI ); if ( yaw_ < 0.0f ) { yaw_ = Ogre::Math::TWO_PI + yaw_; } } void FPSCamera::yaw( float angle ) { yaw_ += angle; normalizeYaw(); update(); } void FPSCamera::pitch( float angle ) { pitch_ += angle; normalizePitch(); update(); } void FPSCamera::roll( float angle ) { } void FPSCamera::setFrom( CameraBase* camera ) { CameraBase::setPosition( camera->getPosition() ); CameraBase::setOrientation( camera->getOrientation() ); } void FPSCamera::setOrientation( float x, float y, float z, float w ) { Ogre::Quaternion quat( w, x, y, z ); yaw_ = quat.getYaw( false ).valueRadians(); pitch_ = quat.getPitch( false ).valueRadians(); Ogre::Vector3 direction = quat * Ogre::Vector3::NEGATIVE_UNIT_Z; if ( direction.dotProduct( Ogre::Vector3::NEGATIVE_UNIT_Z ) < 0 ) { if ( pitch_ > Ogre::Math::HALF_PI ) { pitch_ = -Ogre::Math::HALF_PI + (pitch_ - Ogre::Math::HALF_PI); } else if ( pitch_ < -Ogre::Math::HALF_PI ) { pitch_ = Ogre::Math::HALF_PI - (-pitch_ - Ogre::Math::HALF_PI); } yaw_ = -yaw_; if ( direction.dotProduct( Ogre::Vector3::UNIT_X ) < 0 ) { yaw_ -= Ogre::Math::PI; } else { yaw_ += Ogre::Math::PI; } } normalizePitch(); normalizeYaw(); update(); } Ogre::Quaternion FPSCamera::getOrientation() { return camera_->getOrientation(); } void FPSCamera::move( float x, float y, float z ) { Ogre::Vector3 translate( x, y, z ); camera_->setPosition( camera_->getPosition() + getOrientation() * translate ); } void FPSCamera::setPosition( float x, float y, float z ) { camera_->setPosition( x, y, z ); } Ogre::Vector3 FPSCamera::getPosition() { return camera_->getPosition(); } void FPSCamera::lookAt( const Ogre::Vector3& point ) { camera_->lookAt( point ); CameraBase::setOrientation( camera_->getOrientation() ); update(); } void FPSCamera::mouseLeftDrag( int diff_x, int diff_y, bool ctrl, bool alt, bool shift ) { yaw( -diff_x*0.005 ); pitch( -diff_y*0.005 ); } void FPSCamera::mouseMiddleDrag( int diff_x, int diff_y, bool ctrl, bool alt, bool shift ) { move( diff_x*0.01, -diff_y*0.01, 0.0f ); } void FPSCamera::mouseRightDrag( int diff_x, int diff_y, bool ctrl, bool alt, bool shift ) { move( 0.0f, 0.0f, diff_y*0.1 ); } void FPSCamera::scrollWheel( int diff, bool ctrl, bool alt, bool shift ) { move( 0.0f, 0.0f, -diff * 0.01 ); } void FPSCamera::fromString(const std::string& str) { std::istringstream iss(str); iss >> pitch_; iss.ignore(); iss >> yaw_; iss.ignore(); Ogre::Vector3 vec; iss >> vec.x; iss.ignore(); iss >> vec.y; iss.ignore(); iss >> vec.z; iss.ignore(); camera_->setPosition(vec); update(); } std::string FPSCamera::toString() { std::ostringstream oss; oss << pitch_ << " " << yaw_ << " " << camera_->getPosition().x << " " << camera_->getPosition().y << " " << camera_->getPosition().z; return oss.str(); } } // namespace ogre_tools
23.52459
136
0.676481
talkingrobots
6be5bdf8ee06389987bc2aec558020fc8ab87a24
270
hpp
C++
gnet/include/noncopyable.hpp
gapry/GNet
4d63540e1f532fae1a44a97f9b2d74a6754f2513
[ "MIT" ]
1
2021-05-19T03:56:47.000Z
2021-05-19T03:56:47.000Z
gnet/include/noncopyable.hpp
gapry/GNet
4d63540e1f532fae1a44a97f9b2d74a6754f2513
[ "MIT" ]
null
null
null
gnet/include/noncopyable.hpp
gapry/GNet
4d63540e1f532fae1a44a97f9b2d74a6754f2513
[ "MIT" ]
null
null
null
#pragma once namespace gnet { template<class T> class noncopyable { protected: noncopyable() = default; ~noncopyable() noexcept = default; private: noncopyable(noncopyable const&) = delete; auto operator=(T const&) -> void = delete; }; } // namespace gnet
14.210526
44
0.692593
gapry
6be89af3018eb4f867beea416f18d83030109bd9
236
cpp
C++
chapter-11/11.21.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-11/11.21.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-11/11.21.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
// map<string, size_t> word_count // string word // while(cin >> word) ++word_count.insert({word, 0}).first->second; // see the privileges of operators in P147 // while(cin >> word) ++((((word_count.insert)({word, 0})).first)->second)
33.714286
74
0.661017
zero4drift
6bf0bb379c365859d6061f42d6779c6c8348871b
259
hpp
C++
legacy/include/distconv/tensor/stream.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
legacy/include/distconv/tensor/stream.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
legacy/include/distconv/tensor/stream.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#pragma once namespace distconv { namespace tensor { template <typename Allocator> struct Stream; struct DefaultStream { DefaultStream() = default; DefaultStream(int v) {} static DefaultStream value; }; } // namespace tensro } // namespae distconv
14.388889
29
0.733591
benson31
6bf3f4b4e1214252547d37aa3bf1d9163f695b8b
254
cpp
C++
day-10-4-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-10-4-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-10-4-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
//字符串数组 #include <stdio.h> int main(void) { int i; char cs[][6] = { "turbo","naaaa","dohc" }; //此处的数组[6]则是限制括号内的数字 for (i = 0; i < 3; i++) printf("cs[%d] = \"%s\"\n", i, cs[i]); //其实那个\"%s\"的作用就是为了多出 " "的,因为单个斜杠不显示 return 0; }
19.538462
44
0.488189
duasong111
6bf8fca4274fc3f829148363b44e5efb165ce604
8,476
cc
C++
modules/task_1/danshin_g_matrix_max_by_rows/main.cc
Gekata-2/pp_2021_autumn
caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_1/danshin_g_matrix_max_by_rows/main.cc
Gekata-2/pp_2021_autumn
caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/danshin_g_matrix_max_by_rows/main.cc
Gekata-2/pp_2021_autumn
caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Gleb "belgad" Danshin #include <gtest/gtest.h> #include <cstring> #include "../../../modules/task_1/danshin_g_matrix_max_by_rows/matrix_max_by_rows.h" #include <gtest-mpi-listener.hpp> TEST(DanshinGMatrixMaxByRow, ConstMatrixSize5x5) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 5; col_num = 5; matrix = new int[row_num * col_num] { 1, 3, 5, 4, 2, 1, 13, 45, 67, 89, -1, 1, -1, 1, -1, 0, 0, 0, 0, 0, -1, -2, -3, -4, -5 }; answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, ConstMatrixSize10x5) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 10; col_num = 5; matrix = new int[row_num * col_num] { 1, 3, 5, 4, 2, 1, 13, 45, 67, 89, -1, 1, -1, 1, -1, 0, 0, 0, 0, 0, -1, -2, -3, -4, -5, -1, 3, -5, 4, -2, 99, 78, 57, 36, 15, 2, 2, 2, 2, 6, -100000000, 100000000, 0, 0, 0, -1000, 1000, -1000, 1000, -2000 }; answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, ConstMatrixSize5x10) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 5; col_num = 10; matrix = new int[row_num * col_num] { 1, 3, 5, 4, 2, -1, 3, -5, 4, -2, 1, 13, 45, 67, 89, 99, 78, 57, 36, 15, -1, 1, -1, 1, -1, 2, 2, 2, 2, 6, 0, 0, 0, 0, 0, -100000000, 100000000, 0, 0, 0, -1, -2, -3, -4, -5, -1000, 1000, -1000, 1000, -2000 }; answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, ConstMatrixSize10x10) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 10; col_num = 10; matrix = new int[row_num * col_num] { 1, 3, 5, 4, 2, -1, 3, -5, 4, -2, 1, 13, 45, 67, 89, 99, 78, 57, 36, 15, -1, 1, -1, 1, -1, 2, 2, 2, 2, 6, 0, 0, 0, 0, 0, -100000000, 100000000, 0, 0, 0, -1, -2, -3, -4, -5, -1000, 1000, -1000, 1000, -2000, -1, 3, -5, 4, -2, 6, -8, 9, -10, 9, 99, 78, 57, 36, 15, -6, -27, -48, -69, -90, 2, 2, 2, 2, 6, 6, 6, 6, 2, 2, -100000000, 100000000, 0, 0, 0, -100000000, 100000000, -100000000, 100000000, 1000000000, -1000, 1000, -1000, 1000, -2000, -1000, 2000, 1000, -2000, 2000 }; answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, RandMatrixSize100x100) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 100; col_num = 100; matrix = GetRandomMatrix(row_num, col_num); answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, RandMatrixSize250x250) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 250; col_num = 250; matrix = GetRandomMatrix(row_num, col_num); answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, RandMatrixSize250x500) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 250; col_num = 500; matrix = GetRandomMatrix(row_num, col_num); answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, RandMatrixSize500x250) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 500; col_num = 250; matrix = GetRandomMatrix(row_num, col_num); answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } TEST(DanshinGMatrixMaxByRow, RandMatrixSize500x500) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int *matrix = nullptr, row_num = 0, col_num = 0; int *answer_sequence = nullptr, *answer_parallel = nullptr; if (rank == 0) { row_num = 500; col_num = 500; matrix = GetRandomMatrix(row_num, col_num); answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num); } answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num); if (rank == 0) { EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int))); delete [] matrix; delete [] answer_sequence; } delete [] answer_parallel; } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
36.068085
101
0.604412
Gekata-2
6bffc1817191a100adbdbd8d9e9fc9f454789e06
10,343
cpp
C++
includes/textureLoading.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
2
2019-05-20T11:12:07.000Z
2021-03-25T04:24:57.000Z
includes/textureLoading.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
null
null
null
includes/textureLoading.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
null
null
null
#include <textureLoading.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> static unsigned int getint(FILE *fp) { int c, c1, c2, c3; // get 4 bytes c = getc(fp); c1 = getc(fp); c2 = getc(fp); c3 = getc(fp); return ((unsigned int) c) + (((unsigned int) c1) << 8) + (((unsigned int) c2) << 16) + (((unsigned int) c3) << 24); } static unsigned int getshort(FILE *fp) { int c, c1; //get 2 bytes c = getc(fp); c1 = getc(fp); return ((unsigned int) c) + (((unsigned int) c1) << 8); } // quick and dirty bitmap loader...for 24 bit bitmaps with 1 plane only. // See http://www.dcs.ed.ac.uk/~mxr/gfx/2d/BMP.txt for more info. int ImageLoad(const char *filename, Image *image) { FILE *file; unsigned long size; // size of the image in bytes. unsigned long i; // standard counter. unsigned short int planes; // number of planes in image (must be 1) unsigned short int bpp; // number of bits per pixel (must be 24) char temp; // used to convert bgr to rgb color. // make sure the file is there. if ((file = fopen(filename, "rb"))==NULL) { printf("File Not Found : %s\n",filename); return 0; } // seek through the bmp header, up to the width/height: fseek(file, 18, SEEK_CUR); // No 100% errorchecking anymore!!! // read the width image->sizeX = getint (file); //printf("Width of %s: %lu\n", filename, image->sizeX); // read the height image->sizeY = getint (file); //printf("Height of %s: %lu\n", filename, image->sizeY); // calculate the size (assuming 24 bits or 3 bytes per pixel). size = image->sizeX * image->sizeY * 3; // read the planes planes = getshort(file); if (planes != 1) { printf("Planes from %s is not 1: %u\n", filename, planes); return 0; } // read the bpp bpp = getshort(file); if (bpp != 24) { printf("Bpp from %s is not 24: %u\n", filename, bpp); return 0; } // seek past the rest of the bitmap header. fseek(file, 24, SEEK_CUR); // read the data. image->data = (char *) malloc(size); if (image->data == NULL) { printf("Error allocating memory for color-corrected image data"); return 0; } if ((i = fread(image->data, size, 1, file)) != 1) { printf("Error reading image data from %s.\n", filename); return 0; } for (i=0;i<size;i+=3) { // reverse all of the colors. (bgr -> rgb) temp = image->data[i]; image->data[i] = image->data[i+2]; image->data[i+2] = temp; } // we're done. return 1; } // Load Bitmaps And Convert To Textures unsigned int LoadGLTextures(const char* path) { // Load Texture Image *image1; unsigned int texterID; // allocate space for texture image1 = (Image *) malloc(sizeof(Image)); if (image1 == NULL) { printf("Error allocating space for image"); exit(0); } if (!ImageLoad(path, image1)) { exit(1); } // Create Textures glGenTextures(1, &texterID); // texture 1 (poor quality scaling) glBindTexture(GL_TEXTURE_2D, texterID); // 2d texture (x and y size) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // 2d texture, level of detail 0 (normal), 3 components (red, green, blue), x size from image, y size from image, // border 0 (normal), rgb color data, unsigned byte data, and finally the data itself. glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data); return texterID; }; GLuint loadTex_stb(const char *path) { int my_image_width, my_image_height; unsigned char* my_image_data; if(stbi_load(path, &my_image_width, &my_image_height, NULL, 4)) my_image_data = stbi_load(path, &my_image_width, &my_image_height, NULL, 4); else cout<<"Can't find file > :"<<path<<endl; // Turn the RGBA pixel data into an OpenGL texture: GLuint my_opengl_texture; glGenTextures(1, &my_opengl_texture); glBindTexture(GL_TEXTURE_2D, my_opengl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, my_image_width, my_image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, my_image_data); stbi_set_flip_vertically_on_load(true); return my_opengl_texture; } GLuint logl_loadTex_stb(const char *path, bool gammaCorrection) { GLuint textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0); if (data) { GLenum internalFormat; GLenum dataFormat; if (nrComponents == 1) { internalFormat = dataFormat = GL_RED; } else if (nrComponents == 3) { internalFormat = gammaCorrection ? GL_SRGB : GL_RGB; dataFormat = GL_RGB; } else if (nrComponents == 4) { internalFormat = gammaCorrection ? GL_SRGB_ALPHA : GL_RGBA; dataFormat = GL_RGBA; } glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, dataFormat == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, dataFormat == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; } unsigned int logl_loadTex_stb(char const * path) { unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; } GLuint loadTex_stb(const char *path, int &my_image_width, int &my_image_height) { //int my_image_width, my_image_height; unsigned char* my_image_data; if(stbi_load(path, &my_image_width, &my_image_height, NULL, 4)) my_image_data = stbi_load(path, &my_image_width, &my_image_height, NULL, 4); else cout<<"Can't find file > :"<<path<<endl; stbi_set_flip_vertically_on_load(false); // Turn the RGBA pixel data into an OpenGL texture: GLuint my_opengl_texture; glGenTextures(1, &my_opengl_texture); glBindTexture(GL_TEXTURE_2D, my_opengl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, my_image_width, my_image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, my_image_data); return my_opengl_texture; } unsigned int loadCubemap(vector<std::string> faces) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); stbi_set_flip_vertically_on_load(false); int width, height, nrChannels; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return textureID; }
34.023026
246
0.685101
MuUusta
d4031270386dc644c650974438d059ec12860c2d
666
cpp
C++
solutions/25.reverse-nodes-in-k-group.228894559.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/25.reverse-nodes-in-k-group.228894559.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/25.reverse-nodes-in-k-group.228894559.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { int c = k; ListNode *temp = head; while (c && temp) { c--; temp = temp->next; } if (c) return head; ListNode *first = head; ListNode *t1 = NULL; for (int i = 0; i < k && head != NULL; i++) { ListNode *t2 = head->next; head->next = t1; t1 = head; head = t2; } if (head) { first->next = reverseKGroup(head, k); } return t1; } };
16.65
50
0.493994
satu0king
d4056c16701e69db4fbd6b7b219e5fbbe02b674d
3,358
cpp
C++
qt-ticket/src/useruletablemodel.cpp
waitWindComing/QT
c8401679b7265785ec8c7e97eea7e1e37631f37d
[ "Apache-2.0" ]
null
null
null
qt-ticket/src/useruletablemodel.cpp
waitWindComing/QT
c8401679b7265785ec8c7e97eea7e1e37631f37d
[ "Apache-2.0" ]
null
null
null
qt-ticket/src/useruletablemodel.cpp
waitWindComing/QT
c8401679b7265785ec8c7e97eea7e1e37631f37d
[ "Apache-2.0" ]
null
null
null
#include "useruletablemodel.h" #include <qDebug> UseRuleTableModel::UseRuleTableModel(const QList<UseRule *> &useRules, QObject* parent) :_useRules(useRules), QAbstractTableModel(parent) { _header << trUtf8("名称") << trUtf8("最低消费") << trUtf8("最大抵扣") << trUtf8("类型") << trUtf8("信息") << trUtf8("选择"); } int UseRuleTableModel::rowCount(const QModelIndex& parent) const { return _useRules.size(); } int UseRuleTableModel::columnCount(const QModelIndex& parent) const { return 6; } QVariant UseRuleTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (section < 6 && role == Qt::DisplayRole) { return _header[section]; } else { return QVariant(); } } QVariant UseRuleTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= _useRules.size()) return QVariant(); UseRule *useRule = _useRules.at(index.row()); if (role == Qt::DisplayRole) { if (index.column() == 0) { return useRule->getRuleName(); } else if (index.column() == 1) { QString rst; return rst.setNum(useRule->getLeastConsume() / 100.0, 'f', 2); } else if (index.column() == 2) { QString rst; return rst.setNum(useRule->getMaxDeduction() / 100.0, 'f', 2); } else if (index.column() == 3) { if (UseRule::Discount == useRule->getType()) { return trUtf8("折扣券"); } else { return trUtf8("代金券"); } } else if (index.column() == 4) { QString ruleinfo; if (UseRule::Discount == useRule->getType()) { if (useRule->getDiscountType() == 0) { ruleinfo = QString("%1:%2").arg(trUtf8("折扣转换系数")).arg(useRule->getConvertRate()); } else { ruleinfo = QString("%1:%2%").arg(trUtf8("新折扣率")).arg(useRule->getDiscount()); } } else { ruleinfo = QString("%1:%2%").arg(trUtf8("抵扣率")).arg(useRule->getRate()); } return ruleinfo; } else { // radiobox return QVariant(); } } if (role == Qt::CheckStateRole) { return useRule->getCheckState(); } return QVariant(); } Qt::ItemFlags UseRuleTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; if (index.column() == 5) { return Qt::ItemIsEnabled | Qt::ItemIsEditable; } else { return Qt::ItemIsEnabled; } } bool UseRuleTableModel::setData ( const QModelIndex & index, const QVariant & value, int role ) { Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); UseRule *useRule = _useRules.at(index.row()); useRule->setCheckState(state); emit dataChanged(createIndex(index.row(), 0), createIndex(index.row(), 6)); return true; } void UseRuleTableModel::clearChecked() { for (QList<UseRule *>::const_iterator i = _useRules.begin(); i != _useRules.end(); ++i) { (*i)->setCheckState(Qt::Unchecked); } } void UseRuleTableModel::itemAppended() { beginInsertRows(QModelIndex(), _useRules.size(), _useRules.size()); endInsertRows(); } void UseRuleTableModel::refresh() { emit layoutChanged(); }
29.45614
112
0.581298
waitWindComing
d40960e250f4afb2536688a7804e145f19e73e1c
9,716
cpp
C++
src/CCsharpCounter.cpp
dutchedge/Unified_Code_Count
8c2d12942595dc11f13f36e2282e3821707b8ffd
[ "DOC" ]
12
2015-06-08T16:19:33.000Z
2020-02-11T13:40:58.000Z
src/CCsharpCounter.cpp
dutchedge/Unified_Code_Count
8c2d12942595dc11f13f36e2282e3821707b8ffd
[ "DOC" ]
null
null
null
src/CCsharpCounter.cpp
dutchedge/Unified_Code_Count
8c2d12942595dc11f13f36e2282e3821707b8ffd
[ "DOC" ]
6
2016-09-09T11:55:19.000Z
2020-07-08T16:04:04.000Z
//! Code counter class methods for the C# language. /*! * \file CCsharpCounter.cpp * * This file contains the code counter class methods for the C# language. */ #include "CCsharpCounter.h" /*! * Constructs a CCsharpCounter object. */ CCsharpCounter::CCsharpCounter() { classtype = CSHARP; language_name = "C#"; isVerbatim = false; file_extension.push_back(".cs"); directive.push_back("#define"); directive.push_back("#else"); directive.push_back("#elif"); directive.push_back("#endif"); directive.push_back("#endregion"); directive.push_back("#error"); directive.push_back("#if"); directive.push_back("#line"); directive.push_back("#region"); directive.push_back("#undef"); directive.push_back("#warning"); data_name_list.push_back("abstract"); data_name_list.push_back("bool"); data_name_list.push_back("byte"); data_name_list.push_back("char"); data_name_list.push_back("class"); data_name_list.push_back("const"); data_name_list.push_back("decimal"); data_name_list.push_back("delegate"); data_name_list.push_back("double"); data_name_list.push_back("enum"); data_name_list.push_back("event"); data_name_list.push_back("explicit"); data_name_list.push_back("extern"); data_name_list.push_back("float"); data_name_list.push_back("implicit"); data_name_list.push_back("int"); data_name_list.push_back("interface"); data_name_list.push_back("internal"); data_name_list.push_back("long"); data_name_list.push_back("namespace"); data_name_list.push_back("object"); data_name_list.push_back("operator"); data_name_list.push_back("override"); data_name_list.push_back("private"); data_name_list.push_back("protected"); data_name_list.push_back("public"); data_name_list.push_back("readonly"); data_name_list.push_back("sbyte"); data_name_list.push_back("sealed"); data_name_list.push_back("short"); data_name_list.push_back("static"); data_name_list.push_back("string"); data_name_list.push_back("struct"); data_name_list.push_back("uint"); data_name_list.push_back("ulong"); data_name_list.push_back("unsafe"); data_name_list.push_back("ushort"); data_name_list.push_back("using"); data_name_list.push_back("virtual"); data_name_list.push_back("void"); data_name_list.push_back("volatile"); exec_name_list.push_back("as"); exec_name_list.push_back("base"); exec_name_list.push_back("break"); exec_name_list.push_back("case"); exec_name_list.push_back("catch"); exec_name_list.push_back("checked"); exec_name_list.push_back("continue"); exec_name_list.push_back("default"); exec_name_list.push_back("do"); exec_name_list.push_back("else"); exec_name_list.push_back("finally"); exec_name_list.push_back("fixed"); exec_name_list.push_back("for"); exec_name_list.push_back("foreach"); exec_name_list.push_back("goto"); exec_name_list.push_back("if"); exec_name_list.push_back("lock"); exec_name_list.push_back("new"); exec_name_list.push_back("return"); exec_name_list.push_back("sizeof"); exec_name_list.push_back("stackalloc"); exec_name_list.push_back("switch"); exec_name_list.push_back("this"); exec_name_list.push_back("throw"); exec_name_list.push_back("try"); exec_name_list.push_back("typeof"); exec_name_list.push_back("unchecked"); exec_name_list.push_back("while"); math_func_list.push_back("abs"); math_func_list.push_back("cbrt"); math_func_list.push_back("ceil"); math_func_list.push_back("copysign"); math_func_list.push_back("erf"); math_func_list.push_back("erfc"); math_func_list.push_back("exp"); math_func_list.push_back("exp2"); math_func_list.push_back("expm1"); math_func_list.push_back("fabs"); math_func_list.push_back("floor"); math_func_list.push_back("fdim"); math_func_list.push_back("fma"); math_func_list.push_back("fmax"); math_func_list.push_back("fmin"); math_func_list.push_back("fmod"); math_func_list.push_back("frexp"); math_func_list.push_back("hypot"); math_func_list.push_back("ilogb"); math_func_list.push_back("ldexp"); math_func_list.push_back("lgamma"); math_func_list.push_back("llrint"); math_func_list.push_back("lrint"); math_func_list.push_back("llround"); math_func_list.push_back("lround"); math_func_list.push_back("modf"); math_func_list.push_back("nan"); math_func_list.push_back("nearbyint"); math_func_list.push_back("nextafter"); math_func_list.push_back("nexttoward"); math_func_list.push_back("pow"); math_func_list.push_back("remainder"); math_func_list.push_back("remquo"); math_func_list.push_back("rint"); math_func_list.push_back("round"); math_func_list.push_back("scalbln"); math_func_list.push_back("scalbn"); math_func_list.push_back("sqrt"); math_func_list.push_back("tgamma"); math_func_list.push_back("trunc"); trig_func_list.push_back("cos"); trig_func_list.push_back("cosh"); trig_func_list.push_back("sin"); trig_func_list.push_back("sinh"); trig_func_list.push_back("tan"); trig_func_list.push_back("tanh"); trig_func_list.push_back("acos"); trig_func_list.push_back("acosh"); trig_func_list.push_back("asinh"); trig_func_list.push_back("atanh"); trig_func_list.push_back("asin"); trig_func_list.push_back("atan"); trig_func_list.push_back("atan2"); log_func_list.push_back("log"); log_func_list.push_back("log10"); log_func_list.push_back("log1p"); log_func_list.push_back("log2"); log_func_list.push_back("logb"); cmplx_preproc_list.push_back("define"); cmplx_preproc_list.push_back("elif"); cmplx_preproc_list.push_back("else"); cmplx_preproc_list.push_back("endif"); cmplx_preproc_list.push_back("endregion"); cmplx_preproc_list.push_back("error"); cmplx_preproc_list.push_back("if"); cmplx_preproc_list.push_back("import"); cmplx_preproc_list.push_back("line"); cmplx_preproc_list.push_back("region"); cmplx_preproc_list.push_back("undef"); cmplx_preproc_list.push_back("warning"); cmplx_cyclomatic_list.push_back("if"); cmplx_cyclomatic_list.push_back("case"); cmplx_cyclomatic_list.push_back("while"); cmplx_cyclomatic_list.push_back("for"); cmplx_cyclomatic_list.push_back("foreach"); cmplx_cyclomatic_list.push_back("catch"); cmplx_cyclomatic_list.push_back("?"); } /*! * Perform preprocessing of file lines before counting. * * \param fmap list of file lines * * \return method status */ int CCsharpCounter::PreCountProcess(filemap* fmap) { size_t i; bool found; filemap::iterator fit; for (fit = fmap->begin(); fit != fmap->end(); fit++) { if (fit->line.empty()) continue; // check for parenthesis within attribute brackets [...()] found = false; for (i = 0; i < fit->line.length(); i++) { if (fit->line[i] == '[') found = true; else if (found) { if (fit->line[i] == ']') found = false; else if (fit->line[i] == '(' || fit->line[i] == ')') fit->line[i] = '$'; } } } return 0; } /*! * Replaces up to ONE quoted string inside a string starting at idx_start. * * \param strline string to be processed * \param idx_start index of line character to start search * \param contd specifies the quote string is continued from the previous line * \param CurrentQuoteEnd end quote character of the current status * * \return method status */ int CCsharpCounter::ReplaceQuote(string &strline, size_t &idx_start, bool &contd, char &CurrentQuoteEnd) { size_t idx_end, idx_quote, idx_verbatim; char noQuoteEscapeFront = 0x00; if (contd) { idx_start = 0; if (strline[0] == CurrentQuoteEnd) { if (!isVerbatim || (strline.length() < 2) || (strline[1] != '"')) { idx_start = 1; contd = false; return 1; } } else strline[0] = '$'; } else { // accommodate C# verbatim string (e.g. @"\") isVerbatim = false; idx_verbatim = strline.find_first_of("@"); if (idx_verbatim != string::npos && idx_verbatim + 1 == idx_start) isVerbatim = true; // handle two quote chars in some languages, both " and ' may be accepted idx_start = FindQuote(strline, QuoteStart, idx_start, QuoteEscapeFront); if (idx_start != string::npos) { idx_quote = QuoteStart.find_first_of(strline[idx_start]); CurrentQuoteEnd = QuoteEnd[idx_quote]; } else { idx_start = strline.length(); return 0; } } // accommodate C# verbatim string (e.g. @"\") if (isVerbatim) // verbatim string idx_end = CUtil::FindCharAvoidEscape(strline, CurrentQuoteEnd, idx_start + 1, noQuoteEscapeFront); else idx_end = CUtil::FindCharAvoidEscape(strline, CurrentQuoteEnd, idx_start + 1, QuoteEscapeFront); if (idx_end == string::npos) { idx_end = strline.length() - 1; strline.replace(idx_start + 1, idx_end - idx_start, idx_end - idx_start, '$'); contd = true; idx_start = idx_end + 1; } else { if ((isVerbatim && (strline.length() > idx_end + 1) && (strline[idx_end+1] == '"')) || ((QuoteEscapeRear) && (strline.length() > idx_end + 1) && (strline[idx_end+1] == QuoteEscapeRear))) { strline[idx_end] = '$'; strline[idx_end+1] = '$'; } else { isVerbatim = false; contd = false; strline.replace(idx_start + 1, idx_end - idx_start - 1, idx_end - idx_start - 1, '$'); idx_start = idx_end + 1; } } return 1; } /*! * Constructs a CCsharpHtmlCounter object. */ CCsharpHtmlCounter::CCsharpHtmlCounter() { classtype = CSHARP_HTML; language_name = "C#/HTML"; file_extension.clear(); file_extension.push_back(".*cshtm"); } /*! * Constructs a CCsharpXmlCounter object. */ CCsharpXmlCounter::CCsharpXmlCounter() { classtype = CSHARP_XML; language_name = "C#/XML"; file_extension.clear(); file_extension.push_back(".*csxml"); } /*! * Constructs a CCsharpAspCounter object. */ CCsharpAspCounter::CCsharpAspCounter() { classtype = CSHARP_ASP_S; language_name = "C#/ASPNET"; file_extension.clear(); file_extension.push_back(".*csasps"); }
28.576471
104
0.729621
dutchedge
d40c7c2597e6bd0f2c60fbcb6c61c868c7ab704d
34,479
hpp
C++
externals/source/testdog/pack/inc/testdog/runner.hpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
externals/source/testdog/pack/inc/testdog/runner.hpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
externals/source/testdog/pack/inc/testdog/runner.hpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // PROJECT : TEST-DOG // FILENAME : testdog/runner.hpp // DESCRIPTION : Test runner class. // COPYRIGHT : Andy Thomas (C) 2010 //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // LICENSE //--------------------------------------------------------------------------- // This file is part of the "TEST-DOG" program. // TEST-DOG is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // TEST-DOG is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with TEST-DOG. If not, see <http://www.gnu.org/licenses/>. //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // HEADER GUARD //--------------------------------------------------------------------------- #ifndef TDOG_RUNNER_H #define TDOG_RUNNER_H //--------------------------------------------------------------------------- // INCLUDES //--------------------------------------------------------------------------- #include "private/basic_test.hpp" #include "private/test_case.hpp" #include <string> #include <vector> #include <map> #include <ctime> #include <ostream> //--------------------------------------------------------------------------- // DOCUMENTATION //--------------------------------------------------------------------------- //! \file testdog/runner.hpp //! \brief This file provides the testdog::runner class and associated types. //! \sa testdog::runner //--------------------------------------------------------------------------- // DECLARATIONS //--------------------------------------------------------------------------- // Namespace namespace testdog { //! \brief An enumerated type used to designate the style of test run reports. //! \details Test reports are subdivided according to their "log level", and //! are considered to be verbose or standard. //! //! Standard reports contain only summary information pertaining to test //! cases which pass, but further details are provided for those tests which //! fail. Whereas verbose reports contain the same detailed trace information //! irrespective of whether the test case passed or not. //! \sa runner::set_report_style(), runner::generate_report() enum report_style_t { RS_NONE = 0, //!< None (no report is generated). RS_TEXT_STD, //!< Human readable test report. RS_TEXT_VERBOSE, //!< Human readable test report (verbose). RS_XML, //!< XML test report (verbose). RS_HTML_STD, //!< HTML test report. RS_HTML_VERBOSE, //!< HTML test report (verbose). RS_HTML_SUMMARY, //!< HTML test report (summary only). }; //! \brief An enumerated type used to designate what tests should be run. //! \sa runner::run() enum run_scope_t { RUN_NONE = 0, //!< Run none (no tests were run). RUN_ALL, //!< Run all tests. RUN_SUITE, //!< Run only the specified test suite. RUN_TEST //!< Run only the specified test case. }; //! \brief An enumerated type used to designate a required statistic from //! the last test run. //! \sa runner::stat_result() enum result_stat_t { ST_RAN = 0, //!< Number of tests executed in the test run. ST_SKIPPED, //!< Number of tests skipped (i.e. were disabled). ST_PASSED, //!< Number of tests that passed. ST_FAILED, //!< Number of tests that failed. ST_ERRORS, //!< Number of tests which implementation errors. ST_PASS_RATE //!< Percentage of tests that passed. }; //! \brief An enumerated type used to provide the a test case result. //! \details The runner::test_result() method can be used to query the //! result state of any test in the runner. //! \sa runner::test_result() enum test_result_t { TR_NOT_EXIST = 0, //!< The test case does not exist in the runner. TR_NOT_RUN, //!< Test was not run. TR_PASSED, //!< All test conditions passed OK. TR_FAILED, //!< One or more test conditions failed. TR_TEST_ERROR //!< The test failed because of a possible implementation error. }; // Forward declaration class basic_reporter; //--------------------------------------------------------------------------- // MACROS //--------------------------------------------------------------------------- //! \brief Synonym for: testdog::runner::global() //! \details This macro is provided for convenience. The following two //! lines of code are equivalent: //! //! Example: //! //! \code //! // 1. Run all tests //! int rslt = testdog::runner::global().run(); //! ... //! // 2. Run all tests //! int rslt = TDOG().run(); //! \endcode //! \sa runner::global() #define TDOG() testdog::runner::global() //--------------------------------------------------------------------------- // CLASS runner //--------------------------------------------------------------------------- //! \class runner //! \brief The runner class is used to run test cases and collate //! result information. //! \details The runner cannot be instantiated directly, rather access to a //! global instance is granted through its singleton method: runner::global(). class runner { protected: // Protected properties std::string m_project_name; std::string m_project_version; report_style_t m_report_style; std::string m_report_charset; std::string m_html_report_stylesheet; bool m_report_loc; int m_text_report_break_width; bool m_html_report_author_col; int m_tests_ran; int m_tests_skipped; int m_tests_passed; int m_tests_failed; int m_test_errors; run_scope_t m_run_scope; std::time_t m_start_time; std::time_t m_end_time; bool m_contains_suites; int m_global_time_limit; std::string m_prev_suite_name; std::vector<basic_test*> m_basic_tests; typedef std::map<std::string, bool> suite_state_t; suite_state_t m_suite_state_map; // Protected methods basic_test* m_find_tc(const std::string& tname) const; bool m_suite_enabled(const std::string& sname) const; basic_reporter* m_create_reporter(report_style_t rs) const; void m_clear_results(); // Hidden contructor runner(); public: //! @name Class Instantiation //! @{ //! \brief Destructor. virtual ~runner(); //! \brief Singleton access //! \details There is no public constructor for this class, and all //! access is via this singleton method to a single class instance. //! //! Example: //! //! \code //! // Run all tests //! testdog::runner::global().run(); //! \endcode //! //! \return Reference to global instance static runner& global(); static void create(); static void destroy(); //! @} //! @name Project Information //! @{ //! \brief Returns the user supplied name of the project under test. //! \details The project name is an optional string which is displayed //! in test report outputs. //! \return Project name string //! \sa set_project_name(), project_version() std::string project_name() const; //! \brief Sets the name of the project under test. //! \details The project name is an optional string which is displayed //! in test report outputs. //! //! Example: //! \code //! testdog::runner().global().set_project_name("smppd"); //! \endcode //! \param[in] pname Project name //! \sa project_name(), set_project_version() void set_project_name(const std::string& pname); //! \brief Returns the user supplied version string for the test project. //! \details The project version is an optional string which is displayed //! in test report outputs. //! \return Project version string //! \sa set_project_version(), project_name() std::string project_version() const; //! \brief Sets the version string of the project under test. //! \details The project version is an optional string which is displayed //! in test report outputs. //! //! Example: //! /code //! testdog::runner().global().set_project_version("3.1.6"); //! /endcode //! \param[in] ver Project version string //! \sa project_version(), set_project_name() void set_project_version(const std::string& ver); //! @} //! @name Test Registration //! @{ //! \brief Explicitly registers a test case instance with the runner. //! \details Normally there is no need to call this method, as test cases //! automatically register themselves with the global runner instance //! when they are instantiated. //! //! However, it is possible to disable the automatic registration of //! test cases by pre-defining the TDOG_DISABLE_AUTO_REG macro. In this case, //! the register_test() method must be used to add tests to the runner //! explicitly. In addition, the TDOG_TEST_REFINST() macro must be used to //! reference the underlying test case implementation instance, as follows: //! //! \code //! #define TDOG_DISABLE_AUTO_REG //! #include <testdog/unit_test.hpp> //! //! // Define test //! TDOG_TEST_CASE(some_test) //! { //! ... //! } //! //! int main(int argc, char **argv) //! { //! // Explicitly register the test //! testdog::runner::global().register_test(TDOG_TEST_REFINST(some_test)); //! ... //! } //! \endcode //! //! If the test case belongs within a test suite, you should use the //! the suite name as a namespaced prefix. For example: //! //! \code //! testdog::runner::global().register_test(TDOG_TEST_REFINST(suite_name::some_test)); //! \endcode //! //! With self-registration, tests are run in the order that they are //! declared. One possible benefit of registering tests explicitly, therefore, //! is that it provides some control over the run order. //! \param[in] tc Underlying test instance //! \sa TDOG_TEST_REFINST(), registered_count() void register_test(test_case& tc); //! \overload //! \param[in] tc Underlying test instance void register_test(basic_test& tc); //! \brief Returns the number of tests registered in the runner. //! \return Number of tests //! \sa register_test(), stat_result() int registered_count() const; //! \brief Clears all tests registered with the runner. //! \sa register_test() void clear_tests(); //! \brief Returns whether the test case with the given name exists. //! \details The test name should be fully qualified with the suite name. //! //! For example: //! \code //! bool ex = testdog::runner::global().test_exists("SUITE_NAME::TEST_NAME"); //! \endcode //! //! Test names are case sensitive. //! //! If the test case is not part of a suite, just the test name should //! be used. //! \param[in] tname Test case name //! \return Boolean result //! \sa suite_exists() bool test_exists(const std::string& tname) const; //! \brief Returns whether the test suite with the given name exists. //! \details Suite names are case sensitive. //! \param[in] sname Suite name //! \return Boolean result //! \sa test_exists(), contains_suites() bool suite_exists(const std::string& sname) const; //! \brief Returns true if one or more tests were declared within //! a test suite. //! \return Boolean result //! \sa suite_exists() bool contains_suites() const; //! \brief Enumerates the fully qualified names of all test cases registered //! with the runner. //! \details The results are returned using "rslt_out", which //! supplies a vector array of std::string. The rslt_out array will //! first be emptied before being re-populated with test case names. //! //! Test names are provided in the order which they were originally //! registered, which is also their run order. //! \param[out] rslt_out A vector array of strings used to retrieve results //! \return A reference to rslt_out //! \sa enum_suite_names() std::vector<std::string>& enum_test_names( std::vector<std::string>& rslt_out) const; //! \brief Enumerates the names of all test suites in the runner. //! \details The results are returned using "rslt_out", which //! supplies a vector array of std::string. The rslt_out array will //! first be emptied before being repopulated with test suite names. //! //! An empty string will be used to designate the default suit, i.e. //! where test cases are declared outside of a test suite. //! \param[out] rslt_out A vector array of strings used to retrieve results //! \return A reference to rslt_out //! \sa enum_test_names() std::vector<std::string>& enum_suite_names( std::vector<std::string>& rslt_out) const; //! @} //! @name Disabling Tests //! @{ //! \brief Returns whether a test case with the given name is enabled. //! \details Tests which have been disabled will not be executed by the runner. //! //! Use the fully qualified test name. For example: //! //! \code //! bool en = testdog::runner::global().test_enabled("SUITE_NAME::TEST_NAME"); //! \endcode //! //! Test names are case sensitive. //! //! If the test case is not part of a suite, just the test name should be //! used without any namespace. //! //! The default enabled state for tests is true. The result will be false //! if a test of the given name does not exist. //! //! Note. The enabled state of test cases and their suites are independent, //! and both must be enabled for a test to run. //! \param[in] tname Test case name //! \return Boolean result value //! \sa set_test_enabled(), suit_enabled(), test_exists() bool test_enabled(const std::string& tname) const; //! \brief Allows an individual test case with the given name to be disabled //! (or re-enabled). //! \details Tests which have been disabled will not be executed by the runner. //! //! Use the fully qualified test name. For example: //! //! \code //! testdog::runner::global().set_test_enabled("SUITE_NAME::TEST_NAME", false); //! \endcode //! //! Test names are case sensitive. //! //! If the test case is not part of a suite, just the test name should be //! used without any namespace. //! //! The default enabled state for tests is true. This call does nothing if //! a test of the given name does not exist. //! //! Note. The enabled state of test cases and their suites are independent, //! and both must be enabled for a test to run. //! \param[in] tname Test case name //! \param[in] e Enabled flag //! \sa test_enabled(), set_all_tests_enabled(), set_suit_enabled(), //! test_exists() void set_test_enabled(const std::string& tname, bool e); //! \brief Sets the enabled states for all tests (in all suites). //! \param[in] e Enabled flag //! \sa set_all_suites_enabled(), set_test_enabled() void set_all_tests_enabled(bool e); //! \brief Returns whether the test suite with the given name is enabled. //! \details Tests belonging to a disabled suite will not be executed by //! the runner. //! //! When calling this method, use the fully qualified test name. For example: //! //! \code //! bool en = testdog::runner::global().suite_enabled("SUITE_NAME"); //! \endcode //! //! The default enabled state for suites is true. Suite names are case //! sensitive. The result will be false if a suite of the given name does //! not exist. //! //! Note. The enabled state of test cases and their suites are independent, //! and both must be enabled for a test to run. //! \param[in] sname Suite name //! \return Boolean result value //! \sa set_suite_enabled(), test_enabled(), suit_exists() bool suite_enabled(const std::string& sname) const; //! \brief Allows the test suite with the given name to be disabled //! (or re-enabled). //! \details Tests belonging to a disabled suite will not be executed by //! the runner. //! //! When calling this method, use the fully qualified test name. For example: //! //! \code //! bool en = testdog::runner::global().suite_enabled("SUITE_NAME"); //! \endcode //! //! The default enabled state for suites is true. Suite names are case //! sensitive. This call does nothing if a suite of the given name does //! not exist. The default suite state can be set by using an empty string //! ("") for its name. //! //! Note. The enabled state of test cases and their suites are independent, //! and both must be enabled for a test to run. //! \param[in] sname Suite name //! \param[in] e Enabled flag //! \sa suite_enabled(), set_all_suites_enabled(), set_test_enabled(), //! suite_exists() void set_suite_enabled(const std::string& sname, bool e); //! \brief Sets the enabled states for all test suites. //! \param[in] e Enabled flag //! \sa set_all_tests_enabled(), set_suite_enabled() void set_all_suites_enabled(bool e); //! @} //! @name Running Tests //! @{ //! \brief Run all tests, or just those specified. //! \details The "scope" parameter defines the scope of the test run, //! and may be one of the following values: //! - RUN_NONE - Run none (no tests were run). //! - RUN_ALL - Run all tests. //! - RUN_SUITE - Run only the specified test suite. //! - RUN_TEST - Run only the specified test case. //! . //! The name parameter supplies the suite name if the scope is RUN_SUITE, //! or the fully qualified test name if RUN_TEST. It is ignored for //! the RUN_ALL scope. //! //! The run() method does nothing if RUN_NONE is specified--this is really //! a result value for use with the run_scope() method. //! //! Both scope and name have default values so that calling run() without //! any parameters will execute all tests. For example, to run all tests //! simply call: //! //! \code //! return testdog::runner::global().run(); //! \endcode //! //! To run an individual test, call: //! //! \code //! testdog::runner::global().run(RUN_TEST, "SUITE_NAME::TEST_NAME"); //! \endcode //! //! To run a single suite, use RUN_SUITE and supply the suite name. Use //! an empty string to run only the tests in the default suite, i.e. those //! tests declared outside of any TDOG_TEST_SUITE() macro. //! //! Test and suite names are case sensitive. //! //! The return value gives the number of test cases which failed, or had //! errors. The value will be 0 if all test cases ran successfully without //! asserting failures or test errors. If, however, no tests were run, //! the return value will be -1, rather than 0. This distinguishes a //! successful test run from one that doesn't actually test anything. //! This may occur if all test cases are disabled or if no //! tests have been registered with the runner. //! \return Number of test failures, or -1 if no tests performed //! \param[in] scope Scope of tests to run //! \param[in] name Name of suite or individual test case //! \sa test_result(), stat_result(), run_scope() int run(run_scope_t scope = RUN_ALL, const std::string& name = ""); //! \brief Returns the "scope" used in the last call to the run() //! method. //! \details If run() was never called, the return value is RUN_NONE. //! \return Last run scope value //! \sa run() run_scope_t run_scope() const; //! \brief Returns the global time limit for test cases in seconds. //! \details The global test contraint is the maximum amount of time //! that individual test cases can take to complete. //! If any test case takes longer than this value, it will be deemed to //! have failed. A value of 0, the default, disables the global time //! constaint. //! //! Time constraints may also be applied to test cases on an individual //! basis, and where a test case has its a local time limit defined, it will //! be used in preference to the global one. //! \return Time limit applied to all test cases //! \sa set_global_time_limit() int global_time_limit() const; //! \brief Sets the global time limit for test cases in seconds. //! \details The global test contraint is the maximum amount of time //! that individual test cases can take to complete. //! If any test case takes longer than this value, it will be deemed to //! have failed. A value of 0, the default, disables the global time //! constaint. //! //! Time constraints may also be applied to test cases on an individual //! basis, and where a test case has its a local time limit defined, it will //! be used in preference to the global one. //! \param[in] gc_sec Time limit in seconds //! \sa global_time_limit() void set_global_time_limit(int gc_sec); //! @} //! @name Generating Test Reports //! @{ //! \brief Returns the report style written to STDOUT during the test run. //! \details This setting controls the style of this report, which can be //! one of: //! - RS_NONE - None (no report is generated). //! - RS_TEXT_STD - Human readable test report. //! - RS_TEXT_VERBOSE - Human readable test report (verbose). //! - RS_XML - XML test report (verbose). //! - RS_HTML_STD - HTML test report. //! - RS_HTML_VERBOSE - HTML test report (verbose). //! - RS_HTML_SUMMARY - HTML test report (summary only). //! . //! A report is generated to STDOUT when one or more test cases are //! run. The default value is RS_TEXT_STD. //! //! Test reports are subdivided according to their "log level", and //! are considered to be verbose or standard. //! //! Standard reports contain only summary information pertaining to test //! cases which pass, but further details are provided for those tests which //! fail. Whereas verbose reports contain the same detailed trace information //! irrespective of whether the test case passed or not. //! \return Stdout reporting style //! \sa set_report_style(), generate_report(), run() report_style_t report_style() const; //! \brief Set the report style written to STDOUT during the test run. //! \details This setting controls the style of this report, which can be //! one of: //! - RS_NONE - None (no report is generated). //! - RS_TEXT_STD - Human readable test report. //! - RS_TEXT_VERBOSE - Human readable test report (verbose). //! - RS_XML - XML test report (verbose). //! - RS_HTML_STD - HTML test report. //! - RS_HTML_VERBOSE - HTML test report (verbose). //! - RS_HTML_SUMMARY - HTML test report (summary only). //! . //! A report is generated to STDOUT when one or more tests are //! run. The default value is RS_TEXT_STD. //! //! Example: //! //! \code //! // Use verbose report //! testdog::runner::global().set_report_style(testdog::RS_TEXT_VERBOSE); //! \endcode //! //! Test reports are subdivided according to their "log level", and //! are considered to be verbose or standard. //! //! Standard reports contain only summary information pertaining to test //! cases which pass, but further details are provided for those tests which //! fail. Whereas verbose reports contain the same detailed trace information //! irrespective of whether the test case passed or not. //! \param[in] rs Report style //! \sa report_style(), generate_report(), run() void set_report_style(report_style_t rs); //! \brief Generates a test report pertaining to the last test run and writes //! it to the supplied output stream. //! \details The report is generated according to the style rs, and //! is useful where test reports in multiple formats are required. Note that //! the report generated with this method would be in addition to that //! written to STDOUT as the the test runs. //! //! Here's an example of where a text style report is written to the STDOUT as //! the tests are executed, and a further XML report is written to file //! after the test run. //! //! \code //! #include <testdog/unit_test.hpp> //! ... //! //! int main(int argc, char **argv) //! { //! // Set default STDOUT report //! testdog::set_report_style(testdog::RS_TEXT_VERBOSE); //! //! // Run all tests //! int rslt = testdog::runner::global().run(); //! //! // Generate XML report file //! std::ofstream file_out; //! file_out.open("test_report.xml"); //! testdog::runner::global().generate_report(file_out, testdog::RS_XML); //! file_out.close(); //! //! return rslt; //! } //! \endcode //! //! Unlike reports normally written to STDOUT during the test run, //! reports generated with a call to generate_report() are not progressive. //! I.e. the report will be realized only after the test run has fully //! completed. //! //! The generate_report() method does nothing if passed the report style //! value RS_NONE. //! \param[in,out] ro Output stream //! \param[in] rs Report style //! \return Reference to output stream //! \sa set_report_style() std::ostream& generate_report(std::ostream& ro, report_style_t rs) const; //! \brief Returns the test report character set encoding. //! \details This is a short string specifying a valid character set encoding //! for use in generating XML and HTML test reports. The value supplied is //! used simply to populate the "charset" field of XML and HTML documents. //! Valid examples include, "utf-8" and "iso-8859-1". //! //! The default value is an empty string which leaves the field unspecified. //! \return Report character set encoding //! \sa set_report_charset(), html_report_stylesheet(), report_style() std::string report_charset() const; //! \brief Sets the test report character set encoding. //! \details This is a short string specifying a valid character set encoding //! for use in generating XML and HTML test reports. The value supplied is //! used simply to populate the "charset" field of XML and HTML documents. //! Valid examples include, "utf-8" and "iso-8859-1". //! //! The default value is an empty string which leaves the field unspecified. //! \param[in] cs Report character set encoding //! \sa report_charset(), set_html_report_stylesheet(), set_report_style() void set_report_charset(const std::string& cs); //! \brief Returns whether filename and line number information is included //! in test reports or not. //! \details The default is true. //! \return Boolean result value //!\sa set_report_loc(), report_style() bool report_loc() const; //! \brief Sets whether filenames and line number information is included //! in test reports or not. //! \details The default is true. //! \param[in] l Location information switch //!\sa set_report_loc(), report_style() void set_report_loc(bool l); //! \brief Returns the number of '-' characters used to create a //! 'breaker line' in the text reporting style. //! \details A 'breaker line' is a sequence of '-' characters used to create //! a visual separator in text report outputs. This setting applies only //! to the RS_TEXT_STD and RS_TEXT_VERBOSE report styles. //! //! A value of 0 will disable the appearence of breaker lines in the output. //! \return Number of characters //! \sa set_text_report_break_width(), report_style() int text_report_break_width() const; //! \brief Sets the number of '-' characters used to create a //! 'breaker line' in the text reporting style. //! \details A 'breaker line' is a sequence of '-' characters used to create //! a visual separator in text report outputs. This setting applies only //! to the RS_TEXT_STD and RS_TEXT_VERBOSE report style. //! //! A value of 0 will disable the appearence of breaker lines in the output. //! \param[in] bw Break width (num of chars) //! \sa text_report_break_width(), set_report_style() void set_text_report_break_width(int bw); //! \brief Gets the stylesheet name for HTML test reports. //! \details The field is used to populate the stylesheet field when //! generating HTML test reports. It is not used for other reports. //! //! The default value is an empty string which means that HTML reports do //! not use a stylesheet. //! \return Stylesheet name //! \sa set_html_report_stylesheet(), report_charset(), report_style() std::string html_report_stylesheet() const; //! \brief Sets the external stylesheet filename for HTML test reports. //! \details The field is used to populate the stylesheet field when //! generating HTML test reports. It is not used for other reports. //! //! Example: //! //! \code //! // Supply the path of a local stylesheet //! testdog::runner::global().set_stylesheet("./styles.css"); //! \endcode //! //! This can be used to override the document's styles. //! //! The default value is an empty string which means that HTML reports do //! not use an external stylesheet. //! \param[in] ss Stylesheet filename //! \sa html_report_stylesheet(), set_report_charset(), set_report_style() void set_html_report_stylesheet(const std::string& ss); //! \brief Returns whether the HTML reports have an "author" column in //! the result tables. //! \details In multi-author environments, it is possible to associate //! author names with test cases. This setting controls whether a separate //! column is used for author names in in HTML reports tables. //! //! This setting applies to the RS_HTML_STD and RS_HTML_VERBOSE and //! RS_HTML_SUMMARY report styles only. The default value is true. //! \return Author flag //! \sa set_html_report_author_col(), text_report_break_width(), report_style() bool html_report_author_col() const; //! \brief Sets whether the HTML reports have an "author" column in //! the result tables. //! \details In multi-author environments, it is possible to associate //! author names with test cases. This setting controls whether a separate //! column is used for author names in in HTML reports tables. //! //! This setting applies to the RS_HTML_STD and RS_HTML_VERBOSE and //! RS_HTML_SUMMARY report styles only. The default value is true. //! \param[in] a Author flag //! \sa html_report_author_col(), set_text_report_break_width(), //! set_report_style() void set_html_report_author_col(bool a); //! @} //! @name Accessing Test Statistics //! @{ //! \brief Returns a statistical result for the last test run. //! \details The result will pertain to the following input values: //! - ST_RAN - Number of tests executed in the test run. //! - ST_SKIPPED - Number of tests skipped (i.e. were disabled). //! - ST_PASSED - Number of tests that passed. //! - ST_FAILED - Number of tests that failed. //! - ST_ERRORS - Number of tests which implementation errors. //! - ST_PASS_RATE - Percentage of tests that passed. //! . //! The return value will be zero if no test run was performed prior to //! calling this method, or -1 if the input value is invalid. //! \param[in] st Required statistic //! \return Statistical count //! \sa test_result(), registered_count() int stat_result(result_stat_t st) const; //! \brief Returns the state of a given test case. //! \details Given a test name, this method returns one of the following //! values: //! - TR_NOT_RUN - Test was not run. //! - TR_PASSED - All test conditions passed OK. //! - TR_FAILED - One or more test conditions failed. //! - TR_TEST_ERROR - The test failed because of a possible implementation error. //! . //! If the test case was declared within a test suite, the suite //! name should prefix the test name with "::" as the separator. If the test //! case is not part of a suite, just the test name should be used. //! //! Example: //! \code //! test_result_t rslt = testdog::runner::global().test_result("SUITE_NAME::TEST_NAME"); //! \endcode //! //! Test names are case sensitive. //! \param[in] tname Test case name //! \return Test result state //! \sa stat_result() test_result_t test_result(const std::string& tname) const; //! \brief Returns the date/time when the last test run started. //! \details The result is in the form of std::time_t and accurate //! only to the second. //! //! If no tests have been run, or the clear_results() method //! was called, the return value is zero. //! \return Test run start time //! \sa end_time(), test_duration() std::time_t start_time() const; //! \brief Returns the date/time when the last test run completed. //! \details The result is in the form of std::time_t and accurate //! only to the second. //! //! If no tests have been run, or the clear_results() method //! was called, the return value is zero. //! \return Test run end time //! \sa start_time(), duration() std::time_t end_time() const; //! \brief Returns the total duration of the last test run in seconds. //! \details If no tests have been run, or the clear_results() method //! was called, the return value is zero. //! \return Duration of the test run //! \sa start_time(), end_time() int duration() const; //! @} }; //--------------------------------------------------------------------------- } // namespace #endif // HEADER GUARD //---------------------------------------------------------------------------
40.326316
91
0.638215
skarab
d40e360b49c504fb7af840b42d9928426493f04a
17,140
cpp
C++
src/Magnum/Implementation/FramebufferState.cpp
costashatz/magnum
8f87ca92334b326a54d27789f370fd8556d557de
[ "MIT" ]
null
null
null
src/Magnum/Implementation/FramebufferState.cpp
costashatz/magnum
8f87ca92334b326a54d27789f370fd8556d557de
[ "MIT" ]
null
null
null
src/Magnum/Implementation/FramebufferState.cpp
costashatz/magnum
8f87ca92334b326a54d27789f370fd8556d557de
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "FramebufferState.h" #include "Magnum/Context.h" #include "Magnum/Extensions.h" #include "Magnum/Renderbuffer.h" #include "State.h" namespace Magnum { namespace Implementation { constexpr const Range2Di FramebufferState::DisengagedViewport; FramebufferState::FramebufferState(Context& context, std::vector<std::string>& extensions): readBinding{0}, drawBinding{0}, renderbufferBinding{0}, maxDrawBuffers{0}, maxColorAttachments{0}, maxRenderbufferSize{0}, #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) maxSamples{0}, #endif #ifndef MAGNUM_TARGET_GLES maxDualSourceDrawBuffers{0}, #endif viewport{DisengagedViewport} { /* Create implementation */ #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) { extensions.emplace_back(Extensions::GL::ARB::direct_state_access::string()); createImplementation = &Framebuffer::createImplementationDSA; createRenderbufferImplementation = &Renderbuffer::createImplementationDSA; } else #endif { createImplementation = &Framebuffer::createImplementationDefault; createRenderbufferImplementation = &Renderbuffer::createImplementationDefault; } /* DSA/non-DSA implementation */ #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) { /* Extension added above */ checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDSA; clearIImplementation = &AbstractFramebuffer::clearImplementationDSA; clearUIImplementation = &AbstractFramebuffer::clearImplementationDSA; clearFImplementation = &AbstractFramebuffer::clearImplementationDSA; clearFIImplementation = &AbstractFramebuffer::clearImplementationDSA; drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDSA; drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDSA; readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDSA; copySub1DImplementation = &AbstractFramebuffer::copySub1DImplementationDSA; copySub2DImplementation = &AbstractFramebuffer::copySub2DImplementationDSA; copySubCubeMapImplementation = &AbstractFramebuffer::copySubCubeMapImplementationDSA; copySub3DImplementation = &AbstractFramebuffer::copySub3DImplementationDSA; renderbufferImplementation = &Framebuffer::renderbufferImplementationDSA; /* The 1D implementation uses the same function as the layered attachment */ texture1DImplementation = &Framebuffer::textureImplementationDSA; /* DSA doesn't have texture target parameter so we need to use different function to specify cube map face */ texture2DImplementation = &Framebuffer::texture2DImplementationDSA; textureImplementation = &Framebuffer::textureImplementationDSA; textureCubeMapImplementation = &Framebuffer::textureCubeMapImplementationDSA; textureLayerImplementation = &Framebuffer::textureLayerImplementationDSA; renderbufferStorageImplementation = &Renderbuffer::storageImplementationDSA; } else if(context.isExtensionSupported<Extensions::GL::EXT::direct_state_access>()) { extensions.emplace_back(Extensions::GL::EXT::direct_state_access::string()); checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDSAEXT; /* I don't bother with EXT_DSA anymore */ clearIImplementation = &AbstractFramebuffer::clearImplementationDefault; clearUIImplementation = &AbstractFramebuffer::clearImplementationDefault; clearFImplementation = &AbstractFramebuffer::clearImplementationDefault; clearFIImplementation = &AbstractFramebuffer::clearImplementationDefault; drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDSAEXT; drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDSAEXT; readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDSAEXT; copySub1DImplementation = &AbstractFramebuffer::copySub1DImplementationDSAEXT; copySub2DImplementation = &AbstractFramebuffer::copySub2DImplementationDSAEXT; copySubCubeMapImplementation = &AbstractFramebuffer::copySub2DImplementationDSAEXT; copySub3DImplementation = &AbstractFramebuffer::copySub3DImplementationDSAEXT; renderbufferImplementation = &Framebuffer::renderbufferImplementationDSAEXT; texture1DImplementation = &Framebuffer::texture1DImplementationDSAEXT; /* The EXT_DSA implementation is the same for both 2D and cube map textures */ texture2DImplementation = &Framebuffer::texture2DImplementationDSAEXT; textureImplementation = &Framebuffer::textureImplementationDSAEXT; textureCubeMapImplementation = &Framebuffer::texture2DImplementationDSAEXT; textureLayerImplementation = &Framebuffer::textureLayerImplementationDSAEXT; renderbufferStorageImplementation = &Renderbuffer::storageImplementationDSAEXT; } else #endif { checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDefault; #ifndef MAGNUM_TARGET_GLES2 clearIImplementation = &AbstractFramebuffer::clearImplementationDefault; clearUIImplementation = &AbstractFramebuffer::clearImplementationDefault; clearFImplementation = &AbstractFramebuffer::clearImplementationDefault; clearFIImplementation = &AbstractFramebuffer::clearImplementationDefault; #endif #ifndef MAGNUM_TARGET_GLES2 drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDefault; #endif #ifndef MAGNUM_TARGET_GLES drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDefault; #endif #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDefault; #endif #ifndef MAGNUM_TARGET_GLES copySub1DImplementation = &AbstractFramebuffer::copySub1DImplementationDefault; #endif copySub2DImplementation = &AbstractFramebuffer::copySub2DImplementationDefault; copySubCubeMapImplementation = &AbstractFramebuffer::copySub2DImplementationDefault; #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) copySub3DImplementation = &AbstractFramebuffer::copySub3DImplementationDefault; #endif renderbufferImplementation = &Framebuffer::renderbufferImplementationDefault; #ifndef MAGNUM_TARGET_GLES texture1DImplementation = &Framebuffer::texture1DImplementationDefault; #endif /* The default implementation is the same for both 2D and cube map textures */ texture2DImplementation = &Framebuffer::texture2DImplementationDefault; #if !defined(MAGNUM_TARGET_WEBGL) && !defined(MAGNUM_TARGET_GLES2) textureImplementation = &Framebuffer::textureImplementationDefault; #endif textureCubeMapImplementation = &Framebuffer::texture2DImplementationDefault; #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) textureLayerImplementation = &Framebuffer::textureLayerImplementationDefault; #endif renderbufferStorageImplementation = &Renderbuffer::storageImplementationDefault; } #ifdef MAGNUM_TARGET_GLES2 /* Framebuffer binding and checking on ES2 */ /* Optimistically set separate binding targets and check if one of the extensions providing them is available */ #ifndef MAGNUM_TARGET_WEBGL bindImplementation = &Framebuffer::bindImplementationDefault; bindInternalImplementation = &Framebuffer::bindImplementationDefault; #endif checkStatusImplementation = &Framebuffer::checkStatusImplementationDefault; #ifndef MAGNUM_TARGET_WEBGL if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_blit>()) { extensions.push_back(Extensions::GL::ANGLE::framebuffer_blit::string()); } else if(context.isExtensionSupported<Extensions::GL::APPLE::framebuffer_multisample>()) { extensions.push_back(Extensions::GL::APPLE::framebuffer_multisample::string()); } else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_blit>()) { extensions.push_back(Extensions::GL::NV::framebuffer_blit::string()); /* NV_framebuffer_multisample requires NV_framebuffer_blit, which has these enums. However, on my system only NV_framebuffer_multisample is supported, but NV_framebuffer_blit isn't. I will hold my breath and assume these enums are available. */ } else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_multisample>()) { extensions.push_back(Extensions::GL::NV::framebuffer_multisample::string()); /* If no such extension is available, reset back to single target */ } else { bindImplementation = &Framebuffer::bindImplementationSingle; bindInternalImplementation = &Framebuffer::bindImplementationSingle; checkStatusImplementation = &Framebuffer::checkStatusImplementationSingle; } #endif #ifndef MAGNUM_TARGET_WEBGL /* Framebuffer draw mapping on ES2 */ if(context.isExtensionSupported<Extensions::GL::EXT::draw_buffers>()) { extensions.push_back(Extensions::GL::EXT::draw_buffers::string()); drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationEXT; } else if(context.isExtensionSupported<Extensions::GL::NV::draw_buffers>()) { extensions.push_back(Extensions::GL::NV::draw_buffers::string()); drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationNV; } else drawBuffersImplementation = nullptr; #else if(context.isExtensionSupported<Extensions::GL::WEBGL::draw_buffers>()) { extensions.push_back(Extensions::GL::WEBGL::draw_buffers::string()); /* The EXT implementation is exposed in Emscripten */ drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationEXT; } else drawBuffersImplementation = nullptr; #endif #endif /* Framebuffer reading implementation in desktop/ES */ #ifndef MAGNUM_TARGET_WEBGL #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::GL::ARB::robustness>()) #else if(context.isExtensionSupported<Extensions::GL::EXT::robustness>()) #endif { #ifndef MAGNUM_TARGET_GLES extensions.emplace_back(Extensions::GL::ARB::robustness::string()); #else extensions.push_back(Extensions::GL::EXT::robustness::string()); #endif readImplementation = &AbstractFramebuffer::readImplementationRobustness; } else readImplementation = &AbstractFramebuffer::readImplementationDefault; /* Framebuffer reading in WebGL */ #else readImplementation = &AbstractFramebuffer::readImplementationDefault; #endif /* Multisample renderbuffer storage implementation */ #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) { /* Extension added above */ renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationDSA; } else if(context.isExtensionSupported<Extensions::GL::EXT::direct_state_access>()) { /* Extension added above */ renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationDSAEXT; } else #endif { #if defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_multisample>()) { extensions.push_back(Extensions::GL::ANGLE::framebuffer_multisample::string()); renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationANGLE; } else if (context.isExtensionSupported<Extensions::GL::NV::framebuffer_multisample>()) { extensions.push_back(Extensions::GL::NV::framebuffer_multisample::string()); renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationNV; } else renderbufferStorageMultisampleImplementation = nullptr; #elif !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationDefault; #endif } /* Framebuffer invalidation implementation on desktop GL */ #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::GL::ARB::invalidate_subdata>()) { extensions.emplace_back(Extensions::GL::ARB::invalidate_subdata::string()); if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) { /* Extension added above */ invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDSA; invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationDSA; } else { invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDefault; invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationDefault; } } else { invalidateImplementation = &AbstractFramebuffer::invalidateImplementationNoOp; invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationNoOp; } /* Framebuffer invalidation implementation on ES2 */ #elif defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) if(context.isExtensionSupported<Extensions::GL::EXT::discard_framebuffer>()) { extensions.push_back(Extensions::GL::EXT::discard_framebuffer::string()); invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDefault; } else { invalidateImplementation = &AbstractFramebuffer::invalidateImplementationNoOp; } /* Always available on ES3 */ #elif !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDefault; invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationDefault; #endif /* Blit implementation on desktop GL */ #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) { /* Extension added above */ blitImplementation = &AbstractFramebuffer::blitImplementationDSA; } else blitImplementation = &AbstractFramebuffer::blitImplementationDefault; /* Blit implementation on ES2 */ #elif defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_blit>()) { extensions.push_back(Extensions::GL::ANGLE::framebuffer_blit::string()); blitImplementation = &AbstractFramebuffer::blitImplementationANGLE; } else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_blit>()) { extensions.push_back(Extensions::GL::NV::framebuffer_blit::string()); blitImplementation = &AbstractFramebuffer::blitImplementationNV; } else blitImplementation = nullptr; /* Always available on ES3 and WebGL 2 */ #elif !defined(MAGNUM_TARGET_GLES2) blitImplementation = &AbstractFramebuffer::blitImplementationDefault; #endif #if defined(MAGNUM_TARGET_WEBGL) && !defined(MAGNUM_TARGET_GLES2) static_cast<void>(context); static_cast<void>(extensions); #endif } void FramebufferState::reset() { readBinding = drawBinding = renderbufferBinding = State::DisengagedBinding; viewport = DisengagedViewport; } }}
49.111748
214
0.751692
costashatz
d410fe2fe8014681408cde2a9711f0967d8b81c2
325
cpp
C++
16. Heaps/07 Delete.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
190
2021-02-10T17:01:01.000Z
2022-03-20T00:21:43.000Z
16. Heaps/07 Delete.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
null
null
null
16. Heaps/07 Delete.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
27
2021-03-26T11:35:15.000Z
2022-03-06T07:34:54.000Z
#include<bits/stdc++.h> using namespace std; class MinHeap { int arr[]; int size; int capacity; public: MinHeap(int c) { arr = new int[c]; size = 0; capacity = c; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int parent(int i) { return (i - 1) / 2; } };
9.285714
23
0.532308
VivekYadav105
d411603bf325af6c52e9fe2e37fb54d32bcf2d30
1,411
cpp
C++
examples/container/bitfield.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
examples/container/bitfield.cpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
examples/container/bitfield.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // 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) #include <fcppt/container/bitfield/object.hpp> #include <fcppt/container/bitfield/operators.hpp> #include <fcppt/config/external_begin.hpp> #include <iostream> #include <fcppt/config/external_end.hpp> //! [bitfield] namespace { enum class person_status { hungry, tired, fcppt_maximum = tired // note the extra field here }; using bitfield = fcppt::container::bitfield::object<person_status>; void output(bitfield const &_field) { std::cout << "Person status: hungry: " << (_field & person_status::hungry) << '\n' << "Person status: tired: " << (_field & person_status::tired) << '\n'; } } int main() { // Initialize the bitfield to all zeros bitfield field(bitfield::null()); output(field); // Set a flag, the bitwise kind of way field |= person_status::hungry; output(field); // And unset it again field &= ~bitfield{person_status::hungry}; // You can access a single flag via operator[] std::cout << "person is hungry: " << field[person_status::hungry] << '\n'; // You can also set a flag this way: field[person_status::hungry] = false; std::cout << ("person is hungry: ") << field[person_status::hungry] << '\n'; } //! [bitfield]
25.654545
84
0.671155
freundlich
d4116138318b85b96e4066df7c006aa82500c72f
9,355
cc
C++
towr/src/quadruped_gait_generator.cc
IoannisDadiotis/towr
cbbe6d30d637b4271558e31bf522536451a9110c
[ "BSD-3-Clause" ]
null
null
null
towr/src/quadruped_gait_generator.cc
IoannisDadiotis/towr
cbbe6d30d637b4271558e31bf522536451a9110c
[ "BSD-3-Clause" ]
null
null
null
towr/src/quadruped_gait_generator.cc
IoannisDadiotis/towr
cbbe6d30d637b4271558e31bf522536451a9110c
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** Copyright (c) 2018, Alexander W. Winkler. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <towr/initialization/quadruped_gait_generator.h> #include <cassert> #include <iostream> #include <towr/models/endeffector_mappings.h> namespace towr { QuadrupedGaitGenerator::QuadrupedGaitGenerator () { int n_ee = 4; ContactState init(n_ee, false); II_ = init; // flight_phase PI_ = bI_ = IP_ = Ib_ = init; // single contact Pb_ = bP_ = BI_ = IB_ = PP_ = bb_ = init; // two leg support Bb_ = BP_ = bB_ = PB_ = init; // three-leg support BB_ = init; // four-leg support phase // flight_phase II_ = ContactState(n_ee, false); // one stanceleg PI_.at(LH) = true; bI_.at(RH) = true; IP_.at(LF) = true; Ib_.at(RF) = true; // two stancelegs Pb_.at(LH) = true; Pb_.at(RF) = true; bP_.at(RH) = true; bP_.at(LF) = true; BI_.at(LH) = true; BI_.at(RH) = true; IB_.at(LF) = true; IB_.at(RF) = true; PP_.at(LH) = true; PP_.at(LF) = true; bb_.at(RH) = true; bb_.at(RF) = true; // three stancelegs Bb_.at(LH) = true; Bb_.at(RH) = true; Bb_.at(RF)= true; BP_.at(LH) = true; BP_.at(RH) = true; BP_.at(LF)= true; bB_.at(RH) = true; bB_.at(LF) = true; bB_.at(RF)= true; PB_.at(LH) = true; PB_.at(LF) = true; PB_.at(RF)= true; // four stancelgs BB_ = ContactState(n_ee, true); // default gait SetGaits({Stand}); } void QuadrupedGaitGenerator::SetCombo (Combos combo) { switch (combo) { case C0: SetGaits({Stand, Walk2, Walk2, Walk2, Walk2E, Stand}); break; // overlap-walk case C1: SetGaits({Stand, Run2, Run2, Run2, Run2E, Stand}); break; // fly trot case C2: SetGaits({Stand, Run3, Run3, Run3, Run3E, Stand}); break; // pace case C3: SetGaits({Stand, Hop1, Hop1, Hop1, Hop1E, Stand}); break; // bound case C4: SetGaits({Stand, Hop3, Hop3, Hop3, Hop3E, Stand}); break; // gallop case C5: SetGaits({Stand, WalkSlow, Stand}); break; // slow walk for centauro default: assert(false); std::cout << "Gait not defined\n"; break; } } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetGait(Gaits gait) const { switch (gait) { case Stand: return GetStrideStand(); case Flight: return GetStrideFlight(); case WalkSlow: return GetStrideWalkSlow(); case Walk1: return GetStrideWalk(); case Walk2: return GetStrideWalkOverlap(); case Walk2E: return RemoveTransition(GetStrideWalkOverlap()); case Run1: return GetStrideTrot(); case Run2: return GetStrideTrotFly(); case Run2E: return GetStrideTrotFlyEnd(); case Run3: return GetStridePace(); case Run3E: return GetStridePaceEnd(); case Hop1: return GetStrideBound(); case Hop1E: return GetStrideBoundEnd(); case Hop2: return GetStridePronk(); case Hop3: return GetStrideGallop(); case Hop3E: return RemoveTransition(GetStrideGallop()); case Hop5: return GetStrideLimp(); default: assert(false); // gait not implemented } } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideStand () const { auto times = { 0.3, }; auto contacts = { BB_, }; return std::make_pair(times, contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideFlight () const { auto times = { 0.3, }; auto contacts = { Bb_, }; return std::make_pair(times, contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStridePronk () const { double push = 0.3; double flight = 0.4; double land = 0.3; auto times = { push, flight, land }; auto phase_contacts = { BB_, II_, BB_, }; return std::make_pair(times, phase_contacts); } // Slow walking stride for Centauro QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideWalkSlow () const { double step = 1.0; double stand = 1.0; // start with stand auto times = { stand, step, stand, step, stand, step, stand, step, stand, }; auto phase_contacts = { BB_, bB_, BB_, Bb_, BB_, PB_, BB_, BP_, BB_ }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideWalk () const { double step = 0.3; double stand = 0.2; auto times = { step, stand, step, stand, step, stand, step, stand, }; auto phase_contacts = { bB_, BB_, Bb_, BB_, PB_, BB_, BP_, BB_ }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideWalkOverlap () const { double three = 0.25; double lateral = 0.13; double diagonal = 0.13; auto times = { three, lateral, three, diagonal, three, lateral, three, diagonal, }; auto phase_contacts = { bB_, bb_, Bb_, Pb_, // start lifting RH PB_, PP_, BP_, bP_, // start lifting LH }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideTrot () const { double t_step = 0.3; double t_stand = 0.2; auto times = { t_step, t_stand, t_step, t_stand, }; auto phase_contacts = { bP_, BB_, Pb_, BB_, }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideTrotFly () const { double stand = 0.4; double flight = 0.1; auto times = { stand, flight, stand, flight, }; auto phase_contacts = { bP_, II_, Pb_, II_, }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideTrotFlyEnd () const { auto times = { 0.4, }; auto phase_contacts = { bP_ }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStridePace () const { double stand = 0.3; double flight = 0.1; auto times = { stand, flight, stand, flight }; auto phase_contacts = { PP_, II_, bb_, II_, }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStridePaceEnd () const { auto times = { 0.3, }; auto phase_contacts = { PP_, }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideBound () const { double stand = 0.3; double flight = 0.1; auto times = { stand, flight, stand, flight }; auto phase_contacts = { BI_, II_, IB_, II_ }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideBoundEnd () const { auto times = { 0.3, }; auto phase_contacts = { BI_, }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideGallop () const { double A = 0.3; // both feet in air double B = 0.2; // overlap double C = 0.2; // transition front->hind auto times = { B, A, B, C, B, A, B, C }; auto phase_contacts = { Bb_, BI_, BP_, // front legs swing forward bP_, // transition phase bB_, IB_, PB_, // hind legs swing forward Pb_ }; return std::make_pair(times, phase_contacts); } QuadrupedGaitGenerator::GaitInfo QuadrupedGaitGenerator::GetStrideLimp () const { double A = 0.1; // three in contact double B = 0.2; // all in contact double C = 0.1; // one in contact auto times = { A, B, C, A, B, C, }; auto phase_contacts = { Bb_, BB_, IP_, Bb_, BB_, IP_, }; return std::make_pair(times, phase_contacts); } } /* namespace towr */
23.743655
90
0.649813
IoannisDadiotis
d4124780e16cb155c4f5f1c306b374d3504951c1
29,410
cpp
C++
Source/System/Physics/ColliderPrimitive/ConvexHull3D/ColliderPolyhedron.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Physics/ColliderPrimitive/ConvexHull3D/ColliderPolyhedron.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Physics/ColliderPrimitive/ConvexHull3D/ColliderPolyhedron.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#include "ColliderPolyhedron.hpp" #include "../../../Graphics/Utility/PrimitiveRenderer.hpp" #include "../../BroadPhase/BoundingAABB.hpp" #include <list> #include "../../../../Manager/Resource/ResourceType/JsonResource.hpp" #include "../../../../External/JSONCPP/json/json.h" namespace Engine5 { ColliderPolyhedron::ColliderPolyhedron() { m_type = eColliderType::Polyhedron; } ColliderPolyhedron::~ColliderPolyhedron() { } void ColliderPolyhedron::Initialize() { if (m_vertices == nullptr) { m_vertices = new std::vector<Vector3>(); } if (m_scaled_vertices == nullptr) { m_scaled_vertices = new std::vector<Vector3>(); } if (m_edges == nullptr) { m_edges = new std::vector<ColliderEdge>(); } if (m_faces == nullptr) { m_faces = new std::vector<ColliderFace>(); } UpdatePrimitive(); } void ColliderPolyhedron::Shutdown() { if (m_vertices != nullptr) { m_vertices->clear(); delete m_vertices; m_vertices = nullptr; } if (m_scaled_vertices != nullptr) { m_scaled_vertices->clear(); delete m_scaled_vertices; m_scaled_vertices = nullptr; } if (m_edges != nullptr) { m_edges->clear(); delete m_edges; m_edges = nullptr; } if (m_faces != nullptr) { m_faces->clear(); delete m_faces; m_faces = nullptr; } } Vector3 ColliderPolyhedron::Support(const Vector3& direction) { Real p = Math::REAL_NEGATIVE_MAX; Vector3 result; std::vector<Vector3>* vertices; if (m_collider_set != nullptr) { vertices = m_scaled_vertices; } else { vertices = m_vertices; } size_t size = vertices->size(); for (size_t i = 0; i < size; ++i) { Real projection = vertices->at(i).DotProduct(direction); if (projection > p) { result = vertices->at(i); p = projection; } } return result; } bool ColliderPolyhedron::TestRayIntersection(const Ray& local_ray, Real& minimum_t, Real& maximum_t) const { bool b_first = true; int hit_count = 0; minimum_t = -1.0f; maximum_t = -1.0f; for (auto& face : *m_faces) { Real t = -1.0f; if (IntersectRayFace(local_ray, face, t) == true) { if (b_first == true) { minimum_t = t; maximum_t = t; b_first = false; } else { if (t > maximum_t) { maximum_t = t; } if (t < minimum_t) { minimum_t = t; } } hit_count++; } } if (hit_count > 0) { if (minimum_t < 0.0f && maximum_t < 0.0f) { return false; } if (minimum_t <= 0.0f) { minimum_t = 0.0f; } return true; } return false; } Vector3 ColliderPolyhedron::GetNormal(const Vector3& local_point_on_collider) { Vector3 normal; for (auto& face : *m_faces) { if (this->IsFaceContainPoint(face, local_point_on_collider, normal) == true) { return normal; } } return normal; } void ColliderPolyhedron::SetMassData(Real density) { if (Math::IsNotEqual(m_material.density, density)) { m_material.density = density; m_material.type = Physics::eMaterial::UserType; } m_centroid = 0.0f; m_local_inertia_tensor.SetZero(); m_mass = 0.0f; Vector3 ref_point = Math::Vector3::ORIGIN; for (auto& face : *m_faces) { auto sub_data = CalculateTetrahedronMassData(ref_point, Vertex(face.a), Vertex(face.b), Vertex(face.c), density); m_centroid += sub_data.mass * sub_data.centroid; m_mass += sub_data.mass; m_local_inertia_tensor += sub_data.inertia; } if (Math::IsZero(m_mass) == false) { m_centroid /= m_mass; } else { m_centroid = 0.0f; } m_local_inertia_tensor = TranslateInertia(m_local_inertia_tensor, m_centroid, m_mass, ref_point - m_centroid); } Real ColliderPolyhedron::GetVolume() { Real volume = 0.0f; Vector3 ref_point = Math::Vector3::ORIGIN; for (auto& face : *m_faces) { Matrix33 tetrahedron_matrix; tetrahedron_matrix.SetColumns(Vertex(face.a) - ref_point, Vertex(face.b) - ref_point, Vertex(face.c) - ref_point); volume += tetrahedron_matrix.Determinant() / 6.0f; } return volume; } void ColliderPolyhedron::SetScaleData(const Vector3& scale) { m_scaled_vertices->clear(); size_t size = m_vertices->size(); m_scaled_vertices->reserve(size); for (size_t i = 0; i < size; ++i) { m_scaled_vertices->push_back(m_vertices->at(i).HadamardProduct(scale.HadamardProduct(m_local.scale))); for (size_t j = 0; j < 3; ++j) { if (m_max_bound[j] < m_scaled_vertices->at(i)[j]) { m_max_bound[j] = m_scaled_vertices->at(i)[j]; } if (m_min_bound[j] > m_scaled_vertices->at(i)[j]) { m_min_bound[j] = m_scaled_vertices->at(i)[j]; } } } } void ColliderPolyhedron::SetUnit() { CalculateMinMaxBound(); auto scale_factor = (m_max_bound - m_min_bound).Inverse(); size_t size = m_vertices->size(); for (size_t i = 0; i < size; ++i) { m_scaled_vertices->at(i) = m_vertices->at(i).HadamardProduct(scale_factor); } UpdatePrimitive(); } void ColliderPolyhedron::UpdateBoundingVolume() { Real bounding_factor = (m_max_bound - m_min_bound).Length(); Vector3 pos = m_rigid_body != nullptr ? m_rigid_body->LocalToWorldPoint(m_local.position) : m_local.position; Vector3 min_max(bounding_factor, bounding_factor, bounding_factor); m_bounding_volume->Set(-min_max + pos, min_max + pos); Vector3 obb_vertices[8]; obb_vertices[0].Set(m_max_bound.x, m_max_bound.y, m_max_bound.z); obb_vertices[1].Set(m_max_bound.x, m_max_bound.y, m_min_bound.z); obb_vertices[2].Set(m_max_bound.x, m_min_bound.y, m_max_bound.z); obb_vertices[3].Set(m_max_bound.x, m_min_bound.y, m_min_bound.z); obb_vertices[4].Set(m_min_bound.x, m_max_bound.y, m_max_bound.z); obb_vertices[5].Set(m_min_bound.x, m_max_bound.y, m_min_bound.z); obb_vertices[6].Set(m_min_bound.x, m_min_bound.y, m_max_bound.z); obb_vertices[7].Set(m_min_bound.x, m_min_bound.y, m_min_bound.z); bool has_body = m_rigid_body != nullptr; Vector3 min = has_body ? m_rigid_body->LocalToWorldPoint(m_local.LocalToWorldPoint(obb_vertices[0])) : m_local.LocalToWorldPoint(obb_vertices[0]); Vector3 max = min; if (has_body) { for (int i = 1; i < 8; ++i) { Vector3 vertex = m_rigid_body->LocalToWorldPoint(m_local.LocalToWorldPoint(obb_vertices[i])); min.x = Math::Min(min.x, vertex.x); min.y = Math::Min(min.y, vertex.y); min.z = Math::Min(min.z, vertex.z); max.x = Math::Max(max.x, vertex.x); max.y = Math::Max(max.y, vertex.y); max.z = Math::Max(max.z, vertex.z); } } else { for (int i = 1; i < 8; ++i) { Vector3 vertex = m_local.LocalToWorldPoint(obb_vertices[i]); min.x = Math::Min(min.x, vertex.x); min.y = Math::Min(min.y, vertex.y); min.z = Math::Min(min.z, vertex.z); max.x = Math::Max(max.x, vertex.x); max.y = Math::Max(max.y, vertex.y); max.z = Math::Max(max.z, vertex.z); } } m_bounding_volume->Set(min, max); } void ColliderPolyhedron::Draw(PrimitiveRenderer* renderer, eRenderingMode mode, const Color& color) const { I32 index = static_cast<I32>(renderer->VerticesSize(mode)); std::vector<Vector3>* vertices; if (m_collider_set != nullptr) { vertices = m_scaled_vertices; } else { vertices = m_vertices; } size_t size = vertices->size(); renderer->ReserveVertices(size, mode); Transform* body_transform = GetBodyTransform(); for (auto& vertex : *vertices) { //collider local space to object space(body local) vertex = LocalToWorldPoint(vertex); vertex = body_transform->LocalToWorldPoint(vertex); //push to renderer renderer->PushVertex(vertex, mode, color); } //add indices if (mode == eRenderingMode::Dot) { for (I32 i = 0; i < size; ++i) { renderer->PushIndex(index + i, mode); } } else if (mode == eRenderingMode::Line) { for (auto& face : *m_faces) { renderer->PushLineIndices(index + (I32)face.a, index + (I32)face.b); renderer->PushLineIndices(index + (I32)face.b, index + (I32)face.c); renderer->PushLineIndices(index + (I32)face.c, index + (I32)face.a); } } else if (mode == eRenderingMode::Face) { for (auto& face : *m_faces) { renderer->PushFaceIndices(index + (I32)face.a, index + (I32)face.b, index + (I32)face.c); } } } Vector3 ColliderPolyhedron::Vertex(size_t i) const { if (m_collider_set != nullptr) { return m_scaled_vertices->at(i); } return m_vertices->at(i); } size_t ColliderPolyhedron::Size() const { if (m_collider_set != nullptr) { return m_scaled_vertices->size(); } return m_vertices->size(); } bool ColliderPolyhedron::SetPolyhedron(const std::vector<Vector3>& input_vertices) { //0. Early quit when not enough vertices. size_t size = input_vertices.size(); if (size < 4) { return false; } //1. Allocate a Polyhedron which will be our return value. if (m_vertices == nullptr) { m_vertices = new std::vector<Vector3>(); m_vertices->reserve(size); } else { m_vertices->clear(); m_vertices->reserve(size); } std::vector<Vector3> vertices = input_vertices; //2. Find a maximal simplex of the current dimension.In our case, //find 4 points which define maximal tetrahedron, and create the tetrahedron which will be our seed partial answer. //CREATE_SIMPLEX(Polyhedron, listVertices). //If this returns a dimension lower than 3, report the degeneracy and quit. size_t dimension = CreateSimplex(vertices); if (dimension < 3) { return false; } //3. Divide the points of the cloud into the outside sets of the four faces of the tetrahedron. //This is done by calling ADD_TO_OUTSIDE_SET(face, listVertices) on each of the 4 faces in turn. //Points that could be put in multiple sets will be randomly placed in one of them, and it does not matter which one. //Any points which are inside or on all of the planes do not contribute to the convex hull. //These points are removed from the rest of the calculation. std::list<OutsideSetFace> outside_set_list; for (auto face : *m_faces) { OutsideSetFace outside_set(face); AddToOutsideSet(vertices, outside_set); outside_set_list.push_back(outside_set); } //4. While(There exists currFace = a face on the current convex hull which has a non - empty outside set of vertices) while (!outside_set_list.empty()) { //1. Find the point in currFace's outside set which is farthest away from the plane of the currFace. //This is the eyePoint. //2. Compute the horizon of the current polyhedron as seen from this eyePoint. //CALCULATE_HORIZON(eyePoint, NULL, currFace, listHorizonEdges, listUnclaimedVertices). //This will mark all of the visible faces as not on the convex hull and place all of their outside set points on the listUnclaimedVertices. //It is creates the listHorizonEdges which is a counterclockwise ordered list of edges around the horizon contour of the polyhedron as viewed from the eyePoint. //3. Construct a cone from the eye point to all of the edges of the horizon. //Before a triangle of this cone is created and added to the polyhedron a test to see if it coplanar to the face on the other side of the horizon edge is applied. //If the faces are coplanar then they are merged together and that horizon edge is marked as not on the convex hull.Then a similar check must also be applied to edges which cross the horizon to see if they are collinear. //If so then the vertex on the horizon which is on this line must be marked as not on the horizon. //4. Divide the points of the listUnclaimedVertices into the outside sets of the new cone faces and the faces which were merged with what would be new cone faces. //This is done by calling ADD_TO_OUTSIDE_SET(face, listUnclaimedVertices) on each of these faces in turn. //Points that could be put in multiple sets will be randomly placed in one of them, and it does not matter which one. //Any points which are inside or on all of the planes do not contribute to the convex hull. //These points are marked as not on the convex hull. //5. Remove all faces, edges, and vertices which have been marked as not on the convex hull. //These faces, edges, and vertices have all been enclosed by the new cone emanating from the eyePoint. //6. Continue the loop } //5. When all the faces with outside points have been processed we are done. //The polyhedron should a clean convex hull where all coplanar faces have been merged. //All collinear edges have been merged. //And all coincident vertices have had their DualFace pointers merged. return true; } void ColliderPolyhedron::Clone(ColliderPrimitive* origin) { if (origin != this && origin != nullptr && origin->Type() == m_type) { ColliderPolyhedron* polyhedron = static_cast<ColliderPolyhedron*>(origin); //collider local space data m_local = polyhedron->m_local; //collider mass data m_centroid = polyhedron->m_centroid; m_mass = polyhedron->m_mass; m_local_inertia_tensor = polyhedron->m_local_inertia_tensor; m_material = polyhedron->m_material; //polyhedron *m_vertices = *polyhedron->m_vertices; *m_scaled_vertices = *polyhedron->m_scaled_vertices; *m_edges = *polyhedron->m_edges; *m_faces = *polyhedron->m_faces; m_min_bound = polyhedron->m_min_bound; m_max_bound = polyhedron->m_max_bound; } } void ColliderPolyhedron::Load(const Json::Value& data) { LoadTransform(data); //polyhedron data if (JsonResource::HasMember(data, "Vertices") && data["Vertices"].isArray() && data["Vertices"].size() >= 4) { m_vertices->clear(); m_scaled_vertices->clear(); for (auto it = data["Vertices"].begin(); it != data["Vertices"].end(); ++it) { if (JsonResource::IsVector3(*it)) { Vector3 vertex = JsonResource::AsVector3(*it); m_vertices->push_back(vertex); } } } if (JsonResource::HasMember(data, "Edges") && data["Edges"].isArray()) { m_edges->clear(); for (auto it = data["Edges"].begin(); it != data["Edges"].end(); ++it) { if (JsonResource::IsVector2(*it)) { m_edges->emplace_back((size_t)data[0].asUInt64(), (size_t)data[1].asUInt64()); } } } if (JsonResource::HasMember(data, "Faces") && data["Faces"].isArray()) { m_faces->clear(); for (auto it = data["Faces"].begin(); it != data["Faces"].end(); ++it) { if (JsonResource::IsVector3(*it)) { m_faces->emplace_back((size_t)data[0].asUInt64(), (size_t)data[1].asUInt64(), (size_t)data[2].asUInt64()); } } } SetPolyhedron(*m_vertices); LoadMaterial(data); LoadMass(data); } void ColliderPolyhedron::Save(const Json::Value& data) { } void ColliderPolyhedron::EditPrimitive(CommandRegistry* registry) { } bool ColliderPolyhedron::IntersectRayFace(const Ray& ray, const ColliderFace& face, Real& t) const { std::vector<Vector3>* vertices; if (m_collider_set != nullptr) { vertices = m_scaled_vertices; } else { vertices = m_vertices; } Vector3 edge1 = (*vertices)[face.b] - (*vertices)[face.a]; Vector3 edge2 = (*vertices)[face.c] - (*vertices)[face.a]; Vector3 h = ray.direction.CrossProduct(edge2); Real a = edge1.DotProduct(h); t = -1.0f; if (Math::IsZero(a)) { return false; } Real f = 1.0f / a; Vector3 s = ray.position - (*vertices)[face.a]; Real u = f * (s.DotProduct(h)); if (u < 0.0f || u > 1.0f) { return false; } Vector3 q = s.CrossProduct(edge1); Real v = f * ray.direction.DotProduct(q); if (v < 0.0f || u + v > 1.0f) { return false; } // At this stage we can compute t to find out where the intersection point is on the line. t = f * edge2.DotProduct(q); if (t > Math::EPSILON) // ray intersection { return true; } // intersect back side of ray. return false; } bool ColliderPolyhedron::IsFaceContainPoint(const ColliderFace& face, const Vector3& point, Vector3& normal) const { std::vector<Vector3>* vertices; if (m_collider_set != nullptr) { vertices = m_scaled_vertices; } else { vertices = m_vertices; } Vector3 v0 = vertices->at(face.a); Vector3 v1 = vertices->at(face.b); Vector3 v2 = vertices->at(face.c); Vector3 edge01 = v1 - v0; Vector3 edge12 = v2 - v1; normal = edge01.CrossProduct(edge12); Vector3 w_test = edge01.CrossProduct(point - v0); if (w_test.DotProduct(normal) < 0.0f) { return false; } w_test = edge12.CrossProduct(point - v1); if (w_test.DotProduct(normal) < 0.0f) { return false; } Vector3 edge3 = v0 - v2; w_test = edge3.CrossProduct(point - v2); if (w_test.DotProduct(normal) < 0.0f) { return false; } normal.SetNormalize(); return true; } Matrix33 ColliderPolyhedron::TranslateInertia(const Matrix33& input, const Vector3& centroid, Real mass, const Vector3& offset) const { return input + mass * (offset.OuterProduct(centroid) + centroid.OuterProduct(offset) + offset.OuterProduct(offset)); } ColliderPolyhedron::SubMassData ColliderPolyhedron::CalculateTetrahedronMassData(const Vector3& ref, const Vector3& v1, const Vector3& v2, const Vector3& v3, Real density) const { SubMassData result; //canonical moment of inertia data. Real axis = 1.0f / 60.0f; Real prod = 1.0f / 120.0f; Matrix33 canonical_matrix(axis, prod, prod, prod, axis, prod, prod, prod, axis); Matrix33 transformation_matrix; transformation_matrix.SetColumns(v1 - ref, v2 - ref, v3 - ref); //calculate sub inertia result.inertia = transformation_matrix.Determinant() * transformation_matrix * canonical_matrix * transformation_matrix.Transpose(); //volume is 1 / 6 of triple product, that is 1/6 det of transformation matrix. result.mass = density * transformation_matrix.Determinant() / 6.0f; //The center-of-mass is just the mean of the four vertex coordinates. result.centroid = (ref + v1 + v2 + v3) * 0.25f; if (ref.IsZero() == false) { result.inertia = TranslateInertia(result.inertia, result.centroid, result.mass, ref); } return result; } void ColliderPolyhedron::CalculateMinMaxBound() { m_max_bound = Math::REAL_NEGATIVE_MAX; m_min_bound = Math::REAL_POSITIVE_MAX; size_t size = m_scaled_vertices->size(); for (size_t i = 0; i < size; ++i) { for (size_t j = 0; j < 3; ++j) { Real value = m_scaled_vertices->at(i)[j]; if (m_max_bound[j] < value) { m_max_bound[j] = value; } if (m_min_bound[j] > value) { m_min_bound[j] = value; } } } } size_t ColliderPolyhedron::CreateSimplex(const std::vector<Vector3>& vertices) const { //1. For each principle direction(X - axis, Y - axis, Z - axis) Vector3 min_vertex, max_vertex; bool b_succeed = false; for (size_t i = 0; i < 3; ++i) { // 1. Find the minimum and maximum point in that dimension Real min = Math::REAL_POSITIVE_MAX; Real max = Math::REAL_NEGATIVE_MAX; for (auto& vertex : vertices) { if (vertex[i] < min) { min = vertex[i]; min_vertex = vertex; } if (vertex[i] > max) { max = vertex[i]; max_vertex = vertex; } } // 2. If min != max then break out of loop with success if (min != max) { b_succeed = true; break; } // 3. Continue the loop } //2. If the loop finished without success return and report that we have a degenerate point cloud, either 1D or 2D. if (b_succeed == false) { return 0; } //3. Find the point which is furthest distant from the line defined by the first two points.If this maximum distance is zero, then our point cloud is 1D, so report the degeneracy. Segment segment(min_vertex, max_vertex); Real max_distance = 0.0f; Real t = 0.0f; Vector3 max_triangle; for (auto& vertex : vertices) { Real distance = segment.DistanceSquared(vertex, t); if (distance > max_distance) { max_distance = distance; max_triangle = vertex; } } if (Math::IsZero(max_distance)) { return 1; } //4. Find the point which has the largest absolute distance from the plane defined by the first three points.If this maximum distance is zero, then our point cloud is 2D, so report the the degeneracy. max_distance = 0.0f; Vector3 max_tetrahedron; for (auto& vertex : vertices) { Real distance = Triangle::DistanceSquared(vertex, min_vertex, max_vertex, max_triangle); if (distance > max_distance) { max_distance = distance; max_tetrahedron = vertex; } } if (Math::IsZero(max_distance)) { return 2; } //5. Create the tetrahedron polyhedron.Remember that if the distance from the plane of the fourth point was negative, then the order of the first three vertices must be reversed. Plane plane; plane.Set(min_vertex, max_vertex, max_triangle); Real order = plane.PlaneTest(max_tetrahedron); if (order > 0.0f) { m_vertices->push_back(min_vertex); m_vertices->push_back(max_vertex); m_vertices->push_back(max_triangle); m_vertices->push_back(max_tetrahedron); } else { m_vertices->push_back(max_triangle); m_vertices->push_back(max_vertex); m_vertices->push_back(min_vertex); m_vertices->push_back(max_tetrahedron); } //6. Return the fact that we created a non - degenerate tetrahedron of dimension 3. m_faces->emplace_back(0, 1, 2); m_faces->emplace_back(1, 2, 3); m_faces->emplace_back(2, 3, 0); m_faces->emplace_back(3, 0, 1); return 3; } void ColliderPolyhedron::AddToOutsideSet(std::vector<Vector3>& vertices, OutsideSetFace& result) const { Vector3 face_a(m_vertices->at(result.a)); Vector3 face_b(m_vertices->at(result.b)); Vector3 face_c(m_vertices->at(result.c)); Plane plane(face_a, face_b, face_c); auto begin = vertices.begin(); auto end = vertices.end(); std::list<std::vector<Vector3>::iterator> erase_list; //1. For each vertex in the listVertices for (auto it = begin; it != end; ++it) { //1. distance = Distance from the plane of the face to the vertex Real distance = plane.Distance(*it); //2. If the vertex is in the plane of the face(i.e.distance == 0) if (Math::IsZero(distance)) { //3. Then check to see if the vertex is coincident with any vertices of the face, and if so merge it into that face vertex. if (Triangle::IsContainPoint(*it, face_a, face_b, face_c)) { //merge erase_list.push_back(it); } } //4. Else If distance > 0 else if (distance > 0.0f) { //5. Then claim the vertex by removing it from this list and adding it the face's set of outside vertices result.outside_vertices.push_back(*it); erase_list.push_back(it); } //6. Continue the loop } for (auto& it : erase_list) { vertices.erase(it); } } void ColliderPolyhedron::CalculateHorizon() { //If the currFace is not on the convex hull //Mark the crossedEdge as not on the convex hull and return. //If the currFace is visible from the eyePoint //Mark the currFace as not on the convex hull. //Remove all vertices from the currFace's outside set, and add them to the listUnclaimedVertices. c. //If the crossedEdge != NULL (only for the first face) then mark the crossedEdge as not on the convex hull d. //Cross each of the edges of currFace which are still on the convex hull //in counterclockwise order starting from the edge after the crossedEdge //(in the case of the first face, pick any edge to start with). //For each currEdge recurse with the call. } }
38.095855
232
0.53985
arian153
d41fd04e7f4b9da20b10302fd3eba3089453ff21
1,694
cpp
C++
c/csc-220/h2.cpp
dindoliboon/archive
a5b54367dbb57260f9230375ac81e86c5fce0d7d
[ "MIT" ]
4
2020-10-02T15:24:20.000Z
2021-11-02T04:20:38.000Z
c/csc-220/h2.cpp
dindoliboon/archive
a5b54367dbb57260f9230375ac81e86c5fce0d7d
[ "MIT" ]
null
null
null
c/csc-220/h2.cpp
dindoliboon/archive
a5b54367dbb57260f9230375ac81e86c5fce0d7d
[ "MIT" ]
2
2019-10-28T01:20:07.000Z
2020-10-02T15:25:13.000Z
/* //////////////////////////////////////////////////////////////////////// NAME: Dindo Liboon DATE: July 17, 2001 PROJECT: Homework #2, CSC-220-01 PURPOSE: Determine if a positive integer that is 4 to 10 digits in length can be divisible by a variety of numbers. COMPILE: cxx h2.cpp \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */ #include <fstream.h> #include "h2.h" /* //////////////////////////////////////////////////////////////////////// INPUT: none OUTPUT: 0 for success PURPOSE: Core application code that will open the data file and read any amount of integers into a buffer stored in the clsdiv class. Integers will be tested for divisibility for certain numbers. Results for each integer will be shown on the screen. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */ int main() { ifstream fpDataIn; clsdiv div; /* read data file until EOF */ fpDataIn.open("h2data"); while (!fpDataIn.eof() && fpDataIn >> div.chBuffer) { /* check for end of integer */ if (div.chBuffer == '.') { /* check if array has items */ if (div.length()) { div.printdiv(); div.reset(); } } else { /* set the next array item */ div.set(); } } fpDataIn.close(); /* quit program successfully */ return 0; } /* //////////////////////////////////////////////////////////////////////// END OF CODE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */
30.8
76
0.403188
dindoliboon
d4215eb81abc80b2d6331fba1e548fca4d4838f4
854
hpp
C++
Server/levelParsing/ParsingLevel.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
1
2019-08-14T12:31:50.000Z
2019-08-14T12:31:50.000Z
Server/levelParsing/ParsingLevel.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
Server/levelParsing/ParsingLevel.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** Epitech scolarship project (4 years remaining) ** File description: ** Made on 2018/11 by ebernard */ #include <map> #include <chrono> #include <string> #include <vector> #include <fstream> #include "Server/includes/Utils.hpp" #include "Server/Monsters/includes/IEnnemy.hpp" namespace Game { class ParsingLevel { public: ParsingLevel(); void startGame(); bool isEnd() const noexcept; std::vector<Game::MonsterInfo> getMonster(float time); int getLevel()const noexcept; bool setStreamLevel(int level); private: bool m_end { false }; std::string m_levelPath; float m_time; std::ifstream m_stream; bool m_isRunning; int m_currentLevel; std::multimap<float, Game::MonsterInfo> m_monsters; }; }
20.829268
62
0.638173
KillianG
d422f00ec915f9ad2cea868b0585ef64ce277d70
9,874
cpp
C++
alife/alifetests.cpp
DeanoC/hermit
5529b1ddcbc0cdae0fa5413aa50c0c7722fb8796
[ "MIT" ]
1
2019-09-13T13:44:29.000Z
2019-09-13T13:44:29.000Z
alife/alifetests.cpp
DeanoC/hermit
5529b1ddcbc0cdae0fa5413aa50c0c7722fb8796
[ "MIT" ]
null
null
null
alife/alifetests.cpp
DeanoC/hermit
5529b1ddcbc0cdae0fa5413aa50c0c7722fb8796
[ "MIT" ]
null
null
null
// License Summary: MIT see LICENSE file #include "al2o3_platform/platform.h" #include "alifetests.hpp" #include "al2o3_memory/memory.h" #include "world2d.hpp" #include "al2o3_vfile/vfile.hpp" #include "render_basics/descriptorset.h" #include "render_basics/buffer.h" #include "render_basics/pipeline.h" #include "render_basics/graphicsencoder.h" #include "render_basics/rootsignature.h" #include "render_basics/shader.h" #include "accel_cuda.hpp" #include "accel_sycl.hpp" namespace { void DestroyRenderable(World2DRender *render); World2DRender* MakeRenderable(World2D const* world, Render_RendererHandle renderer, Render_ROPLayout const* ropLayout) { World2DRender* render = (World2DRender*) MEMORY_CALLOC(1, sizeof(World2DRender)); if(!render) return nullptr; render->renderer = renderer; uint32_t const totalVertexCount = world->width * world->height; uint32_t const totalIndexCount = (world->width-1) * (world->height-1) * 3; uint32_t const indexTypeSize = (totalVertexCount > 0xFFFF) ? 4u : 2u; // build render objects // construct static vertex buffer Render_BufferVertexDesc const vertexDesc { totalVertexCount, sizeof(float) * 5, false }; render->vertexBuffer = Render_BufferCreateVertex(renderer, &vertexDesc); if(!Render_BufferHandleIsValid(render->vertexBuffer)) { DestroyRenderable(render); return false; } uint8_t* vertexData = nullptr; // MAX 64 KB stack else use the heap if(totalVertexCount > (0xFFFF / (sizeof(float) * 5))) { // short term alloc vertexData = (uint8_t*) MEMORY_MALLOC(totalVertexCount * (sizeof(float) * 5)); } else { vertexData = (uint8_t*) STACK_ALLOC(totalVertexCount * (sizeof(float) * 5)); } float * curVertexPtr = (float*)vertexData; for(uint32_t y = 0; y < world->height-1;++y) { for(int32_t x = -(int32_t)(world->width/2); x < (int32_t)(world->width/2);++x) { curVertexPtr[0] = (float)x; curVertexPtr[1] = 0.0f; curVertexPtr[2] = (float)y; curVertexPtr[3] = (float)(x + world->width/2) / (float)(world->width-1); curVertexPtr[4] = (float)y / (float)(world->height-1); curVertexPtr += 5; } } Render_BufferUpdateDesc const vertexUpdateDesc { vertexData, 0, totalVertexCount * sizeof(float) * 5 }; Render_BufferUpload(render->vertexBuffer, &vertexUpdateDesc); // no need to free stack allocated ram if(totalVertexCount > (0xFFFF / (sizeof(float) * 5))) { MEMORY_FREE(vertexData); } // construct the static index buffer Render_BufferIndexDesc const indexDesc { totalIndexCount, indexTypeSize, false }; render->indexBuffer = Render_BufferCreateIndex(renderer, &indexDesc); if(!Render_BufferHandleIsValid(render->indexBuffer)) { DestroyRenderable(render); return false; } uint8_t* indexData = nullptr; // MAX 64 KB stack else use the heap if(totalIndexCount > (0xFFFF / (indexTypeSize*3))) { // short term alloc indexData = (uint8_t*) MEMORY_MALLOC(totalIndexCount * indexTypeSize); } else { indexData = (uint8_t*) STACK_ALLOC(totalIndexCount * indexTypeSize); } uint8_t * curIndexPtr = indexData; for(uint32_t y = 0; y < world->height-1;++y) { for(uint32_t x = 0; x < world->width-1;++x) { switch(indexTypeSize) { case 2: ((uint16_t*)curIndexPtr)[0] = (y * world->height) + x; ((uint16_t*)curIndexPtr)[1] = ((y+1) * world->height) + x; ((uint16_t*)curIndexPtr)[2] = (y * world->height) + (x+1); curIndexPtr += 6; break; case 4: { ((uint32_t*)curIndexPtr)[0] = (y * world->height) + x; ((uint32_t*)curIndexPtr)[1] = ((y+1) * world->height) + x; ((uint32_t*)curIndexPtr)[2] = (y * world->height) + (x+1); curIndexPtr += 12; break; } default: LOGERROR("Invalid index buffer type size"); break; } } } Render_BufferUpdateDesc const indexUpdateDesc { indexData, 0, totalIndexCount * indexTypeSize }; Render_BufferUpload(render->indexBuffer, &indexUpdateDesc); // no need to free stack allocated ram if(totalIndexCount > (0xFFFF / (indexTypeSize*3))) { MEMORY_FREE(indexData); } static Render_BufferUniformDesc const ubDesc{ sizeof(render->uniforms), true }; render->uniformBuffer = Render_BufferCreateUniform(render->renderer, &ubDesc); if (!Render_BufferHandleIsValid(render->uniformBuffer)) { DestroyRenderable(render); return nullptr; } VFile::ScopedFile vfile = VFile::FromFile("resources/alife/world2dmoe_vertex.hlsl", Os_FM_Read); if (!vfile) { DestroyRenderable(render); return nullptr; } VFile::ScopedFile ffile = VFile::FromFile("resources/alife/world2dmoe_fragment.hlsl", Os_FM_Read); if (!ffile) { DestroyRenderable(render); return nullptr; } render->shader = Render_CreateShaderFromVFile(render->renderer, vfile, "VS_main", ffile, "FS_main"); if (!Render_ShaderHandleIsValid(render->shader)) { DestroyRenderable(render); return nullptr; } Render_RootSignatureDesc rootSignatureDesc{}; rootSignatureDesc.shaderCount = 1; rootSignatureDesc.shaders = &render->shader; rootSignatureDesc.staticSamplerCount = 0; render->rootSignature = Render_RootSignatureCreate(render->renderer, &rootSignatureDesc); if (!Render_RootSignatureHandleIsValid(render->rootSignature)) { DestroyRenderable(render); return nullptr; } TinyImageFormat colourFormats[] = { ropLayout->colourFormats[0] }; Render_GraphicsPipelineDesc gfxPipeDesc{}; gfxPipeDesc.shader = render->shader; gfxPipeDesc.rootSignature = render->rootSignature; gfxPipeDesc.vertexLayout = Render_GetStockVertexLayout(render->renderer, Render_SVL_3D_UV); gfxPipeDesc.blendState = Render_GetStockBlendState(render->renderer, Render_SBS_OPAQUE); if(ropLayout->depthFormat == TinyImageFormat_UNDEFINED) { gfxPipeDesc.depthState = Render_GetStockDepthState(render->renderer, Render_SDS_IGNORE); } else { gfxPipeDesc.depthState = Render_GetStockDepthState(render->renderer, Render_SDS_READWRITE_LESS); } gfxPipeDesc.rasteriserState = Render_GetStockRasterisationState(render->renderer, Render_SRS_BACKCULL); gfxPipeDesc.colourRenderTargetCount = 1; gfxPipeDesc.colourFormats = colourFormats; gfxPipeDesc.depthStencilFormat = ropLayout->depthFormat; gfxPipeDesc.sampleCount = 1; gfxPipeDesc.sampleQuality = 0; gfxPipeDesc.primitiveTopo = Render_PT_TRI_LIST; render->pipeline = Render_GraphicsPipelineCreate(render->renderer, &gfxPipeDesc); if (!Render_PipelineHandleIsValid(render->pipeline)) { DestroyRenderable(render); return nullptr; } Render_DescriptorSetDesc const setDesc = { render->rootSignature, Render_DUF_PER_FRAME, 1 }; render->descriptorSet = Render_DescriptorSetCreate(render->renderer, &setDesc); if (!Render_DescriptorSetHandleIsValid(render->descriptorSet)) { DestroyRenderable(render); return nullptr; } Render_DescriptorDesc params[1]; params[0].name = "View"; params[0].type = Render_DT_BUFFER; params[0].buffer = render->uniformBuffer; params[0].offset = 0; params[0].size = sizeof(render->uniforms); Render_DescriptorPresetFrequencyUpdated(render->descriptorSet, 0, 1, params); return render; } void DestroyRenderable(World2DRender *render) { if(!render) return; Render_DescriptorSetDestroy(render->renderer, render->descriptorSet); Render_PipelineDestroy(render->renderer, render->pipeline); Render_ShaderDestroy(render->renderer, render->shader); Render_RootSignatureDestroy(render->renderer, render->rootSignature); Render_BufferDestroy(render->renderer, render->uniformBuffer); Render_BufferDestroy(render->renderer, render->indexBuffer); Render_BufferDestroy(render->renderer, render->vertexBuffer); MEMORY_FREE(render); } void RenderWorld2D(World2D const * world, World2DRender* render, Render_GraphicsEncoderHandle encoder) { // upload the uniforms Render_BufferUpdateDesc uniformUpdate = { &render->uniforms, 0, sizeof(render->uniforms) }; Render_BufferUpload(render->uniformBuffer, &uniformUpdate); Render_GraphicsEncoderBindDescriptorSet(encoder, render->descriptorSet, 0); Render_GraphicsEncoderBindIndexBuffer(encoder, render->indexBuffer, 0); Render_GraphicsEncoderBindVertexBuffer(encoder, render->vertexBuffer, 0); Render_GraphicsEncoderBindPipeline(encoder, render->pipeline); uint32_t const totalIndexCount = (world->width-1) * (world->height-1) * 3; Render_GraphicsEncoderDrawIndexed(encoder, totalIndexCount, 0, 0); } }; // end anon namespace ALifeTests* ALifeTests::Create(Render_RendererHandle renderer, Render_ROPLayout const * targetLayout) { ALifeTests* alt = (ALifeTests*) MEMORY_CALLOC(1, sizeof(ALifeTests)); if(!alt) { return nullptr; } alt->accelCuda = AccelCUDA_Create(); alt->accelSycl = AccelSycl_Create(); alt->world2d = World2D_Create(WT_MOE, 64, 64); if(!alt->world2d) { Destroy(alt); return nullptr; } alt->worldRender = MakeRenderable(alt->world2d, renderer, targetLayout); if(!alt->worldRender){ Destroy(alt); return nullptr; } return alt; } void ALifeTests::Destroy(ALifeTests* alt) { if(!alt) return; DestroyRenderable(alt->worldRender); World2D_Destroy(alt->world2d); AccelSycl_Destroy(alt->accelSycl); AccelCUDA_Destroy(alt->accelCuda); MEMORY_FREE(alt); } void ALifeTests::update(double deltaMS, Render_View const& view) { if(worldRender) { worldRender->uniforms.view.worldToViewMatrix = Math_LookAtMat4F(view.position, view.lookAt, view.upVector); float const f = 1.0f / tanf(view.perspectiveFOV / 2.0f); worldRender->uniforms.view.viewToNDCMatrix = { f / view.perspectiveAspectWoverH, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, view.nearOffset, 0.0f }; worldRender->uniforms.view.worldToNDCMatrix = Math_MultiplyMat4F(worldRender->uniforms.view.worldToViewMatrix, worldRender->uniforms.view.viewToNDCMatrix); } } void ALifeTests::render(Render_GraphicsEncoderHandle encoder) { if(worldRender) { RenderWorld2D(world2d, worldRender, encoder); } }
31.851613
157
0.741847
DeanoC
d424b8f937498c573174f50aa1c4de4b42b5554d
1,033
cpp
C++
arm9/source/_lua/lua.gadget.colorpicker.gradient.cpp
DuffsDevice/winds
35f1b5fd458c527a6c372f94077e784f6fd960b2
[ "MIT" ]
2
2017-02-07T18:25:07.000Z
2021-12-13T18:29:03.000Z
arm9/source/_lua/lua.gadget.colorpicker.gradient.cpp
DuffsDevice/winds
35f1b5fd458c527a6c372f94077e784f6fd960b2
[ "MIT" ]
null
null
null
arm9/source/_lua/lua.gadget.colorpicker.gradient.cpp
DuffsDevice/winds
35f1b5fd458c527a6c372f94077e784f6fd960b2
[ "MIT" ]
null
null
null
#include <_lua/lua.gadget.colorpicker.gradient.h> #include <_lua/lua.func.h> #include <_lua/lua.func.wrap.h> using namespace _luafunc; /*################################## ## Lua-Colorpicker ## ##################################*/ _lua_gradientcolorpicker::_lua_gradientcolorpicker( lua_State* L ) : _lua_gadget( new _gradientColorPicker( optcheck<int>( L , 1 ) , optcheck<int>( L , 2 ) , optcheck<int>( L , 3 ) , optcheck<int>( L , 4 ) , lightcheck<_color>( L , 5 , _color::blue ) , lightcheck<_style>( L , 6 , _style() ) ) ) {} //! Lua-button const char _lua_gradientcolorpicker::className[] = "GradientColorPicker"; Lunar<_lua_gradientcolorpicker>::FunctionType _lua_gradientcolorpicker::methods[] = { LUA_CLASS_FUNC_END }; Lunar<_lua_gradientcolorpicker>::PropertyType _lua_gradientcolorpicker::properties[] = { { "color" , wrap( _lua_gradientcolorpicker , &_gradientColorPicker::getColor ) , wrap( _lua_gradientcolorpicker , &_gradientColorPicker::setColor ) }, LUA_CLASS_ATTR_END };
44.913043
228
0.662149
DuffsDevice
d424f265dd71f3f060b972919d0aeaf762458041
4,710
cc
C++
Fields/QualityScoreCompressor.cc
sfu-compbio/deez
92cd56befd0c6fbd3355e75ab1747913c11ec716
[ "BSD-3-Clause" ]
13
2015-04-11T13:30:41.000Z
2020-06-24T16:58:18.000Z
Fields/QualityScoreCompressor.cc
sfu-compbio/deez
92cd56befd0c6fbd3355e75ab1747913c11ec716
[ "BSD-3-Clause" ]
1
2017-09-29T08:56:30.000Z
2017-09-29T08:56:30.000Z
Fields/QualityScoreCompressor.cc
sfu-compbio/deez
92cd56befd0c6fbd3355e75ab1747913c11ec716
[ "BSD-3-Clause" ]
6
2015-07-06T19:30:59.000Z
2022-03-11T07:22:24.000Z
#include "QualityScore.h" #include <cmath> using namespace std; #include "../Streams/Stream.h" #include "../Streams/BzipStream.h" QualityScoreCompressor::QualityScoreCompressor(void): StringCompressor<QualityCompressionStream>(), statMode(true), offset(0) { memset(lossy, 0, 128 * sizeof(int)); memset(stat, 0, 128 * sizeof(int)); switch (optQuality) { case 0: break; case 1: streams[0] = make_shared<SAMCompStream<QualRange>>(); break; case 2: streams[0] = make_shared<ArithmeticOrder2CompressionStream<QualRange>>(); break; default: throw DZException("Invalid stream specified"); break; } const char* qualities[] = { "default", "samcomp", "arithmetic" }; LOG("Using quality mode %s", qualities[optQuality]); } size_t QualityScoreCompressor::shrink(char *qual, size_t len, int flag) { if (!len || (len == 1 && qual[0] == '*')) { *qual = 0; return 0; } if (flag & 0x10) for (size_t j = 0; j < len / 2; j++) swap(qual[j], qual[len - j - 1]); ssize_t sz = len; if (sz >= 2) { sz -= 2; while (sz && qual[sz] == qual[len - 1]) sz--; sz += 2; } qual[sz] = 0; assert(sz > 0); return sz; } int QualityScoreCompressor::getOffset() { return offset; } void QualityScoreCompressor::updateOffset(int *st) { if (offset) return; for (int i = 0; i < 128; i++) stat[i] += st[i]; } void QualityScoreCompressor::calculateOffset() { if (offset) return; offset = 64; for (int i = 33; i < 64; i++) { if (i < 59 && stat[i]) { offset = 33; break; } if (stat[i]) { offset = 59; break; } } if (optLossy && statMode) { calculateLossyTable(optLossy); statMode = false; } } void QualityScoreCompressor::offsetRecord (Record &rc) { assert(offset); char *qual = (char*)rc.getQuality(); lossyTransform(qual, strlen(qual)); while (*qual) { if (*qual < offset) throw DZException("Quality scores out of range with L offset %d [%c]", offset, *qual); *qual = (*qual - offset) + 1; if (*qual >= QualRange) throw DZException("Quality scores out of range with R offset %d [%c]", offset, *qual + offset - 1); qual++; } } void QualityScoreCompressor::outputRecords (const Array<Record> &records, Array<uint8_t> &out, size_t out_offset, size_t k) { ZAMAN_START(QualityScoreOutput); out.add(offset); out_offset++; Array<uint8_t> buffer(totalSize, MB); for (size_t i = 0; i < k; i++) { const char *q = records[i].getQuality(); while (*q) buffer.add(*q), q++; buffer.add(0); totalSize -= (q - records[i].getQuality()) + 1; } compressArray(streams.front(), buffer, out, out_offset); memset(stat, 0, 128 * sizeof(int)); offset = 0; ZAMAN_END(QualityScoreOutput); } double QualityScoreCompressor::phredScore (char c, int offset) { return pow(10, (offset - c) / 10.0); } bool statSort (const pair<char, int> &a, const pair<char, int> &b) { return (a.second > b.second || (a.second == b.second && a.first < b.first)); } void QualityScoreCompressor::calculateLossyTable (int percentage) { if (!offset) throw DZException("Offset not calculated"); // calculate replacements for (int c = 0; c < 128; c++) lossy[c] = c; // if percentage is 0% then keep original qualities if (!percentage) return; vector<char> alreadyAssigned(128, 0); // Discard all elements with >30% error for (char hlimit = offset; 100 * phredScore(hlimit, offset) > 30; hlimit++) { lossy[hlimit] = offset; alreadyAssigned[hlimit] = 1; } // sort stats by maximum value pair<char, int> bmm[128]; for (int i = 0; i < 128; i++) bmm[i] = make_pair(i, stat[i]); sort(bmm, bmm + 128, statSort); // obtain replacement table double p = percentage / 100.0; for (int i = 0; i < 128 && bmm[i].second; i++) { if (!alreadyAssigned[bmm[i].first] && stat[bmm[i].first] >= stat[bmm[i].first - 1] && stat[bmm[i].first] >= stat[bmm[i].first + 1]) { double er = phredScore(bmm[i].first, offset); double total = er; char left = bmm[i].first, right = bmm[i].first; for (int c = bmm[i].first - 1; c >= 0; c--) { total += phredScore(c, offset); if (alreadyAssigned[c] || total / (bmm[i].first - c + 1) > er + (er * p)) { left = c + 1; break; } } total = er; for (int c = bmm[i].first + 1; c < 128; c++) { total += phredScore(c, offset); if (alreadyAssigned[c] || total / (c - bmm[i].first + 1) < er - (er * p)) { right = c - 1; break; } } for (char c = left; c <= right; c++) { lossy[c] = bmm[i].first; alreadyAssigned[c] = 1; } } } } void QualityScoreCompressor::lossyTransform (char *qual, size_t len) { if (!optLossy) return; if (!statMode) for (size_t i = 0; i < len; i++) qual[i] = lossy[qual[i]]; }
23.432836
124
0.614013
sfu-compbio
d42892cc9e81c75a6ef583d1782ae4ed0e76e04e
268
cpp
C++
C++11/language/class/ideone_e3Ar56.cpp
varunnagpaal/cpp
1b7e1678d05d93227caea49b5629cadd217553de
[ "MIT" ]
1
2016-12-15T12:56:41.000Z
2016-12-15T12:56:41.000Z
C++11/language/class/ideone_e3Ar56.cpp
varunnagpaal/cpp
1b7e1678d05d93227caea49b5629cadd217553de
[ "MIT" ]
null
null
null
C++11/language/class/ideone_e3Ar56.cpp
varunnagpaal/cpp
1b7e1678d05d93227caea49b5629cadd217553de
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class A { private : int i; public: void funct(){i++; cout<<"i:"<<i<<endl;} void anFunct(){ cout<<"A "<<endl; } }; int main() { A* ptrA = NULL; ptrA->anFunct(); ptrA->funct(); return 0; }
14.888889
51
0.514925
varunnagpaal
d42ac706b5a8c53c96fa067469d5159dbb64dde7
1,068
cpp
C++
Stacks-and-Queues/EvaluateExpression.cpp
ssokjin/Interview-Bit
8714d3d627eb5875f49d205af779b59ca33ab4a3
[ "MIT" ]
513
2016-08-16T12:52:14.000Z
2022-03-30T19:32:10.000Z
Stacks-and-Queues/EvaluateExpression.cpp
ssokjin/Interview-Bit
8714d3d627eb5875f49d205af779b59ca33ab4a3
[ "MIT" ]
25
2018-02-14T15:25:48.000Z
2022-03-23T11:52:08.000Z
Stacks-and-Queues/EvaluateExpression.cpp
ssokjin/Interview-Bit
8714d3d627eb5875f49d205af779b59ca33ab4a3
[ "MIT" ]
505
2016-09-02T15:04:20.000Z
2022-03-25T06:36:31.000Z
// https://www.interviewbit.com/problems/evaluate-expression/ int Solution::evalRPN(vector<string> &A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details stack<int> st; for(int i = 0; i < A.size(); i++){ if(A[i] == "+" || A[i] == "-" || A[i] == "*" || A[i] == "/"){ int first = st.top(); st.pop(); int second = st.top(); st.pop(); if(A[i] == "+"){ st.push(second+first); } else if(A[i] == "-"){ st.push(second-first); } else if(A[i] == "*"){ st.push(second*first); } else{ st.push(second/first); } } else{ st.push(atoi(A[i].c_str())); } } return st.top(); }
28.105263
93
0.438202
ssokjin
2d72c22f457c086fcf9176e0a7caf98191d7c294
9,073
cc
C++
tests/testapp/testapp_tenant.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
null
null
null
tests/testapp/testapp_tenant.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
null
null
null
tests/testapp/testapp_tenant.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2021-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "testapp.h" #include "testapp_client_test.h" #include <cbsasl/password_database.h> #include <cbsasl/user.h> class TenantTest : public TestappClientTest { public: void SetUp() override { memcached_cfg["enforce_tenant_limits_enabled"] = true; reconfigure(); } void TearDown() override { memcached_cfg["enforce_tenant_limits_enabled"] = false; reconfigure(); } /// get the tenant-specific data for the tenant used in the unit /// test ({"domain":"local","user":"jones"}) /// @throws std::runtime_error for errors (which would cause the calling /// test to fail (which is what we expect)) nlohmann::json getTenantStats() { bool found = false; nlohmann::json ret; adminConnection->stats( [&found, &ret](const auto& key, const auto& value) { if (key != R"({"domain":"local","user":"jones"})") { throw std::runtime_error( "Internal error: Unexpected tenant received: " + key); } ret = nlohmann::json::parse(value); found = true; }, R"(tenants {"domain":"local","user":"jones"})"); if (!found) { throw std::runtime_error( "Did not find any tenant stats for jones!"); } return ret; } }; INSTANTIATE_TEST_SUITE_P(TransportProtocols, TenantTest, ::testing::Values(TransportProtocols::McbpPlain), ::testing::PrintToStringParamName()); TEST_P(TenantTest, TenantStats) { // We should not have any tenants yet adminConnection->stats( [](const std::string& key, const std::string& value) -> void { FAIL() << "We just enabled tenant stats so no one should " "exist, but received: " << std::endl << key << " - " << value; }, "tenants"); adminConnection->createBucket("rbac_test", "", BucketType::Memcached); auto clone = getConnection().clone(); clone->authenticate("jones", "jonespassword", "PLAIN"); auto json = getTenantStats(); // We've not sent any commands after we authenticated EXPECT_EQ(0, json["ingress_bytes"].get<int>()); // But we did send the reply to the AUTH so we should have // sent 1 mcbp response header EXPECT_EQ(sizeof(cb::mcbp::Header), json["egress_bytes"].get<int>()); EXPECT_EQ(1, json["connections"]["current"].get<int>()); EXPECT_EQ(1, json["connections"]["total"].get<int>()); clone->execute(BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop}); json = getTenantStats(); EXPECT_EQ(sizeof(cb::mcbp::Header), json["ingress_bytes"].get<int>()); EXPECT_EQ(sizeof(cb::mcbp::Header) + sizeof(cb::mcbp::Header), json["egress_bytes"].get<int>()); EXPECT_EQ(1, json["connections"]["current"].get<int>()); EXPECT_EQ(1, json["connections"]["total"].get<int>()); // Reconnect and verify that we keep the correct # for total connections clone->reconnect(); clone->authenticate("jones", "jonespassword", "PLAIN"); json = getTenantStats(); EXPECT_EQ(sizeof(cb::mcbp::Header), json["ingress_bytes"].get<int>()); EXPECT_EQ(3 * sizeof(cb::mcbp::Header), json["egress_bytes"].get<int>()); // We can't validate the "current" connection here, reconnect // could cause us to end up on a different front end thread // on memcached and we can't really predict the scheduling // so we could end up getting here _before_ the disconnect // logic happened on the other thread (we've seen this in // one CV unit test failure already) EXPECT_EQ(2, json["connections"]["total"].get<int>()); if (!folly::kIsSanitize) { // NOLINT // make sure we can rate limit. Hopefully the CV allows for 6000 noop/s bool error = false; while (!error) { auto rsp = clone->execute( BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop}); if (!rsp.isSuccess()) { EXPECT_EQ(cb::mcbp::Status::RateLimitedMaxCommands, rsp.getStatus()) << rsp.getDataString(); error = true; } } std::this_thread::sleep_for(std::chrono::seconds{1}); auto rsp = clone->execute( BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop}); ASSERT_TRUE(rsp.isSuccess()) << to_string(rsp.getStatus()); } // verify that we can't create as many connections that we want bool done = false; std::vector<std::unique_ptr<MemcachedConnection>> connections; while (!done) { // We should always be able to connect (as we don't know who // the tenant is so we can't be disconnected for that) connections.push_back(clone->clone()); // We should always be able to authenticate (we don't want to "break" // clients by reporting authenticate error for a correct username // password combination, but that you're out of connections) connections.back()->authenticate("jones", "jonespassword", "PLAIN"); // But we'll disconnect you upon the first command you try to // execute auto rsp = connections.back()->execute( BinprotGenericCommand(cb::mcbp::ClientOpcode::Noop)); if (!rsp.isSuccess()) { // Command failed, so it should be rate limited ASSERT_EQ(cb::mcbp::Status::RateLimitedMaxConnections, rsp.getStatus()); done = true; } } // Verify that the stats recorded the rate limiting json = getTenantStats(); const auto& limited = json["rate_limited"]; EXPECT_EQ(1, limited["num_connections"].get<int>()); if (!folly::kIsSanitize) { // NOLINT EXPECT_EQ(1, limited["num_ops_per_min"].get<int>()); } // Verify that the number of current connections is correct: EXPECT_EQ(10, json["connections"]["current"].get<int>()); // Close all of the connections, and verify that the current connection // counter should drop. Multiple threads are involved so we need to // run a loop and wait.. connections.clear(); auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(30); int current = 0; do { json = getTenantStats(); current = json["connections"]["current"].get<int>(); if (current != 1) { // back off to let the other threads run so we don't busy-wait std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } while (current != 1 && std::chrono::steady_clock::now() < timeout); if (current != 1) { FAIL() << "Timed out waiting for current connections to drop to 1"; } // verify that we can request all tenants bool found = false; adminConnection->stats( [&found](const std::string& key, const std::string& value) -> void { EXPECT_EQ("0", key); EXPECT_NE(std::string::npos, value.find( R"("id":{"domain":"local","user":"jones"})")); found = true; }, "tenants"); ASSERT_TRUE(found) << "Expected tenant data to be found for jones"; // Verify that I can tune the tenants limits. Lower the max limit to // 5 connections auto& db = mcd_env->getPasswordDatabase(); auto user = db.find("jones"); auto limits = user.getLimits(); limits.num_connections = 5; user.setLimits(limits); db.upsert(std::move(user)); mcd_env->refreshPasswordDatabase(*adminConnection); for (uint64_t ii = 1; ii < limits.num_connections; ++ii) { connections.push_back(clone->clone()); connections.back()->authenticate("jones", "jonespassword", "PLAIN"); auto rsp = connections.back()->execute( BinprotGenericCommand(cb::mcbp::ClientOpcode::Noop)); ASSERT_TRUE(rsp.isSuccess()) << "We should be able to fill the limit"; } connections.push_back(clone->clone()); connections.back()->authenticate("jones", "jonespassword", "PLAIN"); auto rsp = connections.back()->execute( BinprotGenericCommand(cb::mcbp::ClientOpcode::Noop)); ASSERT_EQ(cb::mcbp::Status::RateLimitedMaxConnections, rsp.getStatus()) << rsp.getDataString(); adminConnection->deleteBucket("rbac_test"); }
41.619266
80
0.59385
nawazish-couchbase
2d7884c99a246e3606791552dc1a53326ad46bce
12,169
cpp
C++
src/vision/pixel_histograms.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/vision/pixel_histograms.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/vision/pixel_histograms.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ #include "vision/pixel_histograms.h" #include "core/image.h" #include "vision/vision_params.h" #include <cassert> #include <iostream> using namespace vulcan; using namespace vulcan::vision; pixel_histogram_method_t convert_string_to_method(const std::string& methodString); uint16_t calculate_bin_size(uint16_t numBins, uint16_t maxBinValue); // Histogram comparison metrics float histogram_intersection(const std::vector<float>& histA, const std::vector<float>& histB); boost::shared_ptr<PixelHistogram> PixelHistogram::createPixelHistogram(pixel_histogram_method_t method, const Image& image, const std::vector<Point<int16_t>>& pixels, const histogram_params_t& params) { boost::shared_ptr<PixelHistogram> histogram; switch (method) { case HISTOGRAM_OPPONENT_COLOR: histogram.reset(new OpponentColorHistogram(params.opponentParams)); break; case HISTOGRAM_RGB: histogram.reset(new RGBColorHistogram(params.rgbParams)); break; case HISTOGRAM_SIMPLE_COLOR_CONSTANCY: histogram.reset(new SimpleColorConstancyHistogram(params.constancyParams)); break; case HISTOGRAM_INTENSITY: std::cerr << "ERROR:Intensity histogram not currently implemented" << std::endl; assert(false); break; default: std::cerr << "ERROR:Unknown histogram type" << std::endl; assert(false); break; } histogram->method = method; histogram->calculateHistogram(image, pixels); return histogram; } boost::shared_ptr<PixelHistogram> PixelHistogram::createPixelHistogram(const std::string& method, const Image& image, const std::vector<Point<int16_t>>& pixels, const histogram_params_t& params) { return createPixelHistogram(convert_string_to_method(method), image, pixels, params); } boost::shared_ptr<PixelHistogram> PixelHistogram::copyPixelHistogram(pixel_histogram_method_t method, const std::vector<float>& values, const std::vector<uint16_t>& dimensions) { boost::shared_ptr<PixelHistogram> histogram; switch (method) { case HISTOGRAM_OPPONENT_COLOR: histogram.reset(new OpponentColorHistogram(values, dimensions)); break; case HISTOGRAM_RGB: histogram.reset(new RGBColorHistogram(values, dimensions)); break; case HISTOGRAM_SIMPLE_COLOR_CONSTANCY: histogram.reset(new SimpleColorConstancyHistogram(values, dimensions)); break; case HISTOGRAM_INTENSITY: std::cerr << "ERROR:Intensity histogram not currently implemented" << std::endl; assert(false); break; default: std::cerr << "ERROR:Unknown histogram type" << std::endl; assert(false); break; } histogram->method = method; return histogram; } boost::shared_ptr<PixelHistogram> PixelHistogram::copyPixelHistogram(const std::string& method, const std::vector<float>& values, const std::vector<uint16_t>& dimensions) { return copyPixelHistogram(convert_string_to_method(method), values, dimensions); } PixelHistogram::PixelHistogram(const std::vector<uint16_t>& dimensions, const std::vector<float>& values) : dimensions(dimensions) , values(values) { } float PixelHistogram::compare(boost::shared_ptr<PixelHistogram> toCompare) { assert(this->method == toCompare->method); return this->calculateHistogramSimilarity(toCompare); } // Implementation for RGBColorHistogram RGBColorHistogram::RGBColorHistogram(const std::vector<float>& values, const std::vector<uint16_t>& dimensions) : PixelHistogram(dimensions, values) { } RGBColorHistogram::RGBColorHistogram(const rgb_histogram_params_t& params) { dimensions.resize(3); dimensions[0] = params.rBins; dimensions[1] = params.gBins; dimensions[2] = params.bBins; values.resize(params.rBins * params.gBins * params.bBins, 0); } void RGBColorHistogram::calculateHistogram(const Image& image, const std::vector<Point<int16_t>>& pixels) { int rowStride = dimensions[0]; int sliceStride = dimensions[0] * dimensions[1]; int rBinSize = calculate_bin_size(dimensions[0], 256); int gBinSize = calculate_bin_size(dimensions[1], 256); int bBinSize = calculate_bin_size(dimensions[2], 256); uint8_t rValue = 0; uint8_t gValue = 0; uint8_t bValue = 0; unsigned int row = 0; unsigned int column = 0; unsigned int slice = 0; assert(pixels.size() > 0); for (auto pixelIt = pixels.begin(), endIt = pixels.end(); pixelIt != endIt; ++pixelIt) { image.getPixel(pixelIt->x, pixelIt->y, rValue, gValue, bValue); row = rValue / rBinSize; column = (gValue / gBinSize) * rowStride; slice = (bValue / bBinSize) * sliceStride; if (row + column + slice > values.size()) { std::cerr << "ERROR:RGBHistogram:Pixel out of bounds:RGB(" << (int)rValue << ',' << (int)gValue << ',' << (int)bValue << ")->(" << row << ',' << column << ',' << slice << ")\n"; assert(false); } ++values[row + column + slice]; } for (auto valueIt = values.begin(), endIt = values.end(); valueIt != endIt; ++valueIt) { *valueIt /= pixels.size(); } } float RGBColorHistogram::calculateHistogramSimilarity(boost::shared_ptr<PixelHistogram> histogram) { return histogram_intersection(values, histogram->getValues()); } // Implementation for OpponentColorHistogram OpponentColorHistogram::OpponentColorHistogram(const std::vector<float>& values, const std::vector<uint16_t>& dimensions) : PixelHistogram(dimensions, values) { } OpponentColorHistogram::OpponentColorHistogram(const opponent_color_histogram_params_t& params) { dimensions.resize(3); dimensions[0] = params.rgBins; dimensions[1] = params.byBins; dimensions[2] = params.wbBins; values.resize((params.rgBins * params.byBins * params.wbBins), 0); } void OpponentColorHistogram::calculateHistogram(const Image& image, const std::vector<Point<int16_t>>& pixels) { int rowStride = dimensions[0]; int sliceStride = dimensions[0] * dimensions[1]; int rgBinSize = calculate_bin_size(dimensions[0], 256); int byBinSize = calculate_bin_size(dimensions[1], 256); int wbBinSize = calculate_bin_size(dimensions[2], 256); uint8_t rValue = 0; uint8_t gValue = 0; uint8_t bValue = 0; unsigned int row = 0; unsigned int column = 0; unsigned int slice = 0; for (auto pixelIt = pixels.begin(), endIt = pixels.end(); pixelIt != endIt; ++pixelIt) { image.getPixel(pixelIt->x, pixelIt->y, rValue, gValue, bValue); row = abs(rValue - gValue) / rgBinSize; column = abs(2 * static_cast<int>(bValue) - rValue - gValue) / byBinSize; slice = (static_cast<int>(rValue) + gValue + bValue) / wbBinSize; std::cout << "vals:" << row << ' ' << column << ' ' << slice << " stride:" << rowStride << ' ' << sliceStride << '\n'; column *= rowStride; slice *= sliceStride; if (row + column + slice > values.size()) { std::cerr << "ERROR:OpponentColorHistogram:Pixel out of bounds:RGB(" << (int)rValue << ',' << (int)gValue << ',' << (int)bValue << ")->(" << row << ',' << column << ',' << slice << ")\n"; assert(false); } ++values[row + column + slice]; } for (auto valueIt = values.begin(), endIt = values.end(); valueIt != endIt; ++valueIt) { *valueIt /= pixels.size(); } } float OpponentColorHistogram::calculateHistogramSimilarity(boost::shared_ptr<PixelHistogram> histogram) { return histogram_intersection(values, histogram->getValues()); } // Implementation for SimpleColorConstancyHistogram SimpleColorConstancyHistogram::SimpleColorConstancyHistogram(const std::vector<float>& values, const std::vector<uint16_t>& dimensions) : PixelHistogram(dimensions, values) { } SimpleColorConstancyHistogram::SimpleColorConstancyHistogram(const simple_color_constancy_histogram_params_t& params) { dimensions.resize(2); dimensions[0] = params.rPrimeBins; dimensions[1] = params.gPrimeBins; values.resize((params.rPrimeBins * params.gPrimeBins), 0); } void SimpleColorConstancyHistogram::calculateHistogram(const Image& image, const std::vector<Point<int16_t>>& pixels) { int rowStride = dimensions[0]; int rBinSize = calculate_bin_size(dimensions[0], 256); int gBinSize = calculate_bin_size(dimensions[1], 256); uint8_t rValue = 0; uint8_t gValue = 0; uint8_t bValue = 0; int pixelSum = 0; int row = 0; int column = 0; for (auto pixelIt = pixels.begin(), endIt = pixels.end(); pixelIt != endIt; ++pixelIt) { image.getPixel(pixelIt->x, pixelIt->y, rValue, gValue, bValue); pixelSum = rValue + gValue + bValue; row = (rValue / pixelSum) / rBinSize; column = (gValue / pixelSum) / gBinSize; column *= rowStride; ++values[row + column]; } for (auto valueIt = values.begin(), endIt = values.end(); valueIt != endIt; ++valueIt) { *valueIt /= pixels.size(); } } float SimpleColorConstancyHistogram::calculateHistogramSimilarity(boost::shared_ptr<PixelHistogram> histogram) { return histogram_intersection(values, histogram->getValues()); } // Helpers pixel_histogram_method_t convert_string_to_method(const std::string& methodString) { if (methodString == HISTOGRAM_OPPONENT_COLOR_STRING) { return HISTOGRAM_OPPONENT_COLOR; } else if (methodString == HISTOGRAM_RGB_STRING) { return HISTOGRAM_RGB; } else if (methodString == HISTOGRAM_SIMPLE_COLOR_CONSTANCY_STRING) { return HISTOGRAM_SIMPLE_COLOR_CONSTANCY; } else if (methodString == HISTOGRAM_INTENSITY_STRING) { return HISTOGRAM_INTENSITY; } else { std::cerr << "ERROR: Unknown histogram method: " << methodString << std::endl; assert(false); } return HISTOGRAM_RGB; } uint16_t calculate_bin_size(uint16_t numBins, uint16_t maxBinValue) { uint16_t binSize = maxBinValue / numBins; // If the max value and the bin size don't divide evenly, then increase the bin size by // to account for the extra pixels. NOTE: This is a junky solution, but it'll have to do // for now if (maxBinValue % numBins != 0) { ++binSize; } return binSize; } // Histogram comparison metrics float histogram_intersection(const std::vector<float>& histA, const std::vector<float>& histB) { /* * This metric comes from "Color Indexing" by Swain and Ballard, 1991 * * Because the histograms are normalized, the histogram intersection is the * city-block metric between the histograms. Thus, the intersection becomes: * * H(A, B) = 1 - 0.5*sum(abs(histA_i - histB_i)) */ float totalDiff = 0.0f; for (size_t n = 0; n < histA.size(); ++n) { totalDiff += fabs(histA[n] - histB[n]); } return 1.0f - totalDiff / 2.0f; }
31.772846
117
0.635056
anuranbaka
2d801bf2929bf1817171cb0d2ad850387d27862b
4,033
hpp
C++
rcff/include/CXKJ/RCF/Filter.hpp
DayBreakZhang/CXKJ_Code
c7caab736313f029324f1c95714f5a94b2589076
[ "Apache-2.0" ]
null
null
null
rcff/include/CXKJ/RCF/Filter.hpp
DayBreakZhang/CXKJ_Code
c7caab736313f029324f1c95714f5a94b2589076
[ "Apache-2.0" ]
null
null
null
rcff/include/CXKJ/RCF/Filter.hpp
DayBreakZhang/CXKJ_Code
c7caab736313f029324f1c95714f5a94b2589076
[ "Apache-2.0" ]
null
null
null
//****************************************************************************** // RCF - Remote Call Framework // // Copyright (c) 2005 - 2019, Delta V Software. All rights reserved. // http://www.deltavsoft.com // // RCF is distributed under dual licenses - closed source or GPL. // Consult your particular license for conditions of use. // // If you have not purchased a commercial license, you are using RCF // under GPL terms. // // Version: 3.1 // Contact: support <at> deltavsoft.com // //****************************************************************************** #ifndef INCLUDE_RCF_FILTER_HPP #define INCLUDE_RCF_FILTER_HPP #include <string> #include <vector> #include <memory> #include <RCF/Export.hpp> namespace RCF { // collect these constants here so we can avoid collisions static const int RcfFilter_Unknown = 0; static const int RcfFilter_Identity = 1; static const int RcfFilter_OpenSsl = 2; static const int RcfFilter_ZlibCompressionStateless = 3; static const int RcfFilter_ZlibCompressionStateful = 4; static const int RcfFilter_SspiNtlm = 5; static const int RcfFilter_SspiKerberos = 6; static const int RcfFilter_SspiNegotiate = 7; static const int RcfFilter_SspiSchannel = 8; static const int RcfFilter_Xor = 101; class Filter; class ByteBuffer; typedef std::shared_ptr<Filter> FilterPtr; class RCF_EXPORT Filter { public: Filter(); virtual ~Filter(); virtual void resetState(); // TODO: for generality, should take a vector<ByteBuffer> & // (applicable if message arrives fragmented through the transport) // BTW, bytesRequested is meaningful if byteBuffer is empty virtual void read( const ByteBuffer &byteBuffer, std::size_t bytesRequested) = 0; virtual void write(const std::vector<ByteBuffer> &byteBuffers) = 0; virtual void onReadCompleted(const ByteBuffer &byteBuffer) = 0; virtual void onWriteCompleted(std::size_t bytesTransferred) = 0; virtual int getFilterId() const = 0; void setPreFilter(Filter &preFilter); void setPostFilter(Filter &postFilter); virtual std::size_t getFrameSize() { return 0; } protected: Filter &getPreFilter(); Filter &getPostFilter(); Filter *mpPreFilter; Filter *mpPostFilter; }; class RCF_EXPORT IdentityFilter : public Filter { public: void read(const ByteBuffer &byteBuffer, std::size_t bytesRequested); void write(const std::vector<ByteBuffer> &byteBuffers); void onReadCompleted(const ByteBuffer &byteBuffer); void onWriteCompleted(std::size_t bytesTransferred); virtual int getFilterId() const; }; class RcfServer; class FilterFactory { public: virtual ~FilterFactory() {} virtual FilterPtr createFilter(RcfServer & server) = 0; virtual int getFilterId() = 0; }; typedef std::shared_ptr<FilterFactory> FilterFactoryPtr; RCF_EXPORT void connectFilters(const std::vector<FilterPtr> &filters); RCF_EXPORT bool filterData( const std::vector<ByteBuffer> &unfilteredData, std::vector<ByteBuffer> &filteredData, const std::vector<FilterPtr> &filters); RCF_EXPORT bool unfilterData( const ByteBuffer &filteredByteBuffer, std::vector<ByteBuffer> &unfilteredByteBuffers, std::size_t unfilteredDataLen, const std::vector<FilterPtr> &filters); RCF_EXPORT bool unfilterData( const ByteBuffer &filteredByteBuffer, ByteBuffer &unfilteredByteBuffer, std::size_t unfilteredDataLen, const std::vector<FilterPtr> &filters); } // namespace RCF #endif // ! INCLUDE_RCF_FILTER_HPP
29.437956
80
0.617654
DayBreakZhang
2d8832ec13c0f3c2d2d0e1ffb37515a27b7042ab
710
cpp
C++
Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2021-08-11T06:36:42.000Z
2021-08-11T06:36:42.000Z
/* Generate Parentheses ==================== Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Constraints: 1 <= n <= 8 */ class Solution { public: void dfs(int n, int o, int c, vector<string> &ans, string stn) { if (o == n && c == n) { ans.push_back(stn); return; } if (o < n) dfs(n, o + 1, c, ans, stn + "("); if (c < o) dfs(n, o, c + 1, ans, stn + ")"); } vector<string> generateParenthesis(int n) { vector<string> ans; dfs(n, 0, 0, ans, ""); return ans; } };
16.511628
103
0.495775
Akshad7829
2d8a892d31f025bba860efd08d427af16cdeba5f
7,124
cpp
C++
src/qml/qt_native/contractfilterproxy.cpp
user00000001/tesramain
ddd02da923da2f9bc9dfddc1a8b177e1cadfc341
[ "MIT" ]
10
2018-06-07T13:51:04.000Z
2020-03-12T18:27:12.000Z
src/qml/qt_native/contractfilterproxy.cpp
user00000001/tesramain
ddd02da923da2f9bc9dfddc1a8b177e1cadfc341
[ "MIT" ]
null
null
null
src/qml/qt_native/contractfilterproxy.cpp
user00000001/tesramain
ddd02da923da2f9bc9dfddc1a8b177e1cadfc341
[ "MIT" ]
6
2018-10-23T03:12:28.000Z
2020-03-14T16:07:54.000Z
#include "contractfilterproxy.h" #include "contracttablemodel.h" #include "guiutil.h" #include "csvmodelwriter.h" #include "ui_interface.h" #include <script/standard.h> #include <base58.h> #include <wallet.h> ContractFilterProxy::ContractFilterProxy(QObject *parent) : QSortFilterProxyModel(parent) { } void ContractFilterProxy::sortColumn(QString roleName, Qt::SortOrder order) { ContractTableModel::ColumnIndex ci; if(roleName == "label") ci = ContractTableModel::Label; else if(roleName == "address") ci = ContractTableModel::Address; else if(roleName == "abi") ci = ContractTableModel::ABI; sort(ci,order); } void ContractFilterProxy::exportClicked() { QString filename = GUIUtil::getSaveFileName(NULL, tr("Export Contract List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(this); writer.addColumn("Label", ContractTableModel::Label, Qt::EditRole); writer.addColumn("Address", ContractTableModel::Address, Qt::EditRole); writer.addColumn("ABI", ContractTableModel::ABI, Qt::EditRole); if (writer.write()) { emit message(tr("Exporting Successful"), tr("File exported."), CClientUIInterface::MSG_INFORMATION); } else { emit message(tr("Exporting Failed"), tr("There was an error trying to save the contract list to %1. Please try again.").arg(filename), CClientUIInterface::MSG_ERROR); } } QString ContractFilterProxy::saveContract(int mode, const QString &label, const QString &contract,const QString &abiStr,int row ) { QString address; ContractTableModel *sourceModel_ = static_cast<ContractTableModel *> (sourceModel()); switch (mode) { case 0://new address = sourceModel_->addRow( label, contract, abiStr); break; case 1://edit sourceModel_->setData(sourceModel_->index(mapToSource(index(row,0)).row(),(int)ContractTableModel::Label),label,Qt::EditRole); sourceModel_->setData(sourceModel_->index(mapToSource(index(row,0)).row(),(int)ContractTableModel::Address),contract,Qt::EditRole); sourceModel_->setData(sourceModel_->index(mapToSource(index(row,0)).row(),(int)ContractTableModel::ABI),abiStr,Qt::EditRole); break; } if( (mode == 0) && address.isEmpty()) { return GetAddressStatus(); } return "ok"; } QString ContractFilterProxy::GetAddressStatus() { ContractTableModel *sourceModel_ = static_cast<ContractTableModel *> (sourceModel()); switch (sourceModel_->getEditStatus()) { case ContractTableModel::OK: return tr("Failed with unknown reason."); case ContractTableModel::NO_CHANGES: return tr("No changes were made during edit operation."); case ContractTableModel::DUPLICATE_ADDRESS: return tr("The entered address is already in the address book."); } } void ContractFilterProxy::deleteContract(int row) { removeRows(row,1); } QVariant ContractFilterProxy::getData(QString roleName, int sourceRow) { if(roleName == "address"){ QModelIndex index_ = mapToSource(this->index(sourceRow,0)); return index_.data(ContractTableModel::AddressRole).toString(); } else if(roleName == "label") { QModelIndex index_ = mapToSource(this->index(sourceRow,0)); return index_.data(ContractTableModel::LabelRole).toString(); } else if(roleName == "abi") { QModelIndex index_ = mapToSource(this->index(sourceRow,0)); return index_.data(ContractTableModel::ABIRole).toString(); } } QString ContractFilterProxy::updateABI(const QString& address) { ContractTableModel *sourceModel_ = static_cast<ContractTableModel *>(sourceModel()); return sourceModel_->abiForAddress(address); } int ContractFilterProxy::lookupAddress(const QString &address) const { ContractTableModel *sourceModel_ = static_cast<ContractTableModel *>(sourceModel()); return sourceModel_->lookupAddress(address); } //-----------------addressList---------------- void ContractFilterProxy::on_refresh() { m_stringList.clear(); vector<COutput> vecOutputs; assert(pwalletMain != NULL); { // Fill the list with UTXO LOCK2(cs_main, pwalletMain->cs_wallet); // Add all available addresses if 0 address ballance for token is enabled if(m_addressTableModel) { // Fill the list with user defined address for(int row = 0; row < m_addressTableModel->rowCount(); row++) { QModelIndex index = m_addressTableModel->index(row, AddressTableModel::Address); QString strAddress = m_addressTableModel->data(index,Qt::EditRole).toString(); QString type = m_addressTableModel->data(index, AddressTableModel::TypeRole).toString(); if(type == AddressTableModel::Receive) { appendAddress(strAddress); } } // Include zero or unconfirmed coins too pwalletMain->AvailableCoins(vecOutputs, false, NULL, true); } else { // List only the spendable coins pwalletMain->AvailableCoins(vecOutputs); } for(const COutput& out : vecOutputs) { CTxDestination address; const CScript& scriptPubKey = out.tx->vout[out.i].scriptPubKey; bool fValidAddress = ExtractDestination(scriptPubKey, address); if (fValidAddress) { QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString()); appendAddress(strAddress); } } } //TODO: may need to update the current picked address in qml emit addressListChanged(); } void ContractFilterProxy::appendAddress(const QString &strAddress) { CTxDestination address = CBitcoinAddress(strAddress.toStdString()).Get(); if(!IsValidContractSenderAddress(address)) return; if(!m_stringList.contains(strAddress) && IsMine(*pwalletMain, address)) { m_stringList.append(strAddress); } } void ContractFilterProxy::setAddressTableModel(AddressTableModel *addreddTableModel) { ContractTableModel *sourceModel_ = static_cast<ContractTableModel *>(sourceModel()); m_addressTableModel = addreddTableModel; if(m_addressTableModel) { disconnect(m_addressTableModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(on_refresh())); disconnect(m_addressTableModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(on_refresh())); } connect(m_addressTableModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(on_refresh())); connect(m_addressTableModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(on_refresh())); on_refresh(); }
30.973913
142
0.654969
user00000001
2d8d8028a0c63d30214faa2ed6d1d8b008e4e55d
5,953
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/Polygon.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/Polygon.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/Polygon.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: UnityEngine.ProBuilder.Poly2Tri.Triangulatable #include "UnityEngine/ProBuilder/Poly2Tri/Triangulatable.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: IList`1<T> template<typename T> class IList_1; // Forward declaring type: IEnumerable`1<T> template<typename T> class IEnumerable_1; // Forward declaring type: IList`1<T> template<typename T> class IList_1; // Forward declaring type: IEnumerable`1<T> template<typename T> class IEnumerable_1; } // Forward declaring namespace: UnityEngine::ProBuilder::Poly2Tri namespace UnityEngine::ProBuilder::Poly2Tri { // Forward declaring type: TriangulationPoint class TriangulationPoint; // Forward declaring type: DelaunayTriangle class DelaunayTriangle; // Forward declaring type: PolygonPoint class PolygonPoint; // Forward declaring type: TriangulationMode struct TriangulationMode; // Forward declaring type: TriangulationContext class TriangulationContext; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder.Poly2Tri namespace UnityEngine::ProBuilder::Poly2Tri { // Autogenerated type: UnityEngine.ProBuilder.Poly2Tri.Polygon class Polygon : public ::Il2CppObject, public UnityEngine::ProBuilder::Poly2Tri::Triangulatable { public: // protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint> _points // Offset: 0x10 System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint*>* points; // protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint> _steinerPoints // Offset: 0x18 System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint*>* steinerPoints; // protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.Polygon> _holes // Offset: 0x20 System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::Polygon*>* holes; // protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> _triangles // Offset: 0x28 System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle*>* triangles; // public System.Void .ctor(System.Collections.Generic.IList`1<UnityEngine.ProBuilder.Poly2Tri.PolygonPoint> points) // Offset: 0x19181AC static Polygon* New_ctor(System::Collections::Generic::IList_1<UnityEngine::ProBuilder::Poly2Tri::PolygonPoint*>* points); // public System.Void .ctor(System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Poly2Tri.PolygonPoint> points) // Offset: 0x1918554 static Polygon* New_ctor(System::Collections::Generic::IEnumerable_1<UnityEngine::ProBuilder::Poly2Tri::PolygonPoint*>* points); // public System.Void AddHole(UnityEngine.ProBuilder.Poly2Tri.Polygon poly) // Offset: 0x19185E8 void AddHole(UnityEngine::ProBuilder::Poly2Tri::Polygon* poly); // public UnityEngine.ProBuilder.Poly2Tri.TriangulationMode get_TriangulationMode() // Offset: 0x19185E0 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable // Base method: UnityEngine.ProBuilder.Poly2Tri.TriangulationMode Triangulatable::get_TriangulationMode() UnityEngine::ProBuilder::Poly2Tri::TriangulationMode get_TriangulationMode(); // public System.Collections.Generic.IList`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> get_Triangles() // Offset: 0x191868C // Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable // Base method: System.Collections.Generic.IList`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> Triangulatable::get_Triangles() System::Collections::Generic::IList_1<UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle*>* get_Triangles(); // public System.Void AddTriangle(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle t) // Offset: 0x1918694 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable // Base method: System.Void Triangulatable::AddTriangle(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle t) void AddTriangle(UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* t); // public System.Void AddTriangles(System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> list) // Offset: 0x19186FC // Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable // Base method: System.Void Triangulatable::AddTriangles(System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> list) void AddTriangles(System::Collections::Generic::IEnumerable_1<UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle*>* list); // public System.Void Prepare(UnityEngine.ProBuilder.Poly2Tri.TriangulationContext tcx) // Offset: 0x1918764 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable // Base method: System.Void Triangulatable::Prepare(UnityEngine.ProBuilder.Poly2Tri.TriangulationContext tcx) void Prepare(UnityEngine::ProBuilder::Poly2Tri::TriangulationContext* tcx); }; // UnityEngine.ProBuilder.Poly2Tri.Polygon } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::Poly2Tri::Polygon*, "UnityEngine.ProBuilder.Poly2Tri", "Polygon"); #pragma pack(pop)
55.12037
157
0.77104
Futuremappermydud
2d8e8ef8d0b0dd8e2a485f948d26d76631be74e1
7,202
cpp
C++
ioserver/src/ioserver/serialport/AsyncSerialPort.cpp
kaliatech/r7-ioserver
23612ef721a7bf7a8049f3c25fcf46b1fd5b5c62
[ "MIT" ]
1
2018-08-21T12:05:04.000Z
2018-08-21T12:05:04.000Z
ioserver/src/ioserver/serialport/AsyncSerialPort.cpp
kaliatech/r7-ioserver
23612ef721a7bf7a8049f3c25fcf46b1fd5b5c62
[ "MIT" ]
null
null
null
ioserver/src/ioserver/serialport/AsyncSerialPort.cpp
kaliatech/r7-ioserver
23612ef721a7bf7a8049f3c25fcf46b1fd5b5c62
[ "MIT" ]
null
null
null
#include "ioserver/serialport/AsyncSerialPort.h" #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread/mutex.hpp> #include "ioserver/serialport/AsyncSerialEvent.h" #include "easyloggingpp/easylogging++.h" namespace r7 { AsyncSerialPort::AsyncSerialPort() : io_service(), port(io_service), serialPortOpen(false), _readDataBuffer(1024), writeBufferSize(0) { onAsyncReadFunctor = boost::bind( &AsyncSerialPort::onAsyncReadComplete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred); onAsyncWriteFunctor = boost::bind( &AsyncSerialPort::onAsyncWriteComplete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred); } AsyncSerialPort::~AsyncSerialPort() { io_service.stop(); if(isOpen()) { try { close(); } catch(...) { LOG(ERROR) << "Error closing serial port"; } } eventSignal.disconnect_all_slots(); } void AsyncSerialPort::open( const std::string& devname, unsigned int baud_rate, boost::asio::serial_port_base::parity opt_parity, boost::asio::serial_port_base::character_size opt_csize, boost::asio::serial_port_base::flow_control opt_flow, boost::asio::serial_port_base::stop_bits opt_stop) { if(isOpen()) { close(); } //setErrorStatus(true);//If an exception is thrown, error_ remains true this->portStr = devname; port.open(portStr); port.set_option(boost::asio::serial_port_base::baud_rate(baud_rate)); port.set_option(opt_parity); port.set_option(opt_csize); port.set_option(opt_flow); port.set_option(opt_stop); //setErrorStatus(false);//If we get here, no error serialPortOpen=true; //Port is now open LOG(DEBUG) << "Serial port: " << portStr << " opened."; } void AsyncSerialPort::run_io_service() { boost::asio::io_service::work work(io_service); //keeps service running even if no operations ...alternatively could queue up 1st read operation maybe try { io_service.run(); LOG(DEBUG) << "SerialPort io_service run is exiting."; } catch (...) { //would be better to set an error status LOG(ERROR) << "Unexpected exception while running serial port io_service."; close(); //alternatively, keep running } } void AsyncSerialPort::stop_io_service() { io_service.stop() ; } bool AsyncSerialPort::isOpen() { return serialPortOpen; } void AsyncSerialPort::close() { serialPortOpen = false; port.close(); LOG(DEBUG) << "Serial port: " << this->portStr << " closed."; } void AsyncSerialPort::write(const std::vector<unsigned char>& data) { // if (!port.is_open()) { // LOG(DEBUG) << "Underlying serial port not open while writing."; // } if (!isOpen()) { LOG(DEBUG) << "Logical serial port not open while writing."; return; } //scope for the lock { boost::lock_guard<boost::mutex> l(writeQueueMutex); writeQueue.insert(writeQueue.end(),data.begin(),data.end()); } io_service.post(boost::bind(&AsyncSerialPort::doAsyncWrites, this)); } void AsyncSerialPort::doAsyncWrites() { //If a write operation is already in progress, do nothing if(writeBufferSize==0) { boost::lock_guard<boost::mutex> l(writeQueueMutex); writeBufferSize=writeQueue.size(); writeBuffer.reset(new unsigned char[writeQueue.size()]); std::copy(writeQueue.begin(), writeQueue.end(), writeBuffer.get()); writeQueue.clear(); boost::asio::async_write( port, boost::asio::buffer(writeBuffer.get(),writeBufferSize), onAsyncWriteFunctor); } } void AsyncSerialPort::onAsyncWriteComplete(const boost::system::error_code& error, std::size_t bytes_transferred) { if(error) { LOG(ERROR) << "Error writing to serial port. " << error.category().name() << "-" << error.message() << "-" << error.value(); if(!isOpen()) return; //If error occurs we clear the writeBuffer? Perhaps should check bytes_transferred? LOG(DEBUG) << "Clearing write buffer. Bytes transferred before error: " << bytes_transferred; boost::lock_guard<boost::mutex> l(writeQueueMutex); writeBuffer.reset(); writeBufferSize=0; //TODO: Should probably eventually make this configurable, or responsibility of user of this class. i.e. // onAsyncError(error) this->close(); //TODO: Should we check writeQueue and try to automatically reopen/continue? return; } // boost::lock_guard<boost::mutex> l(writeQueueMutex); // if(writeQueue.empty()) // { // writeBuffer.reset(); // writeBufferSize=0; // return; // } boost::lock_guard<boost::mutex> l(writeQueueMutex); writeBuffer.reset(); writeBufferSize=0; if(!writeQueue.empty()) { io_service.post(boost::bind(&AsyncSerialPort::doAsyncWrites, this)); } } void AsyncSerialPort::read(unsigned int numBytes) { if (!isOpen()) return; io_service.post(boost::bind(&AsyncSerialPort::doAsyncRead, this, numBytes)); } void AsyncSerialPort::doAsyncRead(unsigned int numBytes) { boost::asio::async_read(port, boost::asio::buffer(_readDataBuffer, numBytes), onAsyncReadFunctor); } void AsyncSerialPort::onAsyncReadComplete(const boost::system::error_code& error, std::size_t bytes_transferred) { LOG(DEBUG) << "onAsyncReadComplete"; if(error) { //error can be true because the serial port was closed if(!isOpen()) return; #ifdef __APPLE__ if(error.value()==45) { //Bug on OS X, it might be necessary to repeat the setup //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html //doRead(); //return; } #endif //__APPLE__ //doClose(); //setErrorStatus(true); return; } std::vector<unsigned char> readData(_readDataBuffer.begin(), _readDataBuffer.begin() + bytes_transferred); AsyncSerialEvent* evt = new AsyncSerialEvent(this->getSharedPtr(), AsyncSerialEvent::DATA_READ, readData); //notify listeners with buffer contents boost::shared_ptr<AsyncSerialEvent> evtPtr = boost::shared_ptr<AsyncSerialEvent>(evt); eventSignal(evtPtr); } }
27.48855
155
0.586087
kaliatech
2d8eefd1422724afdc7eb2df7c0199441ad12609
4,815
hpp
C++
vts-libs/vts/atlas.hpp
melowntech/vts-libs
ffbf889b6603a8f95d3c12a2602232ff9c5d2236
[ "BSD-2-Clause" ]
2
2020-04-20T01:44:46.000Z
2021-01-15T06:54:51.000Z
externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/atlas.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
2
2020-01-29T16:30:49.000Z
2020-06-03T15:21:29.000Z
externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/atlas.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
1
2019-09-25T05:10:07.000Z
2019-09-25T05:10:07.000Z
/** * Copyright (c) 2017 Melown Technologies SE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef vtslibs_vts_atlas_hpp #define vtslibs_vts_atlas_hpp #include <cstdlib> #include <memory> #include <istream> #include <vector> #include <boost/any.hpp> #include <boost/filesystem/path.hpp> #include "math/geometry_core.hpp" #include "multifile.hpp" #include "../storage/streams.hpp" namespace vtslibs { namespace vts { struct Mesh; class Atlas { public: typedef std::shared_ptr<Atlas> pointer; Atlas() {} virtual ~Atlas() {} virtual std::size_t size() const = 0; void serialize(std::ostream &os) const; void deserialize(std::istream &is , const boost::filesystem::path &path = "unknown"); /** Returns area of given texture image */ double area(std::size_t index) const; /** Returns dimensions of given texture image */ math::Size2 imageSize(std::size_t index) const; bool valid(std::size_t index) const { return index < size(); } bool empty() const { return !size(); } /** Write image at given index to output stream. */ void write(std::ostream &os, std::size_t index) const; /** Write image at given index to output file. */ void write(const boost::filesystem::path &file, std::size_t index) const; static multifile::Table readTable(std::istream &is , const boost::filesystem::path &path = "unknown"); static multifile::Table readTable(const storage::IStream::pointer &is); private: virtual multifile::Table serialize_impl(std::ostream &os) const = 0; virtual void deserialize_impl(std::istream &is , const boost::filesystem::path &path , const multifile::Table &table) = 0; virtual math::Size2 imageSize_impl(std::size_t index) const = 0; virtual void write_impl(std::ostream &os, std::size_t index) const = 0; }; class RawAtlas : public Atlas { public: typedef std::shared_ptr<RawAtlas> pointer; virtual std::size_t size() const { return images_.size(); } typedef std::vector<unsigned char> Image; typedef std::vector<Image> Images; const Image& get(std::size_t index) const { return images_[index]; } void add(const Image &image); void add(const RawAtlas &other); /** Access internal data. */ const Images& get() const { return images_; } private: virtual multifile::Table serialize_impl(std::ostream &os) const; virtual void deserialize_impl(std::istream &is , const boost::filesystem::path &path , const multifile::Table &table); virtual math::Size2 imageSize_impl(std::size_t index) const; virtual void write_impl(std::ostream &os, std::size_t index) const; Images images_; }; /** Inpaint atlas. * * Inpaint atlas. Fails if `vts-libs` library code is not compiled in. */ Atlas::pointer inpaint(const Atlas &atlas, const Mesh &mesh , int textureQuality); inline double Atlas::area(std::size_t index) const { auto s(imageSize(index)); return double(s.width) * double(s.height); } inline void Atlas::write(std::ostream &os, std::size_t index) const { write_impl(os, index); } inline multifile::Table Atlas::readTable(const storage::IStream::pointer &is) { return readTable(*is, is->name()); } } } // namespace vtslibs::vts #endif // vtslibs_vts_atlas_hpp
30.283019
78
0.672274
melowntech
2d969bc84fc0c320b322039f232200d834728a3c
25,479
cpp
C++
src/otbullet/wrapper.cpp
cameni/bullet3
2a05f2d3e56589dafb6849655d30f07e62689573
[ "Zlib" ]
null
null
null
src/otbullet/wrapper.cpp
cameni/bullet3
2a05f2d3e56589dafb6849655d30f07e62689573
[ "Zlib" ]
null
null
null
src/otbullet/wrapper.cpp
cameni/bullet3
2a05f2d3e56589dafb6849655d30f07e62689573
[ "Zlib" ]
1
2020-09-09T08:53:48.000Z
2020-09-09T08:53:48.000Z
#include "discrete_dynamics_world.h" #include "multithread_default_collision_configuration.h" #include <BulletCollision/CollisionShapes/btCompoundShape.h> #include <BulletCollision/CollisionShapes/btCollisionShape.h> #include <BulletCollision/CollisionShapes/btConvexHullShape.h> #include <BulletCollision/CollisionShapes/btSphereShape.h> #include <BulletCollision/CollisionShapes/btCylinderShape.h> #include <BulletCollision/CollisionShapes/btCapsuleShape.h> #include <BulletCollision/CollisionShapes/btConeShape.h> #include <BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h> #include <BulletCollision/CollisionShapes/btTriangleMesh.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h> #include <BulletCollision/BroadphaseCollision/btAxisSweep3.h> #include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h> #include <BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h> #include <LinearMath/btIDebugDraw.h> #include "otbullet.hpp" #include "physics_cfg.h" #include <comm/ref_i.h> #include <comm/commexception.h> #include <comm/taskmaster.h> static btBroadphaseInterface* _overlappingPairCache = 0; static btCollisionDispatcher* _dispatcher = 0; static btConstraintSolver* _constraintSolver = 0; static btDefaultCollisionConfiguration* _collisionConfiguration = 0; static physics * _physics = nullptr; extern uint gOuterraSimulationFrame; //////////////////////////////////////////////////////////////////////////////// #ifdef _LIB extern bool _ext_collider(const void* context, const double3& center, float radius, float lod_dimension, coid::dynarray<bt::triangle>& data, coid::dynarray<uint>& trees, coid::slotalloc<bt::tree_batch>& tree_batches, uint frame ); extern int _ext_collider_obb( const void * context, const double3& center, const float3x3& basis, float lod_dimension, coid::dynarray<bt::triangle>& data, coid::dynarray<uint>& trees, coid::slotalloc<bt::tree_batch>& tree_batches, uint frame, bool& is_above_tm, double3& under_contact, float3& under_normal); extern float _ext_terrain_ray_intersect( const void* planet, const double3& from, const float3& dir, const float2& minmaxlen, float3* norm, double3* pos); extern static float _ext_elevation_above_terrain( const double3& pos, float maxlen, float3* norm, double3* hitpoint); extern float3 _ext_tree_col(btRigidBody * obj, bt::tree_collision_contex & ctx, float time_step, coid::slotalloc<bt::tree_batch>& tree_baFBtches); #else static bool _ext_collider( const void* planet, const double3& center, float radius, float lod_dimension, coid::dynarray<bt::triangle>& data, coid::dynarray<uint>& trees, coid::slotalloc<bt::tree_batch>& tree_batches, uint frame ) { return _physics->terrain_collisions(planet, center, radius, lod_dimension, data, trees, tree_batches, frame); } static int _ext_collider_obb( const void * planet, const double3& center, const float3x3& basis, float lod_dimension, coid::dynarray<bt::triangle>& data, coid::dynarray<uint>& trees, coid::slotalloc<bt::tree_batch>& tree_batches, uint frame, bool& is_above_tm, double3& under_contact, float3& under_normal, coid::dynarray<bt::external_broadphase*>& broadphases) { return _physics->terrain_collisions_aabb(planet, center, basis, lod_dimension, data, trees, tree_batches, frame, is_above_tm, under_contact, under_normal, broadphases); } static float _ext_terrain_ray_intersect( const void* planet, const double3& from, const float3& dir, const float2& minmaxlen, float3* norm, double3* pos) { return _physics->terrain_ray_intersect( planet, from, dir, minmaxlen, norm, pos); } static void _ext_terrain_ray_intersect_broadphase( const void* planet, const double3& from, const float3& dir, const float2& minmaxlen, coid::dynarray32<bt::external_broadphase*>& bps) { _physics->terrain_ray_intersect_broadphase( planet, from, dir, minmaxlen, bps); } static float _ext_elevation_above_terrain( const double3& pos, float maxlen, float3* norm, double3* hitpoint) { return _physics->elevation_above_terrain( pos, maxlen, norm, hitpoint); } static float3 _ext_tree_col(btRigidBody * obj, bt::tree_collision_contex & ctx, float time_step, coid::slotalloc<bt::tree_batch>& tree_batches) { return _physics->tree_collisions(obj, ctx, time_step,tree_batches); } static void _ext_add_static_collider(const void * context,btCollisionObject * obj, const double3& cen, const float3x3& basis) { _physics->add_static_collider(context,obj,cen,basis); } #endif void debug_draw_world() { if (_physics) { _physics->debug_draw_world(); } } void set_debug_drawer_enabled(btIDebugDraw * debug_draw) { if (_physics) { _physics->set_debug_draw_enabled(debug_draw); } } //////////////////////////////////////////////////////////////////////////////// iref<physics> physics::create(double r, void* context, coid::taskmaster* tm) { _physics = new physics; btDefaultCollisionConstructionInfo dccinfo; dccinfo.m_owns_simplex_and_pd_solver = false; _collisionConfiguration = new multithread_default_collision_configuration(dccinfo); _dispatcher = new btCollisionDispatcher(_collisionConfiguration); btVector3 worldMin(-r,-r,-r); btVector3 worldMax(r,r,r); _overlappingPairCache = new bt32BitAxisSweep3(worldMin, worldMax,10000); _overlappingPairCache->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback()); _constraintSolver = new btSequentialImpulseConstraintSolver(); ot::discrete_dynamics_world * wrld = new ot::discrete_dynamics_world( _dispatcher, _overlappingPairCache, _constraintSolver, _collisionConfiguration, &_ext_collider, &_ext_tree_col, &_ext_terrain_ray_intersect, &_ext_elevation_above_terrain, context, tm); wrld->setGravity(btVector3(0, 0, 0)); wrld->_aabb_intersect = &_ext_collider_obb; wrld->_terrain_ray_intersect_broadphase = &_ext_terrain_ray_intersect_broadphase; _physics->_world = wrld; _physics->_world->setForceUpdateAllAabbs(false); _physics->_dbg_drawer = nullptr; // default mode _physics->_dbg_draw_mode = btIDebugDraw::DBG_DrawContactPoints | btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits; return _physics; } iref<physics> physics::get() { if (!_physics) { throw coid::exception("Bullet not initialized yet!"); } return _physics; } //////////////////////////////////////////////////////////////////////////////// void physics::set_simulation_frame(uint frame) { gOuterraSimulationFrame = frame; } //////////////////////////////////////////////////////////////////////////////// void physics::debug_draw_world() { if (_dbg_drawer) { _world->debugDrawWorld(); } } //////////////////////////////////////////////////////////////////////////////// void physics::get_broadphase_handles_aabbs(const bt::external_broadphase* broadphase, coid::dynarray<double3>& minmaxes) { bt32BitAxisSweep3* bp = nullptr; uint revision = 0xffffffff; if (broadphase) { bp = broadphase->_broadphase; revision = broadphase->_revision; } else { bp = static_cast<bt32BitAxisSweep3*>(_world->getBroadphase()); } _world->for_each_object_in_broadphase(bp, revision, [&minmaxes](btCollisionObject* co) { btBroadphaseProxy* bp = co->getBroadphaseHandle(); if (bp && (co->getCollisionFlags() & btCollisionObject::CollisionFlags::CF_DISABLE_VISUALIZE_OBJECT) == 0) { minmaxes.push(double3(bp->m_aabbMin[0], bp->m_aabbMin[1], bp->m_aabbMin[2])); minmaxes.push(double3(bp->m_aabbMax[0], bp->m_aabbMax[1], bp->m_aabbMax[2])); } }); } //////////////////////////////////////////////////////////////////////////////// bt::external_broadphase* physics::create_external_broadphase(const double3& min, const double3& max) { return _world->create_external_broadphase(min,max); } //////////////////////////////////////////////////////////////////////////////// void physics::delete_external_broadphase(bt::external_broadphase * bp) { return _world->delete_external_broadphase(bp); } //////////////////////////////////////////////////////////////////////////////// void physics::update_external_broadphase(bt::external_broadphase * bp) { return _world->update_terrain_mesh_broadphase(bp); } //////////////////////////////////////////////////////////////////////////////// bool physics::add_collision_object_to_external_broadphase(bt::external_broadphase * bp, btCollisionObject * co, unsigned int group, unsigned int mask) { if (bp->_broadphase->is_full()) { return false; } btTransform trans = co->getWorldTransform(); btVector3 minAabb; btVector3 maxAabb; co->getCollisionShape()->getAabb(trans, minAabb, maxAabb); int type = co->getCollisionShape()->getShapeType(); co->setBroadphaseHandle(bp->_broadphase->createProxy( minAabb, maxAabb, type, co, group, mask, 0, 0 )); //bp->_colliders.push(sc); return true; } /* //////////////////////////////////////////////////////////////////////////////// void physics::remove_collision_object_from_external_broadphase(bt::external_broadphase * bp, simple_collider * sc, btCollisionObject * co) { for (uints i = 0; i < bp->_colliders.size(); i++) { if (bp->_colliders[i] == sc) { bp->_colliders.del(i); break; } } bp->_broadphase.destroyProxy(co->getBroadphaseHandle(),nullptr); }*/ //////////////////////////////////////////////////////////////////////////////// void physics::query_volume_sphere(const double3 & pos, float rad, coid::dynarray<btCollisionObject*>& result) { #ifdef _DEBUG bt32BitAxisSweep3 * broad = dynamic_cast<bt32BitAxisSweep3 *>(_world->getBroadphase()); DASSERT(broad != nullptr); #else bt32BitAxisSweep3 * broad = static_cast<bt32BitAxisSweep3 *>(_world->getBroadphase()); #endif _world->query_volume_sphere(broad, pos, rad, [&](btCollisionObject* obj) { if (obj->getUserPointer()) result.push(obj); }); coid::dynarray <bt::external_broadphase*> ebps; _physics->external_broadphases_in_radius(_world->getContext(), pos, rad, gCurrentFrame, ebps); ebps.for_each([&](bt::external_broadphase* ebp) { /*if (ebp->_dirty) { _world->update_terrain_mesh_broadphase(ebp); }*/ DASSERT(!ebp->_dirty); _world->query_volume_sphere(ebp->_broadphase, pos, rad, [&](btCollisionObject* obj) { if (obj->getUserPointer()) result.push(obj); }); }); } //////////////////////////////////////////////////////////////////////////////// void physics::query_volume_frustum(const double3 & pos,const float4 * f_planes_norms, uint8 nplanes, bool include_partial, coid::dynarray<btCollisionObject*>& result) { #ifdef _DEBUG bt32BitAxisSweep3* broad = dynamic_cast<bt32BitAxisSweep3*>(_world->getBroadphase()); DASSERT(broad != nullptr); #else bt32BitAxisSweep3* broad = static_cast<bt32BitAxisSweep3*>(_world->getBroadphase()); #endif _world->query_volume_frustum(broad, pos, f_planes_norms, nplanes, include_partial, [&](btCollisionObject* obj) { result.push(obj); }); coid::dynarray <bt::external_broadphase*> ebps; _physics->external_broadphases_in_frustum(_world->getContext(), pos, f_planes_norms, nplanes, gCurrentFrame, ebps); ebps.for_each([&](bt::external_broadphase* ebp) { /*if (ebp->_dirty) { _world->update_terrain_mesh_broadphase(ebp); }*/ DASSERT(!ebp->_dirty); _world->query_volume_frustum(ebp->_broadphase, pos, f_planes_norms, nplanes, include_partial, [&](btCollisionObject* obj) { if (obj->getUserPointer()) result.push(obj); }); }); } //////////////////////////////////////////////////////////////////////////////// void physics::wake_up_objects_in_radius(const double3 & pos, float rad) { #ifdef _DEBUG bt32BitAxisSweep3 * broad = dynamic_cast<bt32BitAxisSweep3 *>(_world->getBroadphase()); DASSERT(broad != nullptr); #else bt32BitAxisSweep3 * broad = static_cast<bt32BitAxisSweep3 *>(_world->getBroadphase()); #endif _world->query_volume_sphere(broad,pos, rad, [&](btCollisionObject* obj) { obj->setActivationState(ACTIVE_TAG); obj->setDeactivationTime(0); }); } //////////////////////////////////////////////////////////////////////////////// void physics::wake_up_object(btCollisionObject* obj) { obj->setActivationState(ACTIVE_TAG); obj->setDeactivationTime(0); } //////////////////////////////////////////////////////////////////////////////// bool physics::is_point_inside_terrain_ocluder(const double3 & pt) { return _world->is_point_inside_terrain_occluder(btVector3(pt.x,pt.y,pt.z)); } void physics::pause_simulation(bool pause) { _world->pause_simulation(pause); } //////////////////////////////////////////////////////////////////////////////// btTriangleMesh* physics::create_triangle_mesh() { btTriangleMesh* result = new btTriangleMesh(); return result; } //////////////////////////////////////////////////////////////////////////////// void physics::destroy_triangle_mesh(btTriangleMesh* triangle_mesh) { DASSERT(triangle_mesh); delete triangle_mesh; } //////////////////////////////////////////////////////////////////////////////// void physics::add_triangle(btTriangleMesh* mesh, const float v0[3], const float v1[3], const float v2[3]) { btVector3 btv0(static_cast<double>(v0[0]), static_cast<double>(v0[1]), static_cast<double>(v0[2])); btVector3 btv1(static_cast<double>(v1[0]), static_cast<double>(v1[1]), static_cast<double>(v1[2])); btVector3 btv2(static_cast<double>(v2[0]), static_cast<double>(v2[1]), static_cast<double>(v2[2])); mesh->addTriangle(btv0, btv1, btv2); } //////////////////////////////////////////////////////////////////////////////// btCollisionShape* physics::create_shape( bt::EShape sh, const float hvec[3], void* data) { switch(sh) { case bt::SHAPE_CONVEX: return new btConvexHullShape(); case bt::SHAPE_MESH_STATIC: return new btBvhTriangleMeshShape(reinterpret_cast<btTriangleMesh*>(data),false); case bt::SHAPE_SPHERE: return new btSphereShape(hvec[0]); case bt::SHAPE_BOX: return new btBoxShape(btVector3(hvec[0], hvec[1], hvec[2])); case bt::SHAPE_CYLINDER: return new btCylinderShapeZ(btVector3(hvec[0], hvec[1], hvec[2])); case bt::SHAPE_CAPSULE: { if (glm::abs(hvec[1] - hvec[2]) < 0.000001f) { //btCapsuleX return new btCapsuleShapeX(hvec[1], 2.f*(hvec[0] - hvec[1])); } else if(glm::abs(hvec[0] - hvec[2]) < 0.000001f){ //btCapsuleY return new btCapsuleShape(hvec[0], 2.f*(hvec[1] - hvec[0])); } else{ //btCapsuleZ return new btCapsuleShapeZ(hvec[1], 2.f*(hvec[2] - hvec[1])); } } case bt::SHAPE_CONE: return new btConeShapeZ(hvec[0], hvec[2]); } return 0; } //////////////////////////////////////////////////////////////////////////////// ifc_fn btCollisionShape * physics::clone_shape(const btCollisionShape * shape) { return shape->getClone(); } //////////////////////////////////////////////////////////////////////////////// void physics::destroy_shape( btCollisionShape*& shape ) { delete shape; shape = 0; } //////////////////////////////////////////////////////////////////////////////// void physics::add_convex_point( btCollisionShape* shape, const float pt[3] ) { static_cast<btConvexHullShape*>(shape)->addPoint(btVector3(pt[0], pt[1], pt[2]), false); } //////////////////////////////////////////////////////////////////////////////// void physics::close_convex_shape( btCollisionShape* shape ) { shape->setMargin(0.005); static_cast<btConvexHullShape*>(shape)->recalcLocalAabb(); } //////////////////////////////////////////////////////////////////////////////// void physics::set_collision_shape_local_scaling(btCollisionShape * shape, const float3 & scale) { shape->setLocalScaling(btVector3(scale[0], scale[1], scale[2])); } //////////////////////////////////////////////////////////////////////////////// btCompoundShape* physics::create_compound_shape() { btCompoundShape * res = new btCompoundShape(); return res; } //////////////////////////////////////////////////////////////////////////////// void physics::add_child_shape( btCompoundShape* group, btCollisionShape* child, const btTransform& tr ) { group->addChildShape(tr, child); } //////////////////////////////////////////////////////////////////////////////// void physics::remove_child_shape(btCompoundShape* group, btCollisionShape* child) { group->removeChildShape(child); } //////////////////////////////////////////////////////////////////////////////// void physics::update_child( btCompoundShape* group, btCollisionShape * child, const btTransform& tr ) { int index = -1; const int num_children = group->getNumChildShapes(); for (int i = 0; i < num_children; i++) { if (group->getChildShape(i) == child) { index = i; break; } } group->updateChildTransform(index, tr, false); } //////////////////////////////////////////////////////////////////////////////// void physics::get_child_transform(btCompoundShape * group, btCollisionShape * child, btTransform& tr) { int index = -1; const int num_children = group->getNumChildShapes(); for (int i = 0; i < num_children; i++) { if (group->getChildShape(i) == child) { index = i; break; } } tr = group->getChildTransform(index); } //////////////////////////////////////////////////////////////////////////////// void physics::recalc_compound_shape( btCompoundShape* shape ) { shape->recalculateLocalAabb(); } //////////////////////////////////////////////////////////////////////////////// void physics::destroy_compound_shape( btCompoundShape*& shape ) { delete shape; shape = 0; } //////////////////////////////////////////////////////////////////////////////// btCollisionObject* physics::create_collision_object( btCollisionShape* shape, void* usr1, void* usr2 ) { btCollisionObject* obj = new btCollisionObject; obj->setCollisionShape(shape); obj->setUserPointer(usr1); obj->m_userDataExt = usr2; return obj; } //////////////////////////////////////////////////////////////////////////////// btGhostObject* physics::create_ghost_object(btCollisionShape* shape, void* usr1, void* usr2) { btGhostObject* obj = new btGhostObject; obj->setCollisionShape(shape); obj->setUserPointer(usr1); obj->m_userDataExt = usr2; return obj; } //////////////////////////////////////////////////////////////////////////////// void physics::set_collision_info(btCollisionObject* obj, unsigned int group, unsigned int mask) { btBroadphaseProxy* bp = obj->getBroadphaseHandle(); if (bp) { bp->m_collisionFilterGroup = group; bp->m_collisionFilterMask = mask; } } //////////////////////////////////////////////////////////////////////////////// void physics::destroy_collision_object( btCollisionObject*& obj ) { if(obj) delete obj; obj = 0; } //////////////////////////////////////////////////////////////////////////////// void physics::destroy_ghost_object(btGhostObject*& obj) { if (obj) delete obj; obj = 0; } //////////////////////////////////////////////////////////////////////////////// bool physics::add_collision_object( btCollisionObject* obj, unsigned int group, unsigned int mask, bool inactive ) { if(inactive) obj->setActivationState(DISABLE_SIMULATION); /* if (obj->isStaticObject()) { float3x3 basis; double3 cen; _world->get_obb(obj->getCollisionShape(),obj->getWorldTransform(),cen,basis); add_static_collider(_world->get_context(),obj,cen,basis); } else { _world->addCollisionObject(obj, group, mask); }*/ if (!_world->addCollisionObject(obj, group, mask)) { return false; } btGhostObject* ghost = btGhostObject::upcast(obj); if (ghost) { obj->setCollisionFlags(obj->getCollisionFlags() | btCollisionObject::CollisionFlags::CF_NO_CONTACT_RESPONSE | btCollisionObject::CollisionFlags::CF_DISABLE_VISUALIZE_OBJECT); _world->add_terrain_occluder(ghost); } return true; } //////////////////////////////////////////////////////////////////////////////// void physics::remove_collision_object( btCollisionObject* obj ) { _world->removeCollisionObject(obj); btGhostObject* ghost = btGhostObject::upcast(obj); if (ghost) { _world->remove_terrain_occluder(ghost); } } //////////////////////////////////////////////////////////////////////////////// void physics::remove_collision_object_external(btCollisionObject* obj) { _world->removeCollisionObject_external(obj); btGhostObject* ghost = btGhostObject::upcast(obj); if (ghost) { _world->remove_terrain_occluder(ghost); } } //////////////////////////////////////////////////////////////////////////////// int physics::get_collision_flags(const btCollisionObject * co) { return co->getCollisionFlags(); } //////////////////////////////////////////////////////////////////////////////// void physics::set_collision_flags(btCollisionObject * co, int flags) { return co->setCollisionFlags(flags); } //////////////////////////////////////////////////////////////////////////////// void physics::force_update_aabbs() { _world->updateAabbs(); } //////////////////////////////////////////////////////////////////////////////// void physics::update_collision_object( btCollisionObject* obj, const btTransform& tr, bool update_aabb ) { obj->setWorldTransform(tr); if (update_aabb || obj->getBroadphaseHandle()) { //_world->updateSingleAabb(obj); obj->m_otFlags |= bt::OTF_TRANSFORMATION_CHANGED; } } //////////////////////////////////////////////////////////////////////////////// void physics::step_simulation(double step, bt::bullet_stats * stats) { _world->set_ot_stats(stats); _world->stepSimulation(step, 0, step); } //////////////////////////////////////////////////////////////////////////////// void physics::ray_test( const double from[3], const double to[3], void* cb, bt::external_broadphase* bp) { btVector3 afrom = btVector3(from[0], from[1], from[2]); btVector3 ato = btVector3(to[0], to[1], to[2]); if (bp && bp->_dirty) { DASSERT(0 && "should be already updated"); //_world->update_terrain_mesh_broadphase(bp); } _world->rayTest(afrom, ato, *(btCollisionWorld::RayResultCallback*)cb, bp); } void physics::set_current_frame(uint frame) { gCurrentFrame = frame; } //////////////////////////////////////////////////////////////////////////////// bt::ot_world_physics_stats physics::get_stats() { return ((ot::discrete_dynamics_world*)(_world))->get_stats(); } //////////////////////////////////////////////////////////////////////////////// bt::ot_world_physics_stats* physics::get_stats_ptr() { return const_cast<bt::ot_world_physics_stats*>(&((ot::discrete_dynamics_world*)(_world))->get_stats()); } //////////////////////////////////////////////////////////////////////////////// void physics::set_debug_draw_enabled(btIDebugDraw * debug_drawer) { _dbg_drawer = debug_drawer; ((ot::discrete_dynamics_world*)_world)->setDebugDrawer(debug_drawer); if (debug_drawer) { debug_drawer->setDebugMode(_dbg_draw_mode); } } //////////////////////////////////////////////////////////////////////////////// void physics::set_debug_drawer_mode(int debug_mode) { _dbg_draw_mode = debug_mode; if (_dbg_drawer) { _dbg_drawer->setDebugMode(debug_mode); } } //////////////////////////////////////////////////////////////////////////////// btTypedConstraint* physics::add_constraint_ball_socket(btDynamicsWorld * world, btRigidBody* rb_a, const btVector3& pivot_a, btRigidBody* rb_b, const btVector3& pivot_b, bool disable_collision) { btPoint2PointConstraint * p2p = new btPoint2PointConstraint(*rb_a,*rb_b,pivot_a,pivot_b); _physics->_world->addConstraint(p2p,disable_collision); return p2p; } //////////////////////////////////////////////////////////////////////////////// void physics::remove_constraint(btDynamicsWorld * world, btTypedConstraint * constraint) { _physics->_world->removeConstraint(constraint); }
32.211125
195
0.580792
cameni
2d9a13f3d31907a1c5b9fa94b13756818d2f03df
3,087
cpp
C++
src/dslang-dialect.cpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
src/dslang-dialect.cpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
src/dslang-dialect.cpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
// vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : /* * Copyright (c) 2014-2017, Ryan V. Bissell * All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause * See the enclosed "LICENSE" file for exact license terms. */ #define CX_TRACE_SECTION "dslang" #include "dslang-dialect.hpp" #include "dslang-lexer.hpp" #include "sexpr-literal-bool.hpp" #include "sexpr-literal-number.hpp" #include "sexpr-literal-string.hpp" #include "sexpr-ident.hpp" #include "sexpr-cons.hpp" #include "sexpr-quote.hpp" using namespace DSL::detail; using DSL::TokenHandler; // --------------------------------------------------------------------- CX_CONSTRUCTOR(DSL::Dialect::Dialect, :sc_(nullptr)) // this should be first, so it gets matched last registerTokenizer(SexprIdent__Match, SexprIdent__Skip, SexprIdent__Parse); registerTokenizer(SexprQuote__Match, SexprQuote__Skip, SexprQuote__Parse); registerTokenizer(SexprCons__Match, SexprCons__Skip, SexprCons__Parse); registerTokenizer(SexprString__Match, SexprString__Skip, SexprString__Parse); registerTokenizer(SexprNumber__Match, SexprNumber__Skip, SexprNumber__Parse); registerTokenizer(SexprBool__Match, SexprBool__Skip, SexprBool__Parse); CX_ENDMETHOD CX_DESTRUCTOR(DSL::Dialect::~Dialect) for (auto&& pair : tokenizers_) delete pair.second; CX_ENDMETHOD // TODO, if made private, use DSL::detail::Context* for 'sc' CX_METHOD(void DSL::Dialect::SetContext, DSL::Scheme* sc) CX_ASSERT(!sc_); // this shouldn't get called multiple times // TODO, can remove typecast if above TODO is completed sc_ = dynamic_cast<Context*>(sc); CX_ASSERT(sc_); // dynamic cast failed? CX_ENDMETHOD CX_CONSTMETHOD(TokenHandler const* DSL::Dialect::GetTokenHandler, char const* text) #if 1 // C++17 version: for (auto&& [match,handler] : tokenizers_) if (match(text)) CX_RETURN(handler); #else // C++11 version: for (auto&& pair : tokenizers_) if (pair.first(text)) CX_RETURN(pair.second); #endif CX_RETURN(nullptr); CX_ENDMETHOD CX_METHOD(void DSL::Dialect::registerTokenizer, TokenMatcher match, TokenSkipper skip, TokenParser parse) TokenHandler const* phandler = new TokenHandler{skip, parse}; // we use a deque so that custom dialects can override // built-in token handlers, when we iterate for a match tokenizers_.push_front(std::make_pair(match,phandler)); CX_ENDMETHOD #if 0 CX_CONSTMETHOD(bool DSL::Dialect::IsCustomToken, char const * const text) CX_RETURN(false); // class must be overridden for this behavior CX_ENDMETHOD CX_CONSTMETHOD(const SexprCUSTOM* DSL::Dialect::ParseCustom, const string& lexeme) CX_ASSERT(false); // TODO, needs to be fatal, internal error // This is supposed to be overridden, and never called // It is not pure-virtual because the class overall is // designed to be used as the default behavior. CX_RETURN(nullptr); CX_ENDMETHOD #endif
25.725
82
0.695497
ryanvbissell
2d9da9e8ea4881618a1565400df9900f16745d78
17,746
cpp
C++
lib/graphics/src/Font.cpp
MarkRDavison/zeno
cea002e716e624d28130e836bf56e9f2f1d2e484
[ "MIT" ]
null
null
null
lib/graphics/src/Font.cpp
MarkRDavison/zeno
cea002e716e624d28130e836bf56e9f2f1d2e484
[ "MIT" ]
null
null
null
lib/graphics/src/Font.cpp
MarkRDavison/zeno
cea002e716e624d28130e836bf56e9f2f1d2e484
[ "MIT" ]
null
null
null
#include <zeno/Graphics/Font.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include <zeno/Graphics/Image.hpp> #include <zeno/Graphics/Colour.hpp> #include <algorithm> #include <iostream> #include <cmath> #define MARGIN 2 #define DIST_MARGIN 4 #define ATLAS_WIDTH 1024 #define SEED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()[]{}?><,./\\\"' :;~|-`=+_" namespace ze { struct Point { Point() : Point(9999, 9999) { } Point(int _dx, int _dy) { dx = _dx; dy = _dy; } int dx, dy; int DistSq() const { return dx * dx + dy * dy; } }; struct Grid { Grid(unsigned _width, unsigned _height, int _starting) : Width(_width), Height(_height) { grid = new Point * [_height]; for (unsigned y = 0; y < _height; ++y) { grid[y] = new Point[_width]; for (unsigned x = 0; x < _width; ++x) { grid[y][x].dx = _starting; grid[y][x].dy = _starting; } } } ~Grid() { for (unsigned y = 0; y < Height; ++y) { delete[] grid[y]; } delete[] grid; } const unsigned Width; const unsigned Height; Point** grid; }; Point inside = { 0, 0 }; Point empty = { 9999, 9999 }; Point Get(Grid& g, int x, int y) { // OPTIMIZATION: you can skip the edge check code if you make your grid // have a 1-pixel gutter. if (x >= 0 && y >= 0 && x < static_cast<int>(g.Width) && y < static_cast<int>(g.Height)) return g.grid[y][x]; else return empty; } void Put(Grid& g, int x, int y, const Point& p) { g.grid[y][x] = p; } void Compare(Grid& g, Point& p, int x, int y, int offsetx, int offsety) { Point other = Get(g, x + offsetx, y + offsety); other.dx += offsetx; other.dy += offsety; if (other.DistSq() < p.DistSq()) p = other; } void GenerateSDF(Grid& g) { // Pass 0 for (int y = 0; y < static_cast<int>(g.Height); y++) { for (int x = 0; x < static_cast<int>(g.Width); x++) { Point p = Get(g, x, y); Compare(g, p, x, y, -1, 0); Compare(g, p, x, y, 0, -1); Compare(g, p, x, y, -1, -1); Compare(g, p, x, y, 1, -1); Put(g, x, y, p); } for (int x = static_cast<int>(g.Width) - 1; x >= 0; x--) { Point p = Get(g, x, y); Compare(g, p, x, y, 1, 0); Put(g, x, y, p); } } // Pass 1 for (int y = static_cast<int>(g.Height) - 1; y >= 0; y--) { for (int x = static_cast<int>(g.Width) - 1; x >= 0; x--) { Point p = Get(g, x, y); Compare(g, p, x, y, 1, 0); Compare(g, p, x, y, 0, 1); Compare(g, p, x, y, -1, 1); Compare(g, p, x, y, 1, 1); Put(g, x, y, p); } for (int x = 0; x < static_cast<int>(g.Width); x++) { Point p = Get(g, x, y); Compare(g, p, x, y, -1, 0); Put(g, x, y, p); } } } Font::Font(FontType _type /*= FontType::Default*/) : m_GenerationSize(0), type(_type) { FT_Library lib; FT_Init_FreeType(&lib); m_Library = lib; } Font::Font(const std::string& _filename, unsigned _generationSize, FontType _type /*= FontType::Default*/) : type(_type) { FT_Library lib; FT_Init_FreeType(&lib); m_Library = lib; loadFromFile(_filename, _generationSize); } Font::~Font() { if (m_Loaded) { const FT_Library lib = static_cast<FT_Library>(m_Library); FT_Done_FreeType(lib); } } bool genChar(Image& _image, char _c, FT_Face _face) { const FT_UInt glyphIndex = FT_Get_Char_Index(_face, _c); const FT_Error loadGlyphError = FT_Load_Glyph(_face, glyphIndex, FT_LOAD_RENDER); if (loadGlyphError != 0) { // Failed to load glyph return false; } const FT_GlyphSlot glyph = _face->glyph; Grid grid1(glyph->bitmap.width + 2 * DIST_MARGIN, glyph->bitmap.rows + 2 * DIST_MARGIN, 0); Grid grid2(glyph->bitmap.width + 2 * DIST_MARGIN, glyph->bitmap.rows + 2 * DIST_MARGIN, 9999); for (int y = 0; y < static_cast<int>(glyph->bitmap.rows); y++) { for (int x = 0; x < static_cast<int>(glyph->bitmap.width); x++) { // TODO: Put a border around the generated image when atlassing ... if (y >= static_cast<int>(glyph->bitmap.rows) || x >= static_cast<int>(glyph->bitmap.width)) { Put(grid2, x + DIST_MARGIN, y + DIST_MARGIN, inside); Put(grid1, x + DIST_MARGIN, y + DIST_MARGIN, empty); } else { const float value = static_cast<float>(glyph->bitmap.buffer[y * glyph->bitmap.width + x]) / 255.0f; // Points inside get marked with a dx/dy of zero. // Points outside get marked with an infinitely large distance. if (value < 0.5f) { Put(grid1, x + DIST_MARGIN, y + DIST_MARGIN, inside); Put(grid2, x + DIST_MARGIN, y + DIST_MARGIN, empty); } else { Put(grid2, x + DIST_MARGIN, y + DIST_MARGIN, inside); Put(grid1, x + DIST_MARGIN, y + DIST_MARGIN, empty); } } } } GenerateSDF(grid1); GenerateSDF(grid2); _image.create(grid1.Width, grid1.Height); for (int y = 0; y < static_cast<int>(grid1.Height); y++) { for (int x = 0; x < static_cast<int>(grid1.Width); x++) { // Calculate the actual distance from the dx/dy const int dist1 = static_cast<int>(sqrt(static_cast<double>(Get(grid1, x, y).DistSq()))); const int dist2 = static_cast<int>(sqrt(static_cast<double>(Get(grid2, x, y).DistSq()))); const int dist = dist1 - dist2; // Clamp and scale it. int c = dist * 3 + 128; if (c < 0) c = 0; if (c > 255) c = 255; _image.setPixel(x, y, ze::Colour(static_cast<float>(c) / 255.0f, 0.0f, 0.0f)); } } return true; } bool Font::loadFontFile(const std::string& _filename, unsigned _generationSize, FontType _type /*= FontType::Default*/) { m_GlyphData.clear(); m_Loaded = false; m_GenerationSize = _generationSize; type = _type; if (type == FontType::SignedDistanceField) { return loadFromFileSDF(_filename, _generationSize); } return loadFromFileDefault(_filename, _generationSize); } bool Font::createFont() { if (!m_Texture.loadFromImage(m_Image)) { std::cerr << "Failed to create font atlas texture from image" << std::endl; return false; } m_Loaded = true; return true; } bool Font::loadFromFile(const std::string& _filename, unsigned _generationSize, FontType _type /*= FontType::Default*/) { if (!loadFontFile(_filename, _generationSize, _type)) { return false; } return createFont(); } const ze::Texture& Font::getTexture() const { return m_Texture; } void Font::generateText(ze::VertexArray& _vertexArray, const std::string& _text, unsigned _characterSize) { _vertexArray = ze::VertexArray(_text.size() * 6); ze::Vector2f penPosition; const ze::Vector2u textureSize = m_Texture.getSize(); const float charSize = static_cast<float>(_characterSize); const float ratio = charSize / static_cast<float>(m_GenerationSize); for (unsigned i = 0; i < _text.size(); ++i) { const char _c = _text[i]; if (_c == ' ') { penPosition.x += charSize / 8.0f; continue; } if (m_GlyphData.count(_c) == 0) { std::cerr << "Cannot use character '" << _c << "' in text." << std::endl; continue; } const Glyph& g = m_GlyphData[_c]; // Kerning, rise etc const ze::Vector2f charOffset{ 0.0f, static_cast<float>(g.bearingY >> 6) - static_cast<float>(g.h) }; _vertexArray[i * 6 + 0] = ze::Vertex{ ze::Vector3f{ penPosition.x + (charOffset.x) * ratio, penPosition.y + (charOffset.y) * ratio, 0.0f }, ze::Colour::White, ze::Vector2f{ static_cast<float>(g.x) / textureSize.x, 1.0f - (static_cast<float>(g.y + g.h) / textureSize.y) } }; _vertexArray[i * 6 + 1] = ze::Vertex{ ze::Vector3f{ penPosition.x + (charOffset.x + g.w) * ratio, penPosition.y + (charOffset.y) * ratio, 0.0f }, ze::Colour::White, ze::Vector2f{ static_cast<float>(g.x + g.w) / textureSize.x, 1.0f - (static_cast<float>(g.y + g.h) / textureSize.y) } }; _vertexArray[i * 6 + 2] = ze::Vertex{ ze::Vector3f{ penPosition.x + (charOffset.x + g.w) * ratio, penPosition.y + (charOffset.y + g.h) * ratio, 0.0f }, ze::Colour::White, ze::Vector2f{ static_cast<float>(g.x + g.w) / textureSize.x, 1.0f - (static_cast<float>(g.y) / textureSize.y) } }; _vertexArray[i * 6 + 3] = ze::Vertex{ ze::Vector3f{ penPosition.x + (charOffset.x) * ratio, penPosition.y + (charOffset.y) * ratio, 0.0f }, ze::Colour::White, ze::Vector2f{ static_cast<float>(g.x) / textureSize.x, 1.0f - (static_cast<float>(g.y + g.h) / textureSize.y) } }; _vertexArray[i * 6 + 4] = ze::Vertex{ ze::Vector3f{ penPosition.x + (charOffset.x + g.w) * ratio, penPosition.y + (charOffset.y + g.h) * ratio, 0.0f }, ze::Colour::White, ze::Vector2f{ static_cast<float>(g.x + g.w) / textureSize.x, 1.0f - (static_cast<float>(g.y) / textureSize.y) } }; _vertexArray[i * 6 + 5] = ze::Vertex{ ze::Vector3f{ penPosition.x + (charOffset.x) * ratio, penPosition.y + (charOffset.y + g.h) * ratio, 0.0f }, ze::Colour::White, ze::Vector2f{ static_cast<float>(g.x) / textureSize.x, 1.0f - (static_cast<float>(g.y) / textureSize.y) } }; penPosition.x += static_cast<float>(g.w) * ratio; } _vertexArray.create(); } bool Font::loadFromFileSDF(const std::string& _filename, unsigned _generationSize) { const FT_Library lib = static_cast<FT_Library>(m_Library); FT_Face face; const FT_Error newFaceError = FT_New_Face(lib, _filename.c_str(), 0, &face); if (newFaceError != 0) { // Failed to create font face return false; } const FT_Error setPixelError = FT_Set_Pixel_Sizes(face, 0, m_GenerationSize); if (setPixelError != 0) { // Failed to set pixel size return false; } m_Image.create(ATLAS_WIDTH, ATLAS_WIDTH); const std::string chars = SEED_CHARS; unsigned currentX = 0; unsigned currentY = 0; unsigned nextY = 0; for (unsigned i = 0; i < chars.size(); ++i) { const char c = chars[i]; ze::Image image; if (!genChar(image, c, face)) { std::cerr << "Failed to load character '" << c << "'" << std::endl; continue; } if (currentX + image.getSize().x + 2 * MARGIN >= m_Image.getSize().x) { // Need to go to next row currentX = 0; currentY = nextY; if (currentY + image.getSize().y + 2 * MARGIN >= m_Image.getSize().y) { m_Image.expandVertically(m_Image.getSize().y); } } for (unsigned y = 0; y < image.getSize().y; ++y) { for (unsigned x = 0; x < image.getSize().x; ++x) { m_Image.setPixel(currentX + x + MARGIN, currentY + y + MARGIN, image.getPixel(x, y)); } } const auto v1 = face->glyph->metrics.height >> 6; const auto v2 = face->glyph->metrics.horiBearingY >> 6; Glyph g; g.c = c; g.x = currentX + MARGIN; g.y = currentY + MARGIN; g.w = image.getSize().x; g.h = image.getSize().y; g.yOff = static_cast<float>(v2) - static_cast<float>(v1); g.top = face->glyph->bitmap_top; g.left = face->glyph->bitmap_left; g.bearingY = face->glyph->metrics.horiBearingY; g.advanceY = face->glyph->metrics.vertAdvance; g.heightRatio = static_cast<float>(g.h) / static_cast<float>(m_GenerationSize); g.widthRatio = static_cast<float>(g.w) / static_cast<float>(m_GenerationSize); m_GlyphData[c] = g; nextY = std::max(currentY + image.getSize().y + 2 * MARGIN, nextY); currentX += image.getSize().x + 2 * MARGIN; } return true; } bool genCharNonSDF(Image& _image, char _c, FT_Face _face) { const FT_UInt glyphIndex = FT_Get_Char_Index(_face, _c); const FT_Error loadGlyphError = FT_Load_Glyph(_face, glyphIndex, FT_LOAD_RENDER); if (loadGlyphError != 0) { // Failed to load glyph return false; } const FT_GlyphSlot glyph = _face->glyph; _image.create(glyph->bitmap.width + 2 * DIST_MARGIN, glyph->bitmap.rows + 2 * DIST_MARGIN, ze::Colour::Transparent); for (int y = 0; y < static_cast<int>(glyph->bitmap.rows); y++) { for (int x = 0; x < static_cast<int>(glyph->bitmap.width); x++) { if (y >= static_cast<int>(glyph->bitmap.rows) || x >= static_cast<int>(glyph->bitmap.width)) { continue; } const float value = static_cast<float>(glyph->bitmap.buffer[y * glyph->bitmap.width + x]) / 255.0f; _image.setPixel(x + DIST_MARGIN, y + DIST_MARGIN, ze::Colour(value, 0.0f, 0.0f, 1.0f)); } } return true; } bool Font::loadFromFileDefault(const std::string& _filename, unsigned _generationSize) { const FT_Library lib = static_cast<FT_Library>(m_Library); FT_Face face; const FT_Error newFaceError = FT_New_Face(lib, _filename.c_str(), 0, &face); if (newFaceError != 0) { // Failed to create font face return false; } const FT_Error setPixelError = FT_Set_Pixel_Sizes(face, 0, m_GenerationSize); if (setPixelError != 0) { // Failed to set pixel size return false; } m_Image.create(ATLAS_WIDTH, ATLAS_WIDTH); const std::string chars = SEED_CHARS; unsigned currentX = 0; unsigned currentY = 0; unsigned nextY = 0; for (unsigned i = 0; i < chars.size(); ++i) { const char c = chars[i]; ze::Image image; if (!genCharNonSDF(image, c, face)) { std::cerr << "Failed to load character '" << c << "'" << std::endl; continue; } if (currentX + image.getSize().x + 2 * MARGIN >= m_Image.getSize().x) { // Need to go to next row currentX = 0; currentY = nextY; if (currentY + image.getSize().y + 2 * MARGIN >= m_Image.getSize().y) { m_Image.expandVertically(m_Image.getSize().y); } } for (unsigned y = 0; y < image.getSize().y; ++y) { for (unsigned x = 0; x < image.getSize().x; ++x) { m_Image.setPixel(currentX + x + MARGIN, currentY + y + MARGIN, image.getPixel(x, y)); } } const auto v1 = face->glyph->metrics.height >> 6; const auto v2 = face->glyph->metrics.horiBearingY >> 6; Glyph g; g.c = c; g.x = currentX + MARGIN; g.y = currentY + MARGIN; g.w = image.getSize().x; g.h = image.getSize().y; g.yOff = static_cast<float>(v2) - static_cast<float>(v1); g.top = face->glyph->bitmap_top; g.left = face->glyph->bitmap_left; g.bearingY = face->glyph->metrics.horiBearingY; g.advanceY = face->glyph->metrics.vertAdvance; g.heightRatio = static_cast<float>(g.h) / static_cast<float>(m_GenerationSize); g.widthRatio = static_cast<float>(g.w) / static_cast<float>(m_GenerationSize); m_GlyphData[c] = g; nextY = std::max(currentY + image.getSize().y + 2 * MARGIN, nextY); currentX += image.getSize().x + 2 * MARGIN; } return true; } }
35.850505
125
0.503268
MarkRDavison
2d9fc50ce93218efce08ee0e4ed74700e5543f0d
1,411
cpp
C++
lc508_most_frequent_subtree_sum.cpp
hzwr/Basics
cd4d8625636af987efdf36c0bea186928bc9e1a7
[ "MIT" ]
null
null
null
lc508_most_frequent_subtree_sum.cpp
hzwr/Basics
cd4d8625636af987efdf36c0bea186928bc9e1a7
[ "MIT" ]
null
null
null
lc508_most_frequent_subtree_sum.cpp
hzwr/Basics
cd4d8625636af987efdf36c0bea186928bc9e1a7
[ "MIT" ]
null
null
null
/* Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> findFrequentTreeSum(TreeNode* root) { GetSum(root); std::vector<int> sums; for(auto &sum : m_sumOfSubtrees) { if(sum.second == maxCount) { sums.emplace_back(sum.first); } } return sums; } private: int maxCount = 0; std::unordered_map<int, int> m_sumOfSubtrees; int GetSum(TreeNode *root) { if(!root) { return 0; } int sum = root->val + GetSum(root->left) + GetSum(root->right); m_sumOfSubtrees[sum]++; maxCount = max(maxCount, m_sumOfSubtrees[sum]); return sum; } };
26.12963
152
0.564139
hzwr
2da7b4ba09b0f21a8261b13e03d8f0dd62c6e8c6
2,584
cpp
C++
YorozuyaGSLib/source/CCircleZone.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/CCircleZone.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/CCircleZone.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <CCircleZone.hpp> START_ATF_NAMESPACE CCircleZone::CCircleZone() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012d660L))(this); }; void CCircleZone::ctor_CCircleZone() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012d660L))(this); }; bool CCircleZone::Create(struct CMapData* pkMap, char byColor) { using org_ptr = bool (WINAPIV*)(struct CCircleZone*, struct CMapData*, char); return (org_ptr(0x14012da60L))(this, pkMap, byColor); }; void CCircleZone::Destroy() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012db70L))(this); }; char CCircleZone::GetColor() { using org_ptr = char (WINAPIV*)(struct CCircleZone*); return (org_ptr(0x140034b20L))(this); }; int CCircleZone::GetPortalInx() { using org_ptr = int (WINAPIV*)(struct CCircleZone*); return (org_ptr(0x140034b00L))(this); }; char CCircleZone::Goal(struct CMapData* pkMap, float* pfCurPos) { using org_ptr = char (WINAPIV*)(struct CCircleZone*, struct CMapData*, float*); return (org_ptr(0x14012dbe0L))(this, pkMap, pfCurPos); }; bool CCircleZone::Init(unsigned int uiMapInx, int iPlayerInx, int iNth, uint16_t wInx, struct CMapData* pkMap) { using org_ptr = bool (WINAPIV*)(struct CCircleZone*, unsigned int, int, int, uint16_t, struct CMapData*); return (org_ptr(0x14012d740L))(this, uiMapInx, iPlayerInx, iNth, wInx, pkMap); }; bool CCircleZone::IsNearPosition(float* pfCurPos) { using org_ptr = bool (WINAPIV*)(struct CCircleZone*, float*); return (org_ptr(0x14012de20L))(this, pfCurPos); }; void CCircleZone::SendMsgCreate() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012dc60L))(this); }; void CCircleZone::SendMsgGoal() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012dda0L))(this); }; void CCircleZone::SendMsg_FixPosition(int n) { using org_ptr = void (WINAPIV*)(struct CCircleZone*, int); (org_ptr(0x14012dd00L))(this, n); }; CCircleZone::~CCircleZone() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012d6f0L))(this); }; void CCircleZone::dtor_CCircleZone() { using org_ptr = void (WINAPIV*)(struct CCircleZone*); (org_ptr(0x14012d6f0L))(this); }; END_ATF_NAMESPACE
33.558442
114
0.62887
lemkova
2db308fb672853899abcbe30eb98a423d0cd0b59
821
hpp
C++
libs/projectile/include/sge/projectile/triangulation/traits/access_element.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/projectile/include/sge/projectile/triangulation/traits/access_element.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/projectile/include/sge/projectile/triangulation/traits/access_element.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_PROJECTILE_TRIANGULATION_TRAITS_ACCESS_ELEMENT_HPP_INCLUDED #define SGE_PROJECTILE_TRIANGULATION_TRAITS_ACCESS_ELEMENT_HPP_INCLUDED #include <sge/projectile/triangulation/default_tag.hpp> #include <sge/projectile/triangulation/traits/access_element_fwd.hpp> namespace sge::projectile::triangulation::traits { template <typename Vertex> struct access_element<Vertex, sge::projectile::triangulation::default_tag> { static typename Vertex::value_type execute(Vertex const &_vertex, typename Vertex::size_type const _index) { return _vertex.get_unsafe(_index); } }; } #endif
29.321429
74
0.783191
cpreh
2dbb822e03a097c3c3e06fbb7aa3635f62d91418
6,156
cpp
C++
librbr_tests/src/mdp/test_mdp.cpp
kylewray/librbr
ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8
[ "MIT" ]
null
null
null
librbr_tests/src/mdp/test_mdp.cpp
kylewray/librbr
ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8
[ "MIT" ]
11
2015-04-02T01:32:47.000Z
2015-04-02T01:32:47.000Z
librbr_tests/src/mdp/test_mdp.cpp
kylewray/librbr
ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8
[ "MIT" ]
null
null
null
/** * The MIT License (MIT) * * Copyright (c) 2014 Kyle Hollins Wray, University of Massachusetts * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../../include/perform_tests.h" #include <iostream> #include "../../../librbr/include/management/unified_file.h" #include "../../../librbr/include/mdp/mdp.h" #include "../../../librbr/include/mdp/mdp_value_iteration.h" #include "../../../librbr/include/mdp/mdp_policy_iteration.h" #include "../../../librbr/include/core/core_exception.h" #include "../../../librbr/include/core/states/state_exception.h" #include "../../../librbr/include/core/actions/action_exception.h" #include "../../../librbr/include/core/state_transitions/state_transition_exception.h" #include "../../../librbr/include/core/rewards/reward_exception.h" #include "../../../librbr/include/core/policy/policy_exception.h" int test_mdp() { int numSuccesses = 0; UnifiedFile file; std::cout << "MDP: Loading 'grid_world_finite_horizon.mdp'..."; if (!file.load("resources/mdp/grid_world_finite_horizon.mdp")) { std::cout << " Success." << std::endl; numSuccesses++; } else { std::cout << " Failure." << std::endl; } std::cout << "MDP: Solving 'grid_world_finite_horizon.mdp' with MDPValueIteration..."; MDP *mdp = nullptr; MDPValueIteration vi; PolicyMap *policyMap = nullptr; try { mdp = file.get_mdp(); policyMap = vi.solve(mdp); std::cout << " Success." << std::endl; numSuccesses++; } catch (const CoreException &err) { std::cout << " Failure." << std::endl; } catch (const StateException &err) { std::cout << " Failure." << std::endl; } catch (const ActionException &err) { std::cout << " Failure." << std::endl; } catch (const StateTransitionException &err) { std::cout << " Failure." << std::endl; } catch (const RewardException &err) { std::cout << " Failure." << std::endl; } catch (const PolicyException &err) { std::cout << " Failure." << std::endl; } if (policyMap != nullptr) { policyMap->save("tmp/test_mdp_value_iteration_finite_horizon.policy_map"); delete policyMap; } policyMap = nullptr; if (mdp != nullptr) { delete mdp; } mdp = nullptr; std::cout << "MDP: Loading 'grid_world_infinite_horizon.mdp'..."; if (!file.load("resources/mdp/grid_world_infinite_horizon.mdp")) { std::cout << " Success." << std::endl; numSuccesses++; } else { std::cout << " Failure." << std::endl; } std::cout << "MDP: Solving 'grid_world_infinite_horizon.mdp' with MDPValueIteration..."; try { mdp = file.get_mdp(); policyMap = vi.solve(mdp); std::cout << " Success." << std::endl; numSuccesses++; } catch (const CoreException &err) { std::cout << " Failure." << std::endl; } catch (const StateException &err) { std::cout << " Failure." << std::endl; } catch (const ActionException &err) { std::cout << " Failure." << std::endl; } catch (const StateTransitionException &err) { std::cout << " Failure." << std::endl; } catch (const RewardException &err) { std::cout << " Failure." << std::endl; } catch (const PolicyException &err) { std::cout << " Failure." << std::endl; } if (policyMap != nullptr) { policyMap->save("tmp/test_mdp_value_iteration_infinite_horizon.policy_map"); delete policyMap; } policyMap = nullptr; std::cout << "MDP: Solving 'grid_world_infinite_horizon.mdp' with MDPPolicyIteration (Exact)..."; MDPPolicyIteration piExact; try { policyMap = piExact.solve(mdp); std::cout << " Success." << std::endl; numSuccesses++; } catch (const CoreException &err) { std::cout << " Failure." << std::endl; } catch (const StateException &err) { std::cout << " Failure." << std::endl; } catch (const ActionException &err) { std::cout << " Failure." << std::endl; } catch (const StateTransitionException &err) { std::cout << " Failure." << std::endl; } catch (const RewardException &err) { std::cout << " Failure." << std::endl; } catch (const PolicyException &err) { std::cout << " Failure." << std::endl; } if (policyMap != nullptr) { policyMap->save("tmp/test_mdp_policy_iteration_exact_infinite_horizon.policy_map"); delete policyMap; } policyMap = nullptr; std::cout << "MDP: Solving 'grid_world_infinite_horizon.mdp' with MDPPolicyIteration (Modified with k=5)..."; MDPPolicyIteration piModified(5); try { policyMap = piModified.solve(mdp); std::cout << " Success." << std::endl; numSuccesses++; } catch (const CoreException &err) { std::cout << " Failure." << std::endl; } catch (const StateException &err) { std::cout << " Failure." << std::endl; } catch (const ActionException &err) { std::cout << " Failure." << std::endl; } catch (const StateTransitionException &err) { std::cout << " Failure." << std::endl; } catch (const RewardException &err) { std::cout << " Failure." << std::endl; } catch (const PolicyException &err) { std::cout << " Failure." << std::endl; } if (policyMap != nullptr) { policyMap->save("tmp/test_mdp_policy_iteration_modified_infinite_horizon.policy_map"); delete policyMap; } policyMap = nullptr; delete mdp; mdp = nullptr; return numSuccesses; }
32.919786
110
0.674789
kylewray
2dbcc962496b6eb0e8c389e94cc89cc51f887d8f
2,156
cpp
C++
diffusion/math/Local.cpp
lanetszb/dfvm
c6154ba23c4e145fa6889c04f97b69972163f59c
[ "MIT" ]
null
null
null
diffusion/math/Local.cpp
lanetszb/dfvm
c6154ba23c4e145fa6889c04f97b69972163f59c
[ "MIT" ]
null
null
null
diffusion/math/Local.cpp
lanetszb/dfvm
c6154ba23c4e145fa6889c04f97b69972163f59c
[ "MIT" ]
null
null
null
/* MIT License * * Copyright (c) 2020 Aleksandr Zhuravlyov and Zakhar Lanets * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Local.h" #include "funcs.h" #include <algorithm> Local::Local(std::shared_ptr<Props> props, std::shared_ptr<Sgrid> sgrid) : _props(props), _sgrid(sgrid), _alphas(_sgrid->_cellsN, 0) {} void Local::calcTimeSteps() { auto time = std::get<double>(_props->_params["time_period"]); auto timeStep = std::get<double>(_props->_params["time_step"]); double division = time / timeStep; double fullStepsN; auto lastStep = std::modf(division, &fullStepsN); _timeSteps.clear(); _timeSteps = std::vector<double>(fullStepsN, timeStep); if (lastStep > 0) _timeSteps.push_back(lastStep * timeStep); } void Local::calcAlphas(Eigen::Ref<Eigen::VectorXd> concs, const double &timeStep) { auto poroIni = std::get<double>(_props->_params["poro"]); for (int i = 0; i < _alphas.size(); i++) { auto aCoeff = calcAFunc(concs[i], poroIni); _alphas[i] = aCoeff * _sgrid->_cellV / timeStep; } }
38.5
81
0.700835
lanetszb
2dc34cfc58fa45d3a274066306f22561ecf89ca8
700
cc
C++
cpp/accelerated_c++/chapter10/letter_grade.cc
zhouzhiqi/book_and_code
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
[ "Apache-2.0" ]
null
null
null
cpp/accelerated_c++/chapter10/letter_grade.cc
zhouzhiqi/book_and_code
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
[ "Apache-2.0" ]
null
null
null
cpp/accelerated_c++/chapter10/letter_grade.cc
zhouzhiqi/book_and_code
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
[ "Apache-2.0" ]
null
null
null
#include <cstddef> #include <string> using std::string; string letter_grade(double grade) { // range posts for numeric grades static const double numbers[] = { 97, 94, 90, 87, 84, 80, 77, 74, 70, 60, 0 }; // names for the letter grades static const char* const letters[] = { "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F" }; // compute the number of grades given the size of the array // and the size of a single element static const size_t ngrades = sizeof(numbers)/sizeof(*numbers); // given a numeric grade, find and return the associated letter grade for (size_t i = 0; i < ngrades; ++i) { if (grade >= numbers[i]) return letters[i]; } return "?\?\?"; }
22.580645
70
0.62
zhouzhiqi
2dc5379c6c43357a0652fbdb3e263471fbfac99d
624
cpp
C++
pds2/vpls/lista_problematica/main.cpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
pds2/vpls/lista_problematica/main.cpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
pds2/vpls/lista_problematica/main.cpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
#include <iostream> #include "List.hpp" int main(){ int N, K; std::cin >> N >> K; List *L = new List(); for (int i = N; i >= 0; i--){ L->insert(i); //insere um a um os elementos [N, 0] } L->print(); std::cout << L->_size << std::endl; for (int j = 0; j < K; j++){ L->removeFirst(); // remove os primeiros elementos k vezes } L->print(); std::cout << L->_size << std::endl; for (int k = 0; k <= N; k+=2) { L->remove(k); // começa retirando o 0 e vai de 2 em 2, tirando os pares } L->print(); std::cout << L->_size << std::endl; L->clearList(); delete L; return 0; }
18.352941
75
0.516026
pganaclara
2dcad7a307eb3c0502ecaf364023a49632193515
380
cpp
C++
audio.cpp
ervaibhavkumar/QtFrogger
3f7d6e55bd153edf400bdd8bb9961f34bb32fb4d
[ "CC0-1.0" ]
null
null
null
audio.cpp
ervaibhavkumar/QtFrogger
3f7d6e55bd153edf400bdd8bb9961f34bb32fb4d
[ "CC0-1.0" ]
null
null
null
audio.cpp
ervaibhavkumar/QtFrogger
3f7d6e55bd153edf400bdd8bb9961f34bb32fb4d
[ "CC0-1.0" ]
null
null
null
#include "audio.h" #include <QMediaPlayer> namespace Audio { void playSound(QString type) { QMediaPlayer *media = new QMediaPlayer(); if (type == "die") { media->setMedia(QUrl("qrc:/audio/die.mp3")); } else { Q_ASSERT(type == "success"); media->setMedia(QUrl("qrc:/audio/success.mp3")); } media->play(); } }
19
57
0.55
ervaibhavkumar
2dcbb809c0c13f7f2bf3af6a3dcc69f39feed4d1
1,387
cpp
C++
IPSC2014/C.cpp
CodingYue/acm-icpc
667596efae998f5480819870714c37e9af0740eb
[ "Unlicense" ]
1
2015-11-03T09:31:07.000Z
2015-11-03T09:31:07.000Z
IPSC2014/C.cpp
CodingYue/acm-icpc
667596efae998f5480819870714c37e9af0740eb
[ "Unlicense" ]
null
null
null
IPSC2014/C.cpp
CodingYue/acm-icpc
667596efae998f5480819870714c37e9af0740eb
[ "Unlicense" ]
null
null
null
// File Name: C.cpp // Author: YangYue // Created Time: Sun Jun 15 19:16:28 2014 //headers #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cstring> #include <cmath> #include <ctime> #include <string> #include <queue> #include <set> #include <map> #include <iostream> #include <vector> using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> PII; typedef pair<double,double> PDD; typedef pair<LL, LL>PLL; typedef pair<LL,int>PLI; #define lch(n) ((n<<1)) #define rch(n) ((n<<1)+1) #define lowbit(i) (i&-i) #define sqr(x) ((x)*(x)) #define fi first #define se second #define MP make_pair #define PB push_back const int MaxN = 100005; const double eps = 1e-8; const double DINF = 1e100; const int INF = 1000000006; const LL LINF = 1000000000000000005ll; int n; int a[MaxN]; int main() { freopen("in","r",stdin); int cases; scanf("%d", &cases); while (cases--) { set<int> cnt; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", a + i); } vector<int> res; /* for (int i = 0; i < n; ++i) printf("%d ", cnt[a[i]]); puts(""); */ for (int i = 0; i < n; ++i) { if (!cnt.count(a[i])) { cnt.insert(a[i]); res.push_back(a[i]); } } for (int i = 0; i < res.size(); ++i) printf("%d%c", res[i], i == res.size() - 1 ? '\n' : ' '); } return 0; } // hehe ~
17.782051
60
0.596972
CodingYue
2dcc39ddcbf74c75fc4be9bda0f4b577eee7e6ae
1,535
cpp
C++
UVA/UVA297.cpp
avillega/CompetitiveProgramming
f12c1a07417f8fc154ac5297889ca756b49f0f35
[ "Apache-2.0" ]
null
null
null
UVA/UVA297.cpp
avillega/CompetitiveProgramming
f12c1a07417f8fc154ac5297889ca756b49f0f35
[ "Apache-2.0" ]
null
null
null
UVA/UVA297.cpp
avillega/CompetitiveProgramming
f12c1a07417f8fc154ac5297889ca756b49f0f35
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define _ ios_base::sync_with_stdio(false);cin.tie(NULL); #define f(i, s, n) for(int i = s; i < n ; i++) typedef vector< vector<bool> > picture; //false is e and true is f void create(string &a, picture &pic, int iniF, int iniC, int finF, int finC, int &index){ if(a[index] == 'p'){ index++; create(a, pic, iniF, (iniC+finC)/2, (iniF+finF)/2, finC, index); create(a, pic, iniF, iniC, (iniF+finF)/2, (iniC+finC)/2, index ); create(a, pic,(iniF+finF)/2 ,iniC, finF, (iniC+finC)/2, index); create(a, pic, (iniF+finF)/2, (iniC+finC)/2 , finF, finC, index); return; }else if(a[index]=='e'){ index++; }else{ index++; f(i, iniF, finF){ f(j, iniC, finC){ pic[i][j]=true; } } return; } } int main(){_ string a, b; int T, blacks, index; cin >> T; while(T--){ cin >> a; cin >> b; blacks = 0; index = 0; picture pic1(32, vector<bool>(32, false)), pic2(32, vector<bool>(32, false)); create(a, pic1, 0,0, 32,32, index); index = 0; create(b, pic2, 0,0, 32,32, index); f(i, 0, 32){ f(j, 0, 32){ if(pic1[i][j] || pic2[i][j]) blacks++; } } cout << "There are " << blacks << " black pixels.\n"; } return 0; }
27.410714
90
0.448208
avillega
2dd75dc1523557f4a9c0a2abf2a52d94d27691a7
3,689
cpp
C++
hr/medium/minimum_area.cpp
gnom1gnom/cpp-algorithms
e460c0d1720acf0e0548452dfba05651e4868120
[ "Unlicense" ]
null
null
null
hr/medium/minimum_area.cpp
gnom1gnom/cpp-algorithms
e460c0d1720acf0e0548452dfba05651e4868120
[ "Unlicense" ]
null
null
null
hr/medium/minimum_area.cpp
gnom1gnom/cpp-algorithms
e460c0d1720acf0e0548452dfba05651e4868120
[ "Unlicense" ]
null
null
null
/* * Complete the 'minArea' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts following parameters: * 1. INTEGER_ARRAY x * 2. INTEGER_ARRAY y * 3. INTEGER k */ #include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); long minArea(vector<int> x, vector<int> y, int k) { // szukamy lewej dolnej krawędzi // szukamy prawej górnej krawedzi vector<pair<int, int>> vect; for (int i = 0; i < x.size(); i++) { vect.push_back(make_pair(x[i], y[i])); } sort(vect.begin(), vect.end()); pair<int, int> lowerBig = vect.front(); pair<int, int> upperBig = vect.back(); long bokBig = ((upperBig.first - lowerBig.first) > (upperBig.second - lowerBig.second)) ? (upperBig.first - lowerBig.first) : (upperBig.second - lowerBig.second); cout << "large square: " << pow(bokBig + 2, 2) << endl; vector<pair<int, int>> vect_small; int nextIndex = vect.size() / 2; // odejmujemy punk lower albo upper size_t lowerInd{0}, upperInd{vect.size() - 1}; for (int i = vect.size(); i > k && upperInd > lowerInd; i--) { // kwadrat mniejszy o punkt z dołu pair<int, int> lower1 = vect[lowerInd]; pair<int, int> upper1 = vect[upperInd - 1]; long bok1 = ((upper1.first - lower1.first) > (upper1.second - lower1.second)) ? (upper1.first - lower1.first) : (upper1.second - lower1.second); // kwadrat mniejszy o punkt z góry pair<int, int> lower2 = vect[lowerInd + 1]; pair<int, int> upper2 = vect[upperInd]; long bok2 = ((upper2.first - lower2.first) > (upper2.second - lower2.second)) ? (upper2.first - lower2.first) : (upper2.second - lower2.second); // sprawdzamy który ma mniejszy bok // odrzucamy wierdzłołek który generuje większy bok (bok1 >= bok2) ? lowerInd++ : upperInd--; } pair<int, int> lower = vect[lowerInd]; pair<int, int> upper = vect[upperInd]; long bok = ((upper.first - lower.first) > (upper.second - lower.second)) ? (upper.first - lower.first) : (upper.second - lower.second); cout << "small square: " << pow(bok + 2, 2) << endl; return pow(bok + 2, 2); } int main() { /* ofstream fout(getenv("OUTPUT_PATH")); string x_count_temp; getline(cin, x_count_temp); int x_count = stoi(ltrim(rtrim(x_count_temp))); vector<int> x(x_count); for (int i = 0; i < x_count; i++) { string x_item_temp; getline(cin, x_item_temp); int x_item = stoi(ltrim(rtrim(x_item_temp))); x[i] = x_item; } string y_count_temp; getline(cin, y_count_temp); int y_count = stoi(ltrim(rtrim(y_count_temp))); vector<int> y(y_count); for (int i = 0; i < y_count; i++) { string y_item_temp; getline(cin, y_item_temp); int y_item = stoi(ltrim(rtrim(y_item_temp))); y[i] = y_item; } string k_temp; getline(cin, k_temp); int k = stoi(ltrim(rtrim(k_temp))); */ // out 81 // vector<int> x = {0, 3}; // vector<int> y = {0, 7}; // out 36 vector<int> x = {0, 0, 1, 1, 2, 2}; vector<int> y = {0, 1, 0, 1, 0, 1}; int k = 4; long result = minArea(x, y, k); cout << result << "\n"; return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end()); return s; }
24.925676
166
0.584169
gnom1gnom
2dd75efe9f4490c764ffb6e78a35c63f50a350fe
1,515
cpp
C++
android-31/android/telephony/CarrierConfigManager_Apn.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/telephony/CarrierConfigManager_Apn.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/telephony/CarrierConfigManager_Apn.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JString.hpp" #include "./CarrierConfigManager_Apn.hpp" namespace android::telephony { // Fields JString CarrierConfigManager_Apn::KEY_PREFIX() { return getStaticObjectField( "android.telephony.CarrierConfigManager$Apn", "KEY_PREFIX", "Ljava/lang/String;" ); } JString CarrierConfigManager_Apn::KEY_SETTINGS_DEFAULT_PROTOCOL_STRING() { return getStaticObjectField( "android.telephony.CarrierConfigManager$Apn", "KEY_SETTINGS_DEFAULT_PROTOCOL_STRING", "Ljava/lang/String;" ); } JString CarrierConfigManager_Apn::KEY_SETTINGS_DEFAULT_ROAMING_PROTOCOL_STRING() { return getStaticObjectField( "android.telephony.CarrierConfigManager$Apn", "KEY_SETTINGS_DEFAULT_ROAMING_PROTOCOL_STRING", "Ljava/lang/String;" ); } JString CarrierConfigManager_Apn::PROTOCOL_IPV4() { return getStaticObjectField( "android.telephony.CarrierConfigManager$Apn", "PROTOCOL_IPV4", "Ljava/lang/String;" ); } JString CarrierConfigManager_Apn::PROTOCOL_IPV4V6() { return getStaticObjectField( "android.telephony.CarrierConfigManager$Apn", "PROTOCOL_IPV4V6", "Ljava/lang/String;" ); } JString CarrierConfigManager_Apn::PROTOCOL_IPV6() { return getStaticObjectField( "android.telephony.CarrierConfigManager$Apn", "PROTOCOL_IPV6", "Ljava/lang/String;" ); } // QJniObject forward CarrierConfigManager_Apn::CarrierConfigManager_Apn(QJniObject obj) : JObject(obj) {} // Constructors // Methods } // namespace android::telephony
23.671875
85
0.753795
YJBeetle
2dd96491a82cbd24336742059e85bb7440310571
203
hpp
C++
demos/sjtwo/sd_card/project_config.hpp
SJSURoboticsTeam/urc-control_systems-2020
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
[ "Apache-2.0" ]
6
2020-06-20T23:56:42.000Z
2021-12-18T08:13:54.000Z
demos/sjtwo/sd_card/project_config.hpp
SJSURoboticsTeam/urc-control_systems-2020
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
[ "Apache-2.0" ]
153
2020-06-09T14:49:29.000Z
2022-01-31T16:39:39.000Z
demos/sjtwo/sd_card/project_config.hpp
SJSURoboticsTeam/urc-control_systems-2020
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
[ "Apache-2.0" ]
10
2020-08-02T00:55:38.000Z
2022-01-24T23:06:51.000Z
#pragma once // Change the "#if 0" to "#if 1" below to see debug information for every // step of the SD card communication #if 1 #define SJ2_LOG_LEVEL SJ2_LOG_LEVEL_DEBUG #endif #include "config.hpp"
20.3
73
0.743842
SJSURoboticsTeam
2ddb3df5d95cfe1b477fb6c53a77c1e7b6a867da
94
cpp
C++
modules/engine/src/Render/Palette/Palette.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
1
2016-11-12T02:43:29.000Z
2016-11-12T02:43:29.000Z
modules/engine/src/Render/Palette/Palette.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
modules/engine/src/Render/Palette/Palette.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
#include <randar/Render/Palette/Palette.hpp> // Destructor. randar::Palette::~Palette() { }
11.75
44
0.702128
litty-studios
2ddba606153d5f8e2d02c84989be9b1f70aede63
2,122
cpp
C++
tests/messaging/test_call_many.cpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
61
2015-01-08T08:05:28.000Z
2022-01-07T16:47:47.000Z
tests/messaging/test_call_many.cpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
30
2015-04-06T21:41:18.000Z
2021-08-18T13:24:51.000Z
tests/messaging/test_call_many.cpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
64
2015-02-23T20:01:11.000Z
2022-03-14T13:31:20.000Z
/* ** Copyright (C) 2012 Aldebaran Robotics */ #include <map> #include <qi/application.hpp> #include <qi/anyobject.hpp> #include <qi/type/dynamicobjectbuilder.hpp> #include <qi/session.hpp> #include <testsession/testsessionpair.hpp> #include <qi/testutils/testutils.hpp> #include <gtest/gtest.h> qi::AnyObject oclient1, oclient2; static qi::Promise<bool> payload; void onFire1(const int& pl) { if (pl) oclient2.async<void>("onFire2", pl-1); else payload.setValue(true); } void onFire2(const int& pl) { if (pl) oclient1.async<void>("onFire1", pl-1); else payload.setValue(true); } TEST(Test, Recurse) { payload = qi::Promise<bool>(); TestSessionPair p1; TestSessionPair p2(TestSessionPair::ShareServiceDirectory, p1); qi::DynamicObjectBuilder ob1, ob2; ob1.advertiseMethod("onFire1", &onFire1); ob2.advertiseMethod("onFire2", &onFire2); qi::AnyObject oserver1(ob1.object()), oserver2(ob2.object()); unsigned int nbServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 2 : 1; // Two objects with a fire event and a onFire method. ASSERT_TRUE(test::finishesWithValue(p1.server()->registerService("coin1", oserver1))); ASSERT_TRUE(test::finishesWithValue(p2.server()->registerService("coin2", oserver2))); EXPECT_EQ(nbServices, p1.server()->services(qi::Session::ServiceLocality_Local).value().size()); EXPECT_EQ(nbServices, p2.server()->services(qi::Session::ServiceLocality_Local).value().size()); ASSERT_TRUE(test::finishesWithValue(p2.client()->waitForService("coin1"))); ASSERT_TRUE(test::finishesWithValue(p1.client()->waitForService("coin2"))); oclient1 = p2.client()->service("coin1").value(); oclient2 = p1.client()->service("coin2").value(); int niter = 1000; if (TestMode::getTestMode() == TestMode::Mode_SSL) { niter /= 100; } if (getenv("VALGRIND")) { std::cerr << "Valgrind detected, reducing iteration count" << std::endl; niter = 50; } oclient1.call<void>("onFire1", niter); ASSERT_TRUE(test::finishesWithValue(payload.future())); oclient1.reset(); oclient2.reset(); }
29.887324
98
0.694628
arntanguy
2ddd8a850b2a9319a6f723ad224f57a35e38a7d5
10,532
cpp
C++
src/check/proof.cpp
arpj-rebola/rupee-old
b00351cbd3173d329ea183e08c3283c6d86d18a1
[ "MIT" ]
null
null
null
src/check/proof.cpp
arpj-rebola/rupee-old
b00351cbd3173d329ea183e08c3283c6d86d18a1
[ "MIT" ]
null
null
null
src/check/proof.cpp
arpj-rebola/rupee-old
b00351cbd3173d329ea183e08c3283c6d86d18a1
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include "core.hpp" #include "proof.hpp" #include "database.hpp" //************************************************************ // Class ClauseArray //************************************************************ // Builders ClauseArray::ClauseArray(std::uint32_t capacity) : m_array(nullptr), m_size(0U), m_capacity(capacity), m_balanced(capacity) { m_array = static_cast<Short*>(std::malloc(m_capacity * sizeof(Short))); if(m_array == nullptr) { Core::fail("Allocation error"); } } ClauseArray::~ClauseArray() { if(m_array != nullptr) { std::free(m_array); } } //------------------------------------------------------------ // Interface methods void ClauseArray::insertClause(ClauseIterator& it) { while(!it.end()) { insert(it.get()); it.next(); } } void ClauseArray::insertResolvent(ClauseIterator& it1, ClauseIterator& it2, Short pivot) { Short literal; while(!it1.end()) { if((literal = it1.get()) != pivot) { insert(literal); } it1.next(); } pivot = Shortie::complement(pivot); while(!it2.end()) { if((literal = it2.get()) != pivot) { insert(literal); } it2.next(); } } void ClauseArray::reverseClause(ClauseIterator& it) { while(!it.end()) { insert(Shortie::complement(it.get())); it.next(); } } void ClauseArray::reverseResolvent(ClauseIterator& it1, ClauseIterator& it2, Short pivot) { Short literal; while(!it1.end()) { if((literal = it1.get()) != pivot) { insert(Shortie::complement(literal)); } it1.next(); } pivot = Shortie::complement(pivot); while(!it2.end()) { if((literal = it2.get()) != pivot) { insert(Shortie::complement(literal)); } it2.next(); } } void ClauseArray::propagateClause(ClauseIterator& it) { Short literal = Falsified; Short propagation = Falsified; while(!it.end()) { literal = it.get(); if(!m_balanced.contains(Shortie::complement(literal))) { if(propagation != Falsified) { return; } propagation = literal; } it.next(); } if(propagation == Falsified) { propagation = literal; } if(propagation != Falsified) { insert(propagation); } } bool ClauseArray::containsReversed(ClauseIterator& it) { while(!it.end()) { if(!contains(Shortie::complement(it.get()))) { return false; } it.next(); } return true; } bool ClauseArray::containsReversedResolvent(ClauseIterator& it1, ClauseIterator& it2, Short pivot) { Short literal; while(!it1.end()) { if((literal = it1.get()) != pivot) { if(!contains(Shortie::complement(it1.get()))) { return false; } } it1.next(); } pivot = Shortie::complement(pivot); while(!it2.end()) { if((literal = it2.get()) != pivot) { if(!contains(Shortie::complement(it2.get()))) { return false; } } it2.next(); } return true; } bool ClauseArray::upModels(ClauseIterator& it) { Short found = Falsified; Short literal; while(!it.end()) { literal = it.get(); if(!contains(Shortie::complement(literal))) { if(contains(literal)) { return true; } else if(found == Falsified) { found = literal; } else { return true; } } it.next(); } return false; } bool ClauseArray::tautology() { return m_balanced.tautology(); } void ClauseArray::reset() { m_balanced.reset(m_array, m_size); m_size = 0U; } //------------------------------------------------------------ // Private methods bool ClauseArray::contains(Short literal) { return fits(literal) && m_balanced.contains(literal); } void ClauseArray::insert(Short literal) { if(m_balanced.insert(literal)) { if(full()) { reallocate(); } m_array[m_size++] = literal; } } bool ClauseArray::full() { return m_size >= m_capacity; } bool ClauseArray::fits(Short literal) { return literal < m_capacity; } void ClauseArray::reallocate() { m_capacity *= ReallocationFactor; m_array = static_cast<Short*>(std::realloc(m_array, m_capacity * sizeof(Short))); if(m_array == nullptr) { Core::fail("Reallocation error"); } } //************************************************************ // Class LratInference //************************************************************ // Builders LratInference::LratInference(Long clause) : m_kind(PremiseKind), m_clause(clause), m_chain(NoRun), m_resolvents(NoRun), m_deletion(NoRun) {} LratInference::LratInference(std::int32_t kind, Long clause, Long chain) : m_kind(kind), m_clause(clause), m_chain(chain), m_resolvents(NoRun), m_deletion(NoRun) {} //------------------------------------------------------------ // Interface methods void LratInference::addResolvents(Long resolvents) { if(m_resolvents == NoRun) { m_resolvents = resolvents; } else { Core::invalid("Duplicated resolvent chain assigned to instruction"); } } void LratInference::addDeletion(Long deletion) { if(m_deletion == NoRun) { m_deletion = deletion; } else { Core::invalid("Duplicated deletion chain assigned to instruction"); } } bool LratInference::isPremise() { return m_kind == PremiseKind; } bool LratInference::isRup() { return m_kind == RupKind; } bool LratInference::isRat() { return m_kind == RatKind; } Long LratInference::getClause() { return m_clause; } Long LratInference::getChain() { return m_chain; } Long LratInference::getResolvents() { return m_resolvents; } Long LratInference::getDeletion() { return m_deletion; } //************************************************************ // Class LratProof //************************************************************ // Builders LratProof::LratProof(std::uint32_t capacity) : m_array(nullptr), m_size(0U), m_capacity(capacity), m_iterator(0U) { m_array = static_cast<LratInference*>(std::malloc(m_capacity * sizeof(LratInference))); if(m_array == nullptr) { Core::fail("Allocation error"); } } LratProof::~LratProof() { if(m_array != nullptr) { std::free(m_array); } } //------------------------------------------------------------ // Interface methods std::uint32_t LratProof::insertPremise(Long clause) { insert(LratInference(clause)); return m_size - 1; } std::uint32_t LratProof::insertRup(Long clause, Long chain) { insert(LratInference(LratInference::RupKind, clause, chain)); return m_size - 1; } std::uint32_t LratProof::insertRat(Long clause, Long chain) { insert(LratInference(LratInference::RatKind, clause, chain)); return m_size - 1; } void LratProof::addResolventChain(std::uint32_t inference, Long chain) { m_array[inference].addResolvents(chain); } void LratProof::addDeletionChain(std::uint32_t inference, Long chain) { m_array[inference].addDeletion(chain); } bool LratProof::end() { return m_iterator >= m_size; } void LratProof::next() { ++m_iterator; } LratInference& LratProof::get() { return m_array[m_iterator]; } //------------------------------------------------------------ // Private methods void LratProof::insert(const LratInference& inf) { if(full()) { reallocate(); } m_array[m_size++] = inf; } void LratProof::reallocate() { m_capacity *= ReallocationFactor; m_array = static_cast<LratInference*>(std::realloc(m_array, m_capacity * sizeof(LratInference))); if(m_array == nullptr) { Core::fail("Reallocation error"); } } bool LratProof::full() { return m_size >= m_capacity; } //************************************************************ // Class DratInference //************************************************************ // Builders DratInference::DratInference(std::int32_t kind, Long clause, Short pivot) : m_kind(kind), m_clause(clause), m_pivot(pivot) {} //------------------------------------------------------------ // Interface methods bool DratInference::isPremise() { return m_kind == PremiseKind; } bool DratInference::isIntroduction() { return m_kind == IntroductionKind; } bool DratInference::isDeletion() { return m_kind == DeletionKind; } Long DratInference::getClause() { return m_clause; } Short DratInference::getPivot() { return m_pivot; } //************************************************************ // Class DratInference //************************************************************ // Builders DratProof::DratProof(std::uint32_t capacity) : m_array(nullptr), m_size(0U), m_capacity(capacity) { m_array = static_cast<DratInference*>(std::malloc(m_capacity * sizeof(DratInference))); if(m_array == nullptr) { Core::fail("Allocation error"); } } DratProof::~DratProof() { if(m_array != nullptr) { std::free(m_array); } } //------------------------------------------------------------ // Interface methods std::uint32_t DratProof::insertPremise(Long clause) { insert(DratInference(DratInference::PremiseKind, clause, Shortie::NegativeZero)); return m_size - 1; } std::uint32_t DratProof::insertIntroduction(Long clause, Short pivot) { insert(DratInference(DratInference::IntroductionKind, clause, pivot)); return m_size - 1; } std::uint32_t DratProof::insertDeletion(Long clause) { insert(DratInference(DratInference::DeletionKind, clause, Shortie::NegativeZero)); return m_size - 1; } void DratProof::accumulateFormula(std::uint32_t index, ClauseDatabase& db) { if(index - 1 >= m_size || index - 1 < 0) { Core::invalid("Instruction index in SICK file does not correspond to a DRAT proof instruction"); return; } for(std::uint32_t i = 0U; i < index - 1; ++i) { DratInference& inference = m_array[i]; db.setActivity(inference.getClause(), !(inference.isDeletion())); } } DratInference DratProof::getInstruction(std::uint32_t index) { return m_array[index - 1]; } //------------------------------------------------------------ // Private methods void DratProof::insert(const DratInference& inf) { if(full()) { reallocate(); } m_array[m_size++] = inf; } void DratProof::reallocate() { m_capacity *= ReallocationFactor; m_array = static_cast<DratInference*>(std::realloc(m_array, m_capacity * sizeof(DratInference))); if(m_array == nullptr) { Core::fail("Reallocation error"); } } bool DratProof::full() { return m_size >= m_capacity; } //************************************************************ // Class SickInstruction //************************************************************ Short& SickInstruction::pivot() { return m_pivot; } std::uint32_t& SickInstruction::instruction() { return m_instruction; } Long& SickInstruction::naturalClause() { return m_natclause; } Long& SickInstruction::naturalModel() { return m_natmodel; } Long& SickInstruction::resolventClause() { return m_resclause; } Long& SickInstruction::resolventModel() { return m_resmodel; }
21.537832
100
0.612704
arpj-rebola
2de368037e9cbf6f6a474a1fcac22b112ca8f03a
597
cpp
C++
diagonaldiff.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
diagonaldiff.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
diagonaldiff.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <vector> #include <cstdlib> using namespace std; typedef long long int ll; ll getDiff(vector<vector<int>> arr); ll getDiff(vector<vector<int>> arr) { ll sum = 0; for(ll i = 0; i < (ll)arr.size(); i++) { sum += arr[i][i] - arr[i][(ll)arr.size() - i - 1]; } return sum; } int main(int argc, char const *argv[]) { ll n; cin >> n; int temp; vector<vector<int>> arr(n); for(ll i = 0; i < n; i++) { arr[i] = vector<int>(n); for(ll j = 0; j < n; j++) { cin >> temp; arr[i][j] = temp; } } cout << abs(getDiff(arr)) << endl; return 0; }
15.710526
52
0.549414
d3cod3monk78
2de4e2d15a5865802088020fad5bcca7562ea53b
3,995
cc
C++
src/util/LS_trends/rp.cc
mansour2014/ATSP2K_plus
30842b9f086d1e497aeb778e2a352d1e8e520ec3
[ "BSD-4-Clause-UC" ]
1
2019-07-21T14:03:39.000Z
2019-07-21T14:03:39.000Z
src/util/LS_trends/rp.cc
mzmansour/ATSP2K_plus
30842b9f086d1e497aeb778e2a352d1e8e520ec3
[ "BSD-4-Clause-UC" ]
null
null
null
src/util/LS_trends/rp.cc
mzmansour/ATSP2K_plus
30842b9f086d1e497aeb778e2a352d1e8e520ec3
[ "BSD-4-Clause-UC" ]
null
null
null
#include "rep_lib.hh" #include "ls.hh" #include <string> #include<cmath> string& ret_str(string& s) { int a = s.find_first_not_of(" "); s.erase(0,a); a = s.find_last_not_of(" "); s.erase(a+1); // cout << s.size() << "::" << s << "::" << endl; return s; } string& u_format(string& ss, double dr, double du) { if (!dr && !du) { ss = " & "; return ss; } char t1[50]; std::ostrstream BUF1(t1,sizeof(t1)); BUF1.precision(3); BUF1.setf(ios::scientific, ios::floatfield); BUF1 << dr << ends; string s1 = t1; char t2[50]; std::ostrstream BUF2(t2,sizeof(t2)); BUF2.precision(3); BUF2.setf(ios::scientific, ios::floatfield); BUF2 << du << ends; string s2 = t2; char* pe1 = &t1[6]; char* pe2 = &t2[6]; istrstream ie1(pe1); istrstream ie2(pe2); int e1 = 0; int e2 = 0; ie1 >> e1; ie2 >> e2; char t3[10]; std::ostrstream BUF3(t3,sizeof(t3)); BUF3.precision(3); BUF3.setf(ios::scientific, ios::floatfield); BUF3 << e1 << ends; string stmp = t3; string s3(""); if (e1 < 10 && e1 > 0) s3 = " " + stmp; else s3 = stmp; if (!du) { s1.erase(5,8); ss = s1 + "(" + "-" + ")" + " & " + s3; return ss; } s1.erase(5,8); int ediff = e1 - e2; if (ediff >= 4) { ss = s1 + "(" + "0" + ")" + " & " + s3; return ss; } double maxd = (dr <= du) ? du : dr; double maxpd = fabs((du)/maxd)*100; if (maxpd >= 99.99) { char t10[50]; std::ostrstream BUF1(t10,sizeof(t10)); BUF1.precision(2); BUF1.setf(ios::scientific, ios::floatfield); BUF1 << dr << ends; string s10 = t10; s10.erase(4,7); ss = s10 + "(" + "100\\%" + ")" + " & " + s3; return ss; } if (maxpd >= 70) { char t4[10]; char t10[50]; std::ostrstream BUF1(t10,sizeof(t10)); BUF1.precision(2); BUF1.setf(ios::scientific, ios::floatfield); BUF1 << dr << ends; string s10 = t10; s10.erase(4,7); std::ostrstream BUF4(t4,sizeof(t4)); BUF4.precision(1); BUF4.setf(ios::showpoint); BUF4.setf(ios::fixed, ios::floatfield); BUF4 << maxpd << ends; string s4 = t4; ss = s10 + "(" + s4 + "\\%" + ")" + " & " + s3; return ss; } if (!ediff) { char t5[10]; std::ostrstream BUF5(t5,sizeof(t5)); BUF5.precision(2); BUF5.setf(ios::scientific, ios::floatfield); BUF5 << dr << ends; string s5 = t5; s5.erase(4,7); char t6[10]; std::ostrstream BUF6(t6,sizeof(t6)); BUF6.precision(2-ediff); BUF6.setf(ios::showpoint); BUF6.setf(ios::scientific, ios::floatfield); BUF6 << du << ends; string s6 = t6; int SZ = s6.size(); s6.erase(SZ-4,SZ-1); s6.erase(1,1); if (!ediff) ss = s5 + "(" + s6 + ")" + " & " + s3; else ss = s5 + "(" + s6 + ")" + " & " + s3; return ss; } if (ediff == 3) { double DD(10); int I = int(du/(pow(DD,e2))); char t8[10]; std::ostrstream BUF8(t8,sizeof(t8)); BUF8 << I << ends; string s8 = t8; ss = s1 + "(" + s8 + ")" + " & " + s3; return ss; } if (ediff == 2 || ediff == 1) { char t7[10]; std::ostrstream BUF7(t7,sizeof(t7)); BUF7.precision(3-ediff); BUF7.setf(ios::showpoint); BUF7.setf(ios::scientific, ios::floatfield); BUF7 << du << ends; string s7 = t7; int SZ = s7.size(); s7.erase(SZ-4,SZ-1); s7.erase(1,1); if (ediff == 2) ss = s1 + "(" + s7 + ")" + " & " + s3; else ss = s1 + "(" + s7 + ")" + " & " + s3; return ss; } // #0123456789_123456789_123456789 // #3.333e+05(4.343e+03)# // #3.333(434) & 5 # // #3.33(43) & 5 # // #3.33(10\\%) & 5 # ss = " & "; return ss; }
24.212121
64
0.463079
mansour2014
2de62dcc70ac4b26a94f7541a6a172636c76ce7c
6,996
cc
C++
src/memory/ReproCartridgeV1.cc
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/memory/ReproCartridgeV1.cc
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/memory/ReproCartridgeV1.cc
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "ReproCartridgeV1.hh" #include "DummyAY8910Periphery.hh" #include "MSXCPUInterface.hh" #include "serialize.hh" #include <vector> /****************************************************************************** * DOCUMENTATION AS PROVIDED BY MANUEL PAZOS, WHO DEVELOPED THE CARTRIDGE * ****************************************************************************** Repro Cartridge version 1 is similar to Konami Ultimate Collection. It uses the same flashROM, SCC/SCC+. But it only supports Konami SCC mapper. Released were cartridges with the following content (at least): only Metal Gear, only Metal Gear 2 [REGISTER (#7FFF)] If it contains value 0x50, the flash is writable and the mapper is disabled. Otherwise, the mapper is enabled and the flash is readonly. - Mapper supports 4 different ROMs of 2MB each, with the KonamiSCC mapper - Cartridge has a PSG at 0x10, write only - On I/O port 0x13 the 2MB block can be selected (default 0, so up to 3) ******************************************************************************/ namespace openmsx { static std::vector<AmdFlash::SectorInfo> getSectorInfo() { std::vector<AmdFlash::SectorInfo> sectorInfo; // 8 * 8kB sectorInfo.insert(end(sectorInfo), 8, {8 * 1024, false}); // 127 * 64kB sectorInfo.insert(end(sectorInfo), 127, {64 * 1024, false}); return sectorInfo; } ReproCartridgeV1::ReproCartridgeV1( const DeviceConfig& config, Rom&& rom_) : MSXRom(config, std::move(rom_)) , flash(rom, getSectorInfo(), 0x207E, true, config, false) , scc("MGCV1 SCC", config, getCurrentTime(), SCC::SCC_Compatible) , psg("MGCV1 PSG", DummyAY8910Periphery::instance(), config, getCurrentTime()) { powerUp(getCurrentTime()); getCPUInterface().register_IO_Out(0x10, this); getCPUInterface().register_IO_Out(0x11, this); getCPUInterface().register_IO_Out(0x13, this); } ReproCartridgeV1::~ReproCartridgeV1() { getCPUInterface().unregister_IO_Out(0x10, this); getCPUInterface().unregister_IO_Out(0x11, this); getCPUInterface().unregister_IO_Out(0x13, this); } void ReproCartridgeV1::powerUp(EmuTime::param time) { scc.powerUp(time); reset(time); } void ReproCartridgeV1::reset(EmuTime::param time) { flashRomWriteEnabled = false; mainBankReg = 0; sccMode = 0; for (int bank = 0; bank < 4; ++bank) { bankRegs[bank] = bank; } scc.reset(time); psgLatch = 0; psg.reset(time); flash.reset(); invalidateDeviceRCache(); // flush all to be sure } unsigned ReproCartridgeV1::getFlashAddr(unsigned addr) const { unsigned page8kB = (addr >> 13) - 2; if (page8kB >= 4) return unsigned(-1); // outside [0x4000, 0xBFFF] byte bank = bankRegs[page8kB]; // 2MB max return (mainBankReg << 21) | (bank << 13) | (addr & 0x1FFF); } // Note: implementation (mostly) copied from KUC bool ReproCartridgeV1::isSCCAccess(word addr) const { if (sccMode & 0x10) return false; if (addr & 0x0100) { // Address bit 8 must be zero, this is different from a real // SCC/SCC+. According to Manuel Pazos this is a leftover from // an earlier version that had 2 SCCs: the SCC on the left or // right channel reacts when address bit 8 is respectively 0/1. return false; } if (sccMode & 0x20) { // SCC+ range: 0xB800..0xBFFF, excluding 0xBFFE-0xBFFF return (bankRegs[3] & 0x80) && (0xB800 <= addr) && (addr < 0xBFFE); } else { // SCC range: 0x9800..0x9FFF, excluding 0x9FFE-0x9FFF return ((bankRegs[2] & 0x3F) == 0x3F) && (0x9800 <= addr) && (addr < 0x9FFE); } } byte ReproCartridgeV1::readMem(word addr, EmuTime::param time) { if (isSCCAccess(addr)) { return scc.readMem(addr & 0xFF, time); } unsigned flashAddr = getFlashAddr(addr); return (flashAddr != unsigned(-1)) ? flash.read(flashAddr) : 0xFF; // unmapped read } byte ReproCartridgeV1::peekMem(word addr, EmuTime::param time) const { if (isSCCAccess(addr)) { return scc.peekMem(addr & 0xFF, time); } unsigned flashAddr = getFlashAddr(addr); return (flashAddr != unsigned(-1)) ? flash.peek(flashAddr) : 0xFF; // unmapped read } const byte* ReproCartridgeV1::getReadCacheLine(word addr) const { if (isSCCAccess(addr)) return nullptr; unsigned flashAddr = getFlashAddr(addr); return (flashAddr != unsigned(-1)) ? flash.getReadCacheLine(flashAddr) : unmappedRead; } void ReproCartridgeV1::writeMem(word addr, byte value, EmuTime::param time) { unsigned page8kB = (addr >> 13) - 2; if (page8kB >= 4) return; // outside [0x4000, 0xBFFF] // There are several overlapping functional regions in the address // space. A single write can trigger behaviour in multiple regions. In // other words there's no priority amongst the regions where a higher // priority region blocks the write from the lower priority regions. // This only goes for places where the flash is 'seen', so not for the // SCC registers if (isSCCAccess(addr)) { scc.writeMem(addr & 0xFF, value, time); return; // write to SCC blocks write to other functions } // address is calculated before writes to other regions take effect unsigned flashAddr = getFlashAddr(addr); // Main mapper register if (addr == 0x7FFF) { flashRomWriteEnabled = (value == 0x50); invalidateDeviceRCache(); // flush all to be sure } if (!flashRomWriteEnabled) { // Konami-SCC if ((addr & 0x1800) == 0x1000) { // [0x5000,0x57FF] [0x7000,0x77FF] // [0x9000,0x97FF] [0xB000,0xB7FF] bankRegs[page8kB] = value; invalidateDeviceRCache(0x4000 + 0x2000 * page8kB, 0x2000); } // SCC mode register if ((addr & 0xFFFE) == 0xBFFE) { sccMode = value; scc.setChipMode((value & 0x20) ? SCC::SCC_plusmode : SCC::SCC_Compatible); invalidateDeviceRCache(0x9800, 0x800); invalidateDeviceRCache(0xB800, 0x800); } } else { if (flashAddr != unsigned(-1)) { flash.write(flashAddr, value); } } } byte* ReproCartridgeV1::getWriteCacheLine(word addr) const { return ((0x4000 <= addr) && (addr < 0xC000)) ? nullptr // [0x4000,0xBFFF] isn't cacheable : unmappedWrite; } void ReproCartridgeV1::writeIO(word port, byte value, EmuTime::param time) { switch (port & 0xFF) { case 0x10: psgLatch = value & 0x0F; break; case 0x11: psg.writeRegister(psgLatch, value, time); break; case 0x13: mainBankReg = value & 3; invalidateDeviceRCache(); // flush all to be sure break; default: UNREACHABLE; } } template<typename Archive> void ReproCartridgeV1::serialize(Archive& ar, unsigned /*version*/) { // skip MSXRom base class ar.template serializeBase<MSXDevice>(*this); ar.serialize("flash", flash, "scc", scc, "psg", psg, "psgLatch", psgLatch, "flashRomWriteEnabled", flashRomWriteEnabled, "mainBankReg", mainBankReg, "sccMode", sccMode, "bankRegs", bankRegs); } INSTANTIATE_SERIALIZE_METHODS(ReproCartridgeV1); REGISTER_MSXDEVICE(ReproCartridgeV1, "ReproCartridgeV1"); } // namespace openmsx
28.555102
79
0.665666
imulilla
2de70533ced990658f049ae0190745fe7e8b51cb
5,711
cpp
C++
libdsd/src/CDFFFile.cpp
xlm04322/dsd-dop-from-kpidsd
2fe6916b1a5e3194d65b3d59528b3e053c9a9f50
[ "MIT" ]
2
2019-03-12T18:14:52.000Z
2021-12-13T13:08:24.000Z
libdsd/src/CDFFFile.cpp
xlm04322/dsd-dop-from-kpidsd
2fe6916b1a5e3194d65b3d59528b3e053c9a9f50
[ "MIT" ]
null
null
null
libdsd/src/CDFFFile.cpp
xlm04322/dsd-dop-from-kpidsd
2fe6916b1a5e3194d65b3d59528b3e053c9a9f50
[ "MIT" ]
4
2016-09-21T20:24:16.000Z
2021-04-10T08:24:55.000Z
#include "stdafx.h" #include "CDFFFile.h" CDFFFile::CDFFFile() : CLargeFile() { } CDFFFile::~CDFFFile() { } void CDFFFile::Close() { CLargeFile::Close(); } bool CDFFFile::readChunkHeader(DFFChunkHeader& header, ChunkStep& step) { DWORD dwBytesRead = 0; step.headerOffset = Tell(); if (!Read(&header, sizeof header, &dwBytesRead) || dwBytesRead != sizeof header) return false; header.ckID = ntohl(header.ckID); header.ckDataSize = ntohll(header.ckDataSize); step.header = header; step.dataOffset = Tell(); step.dataEndOffset = step.dataOffset + step.header.ckDataSize + (step.header.ckDataSize & 1); return true; } BOOL CDFFFile::Open(CAbstractFile* file) { ChunkStep step; DFFChunkHeader hdr; hFile = file; while (readChunkHeader(hdr, step)) { DFFID parentID = stack.empty() ? 0x0000 : stack.top().header.ckID; bool handled = false; stack.push(step); handled = handled || readFRM8(step, hdr); handled = handled || readPROP(step, hdr); handled = handled || readDIIN(step, hdr); if (!handled) { // default action -- skip that chunk Seek(step.dataEndOffset, NULL, FILE_BEGIN); stack.pop(); } } stack.pop(); if (!stack.empty()) { // invalid stack state -- hiearchy mismatch } return TRUE; } bool CDFFFile::readFRM8(ChunkStep& step, DFFChunkHeader& hdr) { switch (hdr.ckID) { case DFFID_FRM8: { frm8.header = hdr; frm8.offsetToData = step.dataOffset; Read(&frm8.data, sizeof frm8.data, NULL); frm8.setupData(); // descend to subchunks break; } case DFFID_FVER: { Read(&frm8.fver.data, sizeof frm8.fver.data, NULL); frm8.fver.setupData(); stack.pop(); // ascend to parent (FRM8) chunk break; } case DFFID_DSD_: { frm8.dsd.header = hdr; frm8.dsd.offsetToData = step.dataOffset; Seek(step.dataEndOffset, NULL, FILE_BEGIN); stack.pop(); // ascend to parent (FRM8) chunk break; } case DFFID_COMT: { frm8.comt.header = hdr; frm8.comt.offsetToData = step.dataOffset; Read(&frm8.comt.data, sizeof frm8.comt.data, NULL); frm8.comt.setupData(); for (uint32_t i = 0; i < frm8.comt.data.numComments; i++) { Comment comment; Read(&comment.data, sizeof comment.data, NULL); comment.setupData(); assignBuffer(comment.data.count, comment.commentText); frm8.comt.comments.push_back(comment); } Seek(step.dataEndOffset, NULL, FILE_BEGIN); // may contain padding byte(s) stack.pop(); // ascend to parent (FRM8) chunk break; } case DFFID_DST_: case DFFID_DSTI: case DFFID_MANF: default: return false; } return true; } bool CDFFFile::readPROP(ChunkStep& step, DFFChunkHeader& hdr) { switch (hdr.ckID) { case DFFID_PROP: { frm8.prop.header = hdr; frm8.prop.offsetToData = step.dataOffset; Read(&frm8.prop.data, sizeof frm8.prop.data, NULL); frm8.prop.setupData(); // descend to subchunks break; } case DFFID_FS__: frm8.prop.fs.header = hdr; frm8.prop.fs.offsetToData = step.dataOffset; Read(&frm8.prop.fs.data, sizeof frm8.prop.fs.data, NULL); frm8.prop.fs.setupData(); stack.pop(); // ascend to parent (PROP) chunk break; case DFFID_CHNL: frm8.prop.chnl.header = hdr; frm8.prop.chnl.offsetToData = step.dataOffset; Read(&frm8.prop.chnl.data, sizeof frm8.prop.chnl.data, NULL); frm8.prop.chnl.setupData(); for (int i = 0; i < frm8.prop.chnl.data.numChannels; i++) { DFFID id; Read(&id, sizeof id, NULL); id = ntohl(id); frm8.prop.chnl.chID.push_back(id); } stack.pop(); // ascend to parent (PROP) chunk break; case DFFID_CMPR: frm8.prop.cmpr.header = hdr; frm8.prop.cmpr.offsetToData = step.dataOffset; Read(&frm8.prop.cmpr.data, sizeof frm8.prop.cmpr.data, NULL); frm8.prop.cmpr.setupData(); assignBuffer(frm8.prop.cmpr.data.count, frm8.prop.cmpr.compressionName); Seek(step.dataEndOffset, NULL, FILE_BEGIN); stack.pop(); // ascend to parent (PROP) chunk break; case DFFID_ABSS: frm8.prop.abss.header = hdr; frm8.prop.abss.offsetToData = step.dataOffset; Read(&frm8.prop.abss.data, sizeof frm8.prop.abss.data, NULL); frm8.prop.abss.setupData(); stack.pop(); // ascend to parent (PROP) chunk break; case DFFID_LSCO: frm8.prop.lsco.header = hdr; frm8.prop.lsco.offsetToData = step.dataOffset; Read(&frm8.prop.lsco.data, sizeof frm8.prop.lsco.data, NULL); frm8.prop.lsco.setupData(); stack.pop(); // ascend to parent (PROP) chunk break; default: return false; } return true; } bool CDFFFile::readDIIN(ChunkStep& step, DFFChunkHeader& hdr) { switch (hdr.ckID) { case DFFID_DIIN: { frm8.diin.header = hdr; frm8.diin.offsetToData = step.dataOffset; // descend to subchunks break; } case DFFID_DIAR: { frm8.diin.diar.header = hdr; frm8.diin.diar.offsetToData = step.dataOffset; Read(&frm8.diin.diar.data, sizeof frm8.diin.diar.data, NULL); frm8.diin.diar.setupData(); assignBuffer(frm8.diin.diar.data.count, frm8.diin.diar.artistText); Seek(step.dataEndOffset, NULL, FILE_BEGIN); // may contain padding byte stack.pop(); // ascend to parent (DIIN) chunk break; } case DFFID_DITI: { frm8.diin.diti.header = hdr; frm8.diin.diti.offsetToData = step.dataOffset; Read(&frm8.diin.diti.data, sizeof frm8.diin.diti.data, NULL); frm8.diin.diti.setupData(); assignBuffer(frm8.diin.diti.data.count, frm8.diin.diti.titleText); Seek(step.dataEndOffset, NULL, FILE_BEGIN); // may contain padding byte stack.pop(); // ascend to parent (DIIN) chunk break; } default: return false; } return true; } void CDFFFile::assignBuffer(uint32_t bytesToRead, std::string& target) { uint8_t* buf = new uint8_t[bytesToRead + 1]; buf[bytesToRead] = '\0'; Read(buf, bytesToRead, NULL); target.assign((const char*)buf); delete[] buf; }
23.405738
94
0.691823
xlm04322
2deb4e95e8c74884d97ba274b498690c42019070
18,196
cc
C++
src/xenia/ui/windowed_app_context_android.cc
amessier/xenia
6b45cf84472c26436d4a5db61a7b50dab301e398
[ "BSD-3-Clause" ]
1
2022-03-21T07:35:46.000Z
2022-03-21T07:35:46.000Z
src/xenia/ui/windowed_app_context_android.cc
amessier/xenia
6b45cf84472c26436d4a5db61a7b50dab301e398
[ "BSD-3-Clause" ]
null
null
null
src/xenia/ui/windowed_app_context_android.cc
amessier/xenia
6b45cf84472c26436d4a5db61a7b50dab301e398
[ "BSD-3-Clause" ]
null
null
null
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2022 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/ui/windowed_app_context_android.h" #include <android/asset_manager_jni.h> #include <android/configuration.h> #include <android/log.h> #include <android/looper.h> #include <android/native_window.h> #include <android/native_window_jni.h> #include <fcntl.h> #include <jni.h> #include <unistd.h> #include <array> #include <cstdint> #include "xenia/base/assert.h" #include "xenia/base/logging.h" #include "xenia/base/main_android.h" #include "xenia/ui/window_android.h" #include "xenia/ui/windowed_app.h" namespace xe { namespace ui { void AndroidWindowedAppContext::NotifyUILoopOfPendingFunctions() { // Don't check ui_thread_looper_callback_registered_, as it's owned // exclusively by the UI thread, while this may be called by any, and in case // of a pipe error, the callback will be invoked by the looper, which will // trigger all the necessary shutdown, and the pending functions will be // called anyway by the shutdown. UIThreadLooperCallbackCommand command = UIThreadLooperCallbackCommand::kExecutePendingFunctions; if (write(ui_thread_looper_callback_pipe_[1], &command, sizeof(command)) != sizeof(command)) { XELOGE( "AndroidWindowedAppContext: Failed to write a pending function " "execution command to the UI thread looper callback pipe"); return; } ALooper_wake(ui_thread_looper_); } void AndroidWindowedAppContext::PlatformQuitFromUIThread() { // All the shutdown will be done in onDestroy of the activity. if (activity_ && activity_method_finish_) { ui_thread_jni_env_->CallVoidMethod(activity_, activity_method_finish_); } } void AndroidWindowedAppContext::PostInvalidateWindowSurface() { // May be called from non-UI threads. JNIEnv* jni_env = GetAndroidThreadJniEnv(); if (!jni_env) { return; } jni_env->CallVoidMethod(activity_, activity_method_post_invalidate_window_surface_); } AndroidWindowedAppContext* AndroidWindowedAppContext::JniActivityInitializeWindowedAppOnCreate( JNIEnv* jni_env, jobject activity, jstring windowed_app_identifier, jobject asset_manager) { WindowedApp::Creator app_creator; { const char* windowed_app_identifier_c_str = jni_env->GetStringUTFChars(windowed_app_identifier, nullptr); if (!windowed_app_identifier_c_str) { __android_log_write( ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to get the UTF-8 string for the windowed app identifier"); return nullptr; } app_creator = WindowedApp::GetCreator(windowed_app_identifier_c_str); if (!app_creator) { __android_log_print(ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to get the creator for the windowed app %s", windowed_app_identifier_c_str); jni_env->ReleaseStringUTFChars(windowed_app_identifier, windowed_app_identifier_c_str); return nullptr; } jni_env->ReleaseStringUTFChars(windowed_app_identifier, windowed_app_identifier_c_str); } AndroidWindowedAppContext* app_context = new AndroidWindowedAppContext; if (!app_context->Initialize(jni_env, activity, asset_manager)) { delete app_context; return nullptr; } if (!app_context->InitializeApp(app_creator)) { // InitializeApp might have sent commands to the UI thread looper callback // pipe, perform deferred destruction. app_context->RequestDestruction(); return nullptr; } return app_context; } void AndroidWindowedAppContext::JniActivityOnDestroy() { if (app_) { app_->InvokeOnDestroy(); app_.reset(); } // Expecting that the destruction of the app will destroy the window as well, // no need to notify it explicitly. assert_null(activity_window_); RequestDestruction(); } void AndroidWindowedAppContext::JniActivityOnWindowSurfaceLayoutChange( jint left, jint top, jint right, jint bottom) { window_surface_layout_left_ = left; window_surface_layout_top_ = top; window_surface_layout_right_ = right; window_surface_layout_bottom_ = bottom; if (activity_window_) { activity_window_->OnActivitySurfaceLayoutChange(); } } void AndroidWindowedAppContext::JniActivityOnWindowSurfaceChanged( jobject window_surface_object) { // Detach from the old surface. if (window_surface_) { ANativeWindow* old_window_surface = window_surface_; window_surface_ = nullptr; if (activity_window_) { activity_window_->OnActivitySurfaceChanged(); } ANativeWindow_release(old_window_surface); } if (!window_surface_object) { return; } window_surface_ = ANativeWindow_fromSurface(ui_thread_jni_env_, window_surface_object); if (!window_surface_) { return; } if (activity_window_) { activity_window_->OnActivitySurfaceChanged(); } } void AndroidWindowedAppContext::JniActivityPaintWindow(bool force_paint) { if (!activity_window_) { return; } activity_window_->PaintActivitySurface(force_paint); } AndroidWindowedAppContext::~AndroidWindowedAppContext() { Shutdown(); } bool AndroidWindowedAppContext::Initialize(JNIEnv* ui_thread_jni_env, jobject activity, jobject asset_manager) { // Xenia logging is not initialized yet - use __android_log_write or // __android_log_print until InitializeAndroidAppFromMainThread is done. ui_thread_jni_env_ = ui_thread_jni_env; // Initialize the asset manager for retrieving the current configuration. asset_manager_jobject_ = ui_thread_jni_env_->NewGlobalRef(asset_manager); if (!asset_manager_jobject_) { __android_log_write( ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to create a global reference to the asset manager"); Shutdown(); return false; } asset_manager_ = AAssetManager_fromJava(ui_thread_jni_env_, asset_manager_jobject_); if (!asset_manager_) { __android_log_write(ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to create get the AAssetManager"); Shutdown(); return false; } // Get the initial configuration. configuration_ = AConfiguration_new(); if (!configuration_) { __android_log_write(ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to create an AConfiguration"); Shutdown(); return false; } AConfiguration_fromAssetManager(configuration_, asset_manager_); // Get the activity class, needed for the application context here, and for // other activity interaction later. { jclass activity_class_local_ref = ui_thread_jni_env_->GetObjectClass(activity); if (!activity_class_local_ref) { __android_log_write(ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to get the activity class"); Shutdown(); return false; } activity_class_ = reinterpret_cast<jclass>(ui_thread_jni_env_->NewGlobalRef( reinterpret_cast<jobject>(activity_class_local_ref))); ui_thread_jni_env_->DeleteLocalRef( reinterpret_cast<jobject>(activity_class_local_ref)); } if (!activity_class_) { __android_log_write( ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to create a global reference to the activity class"); Shutdown(); return false; } // Get the application context. jmethodID activity_get_application_context = ui_thread_jni_env_->GetMethodID( activity_class_, "getApplicationContext", "()Landroid/content/Context;"); if (!activity_get_application_context) { __android_log_write( ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to get the getApplicationContext method of the activity"); Shutdown(); return false; } jobject application_context_init_ref = ui_thread_jni_env_->CallObjectMethod( activity, activity_get_application_context); if (!application_context_init_ref) { __android_log_write( ANDROID_LOG_ERROR, "AndroidWindowedAppContext", "Failed to get the application context from the activity"); Shutdown(); return false; } // Initialize Xenia globals that may depend on the base globals and logging. xe::InitializeAndroidAppFromMainThread( AConfiguration_getSdkVersion(configuration_), ui_thread_jni_env_, application_context_init_ref); android_base_initialized_ = true; ui_thread_jni_env_->DeleteLocalRef(application_context_init_ref); // Initialize interfacing with the WindowedAppActivity. activity_ = ui_thread_jni_env_->NewGlobalRef(activity); if (!activity_) { XELOGE( "AndroidWindowedAppContext: Failed to create a global reference to the " "activity"); Shutdown(); return false; } bool activity_ids_obtained = true; activity_ids_obtained &= (activity_method_finish_ = ui_thread_jni_env_->GetMethodID( activity_class_, "finish", "()V")) != nullptr; activity_ids_obtained &= (activity_method_post_invalidate_window_surface_ = ui_thread_jni_env_->GetMethodID( activity_class_, "postInvalidateWindowSurface", "()V")) != nullptr; if (!activity_ids_obtained) { XELOGE("AndroidWindowedAppContext: Failed to get the activity class IDs"); Shutdown(); return false; } // Initialize sending commands to the UI thread looper callback, for // requesting function calls in the UI thread. ui_thread_looper_ = ALooper_forThread(); // The context may be created only in the UI thread, which must have an // internal looper. assert_not_null(ui_thread_looper_); if (!ui_thread_looper_) { XELOGE("AndroidWindowedAppContext: Failed to get the UI thread looper"); Shutdown(); return false; } // The looper can be woken up by other threads, so acquiring it. Shutdown // assumes that if ui_thread_looper_ is not null, it has been acquired. ALooper_acquire(ui_thread_looper_); if (pipe(ui_thread_looper_callback_pipe_.data())) { XELOGE( "AndroidWindowedAppContext: Failed to create the UI thread looper " "callback pipe"); Shutdown(); return false; } if (ALooper_addFd(ui_thread_looper_, ui_thread_looper_callback_pipe_[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, UIThreadLooperCallback, this) != 1) { XELOGE( "AndroidWindowedAppContext: Failed to add the callback to the UI " "thread looper"); Shutdown(); return false; } ui_thread_looper_callback_registered_ = true; return true; } void AndroidWindowedAppContext::Shutdown() { if (app_) { app_->InvokeOnDestroy(); app_.reset(); } // The app should destroy the window, but make sure everything is cleaned up // anyway. assert_null(activity_window_); activity_window_ = nullptr; if (ui_thread_looper_callback_registered_) { ALooper_removeFd(ui_thread_looper_, ui_thread_looper_callback_pipe_[0]); ui_thread_looper_callback_registered_ = false; } for (int& pipe_fd : ui_thread_looper_callback_pipe_) { if (pipe_fd == -1) { continue; } close(pipe_fd); pipe_fd = -1; } if (ui_thread_looper_) { ALooper_release(ui_thread_looper_); ui_thread_looper_ = nullptr; } activity_method_finish_ = nullptr; if (activity_) { ui_thread_jni_env_->DeleteGlobalRef(activity_); activity_ = nullptr; } if (android_base_initialized_) { xe::ShutdownAndroidAppFromMainThread(); android_base_initialized_ = false; } if (activity_class_) { ui_thread_jni_env_->DeleteGlobalRef( reinterpret_cast<jobject>(activity_class_)); activity_class_ = nullptr; } if (configuration_) { AConfiguration_delete(configuration_); configuration_ = nullptr; } asset_manager_ = nullptr; if (asset_manager_jobject_) { ui_thread_jni_env_->DeleteGlobalRef(asset_manager_jobject_); asset_manager_jobject_ = nullptr; } ui_thread_jni_env_ = nullptr; } void AndroidWindowedAppContext::RequestDestruction() { // According to ALooper_removeFd documentation: // "...it is possible for the callback to already be running or for it to run // one last time if the file descriptor was already signalled. Calling code // is responsible for ensuring that this case is safely handled. For example, // if the callback takes care of removing itself during its own execution // either by returning 0 or by calling this method..." // If the looper callback is registered, the pipe may have pending commands, // and thus the callback may still be called with the pointer to the context // as the user data. if (!ui_thread_looper_callback_registered_) { delete this; return; } UIThreadLooperCallbackCommand command = UIThreadLooperCallbackCommand::kDestroy; if (write(ui_thread_looper_callback_pipe_[1], &command, sizeof(command)) != sizeof(command)) { XELOGE( "AndroidWindowedAppContext: Failed to write a destruction command to " "the UI thread looper callback pipe"); delete this; return; } ALooper_wake(ui_thread_looper_); } int AndroidWindowedAppContext::UIThreadLooperCallback(int fd, int events, void* data) { // In case of errors, destruction of the pipe (most importantly the write end) // must not be done here immediately as other threads, which may still be // sending commands, would not be aware of that. auto app_context = static_cast<AndroidWindowedAppContext*>(data); if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP | ALOOPER_EVENT_INVALID)) { // Will return 0 to unregister self, this file descriptor is not usable // anymore, so let everything potentially referencing it in QuitFromUIThread // know. app_context->ui_thread_looper_callback_registered_ = false; XELOGE( "AndroidWindowedAppContext: The UI thread looper callback pipe file " "descriptor has encountered an error condition during polling"); app_context->QuitFromUIThread(); return 0; } if (!(events & ALOOPER_EVENT_INPUT)) { // Spurious callback call. Need a non-empty pipe. return 1; } // Process one command with a blocking `read`. The callback will be invoked // again and again if there is still data after this read. UIThreadLooperCallbackCommand command; switch (read(fd, &command, sizeof(command))) { case sizeof(command): break; case -1: // Will return 0 to unregister self, this file descriptor is not usable // anymore, so let everything potentially referencing it in // QuitFromUIThread know. app_context->ui_thread_looper_callback_registered_ = false; XELOGE( "AndroidWindowedAppContext: The UI thread looper callback pipe file " "descriptor has encountered an error condition during reading"); app_context->QuitFromUIThread(); return 0; default: // Something like incomplete data - shouldn't be happening, but not a // reported error. return 1; } switch (command) { case UIThreadLooperCallbackCommand::kDestroy: // Final destruction requested. Will unregister self by returning 0, so // set ui_thread_looper_callback_registered_ to false so Shutdown won't // try to unregister it too. app_context->ui_thread_looper_callback_registered_ = false; delete app_context; return 0; case UIThreadLooperCallbackCommand::kExecutePendingFunctions: app_context->ExecutePendingFunctionsFromUIThread(); break; } return 1; } bool AndroidWindowedAppContext::InitializeApp(std::unique_ptr<WindowedApp> ( *app_creator)(WindowedAppContext& app_context)) { assert_null(app_); app_ = app_creator(*this); if (!app_->OnInitialize()) { app_->InvokeOnDestroy(); app_.reset(); return false; } return true; } } // namespace ui } // namespace xe extern "C" { JNIEXPORT jlong JNICALL Java_jp_xenia_emulator_WindowedAppActivity_initializeWindowedAppOnCreate( JNIEnv* jni_env, jobject activity, jstring windowed_app_identifier, jobject asset_manager) { return reinterpret_cast<jlong>( xe::ui::AndroidWindowedAppContext :: JniActivityInitializeWindowedAppOnCreate( jni_env, activity, windowed_app_identifier, asset_manager)); } JNIEXPORT void JNICALL Java_jp_xenia_emulator_WindowedAppActivity_onDestroyNative( JNIEnv* jni_env, jobject activity, jlong app_context_ptr) { reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr) ->JniActivityOnDestroy(); } JNIEXPORT void JNICALL Java_jp_xenia_emulator_WindowedAppActivity_onWindowSurfaceLayoutChange( JNIEnv* jni_env, jobject activity, jlong app_context_ptr, jint left, jint top, jint right, jint bottom) { reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr) ->JniActivityOnWindowSurfaceLayoutChange(left, top, right, bottom); } JNIEXPORT void JNICALL Java_jp_xenia_emulator_WindowedAppActivity_onWindowSurfaceChanged( JNIEnv* jni_env, jobject activity, jlong app_context_ptr, jobject window_surface_object) { reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr) ->JniActivityOnWindowSurfaceChanged(window_surface_object); } JNIEXPORT void JNICALL Java_jp_xenia_emulator_WindowedAppActivity_paintWindow( JNIEnv* jni_env, jobject activity, jlong app_context_ptr, jboolean force_paint) { reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr) ->JniActivityPaintWindow(bool(force_paint)); } } // extern "C"
35.469786
80
0.713673
amessier
2dedad29c413841e2cfa8e4592f1c5207d64efa4
422
cpp
C++
basic_datastructure/binary_heap/heapSort.cpp
weekieACpper/DataStructre-weekie
9f15d95dd57c02d7d385b151940bbee4f3c2d99b
[ "MIT" ]
null
null
null
basic_datastructure/binary_heap/heapSort.cpp
weekieACpper/DataStructre-weekie
9f15d95dd57c02d7d385b151940bbee4f3c2d99b
[ "MIT" ]
null
null
null
basic_datastructure/binary_heap/heapSort.cpp
weekieACpper/DataStructre-weekie
9f15d95dd57c02d7d385b151940bbee4f3c2d99b
[ "MIT" ]
null
null
null
/* * @Author: weekie * @Date: 2022-03-04 21:02:16 * @LastEditTime: 2022-03-04 21:05:33 * @LastEditors: Please set LastEditors * @Description: 实现堆排序 * @FilePath: /datastructure/basic_datastructre/binary_heap/heapSort.cpp */ #include<maxHeap.hpp> //堆排序 void heapSort(int* array, int size) { maxHeap heap(array, size);//建堆 for (int i = size - 1; i >= 0; i--) { array[i] = heap.extractMax(); } }
23.444444
72
0.635071
weekieACpper
2dee7b31ab8c7e91333b5fb86e1ce4d941b2bb5e
323
cpp
C++
artifact/storm/src/storm/solver/stateelimination/StatePriorityQueue.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/solver/stateelimination/StatePriorityQueue.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/solver/stateelimination/StatePriorityQueue.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/solver/stateelimination/StatePriorityQueue.h" namespace storm { namespace solver { namespace stateelimination { void StatePriorityQueue::update(storm::storage::sparse::state_type) { // Intentionally left empty. } } } }
23.071429
81
0.572755
glatteis
2def344c3e3fa1c905bc0f8f37b53328c24bae73
1,248
hpp
C++
Pods/Headers/Private/GeoFeatures/Internal/geofeatures/Geometry.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Private/GeoFeatures/Internal/geofeatures/Geometry.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Private/GeoFeatures/Internal/geofeatures/Geometry.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
/** * Geometry.hpp * * Copyright 2015 The Climate Corporation * Copyright 2015 Tony Stone * * 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. * * Created by Tony Stone on 6/9/15. * * MODIFIED 2015 BY Tony Stone. Modifications licensed under Apache License, Version 2.0. * */ #pragma once #ifndef __Geometry_HPP_ #define __Geometry_HPP_ namespace geofeatures { /** * @class Geometry * * @brief Base abstract type for all Geometric types. * * @author Tony Stone * @date 6/10/15 */ class Geometry { public: inline Geometry() noexcept {} inline virtual ~Geometry() noexcept {}; }; } // namespace geofeatures #endif //__Geometry_HPP_
24.96
90
0.671474
xarvey
2defd0758e952e32156596da699a0ad6aafae47e
6,081
cpp
C++
media_driver/media_driver_next/agnostic/gen12/codec/hal/dec/av1/pipeline/decode_filmgrain_presubpipeline_g12.cpp
saosipov/media-driver
e280504bb3ccc429aa43f30aa76e0c990df6ccbf
[ "MIT", "Intel", "BSD-3-Clause" ]
null
null
null
media_driver/media_driver_next/agnostic/gen12/codec/hal/dec/av1/pipeline/decode_filmgrain_presubpipeline_g12.cpp
saosipov/media-driver
e280504bb3ccc429aa43f30aa76e0c990df6ccbf
[ "MIT", "Intel", "BSD-3-Clause" ]
null
null
null
media_driver/media_driver_next/agnostic/gen12/codec/hal/dec/av1/pipeline/decode_filmgrain_presubpipeline_g12.cpp
saosipov/media-driver
e280504bb3ccc429aa43f30aa76e0c990df6ccbf
[ "MIT", "Intel", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice 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. */ //! //! \file decode_filmgrain_presubpipeline_g12.cpp //! \brief Defines the preSubpipeline for film grain generate noise //! \details Defines the preSubpipeline for film grain generate noise, including getRandomValues, regressPhase1, regressPhase2 kernels. //! #include "decode_filmgrain_presubpipeline_g12.h" #include "decode_basic_feature.h" #include "decode_pipeline.h" #include "decode_av1_filmgrain_feature_g12.h" #include "decode_av1_feature_defs_g12.h" namespace decode { FilmGrainPreSubPipeline::FilmGrainPreSubPipeline(DecodePipeline *pipeline, MediaTask *task, uint8_t numVdbox) : DecodeSubPipeline(pipeline, task, numVdbox) {} MOS_STATUS FilmGrainPreSubPipeline::Init(CodechalSetting &settings) { DECODE_CHK_NULL(m_pipeline); CodechalHwInterface* hwInterface = m_pipeline->GetHwInterface(); DECODE_CHK_NULL(hwInterface); PMOS_INTERFACE osInterface = hwInterface->GetOsInterface(); DECODE_CHK_NULL(osInterface); InitScalabilityPars(osInterface); m_allocator = m_pipeline->GetDecodeAllocator(); DECODE_CHK_NULL(m_allocator); MediaFeatureManager* featureManager = m_pipeline->GetFeatureManager(); DECODE_CHK_NULL(featureManager); m_basicFeature = dynamic_cast<DecodeBasicFeature*>(featureManager->GetFeature(FeatureIDs::basicFeature)); DECODE_CHK_NULL(m_basicFeature); m_filmGrainFeature = dynamic_cast<Av1DecodeFilmGrainG12 *>(featureManager->GetFeature(Av1FeatureIDs::av1SwFilmGrain)); DECODE_CHK_NULL(m_filmGrainFeature); //Create Packets m_filmGrainGrvPkt = MOS_New(FilmGrainGrvPacket, m_pipeline, m_task, hwInterface); Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline); DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(pipeline, av1FilmGrainGrvPacketId), *m_filmGrainGrvPkt)); DECODE_CHK_STATUS(m_filmGrainGrvPkt->Init()); m_filmGrainRp1Pkt = MOS_New(FilmGrainRp1Packet, m_pipeline, m_task, hwInterface); DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(pipeline, av1FilmGrainRp1PacketId), *m_filmGrainRp1Pkt)); DECODE_CHK_STATUS(m_filmGrainRp1Pkt->Init()); m_filmGrainRp2Pkt = MOS_New(FilmGrainRp2Packet, m_pipeline, m_task, hwInterface); DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(pipeline, av1FilmGrainRp2PacketId), *m_filmGrainRp2Pkt)); DECODE_CHK_STATUS(m_filmGrainRp2Pkt->Init()); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainPreSubPipeline::Prepare(DecodePipelineParams &params) { if (params.m_pipeMode == decodePipeModeBegin) { DECODE_CHK_STATUS(Begin()); } else if (params.m_pipeMode == decodePipeModeProcess) { DECODE_CHK_NULL(params.m_params); CodechalDecodeParams *decodeParams = params.m_params; DECODE_CHK_STATUS(DoFilmGrainGenerateNoise(*decodeParams)); } return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainPreSubPipeline::Begin() { DECODE_CHK_STATUS(DecodeSubPipeline::Reset()); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainPreSubPipeline::DoFilmGrainGenerateNoise(const CodechalDecodeParams &decodeParams) { if (m_filmGrainFeature->m_filmGrainEnabled) { //Step1: Get Random Values DECODE_CHK_STATUS(GetRandomValuesKernel(decodeParams)); //Step2: regressPhase1 DECODE_CHK_STATUS(RegressPhase1Kernel(decodeParams)); //Step3: regressPhase2 DECODE_CHK_STATUS(RegressPhase2Kernel(decodeParams)); } return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainPreSubPipeline::GetRandomValuesKernel(const CodechalDecodeParams &decodeParams) { Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline); DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(pipeline, av1FilmGrainGrvPacketId), true, 0, 0)); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainPreSubPipeline::RegressPhase1Kernel(const CodechalDecodeParams &decodeParams) { Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline); DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(pipeline, av1FilmGrainRp1PacketId), true, 0, 0)); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainPreSubPipeline::RegressPhase2Kernel(const CodechalDecodeParams &decodeParams) { Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline); DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(pipeline, av1FilmGrainRp2PacketId), true, 0, 0)); return MOS_STATUS_SUCCESS; } MediaFunction FilmGrainPreSubPipeline::GetMediaFunction() { if(!MEDIA_IS_SKU(m_pipeline->GetSkuTable(), FtrCCSNode)) { return RenderGenericFunc; } return ComputeVppFunc; } void FilmGrainPreSubPipeline::InitScalabilityPars(PMOS_INTERFACE osInterface) { MOS_ZeroMemory(&m_decodeScalabilityPars, sizeof(ScalabilityPars)); m_decodeScalabilityPars.disableScalability = true; m_decodeScalabilityPars.disableRealTile = true; m_decodeScalabilityPars.enableVE = MOS_VE_SUPPORTED(osInterface); m_decodeScalabilityPars.numVdbox = m_numVdbox; } }
37.537037
136
0.781286
saosipov
2df007d43bd64a839027f78c56d8a469f325895a
3,828
tpp
C++
breeze/encoding/brz/base64_to_binary.tpp
gennaroprota/breeze
7afe88a30dc8ac8b97a76a192dc9b189d9752e8b
[ "BSD-3-Clause" ]
1
2021-04-03T22:35:52.000Z
2021-04-03T22:35:52.000Z
breeze/encoding/brz/base64_to_binary.tpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
null
null
null
breeze/encoding/brz/base64_to_binary.tpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-10-01T04:26:48.000Z
2021-10-01T04:26:48.000Z
// =========================================================================== // Copyright 2016 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breeze/counting/signed_count.hpp" #include <climits> #include <stdexcept> #include <type_traits> namespace breeze_ns { template< typename InputIter, typename OutputIter > void base64_to_binary( InputIter begin, InputIter end, OutputIter out ) { // Table generated by 'generate_inverse_base64_table': see the // extra/ subdirectory. // ----------------------------------------------------------------------- static int const table[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } ; static_assert( UCHAR_MAX == ( signed_count( table ) - 1 ) && ( std::is_same< typename InputIter::value_type, char >::value || std::is_same< typename InputIter::value_type, unsigned char >::value ) ) ; static char const error_message[] = "invalid input to base64_to_binary()" ; int const not_to_be_translated = -1 ; int const block_length = 6 ; int const char_bit = CHAR_BIT ; unsigned block = 0 ; int num_bits = 0 ; bool equals_seen = false ; for ( InputIter curr( begin ) ; curr != end ; ++ curr ) { auto const x = static_cast< unsigned char >( *curr ) ; int const value = table[ x ] ; // Once we've seen an equal sign, only equal signs or // newlines can follow; otherwise the input is ill-formed. // ------------------------------------------------------------------- if ( x == '=' ) { equals_seen = true ; } if ( x != '=' && x != '\n' && equals_seen ) { throw std::runtime_error( error_message ) ; } if ( value == not_to_be_translated ) { if ( x != '\n' && x != '=' ) { throw std::runtime_error( error_message ) ; } } else { block = ( block << block_length ) | value ; num_bits += block_length ; if ( num_bits >= char_bit ) { num_bits -= char_bit ; *out = static_cast< unsigned char >( block >> num_bits ) ; ++ out ; block &= ( ( 1 << num_bits ) - 1 ) ; } } } } } // Local Variables: // mode: c++ // End: // vim: set ft=cpp:
42.065934
81
0.421369
gennaroprota
2df021c5be5a9a6256429e5fd634c66eb398cff0
3,066
cpp
C++
Tools/Src/SFToolLib/Content/Pipeline/SFMeshComponent.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
Tools/Src/SFToolLib/Content/Pipeline/SFMeshComponent.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
Tools/Src/SFToolLib/Content/Pipeline/SFMeshComponent.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "UMMeshComponent.h" #include "UMNodeContent.h" #include "UMVertexBufferContent.h" UMMeshComponent::UMMeshComponent( UMNodeContent& owner ) :UMNodeContentComponent(owner) ,m_pVertexBuffer(nullptr) ,m_pRootBone(nullptr) { if( m_pVertexBuffer == nullptr ) m_pVertexBuffer = new UMVertexBufferContent; } UMMeshComponent::~UMMeshComponent() { if( m_pRootBone != nullptr ) delete m_pRootBone; delete m_pVertexBuffer; } // Initialize components after load/create bool UMMeshComponent::InitializeComponent() { return true; } // Get vertex buffer UMVertexBufferContent *UMMeshComponent::GetVertexBuffer() { return m_pVertexBuffer; } void UMMeshComponent::TransfoSF( const UMTransfoSFMatrix& transfoSF ) { if( m_pVertexBuffer == nullptr || m_pVertexBuffer->GetNumberOfVertex() == 0 ) return; auto positionChannel = m_pVertexBuffer->GetVertexChannel( UMVertexBufferContent::StreamChannelType::POSITION ); if( positionChannel != nullptr ) { auto positions = positionChannel->GetArrayData<float>(); for( UINT iVert = 0 ; iVert < m_pVertexBuffer->GetNumberOfVertex(); iVert++ ) { auto pCur = &positions[iVert*positionChannel->NumElement + 0]; UMVector4 pos( pCur[0], pCur[1], pCur[2] ); pos = transfoSF.MultT( pos ); pCur[0] = (float)pos[0]; pCur[1] = (float)pos[1]; pCur[2] = (float)pos[2]; } } auto noSFalChannel = m_pVertexBuffer->GetVertexChannel( UMVertexBufferContent::StreamChannelType::NOSFAL ); if( noSFalChannel != nullptr ) { UMTransfoSFMatrix noSFalTransfoSF = transfoSF; noSFalTransfoSF.SetTOnly(UMVector4(0,0,0)); auto noSFals = noSFalChannel->GetArrayData<float>(); for( UINT iVert = 0 ; iVert < m_pVertexBuffer->GetNumberOfVertex(); iVert++ ) { auto pCur = &noSFals[iVert*noSFalChannel->NumElement + 0]; UMVector4 pos( pCur[0], pCur[1], pCur[2] ); pos = noSFalTransfoSF.MultT( pos ); pos.NoSFalize(); pCur[0] = (float)pos[0]; pCur[1] = (float)pos[1]; pCur[2] = (float)pos[2]; } } } // Copy Submesh array void UMMeshComponent::SetSubMeshes( const UMArray<SubMesh*>& subMeshes ) { std::for_each(m_SubMeshes.begin(), m_SubMeshes.end(), [](SubMesh*pSubMesh) { delete pSubMesh; }); m_SubMeshes.clear(); m_SubMeshes = subMeshes; } void UMMeshComponent::ForeachSubMeshes( std::function<void(SubMesh*)> action ) { std::for_each(m_SubMeshes.begin(), m_SubMeshes.end(), action); } UINT UMMeshComponent::AddBone( UMNodeContent* pBone, const UMTransfoSFMatrix& bindPose ) { int index = FindBone(pBone); if( index >= 0 ) return index; BoneNode boneNode; boneNode.BindPose = bindPose; boneNode.pBone = pBone; m_SkinBones.push_back(boneNode); return m_SkinBones.size() -1; } int UMMeshComponent::FindBone( UMNodeContent* pBone ) { for(int index = 0; index < (int)m_SkinBones.size(); index++ ) { if( m_SkinBones[index].pBone == pBone ) return index; } return -1; } void UMMeshComponent::ForeachBones( std::function<void(const BoneNode&)> action ) { std::for_each(m_SkinBones.begin(), m_SkinBones.end(), action); }
23.40458
112
0.71559
blue3k
2df69628b3445d5ba6387fbbd0daa3a06e8d08f5
2,340
cpp
C++
files/source/objectmask.cpp
Luminyx1/NewerSMBU
66c719b0afab0c5db5e26b8114d3fc02c15c7300
[ "MIT" ]
null
null
null
files/source/objectmask.cpp
Luminyx1/NewerSMBU
66c719b0afab0c5db5e26b8114d3fc02c15c7300
[ "MIT" ]
null
null
null
files/source/objectmask.cpp
Luminyx1/NewerSMBU
66c719b0afab0c5db5e26b8114d3fc02c15c7300
[ "MIT" ]
null
null
null
#include "game.h" #include "neweru.h" #include "groundmask.h" //Replaces sprite 358 class ObjectMask : public StageActor { public: agl::TextureData texdata; int onCreate(); int onExecute(); int onDraw(); void addMask(Vec3 *pos, float radius); ObjectMask(ActorBuildInfo *); static Actor *build(ActorBuildInfo *); }; ObjectMask::ObjectMask(ActorBuildInfo *buildInfo) : StageActor(buildInfo) {} Actor *ObjectMask::build(ActorBuildInfo *buildInfo) { return new ObjectMask(buildInfo); } const ActorInfo actorInfo = {0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0}; const Profile profile(ObjectMask::build, SCAFFOLD_WITH_BOLT, "ObjectMask", &actorInfo, 0); const ActorFiles actorFiles(SCAFFOLD_WITH_BOLT, 0, 0); int ObjectMask::onCreate() { MaskTexData::loadTexture(MaskTexture::cave, &texdata); onExecute(); return 1; } int ObjectMask::onExecute() { StageActor *player = PlayerMgr::instance->players[0]; position = player->position; return 1; } struct ActorMask { Actors actor; float radius; }; ActorMask actorMasks[] = { GOOMBA, 16, PARAGOOMBA, 16, KOOPA_TROOPA, 16, KOOPA_PARATROOPA, 16, BUZZY_BEETLE, 16, SPIKE_TOP, 16, SPINY, 16, QSWITCH, 16, PSWITCH, 16, BUBBLE_BABY_YOSHI, 24, BALLOON_BABY_YOSHI, 24, GLOW_BABY_YOSHI, 24, MUSHROOM, 16, FIRE_FLOWER, 16, ICE_FLOWER, 16, PROPELLER_MUSHROOM, 16, PENGUIN_MUSHROOM, 16, ACORN_MUSHROOM, 16, MINI_MUSHROOM, 16, LIFE_MUSHROOM, 16, LIFE_MOON, 16, PLAYER_ICEBALL, 12, PLAYER_FIREBALL, 12 }; int ObjectMask::onDraw() { addMask(&position, 48); Actor **current = ActorMgr::instance->actorList.first; while (current < ActorMgr::instance->actorList.last) { Actor *actor = *current; if (actor) { Actors profileId = actor->getProfileId(); for (u32 i = 0; i < 14; i++) { if (actorMasks[i].actor == profileId) { addMask(&((StageActor *)actor)->position, actorMasks[i].radius); break; } } } current++; } return 1; } void ObjectMask::addMask(Vec3 *pos, float radius) { MaskInfo tl = {{pos->X - radius, pos->Y - radius}, 1, {0, 0}}; MaskInfo tr = {{pos->X + radius, pos->Y - radius}, 1, {1, 0}}; MaskInfo br = {{pos->X + radius, pos->Y + radius}, 1, {1, 1}}; MaskInfo bl = {{pos->X - radius, pos->Y + radius}, 1, {0, 1}}; ((NewerBgRenderer *)BgRenderer::instance)->revealMasks.add(&tl, &tr, &br, &bl, &texdata, 3); }
22.941176
93
0.676068
Luminyx1