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
099c20b0ac4b3d8a3d6fd335447416cd08402e26
385
cpp
C++
src/shaderbuffer.cpp
bridgekat/vxrt
f02b421fb646cf7dbc6d60b908296cf8799edbf0
[ "BSD-3-Clause" ]
11
2018-08-07T14:29:31.000Z
2021-01-16T13:24:42.000Z
src/shaderbuffer.cpp
qiaozhanrong/vxrt
f02b421fb646cf7dbc6d60b908296cf8799edbf0
[ "BSD-3-Clause" ]
null
null
null
src/shaderbuffer.cpp
qiaozhanrong/vxrt
f02b421fb646cf7dbc6d60b908296cf8799edbf0
[ "BSD-3-Clause" ]
null
null
null
#include "shaderbuffer.h" ShaderBuffer::ShaderBuffer(const ShaderProgram& program, const std::string& name, GLuint binding) { glGenBuffers(1, &mHandle); GLuint index = glGetProgramResourceIndex(program.handle(), GL_SHADER_STORAGE_BLOCK, name.c_str()); glShaderStorageBlockBinding(program.handle(), index, binding); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, binding, mHandle); }
38.5
99
0.797403
bridgekat
09a3d21a6a6d61b41b5903046e3ed72267aabea1
1,077
cpp
C++
D2DSharp/D2DWrapper/FontFamily.cpp
dmitrykolchev/d2dsharp
5a9f3c39d62a92533c55f260726ef1966fbcf30f
[ "MIT" ]
29
2017-09-10T16:20:02.000Z
2022-03-05T13:26:24.000Z
D2DSharp/D2DWrapper/FontFamily.cpp
dmitrykolchev/d2dsharp
5a9f3c39d62a92533c55f260726ef1966fbcf30f
[ "MIT" ]
2
2019-05-19T06:42:19.000Z
2019-12-19T12:15:50.000Z
D2DSharp/D2DWrapper/FontFamily.cpp
dmitrykolchev/d2dsharp
5a9f3c39d62a92533c55f260726ef1966fbcf30f
[ "MIT" ]
9
2017-10-05T15:52:36.000Z
2022-03-05T13:26:28.000Z
/* * * Authors: * Dmitry Kolchev <dmitrykolchev@msn.com> * */ #include "Stdafx.h" using namespace Managed::Graphics::DirectWrite; LocalizedStrings^ FontFamily::FamilyNames::get() { IDWriteLocalizedStrings* names; ComUtils::CheckResult( GetNative<IDWriteFontFamily>()->GetFamilyNames( &names)); return gcnew LocalizedStrings(names); } Font^ FontFamily::GetFirstMatchingFont(FontWeight weight, FontStretch stretch, FontStyle style) { IDWriteFont* font; ComUtils::CheckResult( GetNative<IDWriteFontFamily>()->GetFirstMatchingFont( (DWRITE_FONT_WEIGHT)weight, (DWRITE_FONT_STRETCH)stretch, (DWRITE_FONT_STYLE)style, &font)); return gcnew Font(font); } FontList^ FontFamily::GetMatchingFonts(FontWeight weight, FontStretch stretch, FontStyle style) { IDWriteFontList* fonts; ComUtils::CheckResult( GetNative<IDWriteFontFamily>()->GetMatchingFonts( (DWRITE_FONT_WEIGHT)weight, (DWRITE_FONT_STRETCH)stretch, (DWRITE_FONT_STYLE)style, &fonts)); return gcnew FontList(fonts); }
21.54
96
0.722377
dmitrykolchev
09a7a0e7c88b34360290459b9986a6d5d8359199
1,776
cpp
C++
verify/verify-yuki/yuki-1303.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
verify/verify-yuki/yuki-1303.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
verify/verify-yuki/yuki-1303.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#define PROBLEM "https://yukicoder.me/problems/no/1303" #include "../../template/template.hpp" // #include "../../data-structure/union-find.hpp" #include "../../fps/ntt-friendly-fps.hpp" #include "../../matrix/matrix-tree.hpp" #include "../../matrix/polynomial-matrix-determinant.hpp" #include "../../modint/montgomery-modint.hpp" #include "../../modulo/binomial.hpp" using mint = LazyMontgomeryModInt<998244353>; using vm = vector<mint>; using vvm = vector<vm>; using fps = FormalPowerSeries<mint>; Binomial<mint> C; int a[111][111]; using namespace Nyaan; void Nyaan::solve() { ini(N, M); UnionFind uf(N); rep(i, M) { ini(u, v); --u, --v; a[u][v] = a[v][u] = 1; uf.unite(u, v); } using P = pair<mint, int>; vvi memo(N); rep(i, N) memo[uf.find(i)].push_back(i); V<P> v; rep(i, N) { if (uf.find(i) == i) { if (sz(memo[i]) == 1) { v.emplace_back(1, 1); continue; } MatrixTree<mint> m(sz(memo[i]) - 1); rep(j, sz(memo[i])) rep(k, j) { if (a[memo[i][j]][memo[i][k]]) m.add(j, k, 1); } v.emplace_back(m.calc(), sz(memo[i])); } } if (sz(v) == 1) { MatrixTree<fps> m(N - 1); rep(i, N) rep(j, i) { if (a[i][j]) m.add(i, j, fps{0, 1}); else m.add(i, j, fps{1}); } auto f = m.calc(); out(0); out(f[N - 1] + f[N - 2]); return; } sort(all(v), [](P a, P b) { return a.second > b.second; }); int n1 = v[0].second, n2 = v[1].second; ll h = -n1 * n2 * 2; mint ans = 1; each(p, v) ans *= p.first; mint sm = 0; rep(j, sz(v)) rep(i, j) { h += v[i].second * v[j].second * 2; if (v[i].second == n1 and v[j].second == n2) { sm += v[i].second * v[j].second; } } out(h); out(ans * sm); }
22.481013
61
0.51295
NachiaVivias
09ab8711d1f0b70018fb10d028dd507d30651b43
2,612
cpp
C++
A1131 Subway Map(30).cpp
Bourbon-Whiskey/PAT-A
40915d7c36077ad8fa4cbfdfe06f6cb50f152813
[ "MIT" ]
8
2019-02-13T02:00:19.000Z
2022-03-22T09:31:22.000Z
A1131 Subway Map(30).cpp
Bourbon-Whiskey/PAT-A
40915d7c36077ad8fa4cbfdfe06f6cb50f152813
[ "MIT" ]
null
null
null
A1131 Subway Map(30).cpp
Bourbon-Whiskey/PAT-A
40915d7c36077ad8fa4cbfdfe06f6cb50f152813
[ "MIT" ]
null
null
null
#include<cstdio> #include<vector> using namespace std; #define maxn 10010 struct Way{ int des; int line; }; vector<Way> G[maxn];//地铁图 int vis[maxn]; int inq[15][maxn];//是否入队 vector<Way> temp,trace; int Change; int depth,st,End; int N,M,K; void Init(){ int i,a,b; Way tmp; scanf("%d",&N); for(i=1;i<=N;i++){ scanf("%d",&M); M--; scanf("%d",&a); while(M--){ scanf("%d",&b); tmp.line=i; tmp.des=b; G[a].push_back(tmp); tmp.des=a; G[b].push_back(tmp); a=b; } } scanf("%d",&K); } int BFS(int i){ int Queue[2*maxn]; int front=0,rear=0; int now,level=0; int j; Queue[rear++]=st; inq[i][st]=1; Queue[rear++]=-1; while(rear>front){ now=Queue[front++]; if(now==-1){ level++; Queue[rear++]=-1; continue; } if(now==End){ break; } for(j=0;j<G[now].size();j++){ if(inq[i][G[now][j].des]==0){ inq[i][G[now][j].des]=1; Queue[rear++]=G[now][j].des; } } } return level; } void DFS(int now,int dep){ int i,c; vis[now]=1; if(dep==depth){ if(now==End){ c=0; for(i=1;i<temp.size();i++){ if(temp[i-1].line!=temp[i].line){ c++; } } if(c<Change){ Change=c; trace=temp; } vis[now]=0; return; }else{ vis[now]=0; return; } }else{ for(i=0;i<G[now].size();i++){ if(vis[G[now][i].des]==0){ temp[dep]=G[now][i]; DFS(G[now][i].des,dep+1); } } } vis[now]=0; } void Print(){ int begin=st,i=0; int cline=trace[0].line; while(1){ if(trace[i].des==End){ printf("Take Line#%d from %04d to %04d.\n",cline,begin,trace[i].des); break; } if(trace[i+1].line!=cline){ printf("Take Line#%d from %04d to %04d.\n",cline,begin,trace[i].des); cline=trace[i+1].line; begin=trace[i].des; } i++; } } void Op(int i){ scanf("%d%d",&st,&End); depth=BFS(i); printf("%d\n",depth); temp.clear(); temp.resize(depth); Change=maxn; DFS(st,0); Print(); } int main(){ int i; Init(); for(i=0;i<K;i++){ Op(i); } return 0; }
19.065693
81
0.402374
Bourbon-Whiskey
09b436275e636ef65513b17825ae555991ae75a6
1,736
hpp
C++
ZappyGUI/sources/zappy/player/Player.hpp
gillioa/Zappy
4de8a9be40b018f68d56ddb7d8813192653838f4
[ "MIT" ]
null
null
null
ZappyGUI/sources/zappy/player/Player.hpp
gillioa/Zappy
4de8a9be40b018f68d56ddb7d8813192653838f4
[ "MIT" ]
null
null
null
ZappyGUI/sources/zappy/player/Player.hpp
gillioa/Zappy
4de8a9be40b018f68d56ddb7d8813192653838f4
[ "MIT" ]
null
null
null
#ifndef PLAYER_HPP__ # define PLAYER_HPP__ #include <map> #include <mutex> #include "Case.hpp" #include "Socket.hpp" enum eOrientation { NORTH = 1, EAST = 2, SOUTH = 3, WEST = 4 }; enum eAction { Expulse = 0, Broadcast, IncantationLaunch, Fork, PutRessources, GetRessources, Nothing, }; enum eStat { Incantation = 0, Not, }; class Player { public: Player(int, unsigned int = 0, unsigned int = 0); ~Player(); void setX(unsigned int); void setY(unsigned int); void setOrientation(eOrientation); eOrientation getOrientation() const; void setLevel(unsigned int); unsigned int getLevel() const; unsigned int getY() const; unsigned int getX() const; int getId() const; void setCurrentAction(eAction); eAction getCurrentAction() const; void setRessource(eRessources, unsigned int); std::map<eRessources, unsigned int> const &getRessource() const; void setBroadCastMsg(std::string const &); std::string const &getBroadCastMsg() const; eStat getCurrentStat() const; void setCurrentStat(eStat); void setIncantationParam(unsigned int, unsigned int, unsigned int); std::vector<unsigned int> const &getIncantationParam() const; unsigned int getBroadCastLevel() const; void updateBroadCastLevel(); std::string const &getStringAction(); void demandInventory(Socket *); private: eAction _currentAction; std::string _strCurAction; std::vector<unsigned int> _incantationParam; eStat _currentStat; unsigned int m_x; unsigned int m_y; unsigned int _level; int m_id; eOrientation _orient; std::string _broadCastMsg; std::map<eRessources, unsigned int> _ressources; std::mutex m_mutex; private: unsigned int m_broadCastLevel; }; #endif // EOF - Player.hpp
23.459459
69
0.726959
gillioa
09b9959001b7d84a202411716121998d6b92cee7
3,918
cpp
C++
src/resource/textureatlas.cpp
GuyTristram/grt
4329ed58f22248ed4924246e148fb6b5f3f7e1bc
[ "MIT" ]
1
2015-10-08T19:11:18.000Z
2015-10-08T19:11:18.000Z
src/resource/textureatlas.cpp
GuyTristram/grt
4329ed58f22248ed4924246e148fb6b5f3f7e1bc
[ "MIT" ]
null
null
null
src/resource/textureatlas.cpp
GuyTristram/grt
4329ed58f22248ed4924246e148fb6b5f3f7e1bc
[ "MIT" ]
null
null
null
#include "resource/textureatlas.h" #include <algorithm> #include <set> #include "core/renderstate.h" #include "core/shaderprogram.h" #include "core/texture.h" #include "core/texturetarget.h" #include "resource/mesh.h" #include "resource/resourcepool.h" TextureAtlas::TextureAtlas( std::vector< std::string > const &sources, int max_atlas_size, int max_source_size ) { int n_sources = sources.size(); ResourcePool pool; std::vector< Texture2D::Ptr > textures; textures.reserve( n_sources ); std::vector< SizeSrc > sizes( n_sources ); int n_channels = 0; for( int i = 0; i != n_sources; ++i ) { Texture2D::Ptr t = pool.texture2d( sources[i].c_str() ); if( !t.get() ) { printf( "Error: failed to load texture %s \n", sources[i].c_str() ); const unsigned char c = 255; t = Texture2D::Ptr( new Texture2D( 1, 1, 1, 0, ( const char * )&c ) ); } textures.push_back( t ); sizes[i] = SizeSrc( int2( std::min( t->width(), max_source_size ), std::min( t->height(), max_source_size ) ), i ); n_channels = std::max( n_channels, t->channels() ); } std::sort( sizes.begin(), sizes.end() ); m_rects.resize( n_sources ); int atlas_width = 16; int atlas_height = 16; while( atlas_width <= max_atlas_size && atlas_height <= max_atlas_size && !fit_all( sizes, atlas_width, atlas_height ) ) { if( atlas_width <= atlas_height ) atlas_width *= 2; else atlas_height *= 2; } //Texture2D::Ptr t = ResourcePool::stock().texture2d( "../src/stone3.jpg" ); if( atlas_width <= max_atlas_size && atlas_height <= max_atlas_size ) { //m_texture.set( new Texture2D( atlas_width, atlas_height, n_channels ) ); m_texture = Texture2D::Ptr( new Texture2D( atlas_width, atlas_height, n_channels, 0, "c" ) ); m_mult = float2( 1.f / float( atlas_width ), 1.f / float( atlas_height ) ); ShaderProgram::Ptr program = ResourcePool::stock().shader_program( "atlas.sp" ); Mesh quad = make_quad(); TextureTarget target; target.attach( m_texture ); target.is_complete(); target.clear(); RenderState state; state.depth_test( false ); for( int i = 0; i != n_sources; ++i ) { program->set( "u_source", textures[i] ); program->set( "u_min", float2( m_rects[i].min ) * m_mult ); program->set( "u_max", float2( m_rects[i].max ) * m_mult ); quad.draw( *program, state, target ); } m_texture->gen_mipmaps(); } } bool TextureAtlas::fit_all( std::vector< SizeSrc > const &sizes, int atlas_width, int atlas_height ) { int n_sources = sizes.size(); std::set< Rect > rects; rects.insert( Rect( int2( 0, 0 ), int2( atlas_width, atlas_height ) ) ); for( int i = 0; i != n_sources; ++i ) { bool fit = false; for( auto r = rects.begin(); r != rects.end(); ++r ) { Rect r1, r2; if( r->split( sizes[i].size, r1, r2 ) ) { m_rects[ sizes[i].src ] = Rect( r->min, r->min + sizes[i].size ); rects.erase( r ); if( r1.area() > 0 ) rects.insert( r1 ); if( r2.area() > 0 ) rects.insert( r2 ); fit = true; break; } } if( !fit ) return false; } return true; } bool TextureAtlas::Rect::split( int2 s, Rect &r1, Rect &r2 ) const { if( !fits( s ) ) return false; int2 diff = size() - s; int2 p1 = int2( min.x + s.x, min.y ); int2 p2 = int2( min.x, min.y + s.y ); if( diff.x > diff.y ) { r1 = Rect( p1, int2( max.x, min.y + s.y ) ); r2 = Rect( p2, max ); } else { r1 = Rect( p1, max ); r2 = Rect( p2, int2( min.x + s.x, max.y ) ); } return true; } TextureAtlas::~TextureAtlas() { } float2 TextureAtlas::min_uv( int i ) const { return float2( m_rects[i].min ) * m_mult; } float2 TextureAtlas::max_uv( int i ) const { return float2( m_rects[i].max ) * m_mult; }
25.277419
101
0.588821
GuyTristram
09c096596fdd6c29da26474d7e60b1134e892b0e
292
cpp
C++
src/Projection.cpp
kr15h/YaronTracker
4c6efe0f8bca6a64164a714633df8a032ce135d1
[ "MIT" ]
1
2018-04-07T14:06:05.000Z
2018-04-07T14:06:05.000Z
src/Projection.cpp
kr15h/YaronTracker
4c6efe0f8bca6a64164a714633df8a032ce135d1
[ "MIT" ]
null
null
null
src/Projection.cpp
kr15h/YaronTracker
4c6efe0f8bca6a64164a714633df8a032ce135d1
[ "MIT" ]
null
null
null
#include "Projection.h" namespace ytr { shared_ptr<Projection> Projection::create(){ return shared_ptr<Projection>(new Projection()); } Projection::Projection(){ } void Projection::update(){ // Do some swarm math } void Projection::draw(){ // TODO: draw swarm } } // namespace ytr
13.272727
49
0.695205
kr15h
09c23575f2f062cd5ff9438d4a80653de1fa4c6e
455
cpp
C++
benchmark/bm_binary_operator.cpp
matazure/mtensor
4289284b201cb09ed1dfc49f44d6738751affd63
[ "MIT" ]
82
2020-04-11T09:33:36.000Z
2022-03-23T03:47:25.000Z
benchmark/bm_binary_operator.cpp
Lexxos/mtensor
feb120923dad3fb4ae3b31dd09931622a63c3d06
[ "MIT" ]
28
2017-04-26T17:12:35.000Z
2019-04-08T04:05:24.000Z
benchmark/bm_binary_operator.cpp
Lexxos/mtensor
feb120923dad3fb4ae3b31dd09931622a63c3d06
[ "MIT" ]
22
2017-01-10T14:57:29.000Z
2019-12-17T08:55:59.000Z
#include "bm_binary_operator.hpp" auto bm_host_tensor2f_add = bm_tensor_add<tensor<float, 2>>; auto bm_host_tensor2f_sub = bm_tensor_add<tensor<float, 2>>; auto bm_host_tensor2f_mul = bm_tensor_add<tensor<float, 2>>; auto bm_host_tensor2f_div = bm_tensor_add<tensor<float, 2>>; BENCHMARK(bm_host_tensor2f_add)->Arg(10_K); BENCHMARK(bm_host_tensor2f_sub)->Arg(10_K); BENCHMARK(bm_host_tensor2f_mul)->Arg(10_K); BENCHMARK(bm_host_tensor2f_div)->Arg(10_K);
41.363636
60
0.808791
matazure
09c663757184d330494ff782fcbafd5da6b80d5f
1,289
hpp
C++
src/components/ProjectileEmitterComponent.hpp
ItsChoudhry/2dGameEngine
dd154816b1a4ab18cdcb5e59f580af9e495f7761
[ "MIT" ]
1
2020-07-17T16:22:01.000Z
2020-07-17T16:22:01.000Z
src/components/ProjectileEmitterComponent.hpp
ItsChoudhry/2dGameEngine
dd154816b1a4ab18cdcb5e59f580af9e495f7761
[ "MIT" ]
null
null
null
src/components/ProjectileEmitterComponent.hpp
ItsChoudhry/2dGameEngine
dd154816b1a4ab18cdcb5e59f580af9e495f7761
[ "MIT" ]
null
null
null
#pragma once #include "../../lib/glm/glm.hpp" #include "../Component.hpp" #include "../EntityManager.hpp" #include "TransformComponent.hpp" class ProjectileEmitterComponent : public Component { private: TransformComponent *m_transform; glm::vec2 m_origin; int m_speed; int m_range; float m_angleRad; bool m_loop; public: ProjectileEmitterComponent(int t_speed, int t_angleDeg, int t_range, bool t_loop) { m_speed = t_speed; m_range = t_range; m_angleRad = glm::radians(static_cast<float>(t_angleDeg)); m_loop = t_loop; } void initialize() override { m_transform = owner->getComponent<TransformComponent>(); m_origin = glm::vec2(m_transform->position.x, m_transform->position.y); m_transform->velocity = glm::vec2(glm::cos(m_angleRad) * m_speed, glm::sin(m_angleRad) * m_speed); } void update(float t_deltaTime) override { if (glm::distance(m_transform->position, m_origin) > m_range) { if (m_loop) { m_transform->position.x = m_origin.x; m_transform->position.y = m_origin.y; } else { owner->destory(); } } } };
25.27451
86
0.589604
ItsChoudhry
09ceffc703de8ad4038fd35bbaedfbd287d2cd7f
442
cpp
C++
e794.cpp
MaowMan/zerojudge
2073408b26108c760360cb4a603ebbf86583c62f
[ "MIT" ]
null
null
null
e794.cpp
MaowMan/zerojudge
2073408b26108c760360cb4a603ebbf86583c62f
[ "MIT" ]
null
null
null
e794.cpp
MaowMan/zerojudge
2073408b26108c760360cb4a603ebbf86583c62f
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> int64_t gcd(int64_t a,int64_t b){ if(b==0) { return a; } else { return gcd(b,a%b); } } int main(){ std::vector<int64_t> data(50); data[0]=0; data[1]=1; for(int i=2;i<50;i++){ data[i]=data[i-1]+data[i-2]; } int n; std::cin>>n; int64_t cache=gcd(data[n+1],data[n]); std::cout<<data[n]/cache<<':'<<data[n+1]/cache<<std::endl; }
17
62
0.504525
MaowMan
09d21f04f727b246c6383abaf42e0ec8041f2e7d
2,751
cpp
C++
PrivateDiary-Qt/PrivateDiary/PrivateDiaryDesktop/mainwindow.cpp
gituser9/Private-Diary
bedda59a32de6dfb4b252b7e53eae2637a0c99f3
[ "MIT" ]
1
2021-12-21T12:53:51.000Z
2021-12-21T12:53:51.000Z
PrivateDiary-Qt/PrivateDiary/PrivateDiaryDesktop/mainwindow.cpp
gituser9/Private-Diary
bedda59a32de6dfb4b252b7e53eae2637a0c99f3
[ "MIT" ]
null
null
null
PrivateDiary-Qt/PrivateDiary/PrivateDiaryDesktop/mainwindow.cpp
gituser9/Private-Diary
bedda59a32de6dfb4b252b7e53eae2637a0c99f3
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->mainToolBar->hide(); ui->menuBar->hide(); appData = std::make_shared<AppData>(); loginPage = new LoginPage(this); loginPage->setAppData(appData); connect(ui->btnRegistration, &QPushButton::clicked, this, &MainWindow::registration); connect(ui->btnAuth, &QPushButton::clicked, this, &MainWindow::auth); // menu connect(ui->actionSettings, &QAction::triggered, this, &MainWindow::showCredentialDialog); connect(ui->actionDownload_Database, &QAction::triggered, this, &MainWindow::downloadDatabase); connect(ui->actionUpload_Database, &QAction::triggered, this, &MainWindow::uploadDatabase); connect(ui->actionLogout, &QAction::triggered, this, &MainWindow::exit); // ui->stackedWidget->setCurrentIndex(Pages::Main); // setupMainPage(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setupMainPage() { appData->setUserPassword(ui->lePassword->text()); mainPage = new MainPage(this); mainPage->setUi(ui); mainPage->setupPage(appData); } void MainWindow::registration() { if (loginPage->registration(ui->leUsername->text(), ui->lePassword->text())) { ui->stackedWidget->setCurrentIndex(Pages::Main); setupMainPage(); } } void MainWindow::auth() { if (loginPage->auth(ui->leUsername->text(), ui->lePassword->text())) { ui->stackedWidget->setCurrentIndex(Pages::Main); setupMainPage(); } } void MainWindow::showCredentialDialog() { CredentialDialog dialog(this); if (dialog.exec() != QDialog::Accepted) { return; } if (loginPage->updateCredentioals(dialog.getLogin(), dialog.getPassword())) { QMessageBox::information(this, tr("Information"), tr("Restart application please.")); } else { QMessageBox::critical(this, tr("Error"), tr("Update credentials error.")); } } void MainWindow::downloadDatabase() { QString homePath = QDir::homePath(); QString dir = QFileDialog::getExistingDirectory(this, tr("Directory for save"), homePath, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); QFile::copy(Constant::dbPath, dir + "/" + Constant::dbName); } void MainWindow::uploadDatabase() { QString homePath = QDir::homePath(); QString fileName = QFileDialog::getOpenFileName(this, tr("Database for upload"), homePath, "*.dbx"); QFile::copy(fileName, Constant::dbPath); mainPage->refresh(); } void MainWindow::exit() { ui->leUsername->clear(); ui->lePassword->clear(); ui->stackedWidget->setCurrentIndex(Pages::Login); }
27.787879
156
0.678662
gituser9
09d3b1d4263472bf8d4e92925c91cf60469b7a59
1,002
cpp
C++
DelaunayVoronoi/DataParser.cpp
wingyiu/ndelvor
a7eeb7791b803b1c73ba2371b38648103b20232a
[ "BSD-3-Clause" ]
1
2019-01-07T01:46:05.000Z
2019-01-07T01:46:05.000Z
DelaunayVoronoi/DataParser.cpp
wingyiu/ndelvor
a7eeb7791b803b1c73ba2371b38648103b20232a
[ "BSD-3-Clause" ]
null
null
null
DelaunayVoronoi/DataParser.cpp
wingyiu/ndelvor
a7eeb7791b803b1c73ba2371b38648103b20232a
[ "BSD-3-Clause" ]
null
null
null
#include "DataParser.h" bool DataParser::hasNext() { if(feof(m_file) == 0) { return true; } else { return false; } } Point* DataParser::getNext() { double *coord = new double[m_dimension]; for(int i=0; i<m_dimension; i++) { fscanf(m_file, "%lf", coord+i); fscanf(m_file, "%*[ ,\n]"); } Point* p = new Point(m_dimension, coord); return p; } unsigned DataParser::getDimension() { return m_dimension; } bool DataParser::isFileValid() { return false; } DataParser::~DataParser() { if(m_file != NULL) { fclose(m_file); } } DataParser::DataParser(const char *filename):m_file(NULL), m_filename(filename), m_dimension(0) { m_file = fopen(m_filename, "r"); fscanf(m_file, " @dimension:%d", &m_dimension); } DataParser::DataParser(FILE *file):m_file(file), m_filename(NULL), m_dimension(0) { } DataParser::DataParser():m_file(NULL), m_filename(NULL), m_dimension(0) { }
14.112676
96
0.598802
wingyiu
09d98e232450818de0b7fcc389977014e0cea640
1,909
cpp
C++
Compiler/Compiler.cpp
cmarrin/Clover
4884b4e51aed180c0cce8fd23b62445109515167
[ "MIT" ]
null
null
null
Compiler/Compiler.cpp
cmarrin/Clover
4884b4e51aed180c0cce8fd23b62445109515167
[ "MIT" ]
null
null
null
Compiler/Compiler.cpp
cmarrin/Clover
4884b4e51aed180c0cce8fd23b62445109515167
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------- This source file is a part of Clover For the latest info, see https://github.com/cmarrin/Clover Copyright (c) 2021-2022, Chris Marrin All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "Compiler.h" #include "CloverCompileEngine.h" #include "NativeCore.h" #include <map> #include <vector> using namespace clvr; bool Compiler::compile(std::istream* istream, Language lang, std::vector<uint8_t>& executable, uint32_t maxExecutableSize, const std::vector<NativeModule*>& modules, std::vector<std::pair<int32_t, std::string>>* annotations) { CompileEngine* engine = nullptr; switch(lang) { default: break; case Language::Clover: engine = new CloverCompileEngine(istream, annotations); break; } if (!engine) { _error = Error::UnrecognizedLanguage; return false; } // Install the modules in the engine // First add the core NativeCore().addFunctions(engine); for (const auto& it : modules) { it->addFunctions(engine); } engine->program(); _error = engine->error(); _expectedToken = engine->expectedToken(); _expectedString = engine->expectedString(); _lineno = engine->lineno(); _charno = engine->charno(); try { if (_error == Error::None) { engine->emit(executable); } } catch(...) { } if (_error == Error::None && executable.size() > maxExecutableSize) { _error = Error::ExecutableTooBig; } delete engine; return _error == Error::None; }
26.887324
84
0.544788
cmarrin
09eb3cf1704fc51817350d764dc8a7f267515bbe
1,866
cpp
C++
SDKs/CryCode/3.8.1/GameDll/AI/HazardModule/HazardShared.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.7.0/GameDll/AI/HazardModule/HazardShared.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.7.0/GameDll/AI/HazardModule/HazardShared.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
// ============================================================================ // ============================================================================ // ============================================================================ // ==== // ==== Hazard Shared // ==== // ==== Various class and types that are shared between the various hazard // ==== module classes. // ==== // #include "StdAfx.h" #include "HazardShared.h" using namespace HazardSystem; // ============================================================================ // ============================================================================ // ============================================================================ // // -- HazardProjectileID -- HazardProjectileID -- HazardProjectileID -- // // ============================================================================ // ============================================================================ // ============================================================================ void HazardProjectileID::Serialize(TSerialize ser) { ser.BeginGroup("HazardProjectileID"); ser.Value("ID", m_ID); ser.EndGroup(); } // ============================================================================ // ============================================================================ // ============================================================================ // // -- HazardSphereID -- HazardSphereID -- HazardSphereID -- HazardSphereID -- // // ============================================================================ // ============================================================================ // ============================================================================ void HazardSphereID::Serialize(TSerialize ser) { ser.BeginGroup("HazardSphereID"); ser.Value("ID", m_ID); ser.EndGroup(); }
30.590164
79
0.237406
amrhead
09f7cca4d474418ae3b10a06adf2602112ba9fee
2,641
hpp
C++
src/Model/ObjectLoading/ModelLoader.hpp
charlieSewell/ICT397-Game-Engine
64d44edfcf397ea0a1133680f908f74ea8bafb22
[ "MIT" ]
1
2021-04-11T04:57:06.000Z
2021-04-11T04:57:06.000Z
src/Model/ObjectLoading/ModelLoader.hpp
charlieSewell/ICT397-Game-Engine
64d44edfcf397ea0a1133680f908f74ea8bafb22
[ "MIT" ]
null
null
null
src/Model/ObjectLoading/ModelLoader.hpp
charlieSewell/ICT397-Game-Engine
64d44edfcf397ea0a1133680f908f74ea8bafb22
[ "MIT" ]
null
null
null
// // Created by Charlie Sewell on 1/04/2021. // #pragma once #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <glm/gtc/type_ptr.hpp> #include "Model/Model.hpp" #include "Model/SkeletalAnimation.hpp" #include "Controller/TextureManager.hpp" /** @class ModelLoader * @brief Class that loads models */ class ModelLoader { public: /** * @brief Loads a model and returns a vector of meshes * @param string - filename * @return vector<Mesh> */ Model loadModel(const std::string& filename); private: ///string that stores the directory std::string directory; /** * @brief processes and indivudial node in the scene * @param vector<Mesh> - meshes * @param aiNode* - node * @param const aiScene* - scene * @param mat4 - transform */ void processNode(std::vector<SkeletalAnimation> &animations, std::vector<Mesh> &meshes, std::vector<Bone> &bones, std::map<std::string, unsigned int> &boneMap, aiNode *node, const aiScene *scene, glm::mat4 transform); /** * @brief Processes a singular mesh of a model * @param aiMesh* - mesh * @param const aiScene* - scene * @param mat4 - transform * @return Mesh */ Mesh processMesh(aiMesh *mesh, const aiScene *scene,glm::mat4 transform); /** * @brief Loads the Textures for a model * @param aiMaterial* - mat * @param aiTextureType - type * @param string - typeName * @return vector<ModelTexture> */ std::vector<ModelTexture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, const std::string& typeName); ///Finds the root node of the skeleton aiNode* findRootNode(aiNode* node, aiMesh* mesh); ///Loads in the Node Heirachy void loadAnimNodes(aiNode* node,aiMesh* mesh); ///Creates a node heirachy given a aiNode Node loadNodeHeirachy(aiNode *root); ///Adds the Bone Data void addBoneData(unsigned int BoneID, float Weight); ///Loads a models animations void loadAnimations(std::vector<SkeletalAnimation> &animations, const aiScene *scene); ///Loads the bones of a mesh void loadBones(std::vector<Mesh> &meshes, std::vector<Bone> &bones, std::map<std::string,unsigned int> &boneMap, unsigned int meshIndex, const aiMesh *mesh); ///List of textures currently loaded for a model std::vector<ModelTexture> textures_loaded; /// Number of bones in current model int numBones = 0; ///Root animation node Node rootAnimNode; };
33.858974
117
0.649375
charlieSewell
09f9c638b95c75c1c87c83eed95c2299923bd1a9
881
cpp
C++
CloakEngine/Manager.cpp
Bizzarrus/CloakEngine
0890eaada76b91be89702d2a6ec2dcf9b2901fb9
[ "BSD-2-Clause" ]
null
null
null
CloakEngine/Manager.cpp
Bizzarrus/CloakEngine
0890eaada76b91be89702d2a6ec2dcf9b2901fb9
[ "BSD-2-Clause" ]
null
null
null
CloakEngine/Manager.cpp
Bizzarrus/CloakEngine
0890eaada76b91be89702d2a6ec2dcf9b2901fb9
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #define NO_LIB_LOAD #include "Implementation/Rendering/Manager.h" #include "Implementation/Rendering/DX12/Lib.h" #include <atomic> namespace CloakEngine { namespace Impl { namespace Rendering { inline namespace Manager_v1 { CE::RefPointer<IManager> CLOAK_CALL IManager::Create(In API::Global::Graphic::RenderMode Type) { CE::RefPointer<IManager> r = nullptr; switch (Type) { case CloakEngine::API::Global::Graphic::RenderMode::DX12: r = DX12::Lib::CreateManager(); if (r != nullptr) { break; } default: API::Global::Log::WriteToLog("No render type supported!", API::Global::Log::Type::Error); break; } return r; } void CLOAK_CALL IManager::GetSupportedModes(Out API::List<API::Global::Graphic::RenderMode>* modes) { } } } } }
26.69697
104
0.628831
Bizzarrus
09fa5f0c7deb760c8d18ddf9e61238f904f69337
554
cpp
C++
1-Intro/06-floatEdouble.cpp
pablo147sousa/IF-Cpp
25606c16d18d35143fc564fe1ca7aa4ab7f7bc10
[ "MIT" ]
null
null
null
1-Intro/06-floatEdouble.cpp
pablo147sousa/IF-Cpp
25606c16d18d35143fc564fe1ca7aa4ab7f7bc10
[ "MIT" ]
null
null
null
1-Intro/06-floatEdouble.cpp
pablo147sousa/IF-Cpp
25606c16d18d35143fc564fe1ca7aa4ab7f7bc10
[ "MIT" ]
2
2021-06-01T20:48:10.000Z
2021-06-05T17:31:22.000Z
// Dados de ponto flutuante (float e double) em C e C++ /** * Números de ponto flutuante representam os números * pertencentes ao conjunto dos Reais. * A diferença entre float e double é que o ultimo * apresenta o dobro de tamanho em relação a float e por * isso possui uma maior precisão. * O maior tipo que há é o long double, que possui * um tamanho de 12 Bytes. * Os operadores aritméticos funcionam também para * números de ponto flutuante. */ #include <stdio.h> int main() { float real = 42.4242; return 0; }
26.380952
57
0.684116
pablo147sousa
09fbea11b9056610461e6f7411e3cf6fec031e8b
586
hpp
C++
upgrade/pack_builder/ImageEncryptorNone.hpp
oguzcanphilips/embeddedinfralib
f1b083d61a34d123d34ab7cd51267377aa2f7855
[ "Unlicense" ]
54
2019-04-02T14:42:54.000Z
2022-03-20T23:02:19.000Z
upgrade/pack_builder/ImageEncryptorNone.hpp
oguzcanphilips/embeddedinfralib
f1b083d61a34d123d34ab7cd51267377aa2f7855
[ "Unlicense" ]
32
2019-03-26T06:57:29.000Z
2022-03-25T00:04:44.000Z
upgrade/pack_builder/ImageEncryptorNone.hpp
oguzcanphilips/embeddedinfralib
f1b083d61a34d123d34ab7cd51267377aa2f7855
[ "Unlicense" ]
20
2019-03-25T15:49:49.000Z
2022-03-20T23:02:22.000Z
#ifndef UPGRADE_PACK_BUILDER_IMAGE_ENCRYPTOR_NONE_HPP #define UPGRADE_PACK_BUILDER_IMAGE_ENCRYPTOR_NONE_HPP #include "upgrade/pack_builder/ImageSecurity.hpp" #include <cstdint> #include <vector> namespace application { class ImageEncryptorNone : public ImageSecurity { public: static const uint32_t encryptionAndMacMethod = 0; static const std::size_t blockLength = 16; virtual uint32_t EncryptionAndMacMethod() const override; virtual std::vector<uint8_t> Secure(const std::vector<uint8_t>& data) const override; }; } #endif
25.478261
93
0.744027
oguzcanphilips
09ff20f9c45a46b716a8aa03c7a7b46664c46241
24,475
cpp
C++
src/ie_render_engine.cpp
wtkooa/imagine
105695085b369825b70ff3ca4b0076f8ce15c957
[ "MIT" ]
1
2017-09-21T16:53:27.000Z
2017-09-21T16:53:27.000Z
src/ie_render_engine.cpp
wtkooa/imagine
105695085b369825b70ff3ca4b0076f8ce15c957
[ "MIT" ]
null
null
null
src/ie_render_engine.cpp
wtkooa/imagine
105695085b369825b70ff3ca4b0076f8ce15c957
[ "MIT" ]
null
null
null
//___|"ie_render_engine.cpp"|___________________________________________________ // // Project: Imagine: 3D Environment Engine // Version: 0.1.0 // Author: David Lipps // License: MIT License // // Copyright (c) 2017 David E Lipps //______________________________________________________________________________ #include "ie_render_engine.h" #include <iostream> #define GL_GLEXT_PROTOTYPES //Needs to be defined for some GL funcs to work. #include <GL/gl.h> #include <GL/glu.h> #include <glm/mat4x4.hpp> #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include "ie_assets.h" #include "ie_const.h" #include "ie_nodes.h" #include "ie_scenegraph.h" #include "ie_vram.h" //___|RECEIVING MESSAGES|_______________________________________________________ void ie::RenderEngine::receiveMessage(AssetStatusMessage msg) { materials = msg.materials; models = msg.models; rus = msg.rus; shaders = msg.shaders; shaderNameIdMap = msg.shaderNameIdMap; lights = msg.lights; lightNameIdMap = msg.lightNameIdMap; terrains = msg.terrains; terrainNameIdMap = msg.terrainNameIdMap; textures = msg.textures; textureNameIdMap = msg.textureNameIdMap; } void ie::RenderEngine::receiveMessage(VramStatusToRenderMessage msg) { vPair = msg.vPair; vnPair = msg.vnPair; vtnPair = msg.vtnPair; vtncbPair = msg.vtncbPair; terrainIndexPair = msg.terrainIndexPair; } void ie::RenderEngine::receiveMessage(GraphStatusMessage msg) { firstBucket = msg.bucket; } //______________________________________________________________________________ //___|RENDERERS|________________________________________________________________ void ie::RenderEngine::render(void) { RenderBucket* currentBucket = firstBucket; while (currentBucket != NULL) { std::vector<NodePacket>* packets = currentBucket->getPackets(); if (currentBucket->type == PLAYER_RENDER) { //Placeholder } else if (currentBucket->type == CAMERA_RENDER) { for (auto it = packets->begin(); it != packets->end(); it++) { NodePacket packet = (*it); updateCamera(packet.node.camera); } } else { RenderState* state = currentBucket->getRenderState(); setState(state); } if (currentBucket->type == MATERIAL_RENDER) { renderMaterialedEntities(packets); } else if (currentBucket->type == TEXTURE_RENDER) { renderTexturedEntities(packets); } else if (currentBucket->type == TERRAIN_RENDER) { renderTerrainEntities(packets); } currentBucket = currentBucket->getNextBucket(); } firstBucket->clear(); } void ie::RenderEngine::setState(RenderState* state) { if (state->shader == STATIC_SHADER) { currentShader = staticShader; } else if (state->shader == TERRAIN_SHADER) { currentShader = terrainShader; } GLint currentProg; glGetIntegerv(GL_CURRENT_PROGRAM, &currentProg); if (currentShader->programId != currentProg) { glUseProgram(currentShader->programId); } if (state->cullFace == true) { glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } } void ie::RenderEngine::updateCamera(CameraNode* camera) { projectionMatrix = camera->projectionMatrix; viewMatrix = camera->viewMatrix; cameraPos = camera->translation; } //STATIC MATERIALED ENTITIES RENDERER void ie::RenderEngine::renderMaterialedEntities(std::vector<NodePacket>* packets) { unsigned int lightId = (*lightNameIdMap)["light0"]; LightAsset* light = &(*lights)[lightId]; glm::vec3 pointLightPos = (*light).posVector; glm::vec3 globalAmbient = (*light).globalAmbient; glm::vec3 lightAmbient = (*light).lightAmbient; glm::vec3 lightSpecular = (*light).lightSpecular; glm::vec3 lightDiffuse = (*light).lightDiffuse; float constantFalloff = (*light).constantFalloff; float linearFalloff = (*light).linearFalloff; float quadraticFalloff = (*light).quadraticFalloff; GLuint cameraPosLoc = currentShader->uniforms["cameraPos"].location; GLuint mtwMatrixLoc = currentShader->uniforms["mtwMatrix"].location; GLuint transformationMatrixLoc = currentShader->uniforms["transformationMatrix"].location; GLuint pointLightPosLoc = currentShader->uniforms["pointLightPos"].location; GLuint globalAmbientLoc = currentShader->uniforms["globalAmbient"].location; GLuint lightAmbientLoc = currentShader->uniforms["lightAmbient"].location; GLuint lightSpecularLoc = currentShader->uniforms["lightSpecular"].location; GLuint lightDiffuseLoc = currentShader->uniforms["lightDiffuse"].location; GLuint lightConstantLoc = currentShader->uniforms["lightConstantFalloff"].location; GLuint lightLinearLoc = currentShader->uniforms["lightLinearFalloff"].location; GLuint lightQuadraticLoc = currentShader->uniforms["lightQuadraticFalloff"].location; GLuint usesGlobalAmbientLoc = currentShader->uniforms["usesGlobalAmbient"].location; GLuint usesLightAmbientLoc = currentShader->uniforms["usesLightAmbient"].location; GLuint usesLightDiffuseLoc = currentShader->uniforms["usesLightDiffuse"].location; GLuint usesLightSpecularLoc = currentShader->uniforms["usesLightSpecular"].location; GLuint usesLightFalloffLoc = currentShader->uniforms["usesLightFalloff"].location; GLuint materialSpecularLoc = currentShader->uniforms["materialSpecular"].location; GLuint materialShininessLoc = currentShader->uniforms["materialShininess"].location; GLuint materialDiffuseLoc = currentShader->uniforms["materialDiffuse"].location; GLuint materialAmbientLoc = currentShader->uniforms["materialAmbient"].location; GLuint materialEmissionLoc = currentShader->uniforms["materialEmission"].location; GLuint usingTextureLoc = currentShader->uniforms["usingTexture"].location; GLint currentBoundVbo; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &currentBoundVbo); GLint requiredVbo = (*vnPair).readVbo; if (requiredVbo != currentBoundVbo) { glBindBuffer(GL_ARRAY_BUFFER, requiredVbo); } glEnableVertexAttribArray(0); glEnableVertexAttribArray(2); glVertexAttribPointer(0, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VN_BYTES, ie::OFFSET_VOID); glVertexAttribPointer(2, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VN_BYTES, ie::OFFSET_1VEC3); glUniform3fv(cameraPosLoc, 1, &cameraPos[0]); glUniform3fv(pointLightPosLoc, 1, &pointLightPos[0]); glUniform3fv(globalAmbientLoc, 1, &globalAmbient[0]); glUniform3fv(lightAmbientLoc, 1, &lightAmbient[0]); glUniform3fv(lightSpecularLoc, 1, &lightSpecular[0]); glUniform3fv(lightDiffuseLoc, 1, &lightDiffuse[0]); glUniform1f(lightConstantLoc, constantFalloff); glUniform1f(lightLinearLoc, linearFalloff); glUniform1f(lightQuadraticLoc, quadraticFalloff); for (auto it = packets->begin(); it != packets->end(); it++) { StaticNode* entity = it->node.stat; RenderUnit* ru = it->asset.ru; glm::mat4 mtwMatrix = entity->mtwMatrix; bool usesGlobalAmbientE = entity->usesGlobalAmbient; bool usesLightAmbientE = entity->usesLightAmbient; bool usesLightDiffuseE = entity->usesLightDiffuse; bool usesLightSpecularE = entity->usesLightSpecular; bool usesLightFalloffE = entity->usesLightFalloff; glm::mat4 transformationMatrix = projectionMatrix * viewMatrix * mtwMatrix; glUniformMatrix4fv(mtwMatrixLoc, 1, GL_FALSE, &mtwMatrix[0][0]); glUniformMatrix4fv(transformationMatrixLoc, 1, GL_FALSE, &transformationMatrix[0][0]); unsigned int materialId = ru->material; unsigned int vramLocation = ru->vramLocation; unsigned int indexAmount = ru->vertexAmount; MaterialAsset* material = &((*materials)[materialId]); float materialShininess = (*material).shininess; glm::vec3 materialAmbient = (*material).ambient; glm::vec3 materialDiffuse = (*material).diffuse; glm::vec3 materialSpecular = (*material).specular; glm::vec3 materialEmission = (*material).emission; bool usesGlobalAmbientM = (*material).usesGlobalAmbient; bool usesLightAmbientM = (*material).usesLightAmbient; bool usesLightDiffuseM = (*material).usesLightDiffuse; bool usesLightSpecularM = (*material).usesLightSpecular; bool usesLightFalloffM = (*material).usesLightFalloff; bool containsTexture = (*material).containsTexture; GLuint diffuseMapId = (*material).diffuseMapId; bool usesGlobalAmbient = usesGlobalAmbientM && usesGlobalAmbientE; bool usesLightAmbient = usesLightAmbientM && usesLightAmbientE; bool usesLightDiffuse = usesLightDiffuseM && usesLightDiffuseE; bool usesLightSpecular = usesLightSpecularM && usesLightSpecularE; bool usesLightFalloff = usesLightFalloffM && usesLightFalloffE; glUniform1f(materialShininessLoc, materialShininess); glUniform3fv(materialSpecularLoc, 1, &materialSpecular[0]); glUniform3fv(materialAmbientLoc, 1, &materialAmbient[0]); glUniform3fv(materialDiffuseLoc, 1, &materialDiffuse[0]); glUniform3fv(materialEmissionLoc, 1, &materialEmission[0]); glUniform1i(usesGlobalAmbientLoc, usesGlobalAmbient); glUniform1i(usesLightAmbientLoc, usesLightAmbient); glUniform1i(usesLightDiffuseLoc, usesLightDiffuse); glUniform1i(usesLightSpecularLoc, usesLightSpecular); glUniform1i(usesLightFalloffLoc, usesLightFalloff); glDrawArrays(GL_TRIANGLES, vramLocation, indexAmount); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(2); } //STATIC TEXTURED ENTITIES RENDERER void ie::RenderEngine::renderTexturedEntities(std::vector<NodePacket>* packets) { unsigned int lightId = (*lightNameIdMap)["light0"]; LightAsset* light = &(*lights)[lightId]; glm::vec3 pointLightPos = (*light).posVector; glm::vec3 globalAmbient = (*light).globalAmbient; glm::vec3 lightAmbient = (*light).lightAmbient; glm::vec3 lightSpecular = (*light).lightSpecular; glm::vec3 lightDiffuse = (*light).lightDiffuse; float constantFalloff = (*light).constantFalloff; float linearFalloff = (*light).linearFalloff; float quadraticFalloff = (*light).quadraticFalloff; GLuint cameraPosLoc = currentShader->uniforms["cameraPos"].location; GLuint mtwMatrixLoc = currentShader->uniforms["mtwMatrix"].location; GLuint transformationMatrixLoc = currentShader->uniforms["transformationMatrix"].location; GLuint pointLightPosLoc = currentShader->uniforms["pointLightPos"].location; GLuint globalAmbientLoc = currentShader->uniforms["globalAmbient"].location; GLuint lightAmbientLoc = currentShader->uniforms["lightAmbient"].location; GLuint lightSpecularLoc = currentShader->uniforms["lightSpecular"].location; GLuint lightDiffuseLoc = currentShader->uniforms["lightDiffuse"].location; GLuint lightConstantLoc = currentShader->uniforms["lightConstantFalloff"].location; GLuint lightLinearLoc = currentShader->uniforms["lightLinearFalloff"].location; GLuint lightQuadraticLoc = currentShader->uniforms["lightQuadraticFalloff"].location; GLuint usesGlobalAmbientLoc = currentShader->uniforms["usesGlobalAmbient"].location; GLuint usesLightAmbientLoc = currentShader->uniforms["usesLightAmbient"].location; GLuint usesLightDiffuseLoc = currentShader->uniforms["usesLightDiffuse"].location; GLuint usesLightSpecularLoc = currentShader->uniforms["usesLightSpecular"].location; GLuint usesLightFalloffLoc = currentShader->uniforms["usesLightFalloff"].location; GLuint materialSpecularLoc = currentShader->uniforms["materialSpecular"].location; GLuint materialShininessLoc = currentShader->uniforms["materialShininess"].location; GLuint materialDiffuseLoc = currentShader->uniforms["materialDiffuse"].location; GLuint materialAmbientLoc = currentShader->uniforms["materialAmbient"].location; GLuint materialEmissionLoc = currentShader->uniforms["materialEmission"].location; GLuint usingTextureLoc = currentShader->uniforms["usingTexture"].location; GLint currentBoundVbo; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &currentBoundVbo); GLint requiredVbo = (*vtnPair).readVbo; if (requiredVbo != currentBoundVbo) { glBindBuffer(GL_ARRAY_BUFFER, requiredVbo); } glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glVertexAttribPointer(0, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTN_BYTES, ie::OFFSET_VOID); glVertexAttribPointer(1, ie::VEC2_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTN_BYTES, ie::OFFSET_1VEC3); glVertexAttribPointer(2, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTN_BYTES, ie::OFFSET_1VEC3_1VEC2); glUniform3fv(cameraPosLoc, 1, &cameraPos[0]); glUniform3fv(pointLightPosLoc, 1, &pointLightPos[0]); glUniform3fv(globalAmbientLoc, 1, &globalAmbient[0]); glUniform3fv(lightAmbientLoc, 1, &lightAmbient[0]); glUniform3fv(lightSpecularLoc, 1, &lightSpecular[0]); glUniform3fv(lightDiffuseLoc, 1, &lightDiffuse[0]); glUniform1f(lightConstantLoc, constantFalloff); glUniform1f(lightLinearLoc, linearFalloff); glUniform1f(lightQuadraticLoc, quadraticFalloff); for (auto it = packets->begin(); it != packets->end(); it++) { StaticNode* entity = it->node.stat; RenderUnit* ru = it->asset.ru; glm::mat4 mtwMatrix = entity->mtwMatrix; bool usesGlobalAmbientE = entity->usesGlobalAmbient; bool usesLightAmbientE = entity->usesLightAmbient; bool usesLightDiffuseE = entity->usesLightDiffuse; bool usesLightSpecularE = entity->usesLightSpecular; bool usesLightFalloffE = entity->usesLightFalloff; glm::mat4 transformationMatrix = projectionMatrix * viewMatrix * mtwMatrix; glUniformMatrix4fv(mtwMatrixLoc, 1, GL_FALSE, &mtwMatrix[0][0]); glUniformMatrix4fv(transformationMatrixLoc, 1, GL_FALSE, &transformationMatrix[0][0]); unsigned int materialId = ru->material; unsigned int vramLocation = ru->vramLocation; unsigned int indexAmount = ru->vertexAmount; MaterialAsset* material = &((*materials)[materialId]); float materialShininess = (*material).shininess; glm::vec3 materialAmbient = (*material).ambient; glm::vec3 materialDiffuse = (*material).diffuse; glm::vec3 materialSpecular = (*material).specular; glm::vec3 materialEmission = (*material).emission; bool usesGlobalAmbientM = (*material).usesGlobalAmbient; bool usesLightAmbientM = (*material).usesLightAmbient; bool usesLightDiffuseM = (*material).usesLightDiffuse; bool usesLightSpecularM = (*material).usesLightSpecular; bool usesLightFalloffM = (*material).usesLightFalloff; bool containsTexture = (*material).containsTexture; unsigned int textureAssetId = (*material).diffuseMapId; GLuint diffuseMapId = (*textures)[textureAssetId].textureId; bool usesGlobalAmbient = usesGlobalAmbientM && usesGlobalAmbientE; bool usesLightAmbient = usesLightAmbientM && usesLightAmbientE; bool usesLightDiffuse = usesLightDiffuseM && usesLightDiffuseE; bool usesLightSpecular = usesLightSpecularM && usesLightSpecularE; bool usesLightFalloff = usesLightFalloffM && usesLightFalloffE; glUniform1f(materialShininessLoc, materialShininess); glUniform3fv(materialSpecularLoc, 1, &materialSpecular[0]); glUniform3fv(materialAmbientLoc, 1, &materialAmbient[0]); glUniform3fv(materialDiffuseLoc, 1, &materialDiffuse[0]); glUniform3fv(materialEmissionLoc, 1, &materialEmission[0]); glUniform1i(usesGlobalAmbientLoc, usesGlobalAmbient); glUniform1i(usesLightAmbientLoc, usesLightAmbient); glUniform1i(usesLightDiffuseLoc, usesLightDiffuse); glUniform1i(usesLightSpecularLoc, usesLightSpecular); glUniform1i(usesLightFalloffLoc, usesLightFalloff); if (containsTexture) { glBindTexture(GL_TEXTURE_2D, diffuseMapId); glUniform1i(usingTextureLoc, 1); } else { glUniform1i(usingTextureLoc, 0); } glDrawArrays(GL_TRIANGLES, vramLocation, indexAmount); if (containsTexture) { glBindTexture(GL_TEXTURE_2D, 0); glUniform1i(usingTextureLoc, 0); } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } //TERRAIN ENTITIES RENDERER void ie::RenderEngine::renderTerrainEntities(std::vector<NodePacket>* packets) { unsigned int lightId = (*lightNameIdMap)["light0"]; LightAsset* light = &(*lights)[lightId]; glm::vec3 pointLightPos = (*light).posVector; glm::vec3 globalAmbient = (*light).globalAmbient; glm::vec3 lightAmbient = (*light).lightAmbient; glm::vec3 lightSpecular = (*light).lightSpecular; glm::vec3 lightDiffuse = (*light).lightDiffuse; float constantFalloff = (*light).constantFalloff; float linearFalloff = (*light).linearFalloff; float quadraticFalloff = (*light).quadraticFalloff; GLuint cameraPosLoc = currentShader->uniforms["cameraPos"].location; GLuint mtwMatrixLoc = currentShader->uniforms["mtwMatrix"].location; GLuint transformationMatrixLoc = currentShader->uniforms["transformationMatrix"].location; GLuint pointLightPosLoc = currentShader->uniforms["pointLightPos"].location; GLuint globalAmbientLoc = currentShader->uniforms["globalAmbient"].location; GLuint lightAmbientLoc = currentShader->uniforms["lightAmbient"].location; GLuint lightSpecularLoc = currentShader->uniforms["lightSpecular"].location; GLuint lightDiffuseLoc = currentShader->uniforms["lightDiffuse"].location; GLuint lightConstantLoc = currentShader->uniforms["lightConstantFalloff"].location; GLuint lightLinearLoc = currentShader->uniforms["lightLinearFalloff"].location; GLuint lightQuadraticLoc = currentShader->uniforms["lightQuadraticFalloff"].location; GLuint usesGlobalAmbientLoc = currentShader->uniforms["usesGlobalAmbient"].location; GLuint usesLightAmbientLoc = currentShader->uniforms["usesLightAmbient"].location; GLuint usesLightDiffuseLoc = currentShader->uniforms["usesLightDiffuse"].location; GLuint usesLightSpecularLoc = currentShader->uniforms["usesLightSpecular"].location; GLuint usesLightFalloffLoc = currentShader->uniforms["usesLightFalloff"].location; GLuint materialSpecularLoc = currentShader->uniforms["materialSpecular"].location; GLuint materialShininessLoc = currentShader->uniforms["materialShininess"].location; GLuint materialDiffuseLoc = currentShader->uniforms["materialDiffuse"].location; GLuint materialAmbientLoc = currentShader->uniforms["materialAmbient"].location; GLuint materialEmissionLoc = currentShader->uniforms["materialEmission"].location; GLuint texture1Loc = currentShader->uniforms["texture1"].location; GLuint texture2Loc = currentShader->uniforms["texture2"].location; GLuint texture3Loc = currentShader->uniforms["texture3"].location; GLuint texture4Loc = currentShader->uniforms["texture4"].location; GLuint texture5Loc = currentShader->uniforms["texture5"].location; GLuint texture6Loc = currentShader->uniforms["texture6"].location; GLuint texture7Loc = currentShader->uniforms["texture7"].location; GLuint texture8Loc = currentShader->uniforms["texture8"].location; GLuint textureAmountLoc = currentShader->uniforms["textureAmount"].location; GLint currentBoundArrayBuffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &currentBoundArrayBuffer); GLint requiredArray = (*vtncbPair).readVbo; if (requiredArray != currentBoundArrayBuffer) { glBindBuffer(GL_ARRAY_BUFFER, requiredArray); } GLint currentBoundElementBuffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER, &currentBoundElementBuffer); GLint requiredIndex = (*terrainIndexPair).readVbo; if (requiredIndex != currentBoundElementBuffer) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, requiredIndex); } glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glVertexAttribPointer(0, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTNCB_BYTES, ie::OFFSET_VOID); glVertexAttribPointer(1, ie::VEC2_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTNCB_BYTES, ie::OFFSET_1VEC3); glVertexAttribPointer(2, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTNCB_BYTES, ie::OFFSET_1VEC3_1VEC2); glVertexAttribPointer(3, ie::VEC3_DIM, GL_FLOAT, GL_FALSE, ie::STRIDE_VTNCB_BYTES, ie::OFFSET_2VEC3_1VEC2); glVertexAttribPointer(4, ie::UVEC2_DIM, GL_UNSIGNED_INT, GL_FALSE, ie::STRIDE_VTNCB_BYTES, ie::OFFSET_3VEC3_1VEC2); glUniform3fv(cameraPosLoc, 1, &cameraPos[0]); glUniform3fv(pointLightPosLoc, 1, &pointLightPos[0]); glUniform3fv(globalAmbientLoc, 1, &globalAmbient[0]); glUniform3fv(lightAmbientLoc, 1, &lightAmbient[0]); glUniform3fv(lightSpecularLoc, 1, &lightSpecular[0]); glUniform3fv(lightDiffuseLoc, 1, &lightDiffuse[0]); glUniform1f(lightConstantLoc, constantFalloff); glUniform1f(lightLinearLoc, linearFalloff); glUniform1f(lightQuadraticLoc, quadraticFalloff); glUniform1i(texture1Loc, 0); glUniform1i(texture2Loc, 1); glUniform1i(texture3Loc, 2); glUniform1i(texture4Loc, 3); glUniform1i(texture5Loc, 4); glUniform1i(texture6Loc, 5); glUniform1i(texture7Loc, 6); glUniform1i(texture8Loc, 7); for (auto it = packets->begin(); it != packets->end(); it++) { TerrainNode* entity = it->node.terrain; TerrainAsset* terrain = it->asset.ta; glm::mat4 mtwMatrix = entity->mtwMatrix; bool usesGlobalAmbientE = entity->usesGlobalAmbient; bool usesLightAmbientE = entity->usesLightAmbient; bool usesLightDiffuseE = entity->usesLightDiffuse; bool usesLightSpecularE = entity->usesLightSpecular; bool usesLightFalloffE = entity->usesLightFalloff; glm::mat4 transformationMatrix = projectionMatrix * viewMatrix * mtwMatrix; glUniformMatrix4fv(mtwMatrixLoc, 1, GL_FALSE, &mtwMatrix[0][0]); glUniformMatrix4fv(transformationMatrixLoc, 1, GL_FALSE, &transformationMatrix[0][0]); float materialShininess = (*terrain).shininess; glm::vec3 materialSpecular = (*terrain).specular; glm::vec3 materialAmbient = (*terrain).ambient; glm::vec3 materialDiffuse = (*terrain).diffuse; glm::vec3 materialEmission = (*terrain).emission; short textureAmount = (*terrain).textureIds.size(); unsigned int vramIndexLocation = (*terrain).vramIndexLocation; unsigned int vramIndexAmount = (*terrain).vramIndexAmount; void* p_vramLocation = (void*)(long(vramIndexLocation)); glUniform1f(materialShininessLoc, materialShininess); glUniform3fv(materialSpecularLoc, 1, &materialSpecular[0]); glUniform3fv(materialAmbientLoc, 1, &materialAmbient[0]); glUniform3fv(materialDiffuseLoc, 1, &materialDiffuse[0]); glUniform3fv(materialEmissionLoc, 1, &materialEmission[0]); glUniform1i(usesGlobalAmbientLoc, usesGlobalAmbientE); glUniform1i(usesLightAmbientLoc, usesLightAmbientE); glUniform1i(usesLightDiffuseLoc, usesLightDiffuseE); glUniform1i(usesLightSpecularLoc, usesLightSpecularE); glUniform1i(usesLightFalloffLoc, usesLightFalloffE); glUniform1i(textureAmountLoc, textureAmount); for (short tex = 0; tex < textureAmount; tex++) { glActiveTexture(GL_TEXTURE0 + tex); unsigned int textureAssetId = (*terrain).textureIds[tex]; GLuint diffuseMapId = (*textures)[textureAssetId].textureId; glBindTexture(GL_TEXTURE_2D, diffuseMapId); } glDrawElements(GL_TRIANGLES, vramIndexAmount, GL_UNSIGNED_INT, p_vramLocation); for (short tex = textureAmount - 1; tex >= 0; tex--) { glActiveTexture(GL_TEXTURE0 + tex); glBindTexture(GL_TEXTURE_2D, 0); } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); } //______________________________________________________________________________ //___|SETTERS AND GETTERS|______________________________________________________ void ie::RenderEngine::setShader(std::string shaderName, ShaderType type) { unsigned int assetId = (*shaderNameIdMap)[shaderName]; ShaderAsset* shader = &(*shaders)[assetId]; if (type == STATIC_SHADER) { staticShader = shader; } else if (type == TERRAIN_SHADER) { terrainShader = shader; } }
41.837607
92
0.748478
wtkooa
e24ef7fec451cdd58eef43b8989ef3fdf1413b16
1,953
cpp
C++
_site/Competitive Programming/Codeforces/1141D.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
1
2019-06-10T04:39:49.000Z
2019-06-10T04:39:49.000Z
_site/Competitive Programming/Codeforces/1141D.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
2
2021-09-27T23:34:07.000Z
2022-02-26T05:54:27.000Z
_site/Competitive Programming/Codeforces/1141D.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
3
2019-06-23T14:15:08.000Z
2019-07-09T20:40:58.000Z
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define ff first #define ss second const long double pi=3.1415926535897932384626433832; const long long mod=1e9+7; //long long primeset[5000000]={}; typedef complex<double> cd; typedef long long ll; //#define For(i,0,n) for(long long i = 0 ; i<n ;i++) cd fast_exp(cd a, long long b) { if (b == 0) return 1; cd res = fast_exp(a, b / 2); res = res * res; if (b % 2 == 1) res = res * a; return res; } long long fastexpon(long long a,long long b,long long mod) { if(b==0) return 1; long long res=fastexpon(a,b/2,mod); res=(res*res)%mod; if(b%2==1) res= (res * a)%mod; return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll n; cin>>n; string s1,s2; cin>>s1>>s2; map<char , vector<pair<int,int>>> m1; map<char , vector<pair<int,int>>> m2; for(int i=0 ; i<n; i++) { m1[s1[i]].pb(mp(i+1, 0)); m2[s2[i]].pb(mp(i+1, 0)); } map<char , int> p1; map<char,int> p2; int k=0; int q1=0 , q2=0; vector <pair<int,int> > ans; for(int i=0 ; i<26 ;i++) { char c=(char)'a'+i; int l1= m1[c].size(); int l2= m2[c].size(); for(int j=0 ;j<min(l1,l2) ;j++) { ans.pb(mp(m1[c][j].ff,m2[c][j].ff)); k++; } if(l1>l2) { for(int j=l2 ; j<l1 ;j++) { //cout<<"hey"; if(q2<m2['?'].size()) { ans.pb(mp(m1[c][j].ff,m2['?'][q2].ff)); q2++; k++; } } } if(l2>l1) { for(int j=l1 ; j<l2 ;j++) { //cout<<m1['?'].size(); if(q1<m1['?'].size()) { ans.pb(mp(m1['?'][q1].ff,m2[c][j].ff)); q1++; k++; } } } } if(q1<m1['?'].size() && q2<m2['?'].size()) { for(int i=0 ; i<min(m2['?'].size()-q2 ,m1['?'].size()-q1) ;i++) { ans.pb(mp(m1['?'][q1+i].ff,m2['?'][q2+i].ff)); k++; } } cout<<k<<'\n'; for(int i=0 ;i<ans.size();i++) { cout<<ans[i].ff<<' '<<ans[i].ss<<'\n'; } return 0; }
15.878049
65
0.5064
anujkyadav07
e2541f4a2aa9f6b5e472d33c870d78529aa5bb84
684
hpp
C++
wxdraw/component/BrushComponent.hpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/component/BrushComponent.hpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/component/BrushComponent.hpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
#pragma once #include "wxdraw/component/Component.hpp" namespace wxdraw::component { /** */ class BrushComponent : public Component<BrushComponent> { using super = Component<BrushComponent>; public: static const char* TYPE; private: BrushPtr brush_; public: BrushComponent(const NodePtr& node); BrushComponent(const BrushComponent& src, const NodePtr& node); ~BrushComponent() override = default; void onCreate() override; WXDRAW_GETTER(Brush, brush_); PropertyPtr generateProperty() override; void beginRender(Renderer& renderer, const Transform& transform) override; void endRender(Renderer& renderer, const Transform& transform) override; }; }
20.117647
76
0.75
yasuikentarow
e25580934946e1e730cd06ffeb0baf5e693da6e4
3,879
cpp
C++
example/example_table.cpp
packetzero/vsqlite
5ac54389f1d1dfc91e34adf229eb20b6e6527d26
[ "MIT" ]
null
null
null
example/example_table.cpp
packetzero/vsqlite
5ac54389f1d1dfc91e34adf229eb20b6e6527d26
[ "MIT" ]
null
null
null
example/example_table.cpp
packetzero/vsqlite
5ac54389f1d1dfc91e34adf229eb20b6e6527d26
[ "MIT" ]
null
null
null
#include <vsqlite/vsqlite.h> using namespace vsqlite; static const SPFieldDef FUSERNAME = FieldDef::alloc(TSTRING, "username"); static const SPFieldDef FUSERID = FieldDef::alloc(TUINT32, "userid"); static const SPFieldDef FUID_ALIAS = FieldDef::alloc(TNONE, "uid"); static const SPFieldDef FHOME = FieldDef::alloc(TSTRING, "home"); struct RawData { int id; std::string name; }; // pretend operating system calls to get data needed for table static void os_enum_users(std::vector<RawData> &dest); static int os_get_user_by_id(uint32_t userid, RawData &dest); static std::string os_get_user_home(uint32_t userid); // 'users' table implementation class MyUsersTable : public VirtualTable { public: MyUsersTable() { } virtual ~MyUsersTable() {} const TableDef &getTableDef() const override { static const TableDef def = { std::make_shared<SchemaId>("users"), { {FUSERID, ColOpt::INDEXED, "ID of the user", 0, { OP_EQ, OP_LIKE }} ,{FUSERNAME, 0, "username"} ,{FHOME, 0, "home"} ,{FUID_ALIAS, ColOpt::ALIAS, "", FUSERID} }, { } // table_attrs }; return def; } struct MyState { std::vector<RawData> _data; std::set<uint32_t> _wantedUserids; size_t _idx; bool _wantsHome {true}; }; /** * If index is used, prepare will be called once for each value * with the OP_EQ constraint. * For example if 'WHERE userid IN (2,7,9,11)' then prepare() will * be called 4 times. * If there are no index constraints, prepare() will be called * once, then calls to next() until it returns 1; */ void prepare(SPQueryContext context) override { // make state auto spState = std::make_shared<MyState>(); context->setUserData(spState); // gather filter constraints for (auto constraint : context->getConstraints()) { if (constraint.columnId == FUSERID && constraint.op == OP_EQ) { spState->_wantedUserids.insert(constraint.value); } } // optimize: check which columns are being requested if (context->getRequestedColumns().count(FHOME) == 0) { spState->_wantsHome = false; } // filter our data if (spState->_wantedUserids.empty()) { os_enum_users(spState->_data); } else { for (auto userid : spState->_wantedUserids) { RawData tmp; if (0 == os_get_user_by_id(userid, tmp)) { spState->_data.push_back(tmp); } } } } bool next(vsqlite::SPQueryContext context, DynMap &row) override { std::shared_ptr<MyState> spState = std::static_pointer_cast<MyState>(context->getUserData()); while (spState->_idx < spState->_data.size()) { RawData &pData = spState->_data[spState->_idx++]; row[FUSERID] = pData.id; row[FUSERNAME] = pData.name; // optimize : if 'home' column not in query, no need to call. if (spState->_wantsHome) { row[FHOME] = os_get_user_home(pData.id); } return true; } return false; } }; SPVirtualTable newMyUsersTable() { return std::make_shared<MyUsersTable>(); } // super-secret internals of fake os calls static std::vector<RawData> _gOsPrivateFakeUserData { {0, "root"} ,{500, "bob"} ,{501, "salamanca"} ,{502, "jimmy"} }; static void os_enum_users(std::vector<RawData> &dest) { for (auto &item : _gOsPrivateFakeUserData) { dest.push_back(item); } } static int os_get_user_by_id(uint32_t userid, RawData &dest) { for (size_t i = 0; i < _gOsPrivateFakeUserData.size(); i++) { if (_gOsPrivateFakeUserData[i].id == userid) { dest = _gOsPrivateFakeUserData[i]; return 0; } } return 1; } static std::string os_get_user_home(uint32_t userid) { if (userid == 0) { return "/root"; } RawData tmp; if (os_get_user_by_id(userid, tmp)) { return ""; } return "/home/" + tmp.name; }
25.188312
97
0.645269
packetzero
e25ebfa007799d6437d558442b4b51049c21340b
4,661
hpp
C++
include/LCD1D_ExtendedJones.hpp
xingularity/OpenLCDFDM
3f07f2d944e00da1ce2495f78a86d636a54fc126
[ "BSD-3-Clause" ]
8
2015-05-28T12:04:17.000Z
2022-03-16T14:22:58.000Z
include/LCD1D_ExtendedJones.hpp
xingularity/OpenLCDFDM
3f07f2d944e00da1ce2495f78a86d636a54fc126
[ "BSD-3-Clause" ]
1
2020-09-13T07:13:08.000Z
2020-09-13T07:13:08.000Z
include/LCD1D_ExtendedJones.hpp
xingularity/OpenLCDFDM
3f07f2d944e00da1ce2495f78a86d636a54fc126
[ "BSD-3-Clause" ]
2
2021-03-08T12:14:48.000Z
2021-03-08T12:14:48.000Z
/* * Copyright (C) 2015 Zong-han, Xie <icbm0926@gmail.com>. * * You may use this file under the terms of the BSD license as follows: * * 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 OpenLCDFDM 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." * */ #ifndef LCD1D_EXTENDEDJONES_HPP #define LCD1D_EXTENDEDJONES_HPP #include "LCD_ExtendedJonesBase.hpp" namespace LCD1D{ using LCDOptics::POLARTRACE; using LCDOptics::MATERIALLAYERS2X2CONT; using LCDOptics::IAngles; using LCDOptics::Angle; using LCDOptics::LIGHTSPECTRUMDATA; using LCD::DIRVEC; using LCDOptics::JONESMAT; using LCD::DOUBLEARRAY1D; using LCD::DOUBLEARRAY2D; using TRANSRESULT = DOUBLEARRAY2D; using STOKESTRACE = std::vector<Eigen::Vector3d>; using STOKESRESULT = std::vector<std::vector<std::vector<STOKESTRACE> > >; ///Main function for extended Jones matrix class ExtendedJones: public LCDOptics::ExtendedJonesBase{ public: ///For sigle wavelength calculation ExtendedJones(MATERIALLAYERS2X2CONT& _materials, const IAngles _inAngles,const double targetLambda, LIGHTSPECTRUMDATA lightSrcSpectrum_ = LIGHTSPECTRUMDATA(), bool _ifLambertian = false, bool _ifStokes=false); ///For multiwavelengths calculation ExtendedJones(MATERIALLAYERS2X2CONT& _materials, const IAngles _inAngles, const double start_lambda_, const double end_lambda_, const double step_lambda_, LIGHTSPECTRUMDATA lightSrcSpectrum_ = LIGHTSPECTRUMDATA(), bool _ifLambertian = false, bool _ifStokes=false); ///main function to calculate extended Jones. void calculateExtendedJones(); ///return the transmission results const DOUBLEARRAY2D& getTransmissions(); ///return the results of stokes values const STOKESRESULT& getStokes(); ///reset directors in materials and the states of computing components to calculate optics based on input directors. void resetLCDiretors(DIRVEC _in, bool ifInterpolateToCenter = false); void resetLCThickness(double _d); ///return if this object calculates stokes values bool isCalcStokes()const {return ifCalcStokes;} private: ///If LC layer is sandwiched between 2 polarizer layers with the theta angles of their optical axis equal to 90 or 270 degree, the stokes value can be calculated. void checkIfCalcStokes(); ///for single-wavelength calculation, no stokes calculation. void calculateOneLambdaNoStokes(int iLambda); ///for single-wavelength calculation and stokes calculation. void calculateOneLambdaWithStokes(int iLambda); ///for multi-wavelength calculation void calculateManyLambda(); void resetTransmissions(); void resetTransEachLambda(); void resetStokes(); ///results of transmissions on corresponding angles in inAngles DOUBLEARRAY2D transmissions; ///array of transmission results of every wavelength std::vector<DOUBLEARRAY2D> transEachLambda; ///store the stokes values STOKESRESULT stokes; ///if user wanna calculate Stokes bool ifCalcStokes{false}; bool ifLambertian{false}; }; }; #endif
48.051546
170
0.729457
xingularity
e26324e4d34b2e2c20e8ebe5cadb084c7584c0ed
118,994
cc
C++
third_party/ukey2/compiled_proto/proto/securegcm.pb.cc
deling-google/nearby
338faab8c902d1de4a244611d5cd9ca68a91a135
[ "Apache-2.0" ]
69
2021-10-18T00:37:29.000Z
2022-03-20T19:53:38.000Z
third_party/ukey2/compiled_proto/proto/securegcm.pb.cc
deling-google/nearby
338faab8c902d1de4a244611d5cd9ca68a91a135
[ "Apache-2.0" ]
14
2021-10-13T19:49:27.000Z
2022-03-31T22:19:13.000Z
third_party/ukey2/compiled_proto/proto/securegcm.pb.cc
deling-google/nearby
338faab8c902d1de4a244611d5cd9ca68a91a135
[ "Apache-2.0" ]
22
2021-10-20T12:36:47.000Z
2022-03-31T18:39:46.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto/securegcm.proto #include "proto/securegcm.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace securegcm { constexpr GcmDeviceInfo::GcmDeviceInfo( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : supported_software_features_() , enabled_software_features_() , user_public_key_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_model_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , locale_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , key_handle_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_os_version_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_os_release_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_os_codename_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_software_version_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_software_package_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , long_device_id_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_manufacturer_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , gcm_registration_id_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , device_master_key_hash_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , apn_registration_id_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , bluetooth_mac_address_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , enrollment_session_id_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , oauth_token_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , android_device_id_(uint64_t{0u}) , counter_(int64_t{0}) , device_os_version_code_(int64_t{0}) , device_software_version_code_(int64_t{0}) , device_display_diagonal_mils_(0) , device_authzen_version_(0) , pixel_experience_(false) , arc_plus_plus_(false) , is_screenlock_state_flaky_(false) , using_secure_screenlock_(false) , auto_unlock_screenlock_supported_(false) , auto_unlock_screenlock_enabled_(false) , bluetooth_radio_supported_(false) , bluetooth_radio_enabled_(false) , mobile_data_supported_(false) , tethering_supported_(false) , ble_radio_supported_(false) , device_type_(1) , notification_enabled_(true){} struct GcmDeviceInfoDefaultTypeInternal { constexpr GcmDeviceInfoDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~GcmDeviceInfoDefaultTypeInternal() {} union { GcmDeviceInfo _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT GcmDeviceInfoDefaultTypeInternal _GcmDeviceInfo_default_instance_; constexpr GcmMetadata::GcmMetadata( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : type_(0) , version_(0){} struct GcmMetadataDefaultTypeInternal { constexpr GcmMetadataDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~GcmMetadataDefaultTypeInternal() {} union { GcmMetadata _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT GcmMetadataDefaultTypeInternal _GcmMetadata_default_instance_; constexpr Tickle::Tickle( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : expiry_time_(uint64_t{0u}){} struct TickleDefaultTypeInternal { constexpr TickleDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~TickleDefaultTypeInternal() {} union { Tickle _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT TickleDefaultTypeInternal _Tickle_default_instance_; constexpr LoginNotificationInfo::LoginNotificationInfo( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : email_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , host_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , source_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , event_type_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , creation_time_(uint64_t{0u}){} struct LoginNotificationInfoDefaultTypeInternal { constexpr LoginNotificationInfoDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~LoginNotificationInfoDefaultTypeInternal() {} union { LoginNotificationInfo _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT LoginNotificationInfoDefaultTypeInternal _LoginNotificationInfo_default_instance_; } // namespace securegcm namespace securegcm { bool AppleDeviceDiagonalMils_IsValid(int value) { switch (value) { case 4000: case 7900: return true; default: return false; } } static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> AppleDeviceDiagonalMils_strings[2] = {}; static const char AppleDeviceDiagonalMils_names[] = "APPLE_PAD" "APPLE_PHONE"; static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry AppleDeviceDiagonalMils_entries[] = { { {AppleDeviceDiagonalMils_names + 0, 9}, 7900 }, { {AppleDeviceDiagonalMils_names + 9, 11}, 4000 }, }; static const int AppleDeviceDiagonalMils_entries_by_number[] = { 1, // 4000 -> APPLE_PHONE 0, // 7900 -> APPLE_PAD }; const std::string& AppleDeviceDiagonalMils_Name( AppleDeviceDiagonalMils value) { static const bool dummy = ::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings( AppleDeviceDiagonalMils_entries, AppleDeviceDiagonalMils_entries_by_number, 2, AppleDeviceDiagonalMils_strings); (void) dummy; int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName( AppleDeviceDiagonalMils_entries, AppleDeviceDiagonalMils_entries_by_number, 2, value); return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() : AppleDeviceDiagonalMils_strings[idx].get(); } bool AppleDeviceDiagonalMils_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, AppleDeviceDiagonalMils* value) { int int_value; bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue( AppleDeviceDiagonalMils_entries, 2, name, &int_value); if (success) { *value = static_cast<AppleDeviceDiagonalMils>(int_value); } return success; } bool DeviceType_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: return true; default: return false; } } static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> DeviceType_strings[6] = {}; static const char DeviceType_names[] = "ANDROID" "BROWSER" "CHROME" "IOS" "OSX" "UNKNOWN"; static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry DeviceType_entries[] = { { {DeviceType_names + 0, 7}, 1 }, { {DeviceType_names + 7, 7}, 4 }, { {DeviceType_names + 14, 6}, 2 }, { {DeviceType_names + 20, 3}, 3 }, { {DeviceType_names + 23, 3}, 5 }, { {DeviceType_names + 26, 7}, 0 }, }; static const int DeviceType_entries_by_number[] = { 5, // 0 -> UNKNOWN 0, // 1 -> ANDROID 2, // 2 -> CHROME 3, // 3 -> IOS 1, // 4 -> BROWSER 4, // 5 -> OSX }; const std::string& DeviceType_Name( DeviceType value) { static const bool dummy = ::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings( DeviceType_entries, DeviceType_entries_by_number, 6, DeviceType_strings); (void) dummy; int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName( DeviceType_entries, DeviceType_entries_by_number, 6, value); return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() : DeviceType_strings[idx].get(); } bool DeviceType_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, DeviceType* value) { int int_value; bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue( DeviceType_entries, 6, name, &int_value); if (success) { *value = static_cast<DeviceType>(int_value); } return success; } bool SoftwareFeature_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: return true; default: return false; } } static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> SoftwareFeature_strings[9] = {}; static const char SoftwareFeature_names[] = "BETTER_TOGETHER_CLIENT" "BETTER_TOGETHER_HOST" "EASY_UNLOCK_CLIENT" "EASY_UNLOCK_HOST" "MAGIC_TETHER_CLIENT" "MAGIC_TETHER_HOST" "SMS_CONNECT_CLIENT" "SMS_CONNECT_HOST" "UNKNOWN_FEATURE"; static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry SoftwareFeature_entries[] = { { {SoftwareFeature_names + 0, 22}, 2 }, { {SoftwareFeature_names + 22, 20}, 1 }, { {SoftwareFeature_names + 42, 18}, 4 }, { {SoftwareFeature_names + 60, 16}, 3 }, { {SoftwareFeature_names + 76, 19}, 6 }, { {SoftwareFeature_names + 95, 17}, 5 }, { {SoftwareFeature_names + 112, 18}, 8 }, { {SoftwareFeature_names + 130, 16}, 7 }, { {SoftwareFeature_names + 146, 15}, 0 }, }; static const int SoftwareFeature_entries_by_number[] = { 8, // 0 -> UNKNOWN_FEATURE 1, // 1 -> BETTER_TOGETHER_HOST 0, // 2 -> BETTER_TOGETHER_CLIENT 3, // 3 -> EASY_UNLOCK_HOST 2, // 4 -> EASY_UNLOCK_CLIENT 5, // 5 -> MAGIC_TETHER_HOST 4, // 6 -> MAGIC_TETHER_CLIENT 7, // 7 -> SMS_CONNECT_HOST 6, // 8 -> SMS_CONNECT_CLIENT }; const std::string& SoftwareFeature_Name( SoftwareFeature value) { static const bool dummy = ::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings( SoftwareFeature_entries, SoftwareFeature_entries_by_number, 9, SoftwareFeature_strings); (void) dummy; int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName( SoftwareFeature_entries, SoftwareFeature_entries_by_number, 9, value); return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() : SoftwareFeature_strings[idx].get(); } bool SoftwareFeature_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, SoftwareFeature* value) { int int_value; bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue( SoftwareFeature_entries, 9, name, &int_value); if (success) { *value = static_cast<SoftwareFeature>(int_value); } return success; } bool InvocationReason_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: return true; default: return false; } } static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> InvocationReason_strings[16] = {}; static const char InvocationReason_names[] = "REASON_ADDRESS_CHANGE" "REASON_CHANGED_ACCOUNT" "REASON_CUSTOM_KEY_INVALIDATION" "REASON_EXPIRATION" "REASON_FAILURE_RECOVERY" "REASON_FAST_PERIODIC" "REASON_FEATURE_TOGGLED" "REASON_INITIALIZATION" "REASON_MANUAL" "REASON_NEW_ACCOUNT" "REASON_PERIODIC" "REASON_PROXIMITY_PERIODIC" "REASON_SERVER_INITIATED" "REASON_SLOW_PERIODIC" "REASON_SOFTWARE_UPDATE" "REASON_UNKNOWN"; static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry InvocationReason_entries[] = { { {InvocationReason_names + 0, 21}, 11 }, { {InvocationReason_names + 21, 22}, 8 }, { {InvocationReason_names + 43, 30}, 14 }, { {InvocationReason_names + 73, 17}, 5 }, { {InvocationReason_names + 90, 23}, 6 }, { {InvocationReason_names + 113, 20}, 4 }, { {InvocationReason_names + 133, 22}, 9 }, { {InvocationReason_names + 155, 21}, 1 }, { {InvocationReason_names + 176, 13}, 13 }, { {InvocationReason_names + 189, 18}, 7 }, { {InvocationReason_names + 207, 15}, 2 }, { {InvocationReason_names + 222, 25}, 15 }, { {InvocationReason_names + 247, 23}, 10 }, { {InvocationReason_names + 270, 20}, 3 }, { {InvocationReason_names + 290, 22}, 12 }, { {InvocationReason_names + 312, 14}, 0 }, }; static const int InvocationReason_entries_by_number[] = { 15, // 0 -> REASON_UNKNOWN 7, // 1 -> REASON_INITIALIZATION 10, // 2 -> REASON_PERIODIC 13, // 3 -> REASON_SLOW_PERIODIC 5, // 4 -> REASON_FAST_PERIODIC 3, // 5 -> REASON_EXPIRATION 4, // 6 -> REASON_FAILURE_RECOVERY 9, // 7 -> REASON_NEW_ACCOUNT 1, // 8 -> REASON_CHANGED_ACCOUNT 6, // 9 -> REASON_FEATURE_TOGGLED 12, // 10 -> REASON_SERVER_INITIATED 0, // 11 -> REASON_ADDRESS_CHANGE 14, // 12 -> REASON_SOFTWARE_UPDATE 8, // 13 -> REASON_MANUAL 2, // 14 -> REASON_CUSTOM_KEY_INVALIDATION 11, // 15 -> REASON_PROXIMITY_PERIODIC }; const std::string& InvocationReason_Name( InvocationReason value) { static const bool dummy = ::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings( InvocationReason_entries, InvocationReason_entries_by_number, 16, InvocationReason_strings); (void) dummy; int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName( InvocationReason_entries, InvocationReason_entries_by_number, 16, value); return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() : InvocationReason_strings[idx].get(); } bool InvocationReason_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, InvocationReason* value) { int int_value; bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue( InvocationReason_entries, 16, name, &int_value); if (success) { *value = static_cast<InvocationReason>(int_value); } return success; } bool Type_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 10: case 11: case 12: case 13: case 14: case 15: case 101: return true; default: return false; } } static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> Type_strings[16] = {}; static const char Type_names[] = "DEVICE_INFO_UPDATE" "DEVICE_PROXIMITY_CALLBACK" "DEVICE_TO_DEVICE_MESSAGE" "DEVICE_TO_DEVICE_RESPONDER_HELLO_PAYLOAD" "ENROLLMENT" "GCMV1_IDENTITY_ASSERTION" "LOGIN_NOTIFICATION" "PROXIMITYAUTH_PAIRING" "TICKLE" "TX_CANCEL_REQUEST" "TX_PING" "TX_REPLY" "TX_REQUEST" "TX_SYNC_REQUEST" "TX_SYNC_RESPONSE" "UNLOCK_KEY_SIGNED_CHALLENGE"; static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry Type_entries[] = { { {Type_names + 0, 18}, 7 }, { {Type_names + 18, 25}, 14 }, { {Type_names + 43, 24}, 13 }, { {Type_names + 67, 40}, 12 }, { {Type_names + 107, 10}, 0 }, { {Type_names + 117, 24}, 11 }, { {Type_names + 141, 18}, 101 }, { {Type_names + 159, 21}, 10 }, { {Type_names + 180, 6}, 1 }, { {Type_names + 186, 17}, 8 }, { {Type_names + 203, 7}, 6 }, { {Type_names + 210, 8}, 3 }, { {Type_names + 218, 10}, 2 }, { {Type_names + 228, 15}, 4 }, { {Type_names + 243, 16}, 5 }, { {Type_names + 259, 27}, 15 }, }; static const int Type_entries_by_number[] = { 4, // 0 -> ENROLLMENT 8, // 1 -> TICKLE 12, // 2 -> TX_REQUEST 11, // 3 -> TX_REPLY 13, // 4 -> TX_SYNC_REQUEST 14, // 5 -> TX_SYNC_RESPONSE 10, // 6 -> TX_PING 0, // 7 -> DEVICE_INFO_UPDATE 9, // 8 -> TX_CANCEL_REQUEST 7, // 10 -> PROXIMITYAUTH_PAIRING 5, // 11 -> GCMV1_IDENTITY_ASSERTION 3, // 12 -> DEVICE_TO_DEVICE_RESPONDER_HELLO_PAYLOAD 2, // 13 -> DEVICE_TO_DEVICE_MESSAGE 1, // 14 -> DEVICE_PROXIMITY_CALLBACK 15, // 15 -> UNLOCK_KEY_SIGNED_CHALLENGE 6, // 101 -> LOGIN_NOTIFICATION }; const std::string& Type_Name( Type value) { static const bool dummy = ::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings( Type_entries, Type_entries_by_number, 16, Type_strings); (void) dummy; int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName( Type_entries, Type_entries_by_number, 16, value); return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() : Type_strings[idx].get(); } bool Type_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Type* value) { int int_value; bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue( Type_entries, 16, name, &int_value); if (success) { *value = static_cast<Type>(int_value); } return success; } // =================================================================== class GcmDeviceInfo::_Internal { public: using HasBits = decltype(std::declval<GcmDeviceInfo>()._has_bits_); static void set_has_android_device_id(HasBits* has_bits) { (*has_bits)[0] |= 131072u; } static void set_has_gcm_registration_id(HasBits* has_bits) { (*has_bits)[0] |= 2048u; } static void set_has_apn_registration_id(HasBits* has_bits) { (*has_bits)[0] |= 8192u; } static void set_has_notification_enabled(HasBits* has_bits) { (*has_bits)[1] |= 8u; } static void set_has_bluetooth_mac_address(HasBits* has_bits) { (*has_bits)[0] |= 16384u; } static void set_has_device_master_key_hash(HasBits* has_bits) { (*has_bits)[0] |= 4096u; } static void set_has_user_public_key(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_device_model(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_locale(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_key_handle(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_counter(HasBits* has_bits) { (*has_bits)[0] |= 262144u; } static void set_has_device_os_version(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_device_os_version_code(HasBits* has_bits) { (*has_bits)[0] |= 524288u; } static void set_has_device_os_release(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_device_os_codename(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static void set_has_device_software_version(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static void set_has_device_software_version_code(HasBits* has_bits) { (*has_bits)[0] |= 1048576u; } static void set_has_device_software_package(HasBits* has_bits) { (*has_bits)[0] |= 256u; } static void set_has_device_display_diagonal_mils(HasBits* has_bits) { (*has_bits)[0] |= 2097152u; } static void set_has_device_authzen_version(HasBits* has_bits) { (*has_bits)[0] |= 4194304u; } static void set_has_long_device_id(HasBits* has_bits) { (*has_bits)[0] |= 512u; } static void set_has_device_manufacturer(HasBits* has_bits) { (*has_bits)[0] |= 1024u; } static void set_has_device_type(HasBits* has_bits) { (*has_bits)[1] |= 4u; } static void set_has_using_secure_screenlock(HasBits* has_bits) { (*has_bits)[0] |= 67108864u; } static void set_has_auto_unlock_screenlock_supported(HasBits* has_bits) { (*has_bits)[0] |= 134217728u; } static void set_has_auto_unlock_screenlock_enabled(HasBits* has_bits) { (*has_bits)[0] |= 268435456u; } static void set_has_bluetooth_radio_supported(HasBits* has_bits) { (*has_bits)[0] |= 536870912u; } static void set_has_bluetooth_radio_enabled(HasBits* has_bits) { (*has_bits)[0] |= 1073741824u; } static void set_has_mobile_data_supported(HasBits* has_bits) { (*has_bits)[0] |= 2147483648u; } static void set_has_tethering_supported(HasBits* has_bits) { (*has_bits)[1] |= 1u; } static void set_has_ble_radio_supported(HasBits* has_bits) { (*has_bits)[1] |= 2u; } static void set_has_pixel_experience(HasBits* has_bits) { (*has_bits)[0] |= 8388608u; } static void set_has_arc_plus_plus(HasBits* has_bits) { (*has_bits)[0] |= 16777216u; } static void set_has_is_screenlock_state_flaky(HasBits* has_bits) { (*has_bits)[0] |= 33554432u; } static void set_has_enrollment_session_id(HasBits* has_bits) { (*has_bits)[0] |= 32768u; } static void set_has_oauth_token(HasBits* has_bits) { (*has_bits)[0] |= 65536u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; GcmDeviceInfo::GcmDeviceInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena, is_message_owned), supported_software_features_(arena), enabled_software_features_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:securegcm.GcmDeviceInfo) } GcmDeviceInfo::GcmDeviceInfo(const GcmDeviceInfo& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_), supported_software_features_(from.supported_software_features_), enabled_software_features_(from.enabled_software_features_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); user_public_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING user_public_key_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_user_public_key()) { user_public_key_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_user_public_key(), GetArenaForAllocation()); } device_model_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_model_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_model()) { device_model_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_model(), GetArenaForAllocation()); } locale_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING locale_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_locale()) { locale_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_locale(), GetArenaForAllocation()); } key_handle_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING key_handle_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_key_handle()) { key_handle_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_key_handle(), GetArenaForAllocation()); } device_os_version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_os_version()) { device_os_version_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_os_version(), GetArenaForAllocation()); } device_os_release_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_release_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_os_release()) { device_os_release_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_os_release(), GetArenaForAllocation()); } device_os_codename_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_codename_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_os_codename()) { device_os_codename_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_os_codename(), GetArenaForAllocation()); } device_software_version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_software_version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_software_version()) { device_software_version_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_software_version(), GetArenaForAllocation()); } device_software_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_software_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_software_package()) { device_software_package_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_software_package(), GetArenaForAllocation()); } long_device_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING long_device_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_long_device_id()) { long_device_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_long_device_id(), GetArenaForAllocation()); } device_manufacturer_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_manufacturer_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_manufacturer()) { device_manufacturer_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_manufacturer(), GetArenaForAllocation()); } gcm_registration_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING gcm_registration_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_gcm_registration_id()) { gcm_registration_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_gcm_registration_id(), GetArenaForAllocation()); } device_master_key_hash_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_master_key_hash_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_device_master_key_hash()) { device_master_key_hash_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_device_master_key_hash(), GetArenaForAllocation()); } apn_registration_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING apn_registration_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_apn_registration_id()) { apn_registration_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_apn_registration_id(), GetArenaForAllocation()); } bluetooth_mac_address_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING bluetooth_mac_address_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_bluetooth_mac_address()) { bluetooth_mac_address_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_bluetooth_mac_address(), GetArenaForAllocation()); } enrollment_session_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING enrollment_session_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_enrollment_session_id()) { enrollment_session_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_enrollment_session_id(), GetArenaForAllocation()); } oauth_token_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING oauth_token_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_oauth_token()) { oauth_token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_oauth_token(), GetArenaForAllocation()); } ::memcpy(&android_device_id_, &from.android_device_id_, static_cast<size_t>(reinterpret_cast<char*>(&notification_enabled_) - reinterpret_cast<char*>(&android_device_id_)) + sizeof(notification_enabled_)); // @@protoc_insertion_point(copy_constructor:securegcm.GcmDeviceInfo) } inline void GcmDeviceInfo::SharedCtor() { user_public_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING user_public_key_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_model_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_model_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING locale_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING locale_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING key_handle_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING key_handle_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_release_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_release_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_codename_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_os_codename_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_software_version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_software_version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_software_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_software_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING long_device_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING long_device_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_manufacturer_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_manufacturer_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING gcm_registration_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING gcm_registration_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING device_master_key_hash_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING device_master_key_hash_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING apn_registration_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING apn_registration_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING bluetooth_mac_address_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING bluetooth_mac_address_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING enrollment_session_id_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING enrollment_session_id_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING oauth_token_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING oauth_token_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&android_device_id_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&ble_radio_supported_) - reinterpret_cast<char*>(&android_device_id_)) + sizeof(ble_radio_supported_)); device_type_ = 1; notification_enabled_ = true; } GcmDeviceInfo::~GcmDeviceInfo() { // @@protoc_insertion_point(destructor:securegcm.GcmDeviceInfo) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<std::string>(); } inline void GcmDeviceInfo::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); user_public_key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_model_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); locale_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); key_handle_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_os_version_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_os_release_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_os_codename_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_software_version_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_software_package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); long_device_id_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_manufacturer_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); gcm_registration_id_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); device_master_key_hash_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); apn_registration_id_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); bluetooth_mac_address_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); enrollment_session_id_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); oauth_token_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void GcmDeviceInfo::ArenaDtor(void* object) { GcmDeviceInfo* _this = reinterpret_cast< GcmDeviceInfo* >(object); (void)_this; } void GcmDeviceInfo::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void GcmDeviceInfo::SetCachedSize(int size) const { _cached_size_.Set(size); } void GcmDeviceInfo::Clear() { // @@protoc_insertion_point(message_clear_start:securegcm.GcmDeviceInfo) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; supported_software_features_.Clear(); enabled_software_features_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { user_public_key_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { device_model_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { locale_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { key_handle_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { device_os_version_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { device_os_release_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000040u) { device_os_codename_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000080u) { device_software_version_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 0x0000ff00u) { if (cached_has_bits & 0x00000100u) { device_software_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000200u) { long_device_id_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000400u) { device_manufacturer_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000800u) { gcm_registration_id_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00001000u) { device_master_key_hash_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00002000u) { apn_registration_id_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00004000u) { bluetooth_mac_address_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00008000u) { enrollment_session_id_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 0x00010000u) { oauth_token_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00fe0000u) { ::memset(&android_device_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&pixel_experience_) - reinterpret_cast<char*>(&android_device_id_)) + sizeof(pixel_experience_)); } if (cached_has_bits & 0xff000000u) { ::memset(&arc_plus_plus_, 0, static_cast<size_t>( reinterpret_cast<char*>(&mobile_data_supported_) - reinterpret_cast<char*>(&arc_plus_plus_)) + sizeof(mobile_data_supported_)); } cached_has_bits = _has_bits_[1]; if (cached_has_bits & 0x0000000fu) { ::memset(&tethering_supported_, 0, static_cast<size_t>( reinterpret_cast<char*>(&ble_radio_supported_) - reinterpret_cast<char*>(&tethering_supported_)) + sizeof(ble_radio_supported_)); device_type_ = 1; notification_enabled_ = true; } _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* GcmDeviceInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional fixed64 android_device_id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 9)) { _Internal::set_has_android_device_id(&_has_bits_); android_device_id_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<uint64_t>(ptr); ptr += sizeof(uint64_t); } else goto handle_unusual; continue; // required bytes user_public_key = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 34)) { auto str = _internal_mutable_user_public_key(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_model = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 58)) { auto str = _internal_mutable_device_model(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string locale = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 66)) { auto str = _internal_mutable_locale(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional bytes key_handle = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 74)) { auto str = _internal_mutable_key_handle(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int64 counter = 12 [default = 0]; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 96)) { _Internal::set_has_counter(&_has_bits_); counter_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_os_version = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 106)) { auto str = _internal_mutable_device_os_version(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int64 device_os_version_code = 14; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 112)) { _Internal::set_has_device_os_version_code(&_has_bits_); device_os_version_code_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_os_release = 15; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 122)) { auto str = _internal_mutable_device_os_release(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_os_codename = 16; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 130)) { auto str = _internal_mutable_device_os_codename(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_software_version = 17; case 17: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 138)) { auto str = _internal_mutable_device_software_version(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int64 device_software_version_code = 18; case 18: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 144)) { _Internal::set_has_device_software_version_code(&_has_bits_); device_software_version_code_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_software_package = 19; case 19: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 154)) { auto str = _internal_mutable_device_software_package(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 device_display_diagonal_mils = 22; case 22: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 176)) { _Internal::set_has_device_display_diagonal_mils(&_has_bits_); device_display_diagonal_mils_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 device_authzen_version = 24; case 24: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 192)) { _Internal::set_has_device_authzen_version(&_has_bits_); device_authzen_version_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bytes long_device_id = 29; case 29: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 234)) { auto str = _internal_mutable_long_device_id(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string device_manufacturer = 31; case 31: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 250)) { auto str = _internal_mutable_device_manufacturer(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional .securegcm.DeviceType device_type = 32 [default = ANDROID]; case 32: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 0)) { uint64_t val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); if (PROTOBUF_PREDICT_TRUE(::securegcm::DeviceType_IsValid(val))) { _internal_set_device_type(static_cast<::securegcm::DeviceType>(val)); } else { ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(32, val, mutable_unknown_fields()); } } else goto handle_unusual; continue; // optional bytes gcm_registration_id = 102; case 102: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 50)) { auto str = _internal_mutable_gcm_registration_id(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional bytes device_master_key_hash = 103; case 103: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 58)) { auto str = _internal_mutable_device_master_key_hash(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional bytes apn_registration_id = 202; case 202: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 82)) { auto str = _internal_mutable_apn_registration_id(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional bool notification_enabled = 203 [default = true]; case 203: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 88)) { _Internal::set_has_notification_enabled(&_has_bits_); notification_enabled_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional string bluetooth_mac_address = 302; case 302: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 114)) { auto str = _internal_mutable_bluetooth_mac_address(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional bool using_secure_screenlock = 400 [default = false]; case 400: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 128)) { _Internal::set_has_using_secure_screenlock(&_has_bits_); using_secure_screenlock_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool auto_unlock_screenlock_supported = 401 [default = false]; case 401: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 136)) { _Internal::set_has_auto_unlock_screenlock_supported(&_has_bits_); auto_unlock_screenlock_supported_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool auto_unlock_screenlock_enabled = 402 [default = false]; case 402: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 144)) { _Internal::set_has_auto_unlock_screenlock_enabled(&_has_bits_); auto_unlock_screenlock_enabled_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool bluetooth_radio_supported = 403 [default = false]; case 403: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 152)) { _Internal::set_has_bluetooth_radio_supported(&_has_bits_); bluetooth_radio_supported_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool bluetooth_radio_enabled = 404 [default = false]; case 404: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 160)) { _Internal::set_has_bluetooth_radio_enabled(&_has_bits_); bluetooth_radio_enabled_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool mobile_data_supported = 405 [default = false]; case 405: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 168)) { _Internal::set_has_mobile_data_supported(&_has_bits_); mobile_data_supported_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool tethering_supported = 406 [default = false]; case 406: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 176)) { _Internal::set_has_tethering_supported(&_has_bits_); tethering_supported_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool ble_radio_supported = 407 [default = false]; case 407: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 184)) { _Internal::set_has_ble_radio_supported(&_has_bits_); ble_radio_supported_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool pixel_experience = 408 [default = false]; case 408: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 192)) { _Internal::set_has_pixel_experience(&_has_bits_); pixel_experience_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool arc_plus_plus = 409 [default = false]; case 409: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 200)) { _Internal::set_has_arc_plus_plus(&_has_bits_); arc_plus_plus_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool is_screenlock_state_flaky = 410 [default = false]; case 410: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 208)) { _Internal::set_has_is_screenlock_state_flaky(&_has_bits_); is_screenlock_state_flaky_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .securegcm.SoftwareFeature supported_software_features = 411; case 411: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 216)) { ptr -= 2; do { ptr += 2; uint64_t val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); if (PROTOBUF_PREDICT_TRUE(::securegcm::SoftwareFeature_IsValid(val))) { _internal_add_supported_software_features(static_cast<::securegcm::SoftwareFeature>(val)); } else { ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(411, val, mutable_unknown_fields()); } if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<3288>(ptr)); } else if (static_cast<uint8_t>(tag) == 218) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedEnumParser<std::string>(_internal_mutable_supported_software_features(), ptr, ctx, ::securegcm::SoftwareFeature_IsValid, &_internal_metadata_, 411); CHK_(ptr); } else goto handle_unusual; continue; // repeated .securegcm.SoftwareFeature enabled_software_features = 412; case 412: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 224)) { ptr -= 2; do { ptr += 2; uint64_t val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); if (PROTOBUF_PREDICT_TRUE(::securegcm::SoftwareFeature_IsValid(val))) { _internal_add_enabled_software_features(static_cast<::securegcm::SoftwareFeature>(val)); } else { ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(412, val, mutable_unknown_fields()); } if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<3296>(ptr)); } else if (static_cast<uint8_t>(tag) == 226) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedEnumParser<std::string>(_internal_mutable_enabled_software_features(), ptr, ctx, ::securegcm::SoftwareFeature_IsValid, &_internal_metadata_, 412); CHK_(ptr); } else goto handle_unusual; continue; // optional bytes enrollment_session_id = 1000; case 1000: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 66)) { auto str = _internal_mutable_enrollment_session_id(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string oauth_token = 1001; case 1001: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 74)) { auto str = _internal_mutable_oauth_token(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* GcmDeviceInfo::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:securegcm.GcmDeviceInfo) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional fixed64 android_device_id = 1; if (cached_has_bits & 0x00020000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFixed64ToArray(1, this->_internal_android_device_id(), target); } // required bytes user_public_key = 4; if (cached_has_bits & 0x00000001u) { target = stream->WriteBytesMaybeAliased( 4, this->_internal_user_public_key(), target); } // optional string device_model = 7; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 7, this->_internal_device_model(), target); } // optional string locale = 8; if (cached_has_bits & 0x00000004u) { target = stream->WriteStringMaybeAliased( 8, this->_internal_locale(), target); } // optional bytes key_handle = 9; if (cached_has_bits & 0x00000008u) { target = stream->WriteBytesMaybeAliased( 9, this->_internal_key_handle(), target); } // optional int64 counter = 12 [default = 0]; if (cached_has_bits & 0x00040000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(12, this->_internal_counter(), target); } // optional string device_os_version = 13; if (cached_has_bits & 0x00000010u) { target = stream->WriteStringMaybeAliased( 13, this->_internal_device_os_version(), target); } // optional int64 device_os_version_code = 14; if (cached_has_bits & 0x00080000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(14, this->_internal_device_os_version_code(), target); } // optional string device_os_release = 15; if (cached_has_bits & 0x00000020u) { target = stream->WriteStringMaybeAliased( 15, this->_internal_device_os_release(), target); } // optional string device_os_codename = 16; if (cached_has_bits & 0x00000040u) { target = stream->WriteStringMaybeAliased( 16, this->_internal_device_os_codename(), target); } // optional string device_software_version = 17; if (cached_has_bits & 0x00000080u) { target = stream->WriteStringMaybeAliased( 17, this->_internal_device_software_version(), target); } // optional int64 device_software_version_code = 18; if (cached_has_bits & 0x00100000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(18, this->_internal_device_software_version_code(), target); } // optional string device_software_package = 19; if (cached_has_bits & 0x00000100u) { target = stream->WriteStringMaybeAliased( 19, this->_internal_device_software_package(), target); } // optional int32 device_display_diagonal_mils = 22; if (cached_has_bits & 0x00200000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(22, this->_internal_device_display_diagonal_mils(), target); } // optional int32 device_authzen_version = 24; if (cached_has_bits & 0x00400000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(24, this->_internal_device_authzen_version(), target); } // optional bytes long_device_id = 29; if (cached_has_bits & 0x00000200u) { target = stream->WriteBytesMaybeAliased( 29, this->_internal_long_device_id(), target); } // optional string device_manufacturer = 31; if (cached_has_bits & 0x00000400u) { target = stream->WriteStringMaybeAliased( 31, this->_internal_device_manufacturer(), target); } cached_has_bits = _has_bits_[1]; // optional .securegcm.DeviceType device_type = 32 [default = ANDROID]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 32, this->_internal_device_type(), target); } cached_has_bits = _has_bits_[0]; // optional bytes gcm_registration_id = 102; if (cached_has_bits & 0x00000800u) { target = stream->WriteBytesMaybeAliased( 102, this->_internal_gcm_registration_id(), target); } // optional bytes device_master_key_hash = 103; if (cached_has_bits & 0x00001000u) { target = stream->WriteBytesMaybeAliased( 103, this->_internal_device_master_key_hash(), target); } // optional bytes apn_registration_id = 202; if (cached_has_bits & 0x00002000u) { target = stream->WriteBytesMaybeAliased( 202, this->_internal_apn_registration_id(), target); } cached_has_bits = _has_bits_[1]; // optional bool notification_enabled = 203 [default = true]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(203, this->_internal_notification_enabled(), target); } cached_has_bits = _has_bits_[0]; // optional string bluetooth_mac_address = 302; if (cached_has_bits & 0x00004000u) { target = stream->WriteStringMaybeAliased( 302, this->_internal_bluetooth_mac_address(), target); } // optional bool using_secure_screenlock = 400 [default = false]; if (cached_has_bits & 0x04000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(400, this->_internal_using_secure_screenlock(), target); } // optional bool auto_unlock_screenlock_supported = 401 [default = false]; if (cached_has_bits & 0x08000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(401, this->_internal_auto_unlock_screenlock_supported(), target); } // optional bool auto_unlock_screenlock_enabled = 402 [default = false]; if (cached_has_bits & 0x10000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(402, this->_internal_auto_unlock_screenlock_enabled(), target); } // optional bool bluetooth_radio_supported = 403 [default = false]; if (cached_has_bits & 0x20000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(403, this->_internal_bluetooth_radio_supported(), target); } // optional bool bluetooth_radio_enabled = 404 [default = false]; if (cached_has_bits & 0x40000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(404, this->_internal_bluetooth_radio_enabled(), target); } // optional bool mobile_data_supported = 405 [default = false]; if (cached_has_bits & 0x80000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(405, this->_internal_mobile_data_supported(), target); } cached_has_bits = _has_bits_[1]; // optional bool tethering_supported = 406 [default = false]; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(406, this->_internal_tethering_supported(), target); } // optional bool ble_radio_supported = 407 [default = false]; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(407, this->_internal_ble_radio_supported(), target); } cached_has_bits = _has_bits_[0]; // optional bool pixel_experience = 408 [default = false]; if (cached_has_bits & 0x00800000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(408, this->_internal_pixel_experience(), target); } // optional bool arc_plus_plus = 409 [default = false]; if (cached_has_bits & 0x01000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(409, this->_internal_arc_plus_plus(), target); } // optional bool is_screenlock_state_flaky = 410 [default = false]; if (cached_has_bits & 0x02000000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(410, this->_internal_is_screenlock_state_flaky(), target); } // repeated .securegcm.SoftwareFeature supported_software_features = 411; for (int i = 0, n = this->_internal_supported_software_features_size(); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 411, this->_internal_supported_software_features(i), target); } // repeated .securegcm.SoftwareFeature enabled_software_features = 412; for (int i = 0, n = this->_internal_enabled_software_features_size(); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 412, this->_internal_enabled_software_features(i), target); } // optional bytes enrollment_session_id = 1000; if (cached_has_bits & 0x00008000u) { target = stream->WriteBytesMaybeAliased( 1000, this->_internal_enrollment_session_id(), target); } // optional string oauth_token = 1001; if (cached_has_bits & 0x00010000u) { target = stream->WriteStringMaybeAliased( 1001, this->_internal_oauth_token(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:securegcm.GcmDeviceInfo) return target; } size_t GcmDeviceInfo::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:securegcm.GcmDeviceInfo) size_t total_size = 0; // required bytes user_public_key = 4; if (_internal_has_user_public_key()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_user_public_key()); } uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .securegcm.SoftwareFeature supported_software_features = 411; { size_t data_size = 0; unsigned int count = static_cast<unsigned int>(this->_internal_supported_software_features_size());for (unsigned int i = 0; i < count; i++) { data_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize( this->_internal_supported_software_features(static_cast<int>(i))); } total_size += (2UL * count) + data_size; } // repeated .securegcm.SoftwareFeature enabled_software_features = 412; { size_t data_size = 0; unsigned int count = static_cast<unsigned int>(this->_internal_enabled_software_features_size());for (unsigned int i = 0; i < count; i++) { data_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize( this->_internal_enabled_software_features(static_cast<int>(i))); } total_size += (2UL * count) + data_size; } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000feu) { // optional string device_model = 7; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_model()); } // optional string locale = 8; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_locale()); } // optional bytes key_handle = 9; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_key_handle()); } // optional string device_os_version = 13; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_os_version()); } // optional string device_os_release = 15; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_os_release()); } // optional string device_os_codename = 16; if (cached_has_bits & 0x00000040u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_os_codename()); } // optional string device_software_version = 17; if (cached_has_bits & 0x00000080u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_software_version()); } } if (cached_has_bits & 0x0000ff00u) { // optional string device_software_package = 19; if (cached_has_bits & 0x00000100u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_software_package()); } // optional bytes long_device_id = 29; if (cached_has_bits & 0x00000200u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_long_device_id()); } // optional string device_manufacturer = 31; if (cached_has_bits & 0x00000400u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_device_manufacturer()); } // optional bytes gcm_registration_id = 102; if (cached_has_bits & 0x00000800u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_gcm_registration_id()); } // optional bytes device_master_key_hash = 103; if (cached_has_bits & 0x00001000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_device_master_key_hash()); } // optional bytes apn_registration_id = 202; if (cached_has_bits & 0x00002000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_apn_registration_id()); } // optional string bluetooth_mac_address = 302; if (cached_has_bits & 0x00004000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_bluetooth_mac_address()); } // optional bytes enrollment_session_id = 1000; if (cached_has_bits & 0x00008000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_enrollment_session_id()); } } if (cached_has_bits & 0x00ff0000u) { // optional string oauth_token = 1001; if (cached_has_bits & 0x00010000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_oauth_token()); } // optional fixed64 android_device_id = 1; if (cached_has_bits & 0x00020000u) { total_size += 1 + 8; } // optional int64 counter = 12 [default = 0]; if (cached_has_bits & 0x00040000u) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64SizePlusOne(this->_internal_counter()); } // optional int64 device_os_version_code = 14; if (cached_has_bits & 0x00080000u) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64SizePlusOne(this->_internal_device_os_version_code()); } // optional int64 device_software_version_code = 18; if (cached_has_bits & 0x00100000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->_internal_device_software_version_code()); } // optional int32 device_display_diagonal_mils = 22; if (cached_has_bits & 0x00200000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_device_display_diagonal_mils()); } // optional int32 device_authzen_version = 24; if (cached_has_bits & 0x00400000u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_device_authzen_version()); } // optional bool pixel_experience = 408 [default = false]; if (cached_has_bits & 0x00800000u) { total_size += 2 + 1; } } if (cached_has_bits & 0xff000000u) { // optional bool arc_plus_plus = 409 [default = false]; if (cached_has_bits & 0x01000000u) { total_size += 2 + 1; } // optional bool is_screenlock_state_flaky = 410 [default = false]; if (cached_has_bits & 0x02000000u) { total_size += 2 + 1; } // optional bool using_secure_screenlock = 400 [default = false]; if (cached_has_bits & 0x04000000u) { total_size += 2 + 1; } // optional bool auto_unlock_screenlock_supported = 401 [default = false]; if (cached_has_bits & 0x08000000u) { total_size += 2 + 1; } // optional bool auto_unlock_screenlock_enabled = 402 [default = false]; if (cached_has_bits & 0x10000000u) { total_size += 2 + 1; } // optional bool bluetooth_radio_supported = 403 [default = false]; if (cached_has_bits & 0x20000000u) { total_size += 2 + 1; } // optional bool bluetooth_radio_enabled = 404 [default = false]; if (cached_has_bits & 0x40000000u) { total_size += 2 + 1; } // optional bool mobile_data_supported = 405 [default = false]; if (cached_has_bits & 0x80000000u) { total_size += 2 + 1; } } cached_has_bits = _has_bits_[1]; if (cached_has_bits & 0x0000000fu) { // optional bool tethering_supported = 406 [default = false]; if (cached_has_bits & 0x00000001u) { total_size += 2 + 1; } // optional bool ble_radio_supported = 407 [default = false]; if (cached_has_bits & 0x00000002u) { total_size += 2 + 1; } // optional .securegcm.DeviceType device_type = 32 [default = ANDROID]; if (cached_has_bits & 0x00000004u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_device_type()); } // optional bool notification_enabled = 203 [default = true]; if (cached_has_bits & 0x00000008u) { total_size += 2 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void GcmDeviceInfo::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const GcmDeviceInfo*>( &from)); } void GcmDeviceInfo::MergeFrom(const GcmDeviceInfo& from) { // @@protoc_insertion_point(class_specific_merge_from_start:securegcm.GcmDeviceInfo) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; supported_software_features_.MergeFrom(from.supported_software_features_); enabled_software_features_.MergeFrom(from.enabled_software_features_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_user_public_key(from._internal_user_public_key()); } if (cached_has_bits & 0x00000002u) { _internal_set_device_model(from._internal_device_model()); } if (cached_has_bits & 0x00000004u) { _internal_set_locale(from._internal_locale()); } if (cached_has_bits & 0x00000008u) { _internal_set_key_handle(from._internal_key_handle()); } if (cached_has_bits & 0x00000010u) { _internal_set_device_os_version(from._internal_device_os_version()); } if (cached_has_bits & 0x00000020u) { _internal_set_device_os_release(from._internal_device_os_release()); } if (cached_has_bits & 0x00000040u) { _internal_set_device_os_codename(from._internal_device_os_codename()); } if (cached_has_bits & 0x00000080u) { _internal_set_device_software_version(from._internal_device_software_version()); } } if (cached_has_bits & 0x0000ff00u) { if (cached_has_bits & 0x00000100u) { _internal_set_device_software_package(from._internal_device_software_package()); } if (cached_has_bits & 0x00000200u) { _internal_set_long_device_id(from._internal_long_device_id()); } if (cached_has_bits & 0x00000400u) { _internal_set_device_manufacturer(from._internal_device_manufacturer()); } if (cached_has_bits & 0x00000800u) { _internal_set_gcm_registration_id(from._internal_gcm_registration_id()); } if (cached_has_bits & 0x00001000u) { _internal_set_device_master_key_hash(from._internal_device_master_key_hash()); } if (cached_has_bits & 0x00002000u) { _internal_set_apn_registration_id(from._internal_apn_registration_id()); } if (cached_has_bits & 0x00004000u) { _internal_set_bluetooth_mac_address(from._internal_bluetooth_mac_address()); } if (cached_has_bits & 0x00008000u) { _internal_set_enrollment_session_id(from._internal_enrollment_session_id()); } } if (cached_has_bits & 0x00ff0000u) { if (cached_has_bits & 0x00010000u) { _internal_set_oauth_token(from._internal_oauth_token()); } if (cached_has_bits & 0x00020000u) { android_device_id_ = from.android_device_id_; } if (cached_has_bits & 0x00040000u) { counter_ = from.counter_; } if (cached_has_bits & 0x00080000u) { device_os_version_code_ = from.device_os_version_code_; } if (cached_has_bits & 0x00100000u) { device_software_version_code_ = from.device_software_version_code_; } if (cached_has_bits & 0x00200000u) { device_display_diagonal_mils_ = from.device_display_diagonal_mils_; } if (cached_has_bits & 0x00400000u) { device_authzen_version_ = from.device_authzen_version_; } if (cached_has_bits & 0x00800000u) { pixel_experience_ = from.pixel_experience_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0xff000000u) { if (cached_has_bits & 0x01000000u) { arc_plus_plus_ = from.arc_plus_plus_; } if (cached_has_bits & 0x02000000u) { is_screenlock_state_flaky_ = from.is_screenlock_state_flaky_; } if (cached_has_bits & 0x04000000u) { using_secure_screenlock_ = from.using_secure_screenlock_; } if (cached_has_bits & 0x08000000u) { auto_unlock_screenlock_supported_ = from.auto_unlock_screenlock_supported_; } if (cached_has_bits & 0x10000000u) { auto_unlock_screenlock_enabled_ = from.auto_unlock_screenlock_enabled_; } if (cached_has_bits & 0x20000000u) { bluetooth_radio_supported_ = from.bluetooth_radio_supported_; } if (cached_has_bits & 0x40000000u) { bluetooth_radio_enabled_ = from.bluetooth_radio_enabled_; } if (cached_has_bits & 0x80000000u) { mobile_data_supported_ = from.mobile_data_supported_; } _has_bits_[0] |= cached_has_bits; } cached_has_bits = from._has_bits_[1]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { tethering_supported_ = from.tethering_supported_; } if (cached_has_bits & 0x00000002u) { ble_radio_supported_ = from.ble_radio_supported_; } if (cached_has_bits & 0x00000004u) { device_type_ = from.device_type_; } if (cached_has_bits & 0x00000008u) { notification_enabled_ = from.notification_enabled_; } _has_bits_[1] |= cached_has_bits; } _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); } void GcmDeviceInfo::CopyFrom(const GcmDeviceInfo& from) { // @@protoc_insertion_point(class_specific_copy_from_start:securegcm.GcmDeviceInfo) if (&from == this) return; Clear(); MergeFrom(from); } bool GcmDeviceInfo::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void GcmDeviceInfo::InternalSwap(GcmDeviceInfo* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); swap(_has_bits_[1], other->_has_bits_[1]); supported_software_features_.InternalSwap(&other->supported_software_features_); enabled_software_features_.InternalSwap(&other->enabled_software_features_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &user_public_key_, lhs_arena, &other->user_public_key_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_model_, lhs_arena, &other->device_model_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &locale_, lhs_arena, &other->locale_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &key_handle_, lhs_arena, &other->key_handle_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_os_version_, lhs_arena, &other->device_os_version_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_os_release_, lhs_arena, &other->device_os_release_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_os_codename_, lhs_arena, &other->device_os_codename_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_software_version_, lhs_arena, &other->device_software_version_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_software_package_, lhs_arena, &other->device_software_package_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &long_device_id_, lhs_arena, &other->long_device_id_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_manufacturer_, lhs_arena, &other->device_manufacturer_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &gcm_registration_id_, lhs_arena, &other->gcm_registration_id_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &device_master_key_hash_, lhs_arena, &other->device_master_key_hash_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &apn_registration_id_, lhs_arena, &other->apn_registration_id_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &bluetooth_mac_address_, lhs_arena, &other->bluetooth_mac_address_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &enrollment_session_id_, lhs_arena, &other->enrollment_session_id_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &oauth_token_, lhs_arena, &other->oauth_token_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(GcmDeviceInfo, ble_radio_supported_) + sizeof(GcmDeviceInfo::ble_radio_supported_) - PROTOBUF_FIELD_OFFSET(GcmDeviceInfo, android_device_id_)>( reinterpret_cast<char*>(&android_device_id_), reinterpret_cast<char*>(&other->android_device_id_)); swap(device_type_, other->device_type_); swap(notification_enabled_, other->notification_enabled_); } std::string GcmDeviceInfo::GetTypeName() const { return "securegcm.GcmDeviceInfo"; } // =================================================================== class GcmMetadata::_Internal { public: using HasBits = decltype(std::declval<GcmMetadata>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_version(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; GcmMetadata::GcmMetadata(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena, is_message_owned) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:securegcm.GcmMetadata) } GcmMetadata::GcmMetadata(const GcmMetadata& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&version_) - reinterpret_cast<char*>(&type_)) + sizeof(version_)); // @@protoc_insertion_point(copy_constructor:securegcm.GcmMetadata) } inline void GcmMetadata::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&version_) - reinterpret_cast<char*>(&type_)) + sizeof(version_)); } GcmMetadata::~GcmMetadata() { // @@protoc_insertion_point(destructor:securegcm.GcmMetadata) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<std::string>(); } inline void GcmMetadata::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void GcmMetadata::ArenaDtor(void* object) { GcmMetadata* _this = reinterpret_cast< GcmMetadata* >(object); (void)_this; } void GcmMetadata::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void GcmMetadata::SetCachedSize(int size) const { _cached_size_.Set(size); } void GcmMetadata::Clear() { // @@protoc_insertion_point(message_clear_start:securegcm.GcmMetadata) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&version_) - reinterpret_cast<char*>(&type_)) + sizeof(version_)); } _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* GcmMetadata::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required .securegcm.Type type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { uint64_t val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); if (PROTOBUF_PREDICT_TRUE(::securegcm::Type_IsValid(val))) { _internal_set_type(static_cast<::securegcm::Type>(val)); } else { ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(1, val, mutable_unknown_fields()); } } else goto handle_unusual; continue; // optional int32 version = 2 [default = 0]; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_version(&has_bits); version_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* GcmMetadata::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:securegcm.GcmMetadata) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required .securegcm.Type type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 1, this->_internal_type(), target); } // optional int32 version = 2 [default = 0]; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(2, this->_internal_version(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:securegcm.GcmMetadata) return target; } size_t GcmMetadata::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:securegcm.GcmMetadata) size_t total_size = 0; // required .securegcm.Type type = 1; if (_internal_has_type()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_type()); } uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional int32 version = 2 [default = 0]; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000002u) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32SizePlusOne(this->_internal_version()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void GcmMetadata::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const GcmMetadata*>( &from)); } void GcmMetadata::MergeFrom(const GcmMetadata& from) { // @@protoc_insertion_point(class_specific_merge_from_start:securegcm.GcmMetadata) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { type_ = from.type_; } if (cached_has_bits & 0x00000002u) { version_ = from.version_; } _has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); } void GcmMetadata::CopyFrom(const GcmMetadata& from) { // @@protoc_insertion_point(class_specific_copy_from_start:securegcm.GcmMetadata) if (&from == this) return; Clear(); MergeFrom(from); } bool GcmMetadata::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void GcmMetadata::InternalSwap(GcmMetadata* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(GcmMetadata, version_) + sizeof(GcmMetadata::version_) - PROTOBUF_FIELD_OFFSET(GcmMetadata, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } std::string GcmMetadata::GetTypeName() const { return "securegcm.GcmMetadata"; } // =================================================================== class Tickle::_Internal { public: using HasBits = decltype(std::declval<Tickle>()._has_bits_); static void set_has_expiry_time(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; Tickle::Tickle(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena, is_message_owned) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:securegcm.Tickle) } Tickle::Tickle(const Tickle& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); expiry_time_ = from.expiry_time_; // @@protoc_insertion_point(copy_constructor:securegcm.Tickle) } inline void Tickle::SharedCtor() { expiry_time_ = uint64_t{0u}; } Tickle::~Tickle() { // @@protoc_insertion_point(destructor:securegcm.Tickle) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<std::string>(); } inline void Tickle::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void Tickle::ArenaDtor(void* object) { Tickle* _this = reinterpret_cast< Tickle* >(object); (void)_this; } void Tickle::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Tickle::SetCachedSize(int size) const { _cached_size_.Set(size); } void Tickle::Clear() { // @@protoc_insertion_point(message_clear_start:securegcm.Tickle) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; expiry_time_ = uint64_t{0u}; _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* Tickle::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional fixed64 expiry_time = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 9)) { _Internal::set_has_expiry_time(&has_bits); expiry_time_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<uint64_t>(ptr); ptr += sizeof(uint64_t); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* Tickle::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:securegcm.Tickle) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional fixed64 expiry_time = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFixed64ToArray(1, this->_internal_expiry_time(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:securegcm.Tickle) return target; } size_t Tickle::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:securegcm.Tickle) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional fixed64 expiry_time = 1; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + 8; } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Tickle::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const Tickle*>( &from)); } void Tickle::MergeFrom(const Tickle& from) { // @@protoc_insertion_point(class_specific_merge_from_start:securegcm.Tickle) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_expiry_time()) { _internal_set_expiry_time(from._internal_expiry_time()); } _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); } void Tickle::CopyFrom(const Tickle& from) { // @@protoc_insertion_point(class_specific_copy_from_start:securegcm.Tickle) if (&from == this) return; Clear(); MergeFrom(from); } bool Tickle::IsInitialized() const { return true; } void Tickle::InternalSwap(Tickle* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); swap(expiry_time_, other->expiry_time_); } std::string Tickle::GetTypeName() const { return "securegcm.Tickle"; } // =================================================================== class LoginNotificationInfo::_Internal { public: using HasBits = decltype(std::declval<LoginNotificationInfo>()._has_bits_); static void set_has_creation_time(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_email(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_host(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_source(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_event_type(HasBits* has_bits) { (*has_bits)[0] |= 8u; } }; LoginNotificationInfo::LoginNotificationInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena, is_message_owned) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:securegcm.LoginNotificationInfo) } LoginNotificationInfo::LoginNotificationInfo(const LoginNotificationInfo& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); email_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING email_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_email()) { email_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_email(), GetArenaForAllocation()); } host_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING host_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_host()) { host_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_host(), GetArenaForAllocation()); } source_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING source_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_source()) { source_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_source(), GetArenaForAllocation()); } event_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING event_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_event_type()) { event_type_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_event_type(), GetArenaForAllocation()); } creation_time_ = from.creation_time_; // @@protoc_insertion_point(copy_constructor:securegcm.LoginNotificationInfo) } inline void LoginNotificationInfo::SharedCtor() { email_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING email_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING host_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING host_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING source_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING source_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING event_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING event_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING creation_time_ = uint64_t{0u}; } LoginNotificationInfo::~LoginNotificationInfo() { // @@protoc_insertion_point(destructor:securegcm.LoginNotificationInfo) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<std::string>(); } inline void LoginNotificationInfo::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); email_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); host_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); source_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); event_type_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void LoginNotificationInfo::ArenaDtor(void* object) { LoginNotificationInfo* _this = reinterpret_cast< LoginNotificationInfo* >(object); (void)_this; } void LoginNotificationInfo::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void LoginNotificationInfo::SetCachedSize(int size) const { _cached_size_.Set(size); } void LoginNotificationInfo::Clear() { // @@protoc_insertion_point(message_clear_start:securegcm.LoginNotificationInfo) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { email_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { host_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { source_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { event_type_.ClearNonDefaultToEmpty(); } } creation_time_ = uint64_t{0u}; _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* LoginNotificationInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional fixed64 creation_time = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 17)) { _Internal::set_has_creation_time(&has_bits); creation_time_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<uint64_t>(ptr); ptr += sizeof(uint64_t); } else goto handle_unusual; continue; // optional string email = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 26)) { auto str = _internal_mutable_email(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string host = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 34)) { auto str = _internal_mutable_host(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string source = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 42)) { auto str = _internal_mutable_source(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string event_type = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 50)) { auto str = _internal_mutable_event_type(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* LoginNotificationInfo::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:securegcm.LoginNotificationInfo) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional fixed64 creation_time = 2; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFixed64ToArray(2, this->_internal_creation_time(), target); } // optional string email = 3; if (cached_has_bits & 0x00000001u) { target = stream->WriteStringMaybeAliased( 3, this->_internal_email(), target); } // optional string host = 4; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 4, this->_internal_host(), target); } // optional string source = 5; if (cached_has_bits & 0x00000004u) { target = stream->WriteStringMaybeAliased( 5, this->_internal_source(), target); } // optional string event_type = 6; if (cached_has_bits & 0x00000008u) { target = stream->WriteStringMaybeAliased( 6, this->_internal_event_type(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:securegcm.LoginNotificationInfo) return target; } size_t LoginNotificationInfo::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:securegcm.LoginNotificationInfo) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001fu) { // optional string email = 3; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_email()); } // optional string host = 4; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_host()); } // optional string source = 5; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_source()); } // optional string event_type = 6; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_event_type()); } // optional fixed64 creation_time = 2; if (cached_has_bits & 0x00000010u) { total_size += 1 + 8; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void LoginNotificationInfo::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const LoginNotificationInfo*>( &from)); } void LoginNotificationInfo::MergeFrom(const LoginNotificationInfo& from) { // @@protoc_insertion_point(class_specific_merge_from_start:securegcm.LoginNotificationInfo) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { _internal_set_email(from._internal_email()); } if (cached_has_bits & 0x00000002u) { _internal_set_host(from._internal_host()); } if (cached_has_bits & 0x00000004u) { _internal_set_source(from._internal_source()); } if (cached_has_bits & 0x00000008u) { _internal_set_event_type(from._internal_event_type()); } if (cached_has_bits & 0x00000010u) { creation_time_ = from.creation_time_; } _has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); } void LoginNotificationInfo::CopyFrom(const LoginNotificationInfo& from) { // @@protoc_insertion_point(class_specific_copy_from_start:securegcm.LoginNotificationInfo) if (&from == this) return; Clear(); MergeFrom(from); } bool LoginNotificationInfo::IsInitialized() const { return true; } void LoginNotificationInfo::InternalSwap(LoginNotificationInfo* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &email_, lhs_arena, &other->email_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &host_, lhs_arena, &other->host_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &source_, lhs_arena, &other->source_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &event_type_, lhs_arena, &other->event_type_, rhs_arena ); swap(creation_time_, other->creation_time_); } std::string LoginNotificationInfo::GetTypeName() const { return "securegcm.LoginNotificationInfo"; } // @@protoc_insertion_point(namespace_scope) } // namespace securegcm PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::securegcm::GcmDeviceInfo* Arena::CreateMaybeMessage< ::securegcm::GcmDeviceInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::securegcm::GcmDeviceInfo >(arena); } template<> PROTOBUF_NOINLINE ::securegcm::GcmMetadata* Arena::CreateMaybeMessage< ::securegcm::GcmMetadata >(Arena* arena) { return Arena::CreateMessageInternal< ::securegcm::GcmMetadata >(arena); } template<> PROTOBUF_NOINLINE ::securegcm::Tickle* Arena::CreateMaybeMessage< ::securegcm::Tickle >(Arena* arena) { return Arena::CreateMessageInternal< ::securegcm::Tickle >(arena); } template<> PROTOBUF_NOINLINE ::securegcm::LoginNotificationInfo* Arena::CreateMaybeMessage< ::securegcm::LoginNotificationInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::securegcm::LoginNotificationInfo >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
39.37591
205
0.717465
deling-google
e264cb3a38e8341b3d9a68fdbf199e7a114bf73f
31,725
cpp
C++
examples_tests/16.OrderIndependentTransparency/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
examples_tests/16.OrderIndependentTransparency/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
examples_tests/16.OrderIndependentTransparency/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h #define _NBL_STATIC_LIB_ #include <iostream> #include <cstdio> #include <nabla.h> #include "../common/Camera.hpp" #include "../common/CommonAPI.h" #include "nbl/ext/ScreenShot/ScreenShot.h" #include "nbl/ext/OIT/OIT.h" using namespace nbl; using namespace core; using namespace ui; /* Uncomment for more detailed logging */ #define LIMIT_TRANSPARENT_FRAGMENTS // #define NBL_MORE_LOGS class OITSampleApp : public ApplicationBase { constexpr static uint32_t WIN_W = 1280; constexpr static uint32_t WIN_H = 720; constexpr static uint32_t SC_IMG_COUNT = 3u; constexpr static uint32_t FRAMES_IN_FLIGHT = 5u; constexpr static uint64_t MAX_TIMEOUT = 99999999999999ull; constexpr static size_t NBL_FRAMES_TO_AVERAGE = 100ull; static_assert(FRAMES_IN_FLIGHT > SC_IMG_COUNT); public: nbl::core::smart_refctd_ptr<nbl::ui::IWindowManager> windowManager; nbl::core::smart_refctd_ptr<nbl::ui::IWindow> window; nbl::core::smart_refctd_ptr<CommonAPI::CommonAPIEventCallback> windowCb; nbl::core::smart_refctd_ptr<nbl::video::IAPIConnection> apiConnection; nbl::core::smart_refctd_ptr<nbl::video::ISurface> surface; nbl::core::smart_refctd_ptr<nbl::video::IUtilities> utilities; nbl::core::smart_refctd_ptr<nbl::video::ILogicalDevice> logicalDevice; nbl::video::IPhysicalDevice* physicalDevice; std::array<video::IGPUQueue*, CommonAPI::InitOutput::MaxQueuesCount> queues; nbl::core::smart_refctd_ptr<nbl::video::ISwapchain> swapchain; nbl::core::smart_refctd_ptr<nbl::video::IGPURenderpass> renderpass; std::array<nbl::core::smart_refctd_ptr<nbl::video::IGPUFramebuffer>, CommonAPI::InitOutput::MaxSwapChainImageCount> fbo; std::array<nbl::core::smart_refctd_ptr<nbl::video::IGPUCommandPool>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; // TODO: Multibuffer and reset the commandpools nbl::core::smart_refctd_ptr<nbl::system::ISystem> system; nbl::core::smart_refctd_ptr<nbl::asset::IAssetManager> assetManager; nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; nbl::core::smart_refctd_ptr<nbl::system::ILogger> logger; nbl::core::smart_refctd_ptr<CommonAPI::InputSystem> inputSystem; nbl::video::IGPUObjectFromAssetConverter cpu2gpu; core::smart_refctd_ptr<video::IDescriptorPool> descriptorPool; video::IDriverMemoryBacked::SDriverMemoryRequirements ubomemreq; core::smart_refctd_ptr<video::IGPUBuffer> gpuubo; core::smart_refctd_ptr<video::IGPUDescriptorSet> gpuds1; asset::ICPUMesh* meshRaw = nullptr; const asset::COBJMetadata* metaOBJ = nullptr; core::smart_refctd_ptr<video::IGPUFence> frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; core::smart_refctd_ptr<video::IGPUSemaphore> imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; core::smart_refctd_ptr<video::IGPUSemaphore> renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; core::smart_refctd_ptr<video::IGPUCommandBuffer> commandBuffers[FRAMES_IN_FLIGHT]; CommonAPI::InputSystem::ChannelReader<IMouseEventChannel> mouse; CommonAPI::InputSystem::ChannelReader<IKeyboardEventChannel> keyboard; Camera camera = Camera(vectorSIMDf(0, 0, 0), vectorSIMDf(0, 0, 0), matrix4SIMD()); using RENDERPASS_INDEPENDENT_PIPELINE_ADRESS = size_t; std::map<RENDERPASS_INDEPENDENT_PIPELINE_ADRESS, core::smart_refctd_ptr<video::IGPUGraphicsPipeline>> gpuPipelines; core::smart_refctd_ptr<video::IGPUMesh> gpumesh; const asset::ICPUMeshBuffer* firstMeshBuffer; const nbl::asset::COBJMetadata::CRenderpassIndependentPipeline* pipelineMetadata; ext::OIT::COIT oit; core::vector<core::smart_refctd_ptr<video::IGPUMeshBuffer>> gpu_transMeshes; core::vector<core::smart_refctd_ptr<video::IGPUMeshBuffer>> gpu_opaqueMeshes; core::vector<core::smart_refctd_ptr<video::IGPUMeshBuffer>> gpu_allMeshes; core::smart_refctd_ptr<video::IGPUDescriptorSet> ds2; core::smart_refctd_ptr<video::IGPUGraphicsPipeline> oit_resolve_ppln; core::smart_refctd_ptr<video::IGPUGraphicsPipeline> oit_pass1_pipeline; uint32_t ds1UboBinding = 0; int resourceIx; uint32_t acquiredNextFBO = {}; std::chrono::steady_clock::time_point lastTime; bool frameDataFilled = false; size_t frameNum = 0ull; size_t frame_count = 0ull; double time_sum = 0; double dtList[NBL_FRAMES_TO_AVERAGE] = {}; auto createDescriptorPool(const uint32_t textureCount) { constexpr uint32_t maxItemCount = 256u; { nbl::video::IDescriptorPool::SDescriptorPoolSize poolSize; poolSize.count = textureCount; poolSize.type = nbl::asset::EDT_COMBINED_IMAGE_SAMPLER; return logicalDevice->createDescriptorPool(static_cast<nbl::video::IDescriptorPool::E_CREATE_FLAGS>(0), maxItemCount, 1u, &poolSize); } } void setWindow(core::smart_refctd_ptr<nbl::ui::IWindow>&& wnd) override { window = std::move(wnd); } nbl::ui::IWindow* getWindow() override { return window.get(); } void setSystem(core::smart_refctd_ptr<nbl::system::ISystem>&& s) override { system = std::move(s); } video::IAPIConnection* getAPIConnection() override { return apiConnection.get(); } video::ILogicalDevice* getLogicalDevice() override { return logicalDevice.get(); } video::IGPURenderpass* getRenderpass() override { return renderpass.get(); } void setSurface(core::smart_refctd_ptr<video::ISurface>&& s) override { surface = std::move(s); } void setFBOs(std::vector<core::smart_refctd_ptr<video::IGPUFramebuffer>>& f) override { for (int i = 0; i < f.size(); i++) { fbo[i] = core::smart_refctd_ptr(f[i]); } } void setSwapchain(core::smart_refctd_ptr<video::ISwapchain>&& s) override { swapchain = std::move(s); } uint32_t getSwapchainImageCount() override { return SC_IMG_COUNT; } virtual nbl::asset::E_FORMAT getDepthFormat() override { return nbl::asset::EF_D32_SFLOAT; } APP_CONSTRUCTOR(OITSampleApp) void onAppInitialized_impl() override { CommonAPI::SFeatureRequest<video::IAPIConnection::E_FEATURE> requiredInstanceFeatures = {}; requiredInstanceFeatures.count = 1u; video::IAPIConnection::E_FEATURE requiredFeatures_Instance[] = { video::IAPIConnection::EF_SURFACE }; requiredInstanceFeatures.features = requiredFeatures_Instance; CommonAPI::SFeatureRequest<video::IAPIConnection::E_FEATURE> optionalInstanceFeatures = {}; CommonAPI::SFeatureRequest<video::ILogicalDevice::E_FEATURE> requiredDeviceFeatures = {}; requiredDeviceFeatures.count = 1u; video::ILogicalDevice::E_FEATURE requiredFeatures_Device[] = { video::ILogicalDevice::EF_SWAPCHAIN }; requiredDeviceFeatures.features = requiredFeatures_Device; CommonAPI::SFeatureRequest< video::ILogicalDevice::E_FEATURE> optionalDeviceFeatures = {}; const auto swapchainImageUsage = static_cast<asset::IImage::E_USAGE_FLAGS>(asset::IImage::EUF_COLOR_ATTACHMENT_BIT); const video::ISurface::SFormat surfaceFormat(asset::EF_R8G8B8A8_SRGB, asset::ECP_COUNT, asset::EOTF_UNKNOWN); CommonAPI::InitOutput initOutput; initOutput.window = core::smart_refctd_ptr(window); initOutput.system = core::smart_refctd_ptr(system); CommonAPI::InitWithDefaultExt(initOutput, video::EAT_OPENGL, "OITSample", WIN_W, WIN_H, SC_IMG_COUNT, swapchainImageUsage, surfaceFormat, nbl::asset::EF_D32_SFLOAT); window = std::move(initOutput.window); windowCb = std::move(initOutput.windowCb); apiConnection = std::move(initOutput.apiConnection); surface = std::move(initOutput.surface); utilities = std::move(initOutput.utilities); logicalDevice = std::move(initOutput.logicalDevice); physicalDevice = initOutput.physicalDevice; queues = std::move(initOutput.queues); swapchain = std::move(initOutput.swapchain); renderpass = std::move(initOutput.renderpass); fbo = std::move(initOutput.fbo); commandPools = std::move(initOutput.commandPools); system = std::move(initOutput.system); assetManager = std::move(initOutput.assetManager); cpu2gpuParams = std::move(initOutput.cpu2gpuParams); logger = std::move(initOutput.logger); inputSystem = std::move(initOutput.inputSystem); bool oit_init = oit.initialize(logicalDevice.get(), WIN_W, WIN_H, cpu2gpuParams); assert(oit_init); core::smart_refctd_ptr<asset::ICPUDescriptorSetLayout> cpu_ds2layout; { asset::ICPUDescriptorSetLayout::SBinding bnd[ext::OIT::COIT::MaxImgBindingCount]; oit.getDSLayoutBindings<asset::ICPUDescriptorSetLayout>(bnd); cpu_ds2layout = core::make_smart_refctd_ptr<asset::ICPUDescriptorSetLayout>(bnd, bnd + ext::OIT::COIT::MaxImgBindingCount); } core::smart_refctd_ptr<video::IGPUDescriptorSetLayout> ds2layout; { video::IGPUObjectFromAssetConverter cpu2gpu; ds2layout = cpu2gpu.getGPUObjectsFromAssets(&cpu_ds2layout.get(), &cpu_ds2layout.get() + 1, cpu2gpuParams)->operator[](0); } auto ds2pool = logicalDevice->createDescriptorPoolForDSLayouts(static_cast<video::IDescriptorPool::E_CREATE_FLAGS>(0), &ds2layout.get(), &ds2layout.get() + 1); { ds2 = logicalDevice->createGPUDescriptorSet(ds2pool.get(), core::smart_refctd_ptr(ds2layout)); video::IGPUDescriptorSet::SDescriptorInfo info[ext::OIT::COIT::MaxImgBindingCount]; video::IGPUDescriptorSet::SWriteDescriptorSet w[ext::OIT::COIT::MaxImgBindingCount]; oit.getDSWrites(w, info, ds2.get()); logicalDevice->updateDescriptorSets(3u, w, 0u, nullptr); } { ds2 = logicalDevice->createGPUDescriptorSet(ds2pool.get(), core::smart_refctd_ptr(ds2layout)); video::IGPUDescriptorSet::SDescriptorInfo info[ext::OIT::COIT::MaxImgBindingCount]; video::IGPUDescriptorSet::SWriteDescriptorSet w[ext::OIT::COIT::MaxImgBindingCount]; const auto writeCount = oit.getDSWrites(w, info, ds2.get()); logicalDevice->updateDescriptorSets(writeCount, w, 0u, nullptr); } { auto layout = logicalDevice->createGPUPipelineLayout(nullptr, nullptr, nullptr, nullptr, core::smart_refctd_ptr(ds2layout), nullptr); const auto& proto = oit.getResolveProtoPipeline(); video::IGPUSpecializedShader* shaders[2]{ proto.vs.get(), proto.fs.get() }; auto rpindep = logicalDevice->createGPURenderpassIndependentPipeline(nullptr, std::move(layout), shaders, shaders + 2, proto.vtx, proto.blend, proto.primAsm, proto.raster); video::IGPUGraphicsPipeline::SCreationParams pplnparams; pplnparams.renderpass = renderpass; pplnparams.renderpassIndependent = rpindep; pplnparams.subpassIx = 0u; oit_resolve_ppln = logicalDevice->createGPUGraphicsPipeline(nullptr, std::move(pplnparams)); } nbl::video::IGPUObjectFromAssetConverter cpu2gpu; { auto* quantNormalCache = assetManager->getMeshManipulator()->getQuantNormalCache(); quantNormalCache->loadCacheFromFile<asset::EF_A2B10G10R10_SNORM_PACK32>(system.get(), sharedOutputCWD / "normalCache101010.sse"); system::path archPath = sharedInputCWD / "white_oak.zip"; auto arch = system->openFileArchive(archPath); // test no alias loading (TODO: fix loading from absolute paths) system->mount(std::move(arch)); asset::IAssetLoader::SAssetLoadParams loadParams; loadParams.workingDirectory = sharedInputCWD; loadParams.logger = logger.get(); auto meshes_bundle = assetManager->getAsset((sharedInputCWD / "white_oak.zip/white_oak.obj").string(), loadParams); assert(!meshes_bundle.getContents().empty()); metaOBJ = meshes_bundle.getMetadata()->selfCast<const asset::COBJMetadata>(); auto cpuMesh = meshes_bundle.getContents().begin()[0]; meshRaw = static_cast<asset::ICPUMesh*>(cpuMesh.get()); quantNormalCache->saveCacheToFile<asset::EF_A2B10G10R10_SNORM_PACK32>(system.get(), sharedOutputCWD / "normalCache101010.sse"); } core::vector<core::smart_refctd_ptr<asset::ICPUMeshBuffer>> transparentMeshes; core::vector<core::smart_refctd_ptr<asset::ICPUMeshBuffer>> opaqueMeshes; asset::ICPURenderpassIndependentPipeline* transPpln; { for (auto& mb : meshRaw->getMeshBufferVector()) { auto* ppln = mb->getPipeline(); if (ppln->getBlendParams().blendParams[0].dstColorFactor != asset::EBF_ZERO) { transparentMeshes.push_back(mb); transPpln = ppln; } else { opaqueMeshes.push_back(mb); } } } { auto srcppln = core::smart_refctd_ptr_static_cast<asset::ICPURenderpassIndependentPipeline>(transPpln->clone()); auto* layout = srcppln->getLayout(); layout->setDescriptorSetLayout(2u, core::smart_refctd_ptr(cpu_ds2layout)); asset::IAssetLoader::SAssetLoadParams lparams; lparams.workingDirectory = localInputCWD; auto fs_bundle = assetManager->getAsset("oit_fill_nodes.frag", lparams); assert(!fs_bundle.getContents().empty()); auto fs = core::smart_refctd_ptr_static_cast<asset::ICPUSpecializedShader>(fs_bundle.getContents().begin()[0]); srcppln->setShaderAtStage(asset::IShader::ESS_FRAGMENT, fs.get()); asset::SVertexInputParams& vtxparams = srcppln->getVertexInputParams(); asset::SPrimitiveAssemblyParams& primparams = srcppln->getPrimitiveAssemblyParams(); asset::SBlendParams& blendparams = srcppln->getBlendParams(); asset::SRasterizationParams& rasterparams = srcppln->getRasterizationParams(); blendparams.blendParams[0].blendEnable = 0; blendparams.blendParams[0].colorWriteMask = 0; rasterparams.faceCullingMode = nbl::asset::EFCM_NONE; rasterparams.depthCompareOp = nbl::asset::ECO_GREATER; rasterparams.depthWriteEnable = 0; rasterparams.depthTestEnable = 1; core::smart_refctd_ptr<video::IGPURenderpassIndependentPipeline> rpindep; { video::IGPUObjectFromAssetConverter c2g; auto gpu_bundle = c2g.getGPUObjectsFromAssets(&srcppln.get(), &srcppln.get() + 1, cpu2gpuParams); assert(gpu_bundle && gpu_bundle->size() && (*gpu_bundle)[0]); rpindep = (*gpu_bundle)[0]; } video::IGPUGraphicsPipeline::SCreationParams pplnparams; pplnparams.renderpass = renderpass; pplnparams.renderpassIndependent = rpindep; pplnparams.subpassIx = 0u; oit_pass1_pipeline = logicalDevice->createGPUGraphicsPipeline(nullptr, std::move(pplnparams)); } firstMeshBuffer = *meshRaw->getMeshBuffers().begin(); pipelineMetadata = metaOBJ->getAssetSpecificMetadata(firstMeshBuffer->getPipeline()); // so we can create just one DS const asset::ICPUDescriptorSetLayout* ds1layout = firstMeshBuffer->getPipeline()->getLayout()->getDescriptorSetLayout(1u); ds1UboBinding = 0u; for (const auto& bnd : ds1layout->getBindings()) if (bnd.type == asset::EDT_UNIFORM_BUFFER) { ds1UboBinding = bnd.binding; break; } size_t neededDS1UBOsz = 0ull; { for (const auto& shdrIn : pipelineMetadata->m_inputSemantics) if (shdrIn.descriptorSection.type == asset::IRenderpassIndependentPipelineMetadata::ShaderInput::ET_UNIFORM_BUFFER && shdrIn.descriptorSection.uniformBufferObject.set == 1u && shdrIn.descriptorSection.uniformBufferObject.binding == ds1UboBinding) neededDS1UBOsz = std::max<size_t>(neededDS1UBOsz, shdrIn.descriptorSection.uniformBufferObject.relByteoffset + shdrIn.descriptorSection.uniformBufferObject.bytesize); } core::smart_refctd_ptr<video::IGPUDescriptorSetLayout> gpuds1layout; { auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&ds1layout, &ds1layout + 1, cpu2gpuParams); if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) assert(false); gpuds1layout = (*gpu_array)[0]; } descriptorPool = createDescriptorPool(1u); ubomemreq = logicalDevice->getDeviceLocalGPUMemoryReqs(); ubomemreq.vulkanReqs.size = neededDS1UBOsz; video::IGPUBuffer::SCreationParams gpuuboCreationParams; gpuuboCreationParams.canUpdateSubRange = true; gpuuboCreationParams.usage = asset::IBuffer::EUF_UNIFORM_BUFFER_BIT; gpuuboCreationParams.sharingMode = asset::E_SHARING_MODE::ESM_CONCURRENT; gpuuboCreationParams.queueFamilyIndexCount = 0u; gpuuboCreationParams.queueFamilyIndices = nullptr; gpuuboCreationParams.canUpdateSubRange = true; gpuubo = logicalDevice->createGPUBufferOnDedMem(gpuuboCreationParams, ubomemreq); gpuds1 = logicalDevice->createGPUDescriptorSet(descriptorPool.get(), std::move(gpuds1layout)); { video::IGPUDescriptorSet::SWriteDescriptorSet write; write.dstSet = gpuds1.get(); write.binding = ds1UboBinding; write.count = 1u; write.arrayElement = 0u; write.descriptorType = asset::EDT_UNIFORM_BUFFER; video::IGPUDescriptorSet::SDescriptorInfo info; { info.desc = gpuubo; info.buffer.offset = 0ull; info.buffer.size = neededDS1UBOsz; } write.info = &info; logicalDevice->updateDescriptorSets(1u, &write, 0u, nullptr); } { cpu2gpuParams.beginCommandBuffers(); auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(transparentMeshes.data(), transparentMeshes.data() + transparentMeshes.size(), cpu2gpuParams); cpu2gpuParams.waitForCreationToComplete(true); if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) assert(false); for (auto& mb : *gpu_array) gpu_transMeshes.push_back(mb); cpu2gpuParams.beginCommandBuffers(); gpu_array = cpu2gpu.getGPUObjectsFromAssets(opaqueMeshes.data(), opaqueMeshes.data() + opaqueMeshes.size(), cpu2gpuParams); cpu2gpuParams.waitForCreationToComplete(true); if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) assert(false); for (auto& mb : *gpu_array) gpu_opaqueMeshes.push_back(mb); gpu_allMeshes.insert(gpu_allMeshes.begin(), gpu_transMeshes.begin(), gpu_transMeshes.end()); gpu_allMeshes.insert(gpu_allMeshes.begin(), gpu_opaqueMeshes.begin(), gpu_opaqueMeshes.end()); } { for (size_t i = 0; i < gpu_allMeshes.size(); ++i) { auto gpuIndependentPipeline = gpu_allMeshes[i]->getPipeline(); nbl::video::IGPUGraphicsPipeline::SCreationParams graphicsPipelineParams; graphicsPipelineParams.renderpassIndependent = core::smart_refctd_ptr<nbl::video::IGPURenderpassIndependentPipeline>(const_cast<video::IGPURenderpassIndependentPipeline*>(gpuIndependentPipeline)); graphicsPipelineParams.renderpass = core::smart_refctd_ptr(renderpass); const RENDERPASS_INDEPENDENT_PIPELINE_ADRESS adress = reinterpret_cast<RENDERPASS_INDEPENDENT_PIPELINE_ADRESS>(graphicsPipelineParams.renderpassIndependent.get()); if (gpuPipelines.find(adress) != gpuPipelines.end()) continue; gpuPipelines[adress] = logicalDevice->createGPUGraphicsPipeline(nullptr, std::move(graphicsPipelineParams)); } } core::vectorSIMDf cameraPosition(0, 5, -10); matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), float(WIN_W) / WIN_H, 0.1, 1000); camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), projectionMatrix, 10.f, 1.f); lastTime = std::chrono::steady_clock::now(); frameDataFilled = false; frame_count = 0ull; time_sum = 0; dtList[NBL_FRAMES_TO_AVERAGE] = {}; for (size_t i = 0ull; i < NBL_FRAMES_TO_AVERAGE; ++i) dtList[i] = 0.0; logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_GRAPHICS].get(), video::IGPUCommandBuffer::EL_PRIMARY, FRAMES_IN_FLIGHT, commandBuffers); for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) { imageAcquire[i] = logicalDevice->createSemaphore(); renderFinished[i] = logicalDevice->createSemaphore(); } resourceIx = -1; } void onAppTerminated_impl() override { const auto& fboCreationParams = fbo[acquiredNextFBO]->getCreationParameters(); auto gpuSourceImageView = fboCreationParams.attachments[0]; bool status = ext::ScreenShot::createScreenShot( logicalDevice.get(), queues[CommonAPI::InitOutput::EQT_TRANSFER_UP], renderFinished[resourceIx].get(), gpuSourceImageView.get(), assetManager.get(), "ScreenShot.png", asset::EIL_PRESENT_SRC, static_cast<asset::E_ACCESS_FLAGS>(0u)); assert(status); } void workLoopBody() override { ++resourceIx; if (resourceIx >= FRAMES_IN_FLIGHT) resourceIx = 0; auto& commandBuffer = commandBuffers[resourceIx]; auto& fence = frameComplete[resourceIx]; if (fence) while (logicalDevice->waitForFences(1u, &fence.get(), false, MAX_TIMEOUT) == video::IGPUFence::ES_TIMEOUT) {} else fence = logicalDevice->createFence(static_cast<video::IGPUFence::E_CREATE_FLAGS>(0)); auto renderStart = std::chrono::steady_clock::now(); const auto renderDt = std::chrono::duration_cast<std::chrono::milliseconds>(renderStart - lastTime).count(); lastTime = renderStart; { // Calculate Simple Moving Average for FrameTime time_sum -= dtList[frame_count]; time_sum += renderDt; dtList[frame_count] = renderDt; frame_count++; if (frame_count >= NBL_FRAMES_TO_AVERAGE) { frameDataFilled = true; frame_count = 0; } } const double averageFrameTime = frameDataFilled ? (time_sum / (double)NBL_FRAMES_TO_AVERAGE) : (time_sum / frame_count); #ifdef NBL_MORE_LOGS logger->log("renderDt = %f ------ averageFrameTime = %f", system::ILogger::ELL_INFO, renderDt, averageFrameTime); #endif // NBL_MORE_LOGS auto averageFrameTimeDuration = std::chrono::duration<double, std::milli>(averageFrameTime); auto nextPresentationTime = renderStart + averageFrameTimeDuration; auto nextPresentationTimeStamp = std::chrono::duration_cast<std::chrono::microseconds>(nextPresentationTime.time_since_epoch()); inputSystem->getDefaultMouse(&mouse); inputSystem->getDefaultKeyboard(&keyboard); camera.beginInputProcessing(nextPresentationTimeStamp); mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, logger.get()); keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, logger.get()); camera.endInputProcessing(nextPresentationTimeStamp); const auto& viewMatrix = camera.getViewMatrix(); const auto& viewProjectionMatrix = camera.getConcatenatedMatrix(); commandBuffer->reset(nbl::video::IGPUCommandBuffer::ERF_RELEASE_RESOURCES_BIT); commandBuffer->begin(0); asset::SViewport viewport; viewport.minDepth = 1.f; viewport.maxDepth = 0.f; viewport.x = 0u; viewport.y = 0u; viewport.width = WIN_W; viewport.height = WIN_H; commandBuffer->setViewport(0u, 1u, &viewport); swapchain->acquireNextImage(MAX_TIMEOUT, imageAcquire[resourceIx].get(), nullptr, &acquiredNextFBO); // clear all pixels to 1.f in first frame, // all later frames will clear their pixels at the end of OIT resolve shader if (frameNum == 0u) { oit.invalidateNodesVisibility(commandBuffer.get()); } nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo; { VkRect2D area; area.offset = { 0,0 }; area.extent = { WIN_W, WIN_H }; asset::SClearValue clear[2] = {}; clear[0].color.float32[0] = 1.f; clear[0].color.float32[1] = 1.f; clear[0].color.float32[2] = 1.f; clear[0].color.float32[3] = 0.f; clear[1].depthStencil.depth = 0.f; clear[1].depthStencil.stencil = 0; beginInfo.clearValueCount = 2u; beginInfo.framebuffer = fbo[acquiredNextFBO]; beginInfo.renderpass = renderpass; beginInfo.renderArea = area; beginInfo.clearValues = clear; } commandBuffer->beginRenderPass(&beginInfo, nbl::asset::ESC_INLINE); core::matrix3x4SIMD modelMatrix; modelMatrix.setTranslation(nbl::core::vectorSIMDf(0, 0, 0, 0)); core::matrix4SIMD mvp = core::concatenateBFollowedByA(viewProjectionMatrix, modelMatrix); core::vector<uint8_t> uboData(gpuubo->getSize()); for (const auto& shdrIn : pipelineMetadata->m_inputSemantics) { if (shdrIn.descriptorSection.type == asset::IRenderpassIndependentPipelineMetadata::ShaderInput::ET_UNIFORM_BUFFER && shdrIn.descriptorSection.uniformBufferObject.set == 1u && shdrIn.descriptorSection.uniformBufferObject.binding == ds1UboBinding) { switch (shdrIn.type) { case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW_PROJ: { memcpy(uboData.data() + shdrIn.descriptorSection.uniformBufferObject.relByteoffset, mvp.pointer(), shdrIn.descriptorSection.uniformBufferObject.bytesize); } break; case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW: { memcpy(uboData.data() + shdrIn.descriptorSection.uniformBufferObject.relByteoffset, viewMatrix.pointer(), shdrIn.descriptorSection.uniformBufferObject.bytesize); } break; case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW_INVERSE_TRANSPOSE: { memcpy(uboData.data() + shdrIn.descriptorSection.uniformBufferObject.relByteoffset, viewMatrix.pointer(), shdrIn.descriptorSection.uniformBufferObject.bytesize); } break; } } } commandBuffer->updateBuffer(gpuubo.get(), 0ull, gpuubo->getSize(), uboData.data()); //draw opaque for (size_t i = 0; i < gpu_opaqueMeshes.size(); ++i) { auto gpuMeshBuffer = gpu_opaqueMeshes[i].get(); auto gpuGraphicsPipeline = gpuPipelines[reinterpret_cast<RENDERPASS_INDEPENDENT_PIPELINE_ADRESS>(gpuMeshBuffer->getPipeline())]; const video::IGPURenderpassIndependentPipeline* gpuRenderpassIndependentPipeline = gpuMeshBuffer->getPipeline(); const video::IGPUDescriptorSet* ds3 = gpuMeshBuffer->getAttachedDescriptorSet(); commandBuffer->bindGraphicsPipeline(gpuGraphicsPipeline.get()); const video::IGPUDescriptorSet* gpuds1_ptr = gpuds1.get(); commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuRenderpassIndependentPipeline->getLayout(), 1u, 1u, &gpuds1_ptr); const video::IGPUDescriptorSet* gpuds3_ptr = gpuMeshBuffer->getAttachedDescriptorSet(); if (gpuds3_ptr) commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuRenderpassIndependentPipeline->getLayout(), 3u, 1u, &gpuds3_ptr); commandBuffer->pushConstants(gpuRenderpassIndependentPipeline->getLayout(), asset::IShader::ESS_FRAGMENT, 0u, gpuMeshBuffer->MAX_PUSH_CONSTANT_BYTESIZE, gpuMeshBuffer->getPushConstantsDataPtr()); commandBuffer->drawMeshBuffer(gpuMeshBuffer); } // OIT 1st pass for (size_t i = 0; i < gpu_transMeshes.size(); ++i) { auto gpuMeshBuffer = gpu_transMeshes[i].get(); const video::IGPURenderpassIndependentPipeline* gpuRenderpassIndependentPipeline = gpuMeshBuffer->getPipeline(); const video::IGPUDescriptorSet* ds3 = gpuMeshBuffer->getAttachedDescriptorSet(); const video::IGPUDescriptorSet* gpuds2_ptr = ds2.get(); const video::IGPUDescriptorSet* gpuds3_ptr = gpuMeshBuffer->getAttachedDescriptorSet(); commandBuffer->bindGraphicsPipeline(oit_pass1_pipeline.get()); const video::IGPUDescriptorSet* gpuds1_ptr = gpuds1.get(); commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, oit_pass1_pipeline->getRenderpassIndependentPipeline()->getLayout(), 1u, 1u, &gpuds1_ptr); commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, oit_pass1_pipeline->getRenderpassIndependentPipeline()->getLayout(), 2u, 1u, &ds2.get()); if (gpuds3_ptr) commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, oit_pass1_pipeline->getRenderpassIndependentPipeline()->getLayout(), 3u, 1u, &gpuds3_ptr); commandBuffer->drawMeshBuffer(gpuMeshBuffer); } // mem barriers on OIT images oit.barrierBetweenPasses(commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS]->getFamilyIndex()); //OIT resolve oit.resolvePass(commandBuffer.get(), oit_resolve_ppln.get(), ds2.get(), 2u); // mem barrier on OIT vis image (written at the end of resolve pass) oit.barrierAfterResolve(commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS]->getFamilyIndex()); commandBuffer->endRenderPass(); commandBuffer->end(); CommonAPI::Submit(logicalDevice.get(), swapchain.get(), commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], imageAcquire[resourceIx].get(), renderFinished[resourceIx].get(), fence.get()); CommonAPI::Present(logicalDevice.get(), swapchain.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], renderFinished[resourceIx].get(), acquiredNextFBO); frameNum++; } bool keepRunning() override { return windowCb->isWindowOpen(); } }; NBL_COMMON_API_MAIN(OITSampleApp)
46.930473
262
0.668905
deprilula28
e266059c3a7ac558c9a2d0d201858cae3956eaea
325
cpp
C++
sandbox/src/sandbox_app.cpp
realjf/kent
c4000bb7a53de54db7575281dc7d6934ca79ce3c
[ "Apache-2.0" ]
null
null
null
sandbox/src/sandbox_app.cpp
realjf/kent
c4000bb7a53de54db7575281dc7d6934ca79ce3c
[ "Apache-2.0" ]
null
null
null
sandbox/src/sandbox_app.cpp
realjf/kent
c4000bb7a53de54db7575281dc7d6934ca79ce3c
[ "Apache-2.0" ]
null
null
null
#include <kent/core/entry_point.h> #include <kent/engine.h> class Sandbox : public Kent::Application { public: Sandbox() : Kent::Application("Sandbox") { std::cout << "Sandbox" << std::endl; } virtual ~Sandbox() = default; }; Kent::Application* Kent::CreateApplication() { return new Sandbox(); }
19.117647
46
0.636923
realjf
e269c6655727f6ee8689d2607d8c1447838ccc38
2,255
hpp
C++
para/include/structures.hpp
asmelko/gmhc
f728aea146de8a3accbf051b0c7b2d1333bb6f8c
[ "MIT" ]
2
2021-04-01T08:37:50.000Z
2021-11-03T21:50:31.000Z
para/include/structures.hpp
asmelko/gmhc
f728aea146de8a3accbf051b0c7b2d1333bb6f8c
[ "MIT" ]
null
null
null
para/include/structures.hpp
asmelko/gmhc
f728aea146de8a3accbf051b0c7b2d1333bb6f8c
[ "MIT" ]
1
2021-04-01T08:38:02.000Z
2021-04-01T08:38:02.000Z
#ifndef COMMON_STRUCTURES_CUH #define COMMON_STRUCTURES_CUH #include <cuda_runtime.h> #include "clustering.hpp" // this file contains structures used in kernels or to pass parameters to kernels // structure that holds indices of cluster pair and distance between them struct chunk_t { float min_dist; clustering::csize_t min_i, min_j; }; // represents 2D coordinates of csize_t type struct csize2 { clustering::csize_t x, y; }; // structure describing a clusters id and size struct cluster_data_t { clustering::asgn_t id; clustering::csize_t size; float* cu_points; }; // representants of clusters in Mahalanobis distance computation struct cluster_representants_t { float* __restrict__ cu_points; clustering::csize_t size; }; // strucutre that represents a neighbor of a cluster // the neighbor is represented by its index and distance to the cluster struct neighbor_t { float distance; clustering::csize_t idx; }; // input structure for kernels struct input_t { float* data; clustering::csize_t count; clustering::csize_t dim; }; // input structure for update kernel struct update_data_t { // merged cluster indices clustering::csize_t old_a; clustering::csize_t old_b; // update array clustering::csize_t* to_update; // variable describing write top of to_update array clustering::csize_t* update_size; }; // input data for kernels struct centroid_data_t { float* centroids; float* inverses; float* mfactors; cluster_representants_t* representants; clustering::csize_t dim; }; // structure that holds parameters for kernel start struct kernel_info { // 1D dimension of grid unsigned int grid_dim = 1; // 1D dimension of block unsigned int block_dim = 32; // size of shared memory clustering::csize_t shared_size = 0; // assigned stream cudaStream_t stream = (cudaStream_t)0; kernel_info(unsigned int grid_dim, unsigned int block_dim, clustering::csize_t shared_size = 0, cudaStream_t stream = (cudaStream_t)0) : grid_dim(grid_dim) , block_dim(block_dim) , shared_size(shared_size) , stream(stream) {} kernel_info() = default; }; #endif
21.893204
81
0.709978
asmelko
e26a50cef4dcdbecfd5366bca667374b37924971
8,637
cpp
C++
src/actions_example/src/fib_server.cpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
src/actions_example/src/fib_server.cpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
src/actions_example/src/fib_server.cpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
/** * Example Fibonacci computation action server source code. * * Roberto Masocco <robmasocco@gmail.com> * * January 10, 2022 */ #include <chrono> #include "../include/actions_example/fib_server.hpp" #ifdef ADVANCED #include "../include/actions_example/adv_qos.hpp" #endif using namespace std::chrono_literals; /** * @brief Creates a new FibonacciComputer node. */ FibonacciComputer::FibonacciComputer() : Node("fibonacci_computer") { #ifdef ADVANCED //! Little point in having a different QoS for services rather than the //! default, but feedbacks and statuses might be important server_opts_.allocator = rcl_get_default_allocator(); server_opts_.goal_service_qos = rmw_qos_profile_services_default; server_opts_.cancel_service_qos = rmw_qos_profile_services_default; server_opts_.result_service_qos = rmw_qos_profile_services_default; server_opts_.status_topic_qos = status_qos_profile; server_opts_.feedback_topic_qos = feedback_qos_profile; server_clbk_group_ = this->create_callback_group( rclcpp::CallbackGroupType::MutuallyExclusive); //! Works will be queried for and executed every 10 seconds work_timer_ = this->create_wall_timer( 10s, std::bind( &FibonacciComputer::work_activation_clbk, this)); #endif //! Create the action server by specifying the node that handles it, //! and the three handler routines for the three computation stages //! You could pass other arguments: //! - rcl_action_server_options_t struct to hold QoS policies and more //! - Callback group (i.e. thread) on which the server's back-end will run #ifndef ADVANCED fib_server_ = rclcpp_action::create_server<Fibonacci>( this, "~/fibonacci", //! Naming conventions apply here too std::bind( &FibonacciComputer::handle_goal, this, std::placeholders::_1, std::placeholders::_2), std::bind( &FibonacciComputer::handle_cancel, this, std::placeholders::_1), std::bind( &FibonacciComputer::handle_accepted, this, std::placeholders::_1)); #else fib_server_ = rclcpp_action::create_server<Fibonacci>( this, "~/fibonacci", std::bind( &FibonacciComputer::handle_goal, this, std::placeholders::_1, std::placeholders::_2), std::bind( &FibonacciComputer::handle_cancel, this, std::placeholders::_1), std::bind( &FibonacciComputer::handle_accepted, this, std::placeholders::_1), server_opts_, server_clbk_group_); #endif RCLCPP_INFO(this->get_logger(), "Node initialized"); } /** * @brief Handles a new goal request. * * @param uuid ID of the new request. * @param goal Pointer to goal object to parse. * @return Handling result code. */ rclcpp_action::GoalResponse FibonacciComputer::handle_goal( const rclcpp_action::GoalUUID & uuid, FibonacciGoalSharedPtr goal) { //! This server accepts requests up to order 20 if (goal->order > 20) { RCLCPP_ERROR( this->get_logger(), "Received invalid request (%s) of order %d REJECTED", rclcpp_action::to_string(uuid).c_str(), goal->order); return rclcpp_action::GoalResponse::REJECT; } RCLCPP_INFO( this->get_logger(), "Received request (%s) of order %d ACCEPTED", rclcpp_action::to_string(uuid).c_str(), goal->order); //! Returning the following code will force the middleware to //! immediately move the goal to the executing state #ifndef ADVANCED return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE; #else //! A deferred scheme is also possible, in which you can decide //! when to execute each goal return rclcpp_action::GoalResponse::ACCEPT_AND_DEFER; #endif } /** * @brief Handles a goal cancellation request. * * @param goal_handle Handle to the goal object. * @return Cancellation operation status. */ rclcpp_action::CancelResponse FibonacciComputer::handle_cancel( const FibonacciGoalHandleSharedPtr goal_handle) { //! This server doesn't cancel short computations if (goal_handle->get_goal()->order < 10) { RCLCPP_ERROR( this->get_logger(), "Received cancellation request for goal (%s) REJECTED", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); return rclcpp_action::CancelResponse::REJECT; } #ifdef ADVANCED new_goal_ = nullptr; #endif //! Note that this will tell the middleware to only ATTEMPT cancellation //! since the scheme is deferred: a flag will be raised and will have to be //! checked by every worker routine (not handled by the middleware) RCLCPP_WARN( this->get_logger(), "Received cancellation request for goal (%s) ACCEPTED", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); return rclcpp_action::CancelResponse::ACCEPT; } /** * @brief Executed when a goal request execution is started. * * @param goal_handle Handle to the goal object. */ void FibonacciComputer::handle_accepted( const FibonacciGoalHandleSharedPtr goal_handle) { #ifdef ADVANCED //! Here you could place the handle pointer in a queue to be processed later new_goal_ = goal_handle; #else //! Here we're inside a service: the callback should return ASAP //! in order not to starve the (by default single-threaded) executor //! This is why we only start a new thread (detached from the C++ //! object to let it run freely until done or killed) std::thread{ std::bind( &FibonacciComputer::compute, this, std::placeholders::_1), goal_handle }.detach(); #endif } /** * @brief Computes the Fibonacci sequence up to a given order. * * @param goal_handle Handle to the goal object. */ void FibonacciComputer::compute( const FibonacciGoalHandleSharedPtr goal_handle) { RCLCPP_INFO( this->get_logger(), "Starting computation for request (%s)", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); //! This object helps us to define sleep times (in real time) rclcpp::WallRate loop_rate(1s); //! Feedback publishing API requires a shared_ptr auto feedback = std::make_shared<Fibonacci::Feedback>(); auto & sequence = feedback->partial_sequence; //! Same holds for the result message auto result = std::make_shared<Fibonacci::Result>(); const auto goal = goal_handle->get_goal(); int order = goal->order; //! This implementation refuses order 0 if (order == 0) { goal_handle->abort(result); //! Terminal API to call RCLCPP_ERROR( this->get_logger(), "Request (%s) has invalid order ABORTED", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); return; } // Initialize sequence sequence.push_back(0); sequence.push_back(1); // Computation loop //! Always check if rclcpp::ok while computing since you need it to //! interact with the middleware! for (int i = 1; (i < order) && rclcpp::ok(); i++) { //! Check if there is a cancel request, and in case mark the goal as such if (goal_handle->is_canceling()) { // Publish what has been computed so far result->set__sequence(sequence); goal_handle->canceled(result); //! Terminal API to call RCLCPP_WARN( this->get_logger(), "Computation (%s) CANCELED", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); return; } // Update sequence sequence.push_back(sequence[i] + sequence[i - 1]); //! Publish feedback (that we're building upon) goal_handle->publish_feedback(feedback); RCLCPP_INFO( this->get_logger(), "Published feedback for goal (%s)", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); //! This simulates computational overhead loop_rate.sleep(); } // Publish result //! ALWAYS check if the middelware is ok! if (rclcpp::ok()) { result->set__sequence(sequence); goal_handle->succeed(result); //! Terminal API to call RCLCPP_INFO( this->get_logger(), "Goal (%s) completed", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); } } /** * @brief Starts queued jobs. */ #ifdef ADVANCED void FibonacciComputer::work_activation_clbk() { if (new_goal_) { FibonacciGoalHandleSharedPtr goal_handle = new_goal_; new_goal_ = nullptr; RCLCPP_WARN( this->get_logger(), "Starting execution of goal (%s)", rclcpp_action::to_string(goal_handle->get_goal_id()).c_str()); goal_handle->execute(); //! Update internal goal state std::thread{ std::bind( &FibonacciComputer::compute, this, std::placeholders::_1), goal_handle }.detach(); } } #endif
29.885813
78
0.69538
IntelligentSystemsLabUTV
e26d30b29888973f66c93f4d342e0dd76e80fa1d
8,337
hpp
C++
contrib/gcc-4.1/libstdc++-v3/include/ext/pb_assoc/detail/resize_policy/hash_load_check_resize_trigger_imp.hpp
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
3
2017-03-06T14:12:57.000Z
2019-11-23T09:35:10.000Z
contrib/gcc-4.1/libstdc++-v3/include/ext/pb_assoc/detail/resize_policy/hash_load_check_resize_trigger_imp.hpp
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
null
null
null
contrib/gcc-4.1/libstdc++-v3/include/ext/pb_assoc/detail/resize_policy/hash_load_check_resize_trigger_imp.hpp
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- // Copyright (C) 2005 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice and // this permission notice appear in supporting documentation. None of // the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied warranty. /* * @file hash_load_check_resize_trigger_imp.hpp.hpp * Contains an implementation of hash_load_check_resize_trigger.. */ PB_ASSOC_CLASS_T_DEC pb_assoc::detail::int_to_type<External_Load_Access> PB_ASSOC_CLASS_C_DEC::s_external_load_access_ind; PB_ASSOC_CLASS_T_DEC PB_ASSOC_CLASS_C_DEC:: hash_load_check_resize_trigger(float load_min, float load_max) : m_load_min(load_min), m_load_max(load_max), m_next_shrink_size(0), m_next_grow_size(0), m_resize_needed(false) { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_find_search_start() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_find_search_collision() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_find_search_end() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_insert_search_start() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_insert_search_collision() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_insert_search_end() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_erase_search_start() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_erase_search_collision() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_erase_search_end() { PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_inserted(size_type num_entries) { PB_ASSOC_DBG_ASSERT(num_entries <= m_next_grow_size); my_size_base::set_size(num_entries); m_resize_needed = (num_entries == m_next_grow_size); PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline void PB_ASSOC_CLASS_C_DEC:: notify_erased(size_type num_entries) { PB_ASSOC_DBG_ASSERT(num_entries >= m_next_shrink_size); my_size_base::set_size(num_entries); m_resize_needed = (num_entries == m_next_shrink_size); PB_ASSOC_DBG_ONLY(assert_valid();) PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC inline bool PB_ASSOC_CLASS_C_DEC:: is_resize_needed() const { PB_ASSOC_DBG_ONLY(assert_valid();) return (m_resize_needed); } PB_ASSOC_CLASS_T_DEC inline bool PB_ASSOC_CLASS_C_DEC:: is_grow_needed(size_type /*size*/, size_type num_entries) const { PB_ASSOC_DBG_ASSERT(m_resize_needed); return (num_entries >= m_next_grow_size); } PB_ASSOC_CLASS_T_DEC inline bool PB_ASSOC_CLASS_C_DEC:: is_shrink_needed(size_type /*size*/, size_type num_entries) const { PB_ASSOC_DBG_ASSERT(m_resize_needed); return (num_entries <= m_next_shrink_size); } PB_ASSOC_CLASS_T_DEC PB_ASSOC_CLASS_C_DEC:: ~hash_load_check_resize_trigger() { } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: notify_resized(size_type new_size) { m_resize_needed = false; m_next_grow_size = size_type(m_load_max* new_size - 1); m_next_shrink_size = size_type(m_load_min* new_size ); PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: notify_externally_resized(size_type new_size) { m_resize_needed = false; size_type new_grow_size = size_type(m_load_max* new_size - 1); size_type new_shrink_size = size_type(m_load_min* new_size ); if (new_grow_size >= m_next_grow_size) { PB_ASSOC_DBG_ASSERT(new_shrink_size > m_next_shrink_size); m_next_grow_size = new_grow_size; PB_ASSOC_DBG_ONLY(assert_valid();) return; } PB_ASSOC_DBG_ASSERT(new_shrink_size <= m_next_shrink_size); m_next_shrink_size = new_shrink_size; PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: notify_cleared() { my_size_base::set_size(0); m_resize_needed = (0 < m_next_shrink_size); PB_ASSOC_DBG_ONLY(assert_valid();) } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: swap(PB_ASSOC_CLASS_C_DEC& r_other) { PB_ASSOC_DBG_ONLY(assert_valid();) PB_ASSOC_DBG_ONLY(r_other.assert_valid();) my_size_base::swap(r_other); std::swap(m_load_min, r_other.m_load_min); std::swap(m_load_max, r_other.m_load_max); std::swap(m_resize_needed, r_other.m_resize_needed); std::swap(m_next_grow_size, r_other.m_next_grow_size); std::swap(m_next_shrink_size, r_other.m_next_shrink_size); PB_ASSOC_DBG_ONLY(assert_valid();) PB_ASSOC_DBG_ONLY(r_other.assert_valid();) } PB_ASSOC_CLASS_T_DEC inline std::pair<float, float> PB_ASSOC_CLASS_C_DEC:: get_loads() const { return (get_loads_imp(s_external_load_access_ind)); } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: set_loads(std::pair<float, float> load_pair) { set_loads_imp(load_pair, s_external_load_access_ind); } PB_ASSOC_CLASS_T_DEC inline std::pair<float, float> PB_ASSOC_CLASS_C_DEC:: get_loads_imp(pb_assoc::detail::int_to_type<true>) const { return (std::make_pair(m_load_min, m_load_max)); } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: set_loads_imp(std::pair<float, float> load_pair, pb_assoc::detail::int_to_type<true>) { const float old_load_min = m_load_min; const float old_load_max = m_load_max; const size_type old_next_shrink_size = m_next_shrink_size; const size_type old_next_grow_size = m_next_grow_size; const bool old_resize_needed = m_resize_needed; try { m_load_min = load_pair.first; m_load_max = load_pair.second; do_resize(static_cast<size_type>( my_size_base::get_size() / ((m_load_min + m_load_max) / 2))); } catch(...) { m_load_min = old_load_min; m_load_max = old_load_max; m_next_shrink_size = old_next_shrink_size; m_next_grow_size = old_next_grow_size; m_resize_needed = old_resize_needed; throw; } } PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: do_resize(size_type /*new_size*/) { abort(); } #ifdef PB_ASSOC_HT_LOAD_CHECK_RESIZE_TRIGGER_DEBUG PB_ASSOC_CLASS_T_DEC void PB_ASSOC_CLASS_C_DEC:: assert_valid() const { PB_ASSOC_DBG_ASSERT(m_load_max > m_load_min); PB_ASSOC_DBG_ASSERT(m_next_grow_size >= m_next_shrink_size); } #endif // #ifdef PB_ASSOC_HT_LOAD_CHECK_RESIZE_TRIGGER_DEBUG
23.617564
85
0.775099
masami256
e279028b499d8d866b58c52dcde0abd4ff1f6d08
10,848
cpp
C++
R-link/r4aimms/src/r4aimms/src/iAimmsFactory.cpp
aimms/R-Link
42007491f3565429e06d6124a476e3d1080ebee5
[ "DOC", "Unlicense" ]
1
2022-03-07T20:22:47.000Z
2022-03-07T20:22:47.000Z
R-link/r4aimms/src/r4aimms/src/iAimmsFactory.cpp
aimms/R-Link
42007491f3565429e06d6124a476e3d1080ebee5
[ "DOC", "Unlicense" ]
null
null
null
R-link/r4aimms/src/r4aimms/src/iAimmsFactory.cpp
aimms/R-Link
42007491f3565429e06d6124a476e3d1080ebee5
[ "DOC", "Unlicense" ]
2
2017-10-07T01:06:24.000Z
2021-02-25T04:53:46.000Z
/* This file is part of R-Link. R-Link 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. R-Link 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 R-Link. If not, see <http://www.gnu.org/licenses/>. */ #define _CRT_NONSTDC_NO_DEPRECATE #include "iAimmsFactory.h" #include <Common/DynamicLib.h> #include <Common/Array.h> #include <sstream> #include <string.h> #include <iomanip> #ifdef _TARGET_PLATFORM_WINDOWS #include <Psapi.h> #else #include <dlfcn.h> #endif namespace { enum { FOUND_NONE, FOUND_LIB_314, FOUND_LIB_313ASC, FOUND_LIB_313UNI }; #ifdef _TARGET_PLATFORM_WINDOWS #define OS_DLL_EXT ".dll" #define OTHER_DLL_EXT ".so" #define STRCOMPARE stricmp // in windows it does not need to be exact #else #define OS_DLL_EXT ".so" #define OTHER_DLL_EXT ".dll" #define STRCOMPARE strcmp #endif const char *AdjustDllExtension(std::string &path) { std::string::size_type period = path.rfind('.'); if (period == std::string::npos) { path += OS_DLL_EXT; } else if ( STRCOMPARE(path.c_str()+period, OS_DLL_EXT) == 0 ) { // already correct } else if ( STRCOMPARE(path.c_str()+period, OTHER_DLL_EXT) == 0 ) { // replace .so by .dll (or v.v.) path.replace(period,std::string::npos,OS_DLL_EXT); } else { path += OS_DLL_EXT; } return path.c_str(); } #ifdef _TARGET_PLATFORM_WINDOWS std::string getLibProperty( const char* szFilename, const char* szPropertyName) { // retrieve the size of the version info DWORD versionInfoSize = GetFileVersionInfoSizeA( szFilename, 0); if (versionInfoSize == 0 ){ throw std::runtime_error("Unable to get dll version info size."); } // retrieve the version info Common::Array<char> memory(versionInfoSize); char* pData = memory.data(); if (!GetFileVersionInfoA(szFilename, 0, versionInfoSize, pData )){ throw std::runtime_error("Unable to get dll version info"); } // construct the property for the version info value to retrieve, // assumed is the default english language & codepage unsigned short language = 1033; unsigned short codePage = 1200; std::ostringstream ossTmp; ossTmp << "\\StringFileInfo\\"; ossTmp << std::hex << std::setfill ('0') << std::setw(4) << language; ossTmp << std::hex << std::setfill ('0') << std::setw(4) << codePage; ossTmp << "\\" << szPropertyName; // query the value from the version info void* pPropertyValue; UINT uiLen = 0; if (!VerQueryValueA(pData, ossTmp.str().c_str(), &pPropertyValue, &uiLen)){ throw std::runtime_error("Unable to get property from dll version info."); } return std::string((char*)pPropertyValue, ((char*)pPropertyValue)+uiLen); } bool isUnicode(char *szImageName) { try { std::string fileDescription = getLibProperty(szImageName, "FileDescription" ); return fileDescription.find("Unicode") != std::string::npos; } catch (...) { return false; } } bool isUnicodeFromHandle(void *dllHandle) { char szImageName[_MAX_PATH]; ::GetModuleFileNameA((HMODULE)dllHandle,szImageName,_MAX_PATH); return isUnicode(szImageName); } #endif bool NameEndsWith(const char *fullPath, const char *dllName) { int offset = (int)strlen(fullPath) - (int)strlen(dllName); if (offset < 0) return false; return (STRCOMPARE(fullPath+offset,dllName) == 0); } void *TryLoadLibrary(const char *dllPath) { #ifdef _TARGET_PLATFORM_WINDOWS return (void*)::LoadLibraryA(dllPath); #else return ::dlopen(dllPath, RTLD_NOW | RTLD_GLOBAL); #endif } void CloseLibrary(void *handle) { if (handle) { #ifdef _TARGET_PLATFORM_WINDOWS FreeLibrary((HMODULE)handle); #else ::dlclose(handle); #endif } } } namespace aimmsifc { /*static*/ iAimmsFactory &iAimmsFactory::Singleton() { static iAimmsFactory instance; return instance; } iAimmsFactory::iAimmsFactory() : m_Existing_iAimmsCCP(0) , m_Existing_iAimmsUTF8(0) , m_Existing_iAimmsUNI(0) {} iAimmsFactory::~iAimmsFactory() { if (m_Existing_iAimmsCCP) { (dynamic_cast<iFactoryManage*>(m_Existing_iAimmsCCP))->Delete(); } if (m_Existing_iAimmsUTF8) { (dynamic_cast<iFactoryManage*>(m_Existing_iAimmsUTF8))->Delete(); } if (m_Existing_iAimmsUNI) { (dynamic_cast<iFactoryManage*>(m_Existing_iAimmsUNI))->Delete(); } } iAimmsA *iAimmsFactory::GetCCPInterface(bool usedInExternalAimmsDLL, const char *dllSearchPath) { if (m_Existing_iAimmsCCP) { return m_Existing_iAimmsCCP; } std::string dllPath; switch( GetAimmsDllPath(usedInExternalAimmsDLL, dllSearchPath, dllPath) ) { case FOUND_LIB_313ASC: m_Existing_iAimmsCCP = CreateiAimmsA_CCP_313asc(dllPath.c_str()); break; case FOUND_LIB_313UNI: m_Existing_iAimmsCCP = CreateiAimmsA_CCP_313uni(dllPath.c_str()); break; case FOUND_LIB_314: m_Existing_iAimmsCCP = CreateiAimmsA_CCP_314(dllPath.c_str()); break; } return m_Existing_iAimmsCCP; } iAimmsA *iAimmsFactory::GetUTF8Interface(bool usedInExternalAimmsDLL, const char *dllSearchPath) { if (m_Existing_iAimmsUTF8) { return m_Existing_iAimmsUTF8; } std::string dllPath; switch( GetAimmsDllPath(usedInExternalAimmsDLL, dllSearchPath, dllPath) ) { case FOUND_LIB_313ASC: m_Existing_iAimmsUTF8 = CreateiAimmsA_UTF8_313asc(dllPath.c_str()); break; case FOUND_LIB_313UNI: m_Existing_iAimmsUTF8 = CreateiAimmsA_UTF8_313uni(dllPath.c_str()); break; case FOUND_LIB_314: m_Existing_iAimmsUTF8 = CreateiAimmsA_UTF8_314(dllPath.c_str()); break; } return m_Existing_iAimmsUTF8; } iAimmsW *iAimmsFactory::GetUnicodeInterface(bool usedInExternalAimmsDLL, const char *dllSearchPath) { if (m_Existing_iAimmsUNI) { return m_Existing_iAimmsUNI; } std::string dllPath; switch( GetAimmsDllPath(usedInExternalAimmsDLL, dllSearchPath, dllPath) ) { case FOUND_LIB_313ASC: m_Existing_iAimmsUNI = CreateiAimmsW_uni_313asc(dllPath.c_str()); break; case FOUND_LIB_313UNI: m_Existing_iAimmsUNI = CreateiAimmsW_uni_313uni(dllPath.c_str()); break; case FOUND_LIB_314: m_Existing_iAimmsUNI = CreateiAimmsW_uni_314(dllPath.c_str()); break; } return m_Existing_iAimmsUNI; } int iAimmsFactory::GetAimmsDllPath(bool usedInExternalAimmsDLL, const char *dllSearchPath, std::string &dllPath) { int rval = FOUND_NONE; if (usedInExternalAimmsDLL) { rval = FindLibAimmsInCurrentModules(dllPath); if (rval != FOUND_NONE) return rval; } return FindLibAimmsViaTrialAndError(dllSearchPath, dllPath); } int iAimmsFactory::FindLibAimmsInCurrentModules(std::string &dllPath) { int rVal = FOUND_NONE; #ifdef _TARGET_PLATFORM_WINDOWS HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId() ); if (!hProcess) { return rVal; } // Get a list of all the modules in this process. HMODULE hMods[1024]; DWORD cbNeeded; if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for ( size_t i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ ) { char moduleName[MAX_PATH]; // Get the full path to the module's file. if ( GetModuleFileNameExA( hProcess, hMods[i], moduleName, sizeof(moduleName) / sizeof(char))) { if (NameEndsWith(moduleName,"libaimms3" OS_DLL_EXT)) { dllPath = moduleName; rVal = FOUND_LIB_314; break; } else if (NameEndsWith(moduleName,"libaimms" OS_DLL_EXT)) { dllPath = moduleName; if ( isUnicode(moduleName) ) { rVal = FOUND_LIB_313UNI; } else { rVal = FOUND_LIB_313ASC; } break; } } } } // Release the handle to the process. CloseHandle( hProcess ); #else void *libHandle; dllPath = "libaimms3.so"; libHandle = TryLoadLibrary(dllPath.c_str()); if (libHandle) { CloseLibrary(libHandle); return FOUND_LIB_314; } // try 3.13, which on linux is always ASCII dllPath = "libaimms.so"; libHandle = TryLoadLibrary(dllPath.c_str()); if (libHandle) { CloseLibrary(libHandle); return FOUND_LIB_313ASC; } dllPath = ""; #endif return rVal; } int iAimmsFactory::FindLibAimmsViaTrialAndError(const char *dllSearchPath, std::string &dllPath) { void *libHandle; if (dllSearchPath && dllSearchPath[0]) { #ifdef _TARGET_PLATFORM_WINDOWS ::SetDllDirectoryA(dllSearchPath); #endif } // try to find aimms3.14 { #ifdef _TARGET_PLATFORM_WINDOWS dllPath = "libaimms3" OS_DLL_EXT; // 3.14 and later, unicode only #endif #ifdef _TARGET_PLATFORM_LINUX if (dllSearchPath){ dllPath = dllSearchPath; dllPath += "/libaimms3" OS_DLL_EXT; // 3.14 and later, unicode only } else{ dllPath += "libaimms3" OS_DLL_EXT; // 3.14 and later, unicode only } #endif libHandle = TryLoadLibrary(dllPath.c_str()); if (libHandle) { CloseLibrary(libHandle); return FOUND_LIB_314; } } // try to find aimms3.13 { #ifdef _TARGET_PLATFORM_WINDOWS dllPath = "libaimms" OS_DLL_EXT; // 3.13 and earlier, unicode or ascii #endif #ifdef _TARGET_PLATFORM_LINUX if (dllSearchPath){ dllPath = dllSearchPath; dllPath = "/libaimms" OS_DLL_EXT; // 3.13 and earlier, unicode or ascii } else{ dllPath = "libaimms" OS_DLL_EXT; // 3.13 and earlier, unicode or ascii } #endif libHandle = TryLoadLibrary(dllPath.c_str()); if (libHandle) { int rval; #ifdef _TARGET_PLATFORM_WINDOWS if ( isUnicodeFromHandle(libHandle) ) { rval = FOUND_LIB_313UNI; } else { rval = FOUND_LIB_313ASC; } #else // on Linux, aimms3.13 and earlier was *always* ascii rval = FOUND_LIB_313ASC; #endif CloseLibrary(libHandle); return rval; } } return FOUND_NONE; } }
27.393939
113
0.657264
aimms
e27d748c143f733e5a48d9efc8c06593a6e3c981
911
cpp
C++
LeetCode/ThousandTwo/1189-max_num_of_balloons.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1189-max_num_of_balloons.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1189-max_num_of_balloons.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 1189. “气球” 的最大数量 给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。 字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。 示例 1: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/09/14/1536_ex1_upd.jpeg 输入:text = "nlaebolko" 输出:1 示例 2: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/09/14/1536_ex2_upd.jpeg 输入:text = "loonbalxballpoon" 输出:2 示例 3: 输入:text = "leetcode" 输出:0 提示: 1 <= text.length <= 10^4 text 全部由小写英文字母组成 */ int maxNumberOfBalloons(string text) { int T[128] = { 0 }, n = INT_MAX; for (char t : text) T[static_cast<int>(t)] += 1; n = min(n, T['a']); n = min(n, T['b']); n = min(n, T['n']); n = min(n, T['l'] / 2); n = min(n, T['o'] / 2); return n; } int main() { OutExpr(maxNumberOfBalloons("nlaebolko"), "%d"); OutExpr(maxNumberOfBalloons("loonbalxballpoon"), "%d"); OutExpr(maxNumberOfBalloons("leetcode"), "%d"); }
18.591837
84
0.655324
Ginkgo-Biloba
e281a9e8a44cdb8bff2c2fad4e6c870d935bd24d
8,769
cpp
C++
Kernel/test/test_i386_page_table_entry.cpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Kernel/test/test_i386_page_table_entry.cpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Kernel/test/test_i386_page_table_entry.cpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
#include "catch.hpp" #include <platform/i386/page_table_entry.hpp> TEST_CASE("test_i386_page_table_entry_is_present_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PRESENT bit to zero REQUIRE(entry.is_present() == false); } TEST_CASE("test_i386_page_table_entry_is_present_1", "[i386]") { i386::PageTableEntry entry; entry.data = 1; // should set the PRESENT bit to one REQUIRE(entry.is_present() == true); } TEST_CASE("test_i386_page_table_entry_set_present_0", "[i386]") { i386::PageTableEntry entry; entry.data = 1; // should set the PRESENT bit to one entry.set_present(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_present_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PRESENT bit to zero entry.set_present(true); REQUIRE(entry.data == 1); } TEST_CASE("test_i386_page_table_entry_is_readwrite_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the READWRITE bit to zero REQUIRE(entry.is_readwrite() == false); } TEST_CASE("test_i386_page_table_entry_is_readwrite_1", "[i386]") { i386::PageTableEntry entry; entry.data = 2; // should set the READWRITE bit to one REQUIRE(entry.is_readwrite() == true); } TEST_CASE("test_i386_page_table_entry_set_readwrite_0", "[i386]") { i386::PageTableEntry entry; entry.data = 2; // should set the READWRITE bit to one entry.set_readwrite(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_readwrite_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the READWRITE bit to zero entry.set_readwrite(true); REQUIRE(entry.data == 2); } TEST_CASE("test_i386_page_table_entry_is_supervisor_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the SUPERVISOR bit to zero REQUIRE(entry.is_supervisor() == false); } TEST_CASE("test_i386_page_table_entry_is_supervisor_1", "[i386]") { i386::PageTableEntry entry; entry.data = 4; // should set the SUPERVISOR bit to one REQUIRE(entry.is_supervisor() == true); } TEST_CASE("test_i386_page_table_entry_set_supervisor_0", "[i386]") { i386::PageTableEntry entry; entry.data = 4; // should set the SUPERVISOR bit to one entry.set_supervisor(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_supervisor_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the SUPERVISOR bit to zero entry.set_supervisor(true); REQUIRE(entry.data == 4); } TEST_CASE("test_i386_page_table_entry_is_page_write_through_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PWT bit to zero REQUIRE(entry.is_page_write_through() == false); } TEST_CASE("test_i386_page_table_entry_is_page_write_through_1", "[i386]") { i386::PageTableEntry entry; entry.data = 8; // should set the PWT bit to one REQUIRE(entry.is_page_write_through() == true); } TEST_CASE("test_i386_page_table_entry_set_page_write_through_0", "[i386]") { i386::PageTableEntry entry; entry.data = 8; // should set the PWT bit to one entry.set_page_write_through(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_page_write_through_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PWT bit to zero entry.set_page_write_through(true); REQUIRE(entry.data == 8); } TEST_CASE("test_i386_page_table_entry_is_page_cache_disabled_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PCD bit to zero REQUIRE(entry.is_page_cache_disabled() == false); } TEST_CASE("test_i386_page_table_entry_is_page_cache_disabled_1", "[i386]") { i386::PageTableEntry entry; entry.data = 16; // should set the PCD bit to one REQUIRE(entry.is_page_cache_disabled() == true); } TEST_CASE("test_i386_page_table_entry_set_page_cache_disabled_0", "[i386]") { i386::PageTableEntry entry; entry.data = 16; // should set the PCD bit to one entry.set_page_cache_disabled(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_page_cache_disabled_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PCD bit to zero entry.set_page_cache_disabled(true); REQUIRE(entry.data == 16); } TEST_CASE("test_i386_page_table_entry_is_accessed_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the A bit to zero REQUIRE(entry.is_accessed() == false); } TEST_CASE("test_i386_page_table_entry_is_accessed_1", "[i386]") { i386::PageTableEntry entry; entry.data = 32; // should set the A bit to one REQUIRE(entry.is_accessed() == true); } TEST_CASE("test_i386_page_table_entry_set_accessed_0", "[i386]") { i386::PageTableEntry entry; entry.data = 32; // should set the A bit to one entry.set_accessed(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_accessed_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the A bit to zero entry.set_accessed(true); REQUIRE(entry.data == 32); } TEST_CASE("test_i386_page_table_entry_is_dirty_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the D bit to zero REQUIRE(entry.is_dirty() == false); } TEST_CASE("test_i386_page_table_entry_is_dirty_1", "[i386]") { i386::PageTableEntry entry; entry.data = (1 << 6); // should set the D bit to one REQUIRE(entry.is_dirty() == true); } TEST_CASE("test_i386_page_table_entry_set_dirty_0", "[i386]") { i386::PageTableEntry entry; entry.data = (1 << 6); // should set the D bit to one entry.set_dirty(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_dirty_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the D bit to zero entry.set_dirty(true); REQUIRE(entry.data == (1 << 6)); } TEST_CASE("test_i386_page_table_entry_is_pat_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PAT bit to zero REQUIRE(entry.is_pat_bit_set() == false); } TEST_CASE("test_i386_page_table_entry_is_pat_1", "[i386]") { i386::PageTableEntry entry; entry.data = (1 << 7); // should set the PAT bit to one REQUIRE(entry.is_pat_bit_set() == true); } TEST_CASE("test_i386_page_table_entry_set_pat_0", "[i386]") { i386::PageTableEntry entry; entry.data = (1 << 7); // should set the PAT bit to one entry.set_pat_bit(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_pat_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the PAT bit to zero entry.set_pat_bit(true); REQUIRE(entry.data == (1 << 7)); } TEST_CASE("test_i386_page_table_entry_is_global_0", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the G bit to zero REQUIRE(entry.is_global() == false); } TEST_CASE("test_i386_page_table_entry_is_global_1", "[i386]") { i386::PageTableEntry entry; entry.data = (1 << 8); // should set the G bit to one REQUIRE(entry.is_global() == true); } TEST_CASE("test_i386_page_table_entry_set_global_0", "[i386]") { i386::PageTableEntry entry; entry.data = (1 << 8); // should set the G bit to one entry.set_global(false); REQUIRE(entry.data == 0); } TEST_CASE("test_i386_page_table_entry_set_global_1", "[i386]") { i386::PageTableEntry entry; entry.data = 0; // should set the G bit to zero entry.set_global(true); REQUIRE(entry.data == (1 << 8)); } TEST_CASE("test_i386_page_table_entry_set_addr_0", "[i386]") { // Set the address to 0 and ensure that the address bits were changed. i386::PageTableEntry entry; entry.data = ~0; entry.set_address(0); REQUIRE(entry.data == 0xFFF); } TEST_CASE("test_i386_page_table_entry_set_addr_1", "[i386]") { // Set the address to ~0 and ensure that the address bits were changed. i386::PageTableEntry entry; entry.data = 0; entry.set_address(~0); REQUIRE(entry.data == 0xFFFFF000); } TEST_CASE("test_i386_page_table_entry_get_address_0", "[i386]") { // Verify that the address can be retrieved via get_address(). i386::PageTableEntry entry; entry.data = 0xDEADBFFF; REQUIRE(entry.get_address() == 0xDEADB000); } TEST_CASE("test_i386_page_table_entry_get_address_1", "[i386]") { // Try a round-trip through get_address() and set_address() i386::PageTableEntry entry; entry.data = 0; entry.set_address(0xDEADB000); REQUIRE(entry.get_address() == 0xDEADB000); }
28.470779
75
0.696659
foxostro
e288b80aeb1ef619dba5fa09d51bb8b49d89696b
626
cpp
C++
audio/supercollider/files/patch-server_scsynth_SC__CoreAudio.cpp
tbrodel/freebsd-ports
b085486326d414b1bac211b29f98cf3c48d8b2c5
[ "BSD-2-Clause" ]
null
null
null
audio/supercollider/files/patch-server_scsynth_SC__CoreAudio.cpp
tbrodel/freebsd-ports
b085486326d414b1bac211b29f98cf3c48d8b2c5
[ "BSD-2-Clause" ]
null
null
null
audio/supercollider/files/patch-server_scsynth_SC__CoreAudio.cpp
tbrodel/freebsd-ports
b085486326d414b1bac211b29f98cf3c48d8b2c5
[ "BSD-2-Clause" ]
null
null
null
--- server/scsynth/SC_CoreAudio.cpp.orig 2016-02-16 01:19:22 UTC +++ server/scsynth/SC_CoreAudio.cpp @@ -131,7 +131,7 @@ void initializeScheduler() { syncOSCOffsetWithTimeOfDay(); - thread resyncThread(resyncThreadFunc); + std::thread resyncThread(resyncThreadFunc); resyncThread.detach(); } #endif // SC_AUDIO_API_COREAUDIO @@ -449,7 +449,7 @@ void SC_ScheduledEvent::Perform() bool SC_AudioDriver::Setup() { mRunThreadFlag = true; - thread thread(std::bind(&SC_AudioDriver::RunThread, this)); + std::thread thread(std::bind(&SC_AudioDriver::RunThread, this)); mThread = std::move(thread); int numSamples;
29.809524
66
0.726837
tbrodel
e288e19bbe7a4b84fc899e2e7d9140113c0e2f0a
358
cc
C++
log.cc
tigerruanyifan/2048
3a439a1a0e2b6d376f9af43d4733ff90b405dae5
[ "Apache-2.0" ]
null
null
null
log.cc
tigerruanyifan/2048
3a439a1a0e2b6d376f9af43d4733ff90b405dae5
[ "Apache-2.0" ]
null
null
null
log.cc
tigerruanyifan/2048
3a439a1a0e2b6d376f9af43d4733ff90b405dae5
[ "Apache-2.0" ]
null
null
null
#include "log.h" using namespace std; Log::Log(Game *g) : g_(g) { g_->AddActionListener(this); fp_.open("log.txt"); } Log::~Log() { fp_.close(); g_->RemoveActionListener(this); } void Log::ActionPerformed(std::string info) { if (info.length() > 0) Println(info); } void Log::Println(const string &log) { fp_ << log << endl; }
17.9
60
0.600559
tigerruanyifan
e28be966654cd4fce91afbfb8197dd7d88d8c4ba
237
cpp
C++
UAlbertaBot/Source/commands/BWAPICommandExecutor.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
2
2017-07-06T18:27:41.000Z
2018-03-14T06:19:43.000Z
UAlbertaBot/Source/commands/BWAPICommandExecutor.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
18
2017-10-29T20:37:47.000Z
2019-08-25T16:01:28.000Z
UAlbertaBot/Source/commands/BWAPICommandExecutor.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
1
2017-09-13T07:02:23.000Z
2017-09-13T07:02:23.000Z
#include "BWAPICommandExecutor.h" AKBot::BWAPICommandExecutor::BWAPICommandExecutor(BWAPI::Game * game) : _game(game) { } void AKBot::BWAPICommandExecutor::onCommand(const std::string & command) { _game->sendText(command.c_str()); }
19.75
72
0.755274
kant2002
e28d102a8aea96c56719ae2e1f4d3201ff0ec118
3,542
hpp
C++
include/ph_debug/debug.hpp
phiwen96/ph_debug
2801fd37467bc609a5ad19272ca0d9402238822d
[ "Apache-2.0" ]
null
null
null
include/ph_debug/debug.hpp
phiwen96/ph_debug
2801fd37467bc609a5ad19272ca0d9402238822d
[ "Apache-2.0" ]
null
null
null
include/ph_debug/debug.hpp
phiwen96/ph_debug
2801fd37467bc609a5ad19272ca0d9402238822d
[ "Apache-2.0" ]
null
null
null
#pragma once using namespace std; #include <ph_time/time.hpp> #include <ph_color/color.hpp> struct _debug { string function_name; string time_called; __thread_id thread_id; _debug (string&& function_name) : function_name {function_name}, time_called {now ()}, thread_id {this_thread::get_id()} { // cout << function_name << " (...) time: " << time_called << " thread: " << thread_id << endl; } ~_debug () { cout << "========================================" << endl; cout << function_name << "\n\t time: " << time_called << "~ " << now () << "\n\tthread: " << thread_id << endl; cout << "========================================" << endl; } }; //[[nodiscard]] auto debug (string called = __builtin_FUNCTION ()) -> _debug { // return {move (called)}; //} #define debug(x) IF_ELSE(x)(auto _##__COUNTER__ = debug (__PRETTY_FUNCTION__))(); #define debug_called_from string _function_line = to_string (__LINE__), string _called_from_function = __builtin_FUNCTION(), int _called_from_line = __builtin_LINE() #define debug_print_called_from(_color, index) out (index, _color + string (__FUNCTION__) + string ("::") + _function_line, _color + _called_from_function + "::" + to_string(_called_from_line)); cout << white; #define D01(color, index) out(index, text {string (__FUNCTION__) + to_string(__LINE__), string (color)}); cout << white; #define BWRITE(color, index, ...) for(int _j = 0; _j < index; ++_j)cout << "\t"; cout << white << " B " << color; cout << BOOST_PP_STRINGIZE (__VA_ARGS__) << endl; cout << white; #define EWRITE(color, index, ...) for(int _j = 0; _j < index; ++_j)cout << "\t"; cout << cyan << " E " << color; cout << BOOST_PP_STRINGIZE (__VA_ARGS__) << endl; cout << white; #define debug_class_print_called_from(_color, index, ...) out (index, string (_color) + class_name + green + "::" + white + string (__FUNCTION__) + "::" + _function_line, white + string ("called from ") + _called_from_function + "::" + to_string(_called_from_line) __VA_OPT__ (,) __VA_ARGS__); cout << white; #define debug_called_from_none string _called_from_function = ""; int _called_from_line = 0; int _function_line = 0; #define d0 debug_called_from #define d1 debug_class_print_called_from /** out (0, "hej", "då", "kiss"); out (0, "hej", "då"); */ template <bool endline = true, int mellanrum = 30> void out (int shiftFirstLeft, auto&& s1, auto&&... s) { for(int i = 0; i < shiftFirstLeft; ++i) { cout << "\t"; } // cout << right << setw(0) << "[" << index << "] " << s << left << "\t" << s2 << endl; // cout << s << internal << std::setfill('*') << setw(40) << s2 << "\n"; // Green b; cout << ph::color::black << " • " << ph::color::white << left << setw (70) << s1; // cout << left << setw (10); ((cout << ph::color::black << " • " << ph::color::white << left << setw (30) << s), ...); cout << setw (0); if constexpr (endline) cout << endl; // ((cout << black << " • " << white << left << setw(60) << s), ...); // cout << setw(20); // cout << setw(30) << s2 << "--" << "\t" << endl; // cout << white; // SET_COLOR_OR_WHITE(color) // cout << format_string(s, "|", s2) << endl; // << setw(4) << hourlyRate << "\n"; // color << "[" << index << "] " << s << setw(20) << s2 << endl; } //void out (auto&& s, auto&& s2, int index) { // out (white, forward<decltype(s)> (s), forward<decltype(s2)> (s2), index); //}
42.166667
309
0.563241
phiwen96
e28e7297c8c13343a0a40239be45f55c570a89dd
581
cpp
C++
my_work/arrays/array_cars.cpp
korayyalcin1903/c-_work
1a5f6103aa68ae9a16077d972bfeba1a4272789f
[ "MIT" ]
null
null
null
my_work/arrays/array_cars.cpp
korayyalcin1903/c-_work
1a5f6103aa68ae9a16077d972bfeba1a4272789f
[ "MIT" ]
null
null
null
my_work/arrays/array_cars.cpp
korayyalcin1903/c-_work
1a5f6103aa68ae9a16077d972bfeba1a4272789f
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; int main(int argc, char const *argv[]) { setlocale(LC_ALL,"Turkish"); int sayac=1; string cars[4]; for(int j=0;j<4;j++) { cout << "Araba Markasi Giriniz:"; cin >> cars[j]; } cout << "--------------------------------------------------------------------\nAraba Markalari\n--------------------------------------------------------------------\n"; for(int i = 0; i < 4;i++) { cout << sayac++ << "." << cars[i] << endl; } return 0; }
24.208333
173
0.364888
korayyalcin1903
e28f663d13ccbf816a182d0054455c4c783db6ff
727
cpp
C++
leetcode/contest/weekly/228/1758.Minimum-Changes-To-Make-Alternating-Binary-String.cpp
leohr/competitive-programming
f97488e0cb777c1df78257ce2644ac4ff8191267
[ "MIT" ]
1
2020-10-08T19:28:40.000Z
2020-10-08T19:28:40.000Z
leetcode/contest/weekly/228/1758.Minimum-Changes-To-Make-Alternating-Binary-String.cpp
leohr/competitive-programming
f97488e0cb777c1df78257ce2644ac4ff8191267
[ "MIT" ]
null
null
null
leetcode/contest/weekly/228/1758.Minimum-Changes-To-Make-Alternating-Binary-String.cpp
leohr/competitive-programming
f97488e0cb777c1df78257ce2644ac4ff8191267
[ "MIT" ]
1
2020-10-24T02:32:27.000Z
2020-10-24T02:32:27.000Z
class Solution { public: int minOperations(string s) { string s1 = "", s2 = ""; for (int i = 0; i < s.size(); ++i) { if (i % 2 == 0) { s1 += "1"; } else { s1 += "0"; } } for (int i = 0; i < s.size(); ++i) { if (i % 2 == 0) { s2 += "0"; } else { s2 += "1"; } } int c1 = 0, c2 = 0; for (int i = 0; i < s.size(); ++i) { if (s[i] != s1[i]) ++c1; } for (int i = 0; i < s.size(); ++i) { if (s[i] != s2[i]) ++c2; } return min(c1, c2); } };
24.233333
44
0.250344
leohr
e293705a73f1d95891c5dd227758af66209c3051
15,981
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Game2D/collectible_item_05.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Game2D/collectible_item_05.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Game2D/collectible_item_05.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
// Generated by imageconverter. Please, do not edit! #include <touchgfx/hal/Config.hpp> LOCATION_EXTFLASH_PRAGMA KEEP extern const unsigned char _collectible_item_05[] LOCATION_EXTFLASH_ATTRIBUTE = { // 28x28 ARGB8888 pixels. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x1e,0x1e,0x1e,0x11,0x18,0x18,0x24,0x15,0x18,0x18,0x24,0x15,0x15,0x15,0x2a,0x0c, 0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x23,0x23,0x28,0x39,0x26,0x2f,0x35,0xad,0x21,0x32,0x36,0xbc,0x21,0x30,0x37,0xbc,0x21,0x29,0x2e,0x8f,0x28,0x1a,0x28,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x24,0x24,0x07,0x4b,0x5f,0x63,0x8d,0x6c,0xb1,0xb7,0xfb,0x31,0xac,0xbd,0xfe,0x2a,0xaa,0xbd,0xfe,0x2b,0x7c,0x89,0xef,0x27,0x34,0x3b,0x4d,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x28,0x28,0x13,0x4d,0x8f,0x93,0xc2, 0x58,0xec,0xf3,0xff,0x42,0xd0,0xe2,0xff,0x25,0xc6,0xdd,0xff,0x2a,0xb4,0xc7,0xfc,0x29,0x4e,0x54,0x88,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x37,0x44,0x4a,0x29,0x53,0xaf,0xb2,0xe3,0x5b,0xeb,0xf1,0xff,0x53,0xdd,0xeb,0xff,0x25,0xc4,0xdb,0xff,0x29,0xc2,0xd8,0xff, 0x2b,0x66,0x71,0xbb,0x22,0x22,0x22,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x54,0x5d,0x3f,0x5b,0xb1,0xb7,0xee,0x5a,0x95,0x98,0xff,0x5f,0xe3,0xeb,0xff,0x2b,0xc5,0xdc,0xff,0x27,0xc5,0xdc,0xff,0x2b,0x77,0x81,0xde,0x25,0x25,0x2f,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x5b,0x61,0x51,0x5c,0xb5,0xba,0xf5,0x52,0xb0,0xb4,0xff,0x64,0xda,0xe2,0xff,0x2c,0xc8,0xde,0xff,0x27,0xc6,0xdd,0xff,0x27,0x80,0x8e,0xf4,0x25,0x2b,0x36,0x2f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x44,0x68,0x6d,0x64,0x5b,0xc0,0xc5,0xfa, 0x4a,0xd9,0xdd,0xff,0x69,0xce,0xd4,0xff,0x35,0xcd,0xe2,0xff,0x27,0xc6,0xdd,0xff,0x2e,0x90,0x9f,0xfe,0x25,0x2f,0x35,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x47,0x75,0x7b,0x7a,0x57,0xca,0xd0,0xfd,0x42,0xe9,0xf0,0xff,0x65,0xc8,0xcc,0xff,0x3d,0xd1,0xe5,0xff,0x26,0xc5,0xdc,0xff, 0x2d,0x9d,0xad,0xff,0x23,0x2e,0x34,0x74,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x47,0x76,0x7b,0x8c,0x56,0xd0,0xd7,0xff,0x3e,0xee,0xf6,0xff,0x6d,0xce,0xd3,0xff,0x3e,0xd1,0xe3,0xff,0x27,0xc5,0xdd,0xff,0x27,0xa5,0xb8,0xff,0x21,0x2d,0x31,0x8b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x45,0x6f,0x72,0x99,0x5a,0xd5,0xdc,0xff,0x3d,0xf3,0xfb,0xff,0x62,0xd1,0xd6,0xff,0x3e,0xce,0xdf,0xff,0x27,0xc6,0xdd,0xff,0x2a,0xac,0xbf,0xff,0x25,0x30,0x35,0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x46,0x6f,0x72,0xa3,0x57,0xd9,0xe0,0xff, 0x3d,0xf5,0xfd,0xff,0x54,0xd1,0xd5,0xff,0x41,0xcd,0xde,0xff,0x27,0xc6,0xdd,0xff,0x2d,0xb2,0xc5,0xff,0x25,0x34,0x38,0xaf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x55,0x00,0x55,0x03,0x47,0x70,0x75,0xa7,0x52,0xdc,0xe2,0xff,0x3d,0xf6,0xfd,0xff,0x50,0xd0,0xd4,0xff,0x45,0xcf,0xdf,0xff,0x27,0xc6,0xdd,0xff, 0x2e,0xb4,0xc7,0xff,0x26,0x34,0x3a,0xb8,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x55,0x00,0x55,0x03,0x48,0x75,0x78,0xaa,0x50,0xdd,0xe3,0xff,0x3d,0xf6,0xfd,0xff,0x4f,0xd0,0xd5,0xff,0x48,0xcf,0xe0,0xff,0x27,0xc6,0xdd,0xff,0x2e,0xb5,0xc8,0xff,0x28,0x35,0x3b,0xbe,0x7f,0x7f,0x7f,0x02,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x55,0x00,0x55,0x03,0x48,0x73,0x78,0xaa,0x50,0xdd,0xe3,0xff,0x3d,0xf6,0xfd,0xff,0x4f,0xd0,0xd5,0xff,0x47,0xd0,0xe0,0xff,0x27,0xc6,0xdd,0xff,0x2e,0xb5,0xc8,0xff,0x27,0x36,0x3b,0xbb,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x47,0x70,0x75,0xa5,0x54,0xdb,0xe1,0xff, 0x3d,0xf6,0xfd,0xff,0x51,0xd0,0xd4,0xff,0x43,0xce,0xdf,0xff,0x27,0xc6,0xdd,0xff,0x2d,0xb3,0xc7,0xff,0x27,0x35,0x3a,0xb4,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x43,0x6b,0x71,0x9f,0x59,0xd9,0xdf,0xff,0x3d,0xf5,0xfd,0xff,0x58,0xd2,0xd6,0xff,0x40,0xcd,0xde,0xff,0x27,0xc6,0xdd,0xff, 0x2d,0xb2,0xc5,0xff,0x26,0x33,0x38,0xad,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x47,0x72,0x76,0x95,0x59,0xd4,0xdb,0xff,0x3e,0xf1,0xf9,0xff,0x67,0xd1,0xd5,0xff,0x3e,0xcf,0xe0,0xff,0x27,0xc6,0xdd,0xff,0x2b,0xad,0xc0,0xff,0x26,0x32,0x36,0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x46,0x75,0x7b,0x86,0x55,0xce,0xd5,0xfe,0x3f,0xed,0xf4,0xff,0x68,0xcc,0xd1,0xff,0x3e,0xd1,0xe4,0xff,0x26,0xc5,0xdd,0xff,0x28,0xa6,0xb9,0xff,0x20,0x2d,0x32,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x48,0x73,0x77,0x71,0x5b,0xc7,0xcd,0xfd, 0x46,0xe6,0xec,0xff,0x64,0xc8,0xcd,0xff,0x3b,0xd0,0xe4,0xff,0x27,0xc6,0xdd,0xff,0x2d,0x9e,0xaf,0xff,0x23,0x2e,0x34,0x74,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x61,0x67,0x5e,0x5b,0xbe,0xc3,0xf9,0x4b,0xd4,0xd8,0xff,0x68,0xd3,0xd9,0xff,0x33,0xcc,0xe0,0xff,0x27,0xc6,0xdd,0xff, 0x2f,0x94,0xa3,0xfe,0x24,0x30,0x35,0x5a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3d,0x5b,0x62,0x4b,0x5e,0xb6,0xba,0xf2,0x56,0xa5,0xa8,0xff,0x64,0xdf,0xe6,0xff,0x2b,0xc7,0xdd,0xff,0x27,0xc6,0xdd,0xff,0x29,0x86,0x94,0xf8,0x25,0x2f,0x33,0x36,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x50,0x54,0x36,0x57,0xb5,0xb9,0xea,0x60,0xc7,0xca,0xff,0x58,0xe2,0xed,0xff,0x28,0xc4,0xdc,0xff,0x27,0xc6,0xdd,0xff,0x2b,0x7a,0x86,0xe1,0x23,0x2b,0x2b,0x1d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x39,0x4a,0x4a,0x1f,0x4f,0xa7,0xac,0xdb, 0x4c,0xf2,0xf9,0xff,0x51,0xd9,0xe8,0xff,0x24,0xc4,0xdb,0xff,0x28,0xc4,0xdb,0xff,0x29,0x6b,0x76,0xc4,0x1c,0x1c,0x1c,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x24,0x24,0x0e,0x4e,0x84,0x88,0xb3,0x64,0xe3,0xe9,0xfe,0x3d,0xcc,0xdf,0xff,0x27,0xc4,0xdb,0xff,0x2b,0xb5,0xc9,0xfd, 0x2c,0x54,0x5d,0x96,0x2a,0x2a,0x2a,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x3f,0x48,0x4a,0x6d,0x56,0x7b,0x80,0xec,0x2e,0x78,0x85,0xf5,0x2b,0x79,0x85,0xf5,0x2b,0x61,0x6b,0xe7,0x23,0x31,0x37,0x4e,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21,0x21,0x21,0x17,0x21,0x24,0x24,0x55,0x22,0x22,0x27,0x60,0x22,0x22,0x27,0x60,0x20,0x20,0x23,0x4f,0x24,0x24,0x24,0x0e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
202.291139
320
0.796446
ramkumarkoppu
e297eeba0e2bf980f88b15bc5d1e7e354fb864d9
2,233
hpp
C++
aviutl/InputPlugin.hpp
ePi5131/aviutl_exedit_sdk
219be3ede890ab5998618d7f11d9e1987d5f9637
[ "BSD-1-Clause" ]
16
2022-03-26T03:16:14.000Z
2022-03-30T08:29:53.000Z
aviutl/InputPlugin.hpp
ePi5131/aviutl_exedit_sdk
219be3ede890ab5998618d7f11d9e1987d5f9637
[ "BSD-1-Clause" ]
null
null
null
aviutl/InputPlugin.hpp
ePi5131/aviutl_exedit_sdk
219be3ede890ab5998618d7f11d9e1987d5f9637
[ "BSD-1-Clause" ]
null
null
null
#pragma once #include <cstdint> #include <Windows.h> #include <aviutl/InputInfo.hpp> #include <aviutl/InputHandle.hpp> namespace AviUtl{ namespace detail { enum class InputPluginFlag : uint32_t { Video = 1 << 0, Audio = 1 << 1, HasConfig = 1 << 8, Builtin = 1 << 20, VFPlugin = 1 << 22, }; template<> struct flag::ops_def<InputPluginFlag>: std::true_type {}; } struct InputPluginDLL { using Flag = detail::InputPluginFlag; Flag flag; const char* name; const char* filefilter; const char* information; BOOL (*func_init)(); BOOL (*func_exit)(); InputHandle (*func_open)(const char* file); BOOL (*func_close)(InputHandle ih); BOOL (*func_info_get)(InputHandle ih, InputInfo* iip); int32_t (*func_read_video)(InputHandle ih, int32_t frame, void* buf); int32_t (*func_read_audio)(InputHandle ih, int32_t start, int32_t length, void* buf); BOOL (*func_is_keyframe)(InputHandle ih, int32_t frame); BOOL (*func_config)(HWND hwnd, HINSTANCE dll_hinst); int32_t reserve[16]; }; struct InputPlugin { using Flag = detail::InputPluginFlag; Flag flag; const char* name; const char* filefilter; const char* information; BOOL (*func_init)(); BOOL (*func_exit)(); InputHandle (*func_open)(const char* file); BOOL (*func_close)(InputHandle ih); BOOL (*func_info_get)(InputHandle ih, InputInfo* iip); int32_t (*func_read_video)(InputHandle ih, int32_t frame, void* buf); int32_t (*func_read_audio)(InputHandle ih, int32_t start, int32_t length, void* buf); BOOL (*func_is_keyframe)(InputHandle ih, int32_t frame); BOOL (*func_config)(HWND hwnd, HINSTANCE dll_hinst); int32_t reserve[16]; char path[260]; char name2[256]; char filefilter2[256]; char information2[256]; HMODULE hmodule; int32_t ref_count; int32_t index; int32_t unknown1; int32_t unknown2; FARPROC proc; int32_t unknown3[3]; }; }
32.362319
93
0.595163
ePi5131
e29b6a88f5d5cee957da7135f5f95417c9d873ad
644
hpp
C++
include/tuc/functional_detail.hpp
reunanen/tuc
ff062b4779920c089f681694e6fbed6f90ce4eb9
[ "MIT" ]
null
null
null
include/tuc/functional_detail.hpp
reunanen/tuc
ff062b4779920c089f681694e6fbed6f90ce4eb9
[ "MIT" ]
null
null
null
include/tuc/functional_detail.hpp
reunanen/tuc
ff062b4779920c089f681694e6fbed6f90ce4eb9
[ "MIT" ]
null
null
null
#pragma once // To be included only via tuc/functional.hpp namespace tuc { namespace detail { template <typename NotVector> void reserve(NotVector&, size_t) { // By default, do nothing (not std::vector) } template <typename VectorElement> void reserve(std::vector<VectorElement>& vector, size_t new_capacity) { vector.reserve(new_capacity); } template <typename ToValue> auto get_compare_function(ToValue to_value) { return [to_value](const auto& lhs, const auto& rhs) { return to_value(lhs) < to_value(rhs); }; } } }
30.666667
113
0.608696
reunanen
e2a3b93bfda0eb91184c8e594e7bb10f90dff4f1
572
cpp
C++
cpp/2449.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
9
2021-01-15T13:36:39.000Z
2022-02-23T03:44:46.000Z
cpp/2449.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
1
2021-07-31T17:11:26.000Z
2021-08-02T01:01:03.000Z
cpp/2449.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; int n, m, cache[200][200]; vector<int> v; int DFS(int l, int r) { if (r <= l) return 0; int& ret = cache[l][r]; if (ret != -1) return ret; ret = 1e9; for (int i = l; i < r; i++) ret = min(ret, DFS(l, i) + DFS(i + 1, r) + (v[l] != v[r])); return ret; } int main() { fastio; cin >> n >> m; for (int i = 0; i < n; i++) { int t; cin >> t; --t; if (v.empty() || v.back() != t) v.push_back(t); } memset(cache, -1, sizeof cache); cout << DFS(0, v.size() - 1) << '\n'; }
22.88
88
0.520979
jinhan814
e2a7bd72187aa802c3630aab24272555111929fd
4,461
hpp
C++
src/corelib/tle5012b_util.hpp
OlafFilies/magnetic-angle-sensor
87618e9df29ab278e2af5eea7d9120769e197f9f
[ "MIT" ]
39
2019-01-08T23:35:11.000Z
2022-03-13T23:43:04.000Z
src/corelib/tle5012b_util.hpp
OlafFilies/magnetic-angle-sensor
87618e9df29ab278e2af5eea7d9120769e197f9f
[ "MIT" ]
16
2018-11-18T19:19:41.000Z
2022-02-14T14:09:37.000Z
src/corelib/tle5012b_util.hpp
OlafFilies/magnetic-angle-sensor
87618e9df29ab278e2af5eea7d9120769e197f9f
[ "MIT" ]
21
2019-01-18T01:32:47.000Z
2022-02-19T15:51:08.000Z
/*! * \file tle5012b_util.hpp * \name tle5012b_util.hpp - core support header for the TLE5012B angle sensor. * \author Infineon Technologies AG * \copyright 2019-2020 Infineon Technologies AG * \version 3.0.0 * \brief GMR-based angle sensor for angular position sensing in automotive applications * \details * This file includes the registry definition macros of all Sensor registers and * the bit settings for each of the register content values. Depending on * the type of secondary interface (PWM, IIF or HSM) the meaning of some register values * differs, so please have look in the TLE5012 manual for the exact meaning. * Also included here are other sensefull macros for handling the TLE5012 sensor. * \ref tle5012corelib * * SPDX-License-Identifier: MIT * */ #ifndef TLE5012B_UTIL_HPP #define TLE5012B_UTIL_HPP #include <stdint.h> #include <stdlib.h> #include "TLE5012b.hpp" /** * @addtogroup tle5012util * * @{ */ // Common macros #define TRIGGER_DELAY 5 //!< \brief 5 microseconds trigger delay time // Sensor registers #define READ_SENSOR 0x8000 //!< \brief base command for read #define WRITE_SENSOR 0x5000 //!< \brief base command for write #define READ_BLOCK_CRC 0x8088 //!< \brief initialize block CRC check command // Bitmasks for several read and write functions #define SYSTEM_ERROR_MASK 0x4000 //!< \brief System error masks for safety words #define INTERFACE_ERROR_MASK 0x2000 //!< \brief Interface error masks for safety words #define INV_ANGLE_ERROR_MASK 0x1000 //!< \brief Angle error masks for safety words #define CRC_POLYNOMIAL 0x1D //!< \brief values used for calculating the CRC #define CRC_SEED 0xFF #define CRC_NUM_REGISTERS 0x0008 //!< \brief number of CRC relevant registers #define MAX_REGISTER_MEM 0x0030 //!< \brief max readable register values buffer #define MAX_NUM_REG 0x16 //!< \brief defines the value for temporary data to read all readable registers #define DELETE_BIT_15 0x7FFF //!< \brief Value used to delete everything except the first 15 bits #define CHANGE_UINT_TO_INT_15 0x8000 //!< \brief Value used to change unsigned 16bit integer into signed #define CHECK_BIT_14 0x4000 //!< \brief #define GET_BIT_14_4 0x7FF0 //!< \brief #define DELETE_7BITS 0x01FF //!< \brief values used to calculate 9 bit signed integer sent by the sensor #define CHANGE_UNIT_TO_INT_9 0x0200 //!< \brief Value used to change unsigned 9bit integer into signed #define CHECK_BIT_9 0x0100 #define POW_2_15 32768.0 //!< \brief values used to for final calculations of angle speed, revolutions, range and value #define POW_2_7 128.0 //!< \brief #define ANGLE_360_VAL 360.0 //!< \brief #define TEMP_OFFSET 152.0 //!< \brief values used to calculate the temperature #define TEMP_DIV 2.776 /** * @brief Error types from safety word */ enum errorTypes { NO_ERROR = 0x00, //!< \brief NO_ERROR = Safety word was OK SYSTEM_ERROR = 0x01, //!< \brief SYSTEM_ERROR = over/under voltage, VDD negative, GND off, ROM defect INTERFACE_ACCESS_ERROR = 0x02, //!< \brief INTERFACE_ACCESS_ERROR = wrong address or wrong lock INVALID_ANGLE_ERROR = 0x03, //!< \brief INVALID_ANGLE_ERROR = NO_GMR_A = 1 or NO_GMR_XY = 1 ANGLE_SPEED_ERROR = 0x04, //!< \brief ANGLE_SPEED_ERROR = combined error, angular speed calculation wrong CRC_ERROR = 0xFF //!< \brief CRC_ERROR = Cyclic Redundancy Check (CRC), which includes the STAT and RESP bits wrong }; //!< \brief Set the UPDate bit high (read from update buffer) or low (read directly) enum updTypes { UPD_low = 0x0000, //!< \brief read normal registers UPD_high = 0x0400, //!< \brief read update buffer registers }; //!< \brief Switch on/off safety word generation enum safetyTypes { SAFE_low = 0x0000, //!< \brief switch of safety word generation SAFE_high = 0x0001, //!< \brief switch on safety word generation }; /** * @} */ #endif /* TLE5012B_UTIL_HPP */
45.060606
140
0.649182
OlafFilies
e2a85454f073198d84e636299f42591f0c868590
748
cpp
C++
vm/mvm.cpp
alex-ilin/factor
b6f33e03990cb7645201486366d543ae724e8fe1
[ "BSD-2-Clause" ]
930
2016-03-01T08:40:07.000Z
2022-03-29T10:37:39.000Z
vm/mvm.cpp
alex-ilin/factor
b6f33e03990cb7645201486366d543ae724e8fe1
[ "BSD-2-Clause" ]
1,231
2016-02-19T21:52:25.000Z
2022-03-27T23:24:50.000Z
vm/mvm.cpp
alex-ilin/factor
b6f33e03990cb7645201486366d543ae724e8fe1
[ "BSD-2-Clause" ]
118
2016-02-19T21:37:05.000Z
2022-02-21T19:44:02.000Z
#include "master.hpp" namespace factor { std::map<THREADHANDLE, factor_vm*> thread_vms; struct startargs { int argc; vm_char** argv; }; // arg must be new'ed because we're going to delete it! void* start_standalone_factor_thread(void* arg) { factor_vm* newvm = new_factor_vm(); startargs* args = (startargs*)arg; int argc = args->argc; vm_char** argv = args->argv; delete args; newvm->start_standalone_factor(argc, argv); return 0; } VM_C_API THREADHANDLE start_standalone_factor_in_new_thread(int argc, vm_char** argv) { startargs* args = new startargs; args->argc = argc; args->argv = argv; return start_thread(start_standalone_factor_thread, args); } }
23.375
77
0.664439
alex-ilin
e2a98cd9456041a56d6790dc356084581bc1d214
729
cpp
C++
graph/test/bridge.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
20
2021-06-21T00:18:54.000Z
2022-03-17T17:45:44.000Z
graph/test/bridge.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
56
2021-06-03T14:42:13.000Z
2022-03-26T14:15:30.000Z
graph/test/bridge.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
2
2021-08-31T04:47:49.000Z
2021-09-09T06:39:57.000Z
#include "../lowlink.hpp" #include <algorithm> #include <iostream> #include <utility> #include <vector> #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_3_B" int main() { int V, E; std::cin >> V >> E; UndirectedGraph graph(V); for (int i = 0; i < E; i++) { int s, t; std::cin >> s >> t; if (s > t) std::swap(s, t); graph.add_edge(s, t); } graph.detectBridge(); std::vector<std::pair<int, int>> bridges; for (int i = 0; i < E; i++) { if (graph.is_bridge[i]) { bridges.emplace_back(graph.edges[i]); } } std::sort(bridges.begin(), bridges.end()); for (auto pa : bridges) { printf("%d %d\n", pa.first, pa.second); } }
27
82
0.556927
ankit6776
e2ac303c1a1ba24949f1ba890fae7b8417ceab4f
246
cpp
C++
Game/Client/WXClient/Network/PacketHandler/CGPlayerShopBuyItemHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/CGPlayerShopBuyItemHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/CGPlayerShopBuyItemHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "CGPlayerShopBuyItem.h" UINT CGPlayerShopBuyItemHandler::Execute( CGPlayerShopBuyItem* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
17.571429
89
0.796748
hackerlank
e2acdcf00114ac060a2cc23af564d1198f49b18d
11,689
cpp
C++
EngineLuke/src/ML_ENGINE/ML_ENGINE/ML/Association/KmeansClustering.cpp
speed0606/team.luke
6354d8237227276316a8f1e4bb10486a9ab968bf
[ "MIT" ]
3
2016-12-03T08:24:51.000Z
2017-02-26T21:28:29.000Z
EngineLuke/src/ML_ENGINE/ML_ENGINE/ML/Association/KmeansClustering.cpp
dk-seo/team.luke
6354d8237227276316a8f1e4bb10486a9ab968bf
[ "MIT" ]
null
null
null
EngineLuke/src/ML_ENGINE/ML_ENGINE/ML/Association/KmeansClustering.cpp
dk-seo/team.luke
6354d8237227276316a8f1e4bb10486a9ab968bf
[ "MIT" ]
2
2017-02-19T23:41:27.000Z
2017-02-26T21:28:31.000Z
/******************************************************************************/ /*! \file KmeansClustering.cpp \project CS399_TeamLuke \author Hanbyul Jeon, Deok-Hwa (DK) Seo Copyright (C) 2016 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /******************************************************************************/ #include "KMeansClustering.h" #include "../Dataframe/Dataframe.h" #include "../Sampling/RandomSampler.h" static double Sq(double v) { return v * v; } KMeansClustering::KMeansClustering(Dataframe & dataframe, std::vector<std::string> & ignores) : _dataframe(dataframe), _clusters(std::vector<std::vector<const Instance*>>()), _o(nullptr) { _ignores.resize(ignores.size()); for (auto & i : ignores) _ignores.push_back(_dataframe.GetAttributeIndex(i)); CalculateLimits(); if (_ignores.size() != 0) qsort(_ignores.data(), _ignores.size(), sizeof(_ignores.front()), compareMyType); } void KMeansClustering::AddIgnore(std::string & ignore) { int att = _dataframe.GetAttributeIndex(ignore); auto result = std::find(_ignores.begin(), _ignores.end(), att); if(result == _ignores.end()) _ignores.push_back(att); if (_ignores.size() != 0) qsort(_ignores.data(), _ignores.size(), sizeof(_ignores.front()), compareMyType); } void KMeansClustering::RemoveIgnore(std::string & ignores) { int att = _dataframe.GetAttributeIndex(ignores); auto result = std::find(_ignores.begin(), _ignores.end(), att); if (result != _ignores.end()) _ignores.erase(result); } void KMeansClustering::SetDebugOutput(std::ofstream* o) { _o = o; } const std::vector<const Instance*>& KMeansClustering::Get(int i) const { return _clusters[i]; } std::vector<DataPoint> KMeansClustering::SampleDataPoints(const int n) { std::vector<DataPoint> points; points.resize(n); // sample n instances RandomSampler sampler; sampler.Sample(_dataframe, n); // push them into output container //const std::vector<const Instance*>& samples = sampler.GetSamples(); auto samples = sampler.GetSamples(); int pointIndex = 0; for (const auto& sample : samples) { int size = sample->GetAttributeCount(); points[pointIndex].mDataPoints.reserve(size); auto ignore = _ignores.cbegin(); for (int i = 0; i < size; ++i) { if (ignore == _ignores.end() || i != *ignore) points[pointIndex].mDataPoints.push_back(sample->GetAttribute(i).AsDouble()); else points[pointIndex].mDataPoints.push_back(-1.0); if (ignore != _ignores.end()) ++ignore; } ++pointIndex; } return std::move(points); } DataPoint KMeansClustering::ToDataPoint(const Instance* instance) { DataPoint point; int attSize = instance->GetAttributeCount(), dataSize = attSize;// -static_cast<int>(_ignores.size()); point.mDataPoints.resize(dataSize); auto ignoreIndex = _ignores.begin(); for (int instIndex = 0, dataIndex = 0; instIndex < attSize; ++instIndex) { if (ignoreIndex == _ignores.end() || instIndex != *ignoreIndex) { point.mDataPoints[dataIndex++] = instance->GetAttribute(instIndex).AsDouble(); } if (ignoreIndex != _ignores.end()) { if (instIndex == *ignoreIndex) point.mDataPoints[dataIndex++] = 0.0; ++ignoreIndex; } } return std::move(point); } const std::vector<std::pair<double, double>>& KMeansClustering::GetLimits() const { return _limits; } const std::vector<double>& KMeansClustering::GetDiff() const { return _diffs; } DataPoint KMeansClustering::CalculateCentroid(const std::vector<const Instance*>& instances) { DataPoint centroid; if (instances.size() == 0) return centroid; centroid.mDataPoints.resize(instances.front()->GetAttributeCount()); // sums all the given points for (auto & instance : instances) { DataPoint point = ToDataPoint(instance); auto ignore = _ignores.cbegin(); for (int i = 0; i < centroid.mDataPoints.size() && i < point.mDataPoints.size(); ++i) { if (ignore == _ignores.end() || i != *ignore) centroid.mDataPoints[i] += point.mDataPoints[i]; if (ignore != _ignores.end()) ++ignore; } } // divide the sum by the number of instances double divisor = static_cast<double>(instances.size() - _ignores.size()); if (divisor != 0.0) // smooth error handling { for (auto & i : centroid.mDataPoints) i /= divisor; } // return it return std::move(centroid); } void KMeansClustering::PrintClusters(std::ofstream& o) { for (int i = 0; i < int(_clusters.size()); ++i) { DataPoint centroid = CalculateCentroid(_clusters[i]); PrintClusters(o, i + 1, centroid); } } void KMeansClustering::PrintClusters(std::ofstream& o, const int group, const DataPoint& centroid) { // print group info o << "Group " << group << " :" << "n=" << _clusters[group - 1].size() << ", " << "centroid=("; auto & points = centroid.mDataPoints; auto ignore = _ignores.cbegin(); for (int i = 0, size = static_cast<int>(points.size()); i < size; ) { if (ignore == _ignores.end() || *ignore != i) o << points[i]; else o << "NULL"; if (ignore != _ignores.end()) ++ignore; if (++i != size) *_o << ", "; } o << ")" << std::endl; o << "---------------------" << std::endl; // print info of instances for (auto& instance : _clusters[group - 1]) { //o << instance->GetAttribute(0).AsString() << " : "; o << "Tuple[" << group << "] : "; auto ignore = _ignores.begin(); for (int attIndex = 0; attIndex < _dataframe.GetAttributeCount(); ++attIndex) { o << _dataframe.GetAttributeName(attIndex) << "="; if (ignore == _ignores.end() || attIndex != *ignore) o << instance->GetAttribute(attIndex).AsString(); else o << "NULL"; if (ignore != _ignores.end()) ++ignore; if (attIndex + 1 != _dataframe.GetAttributeCount()) o << ","; } o << std::endl; } o << std::endl; } ClusterData KMeansClustering::Cluster(const int k) { // randomly select k points from instances ClusterData centroids = std::move(SampleDataPoints(k)); // prints initial centroids if (_o) { for (int i = 0; i < k; ++i) { (*_o) << "Initial centroid for group " << i + 1 << " : "; auto & points = centroids[i].mDataPoints; auto ignore = _ignores.cbegin(); for (int i = 0, size = static_cast<int>(points.size()); i < size; ) { if (ignore == _ignores.end() || *ignore != i) *_o << points[i]; else { *_o << "NULL"; } if (ignore != _ignores.end()) ++ignore; if (++i != size) *_o << ", "; } *_o << std::endl; } (*_o) << std::endl; } // prepare k clusters _clusters.clear(); _clusters.resize(k); int iteration = 0; bool centroidsChanged = true; double sumDist; while (centroidsChanged) // if centroid is not changed, exit loop { // clear up clusters and sumDist to regroup instances for (auto& cluster : _clusters) cluster.clear(); sumDist = 0.0; // assign each instance to a cluster whose centroid is closest to it auto& instances = _dataframe.GetInstances(); for (auto instance = instances.cbegin(); instance != instances.end(); ++instance) { DataPoint point = ToDataPoint(*instance); // find the closest cluster-group double minDistSq = std::numeric_limits<double>::max(); int minDistCluster = 0; for (int i = 0; i < k; ++i) { double distSq = DistSq(centroids[i], point); if (distSq < minDistSq) { minDistSq = distSq; minDistCluster = i; } } // add instance to the group _clusters[minDistCluster].emplace_back(*instance); if (_o) sumDist += sqrtl(minDistSq); } // debug output : iteration info if (_o) { (*_o) << "-----------------------" << std::endl; (*_o) << "iteration " << iteration << std::endl << std::endl; } // update centroids of clusters with their elements centroidsChanged = false; for (int i = 0; i < k; ++i) { DataPoint centroid = CalculateCentroid(_clusters[i]); auto ignore = _ignores.cbegin(); for (int index = 0, size = static_cast<int>(centroid.mDataPoints.size()); index < size; ++index) { if (ignore == _ignores.end() || *ignore != index) { if (centroids[i].mDataPoints.size() > 0 && centroid.mDataPoints[index] != centroids[i].mDataPoints[index]) centroidsChanged = true; } if (ignore != _ignores.end()) ++ignore; } centroids[i] = centroid; if (_o) PrintClusters(*_o, i + 1, centroid); } if (_o) (*_o) << "Sum Distance : " << sumDist << std::endl; ++iteration; } return std::move(centroids); } double KMeansClustering::DistSq(const DataPoint & p1, DataPoint & p2) { double dist = 0.0; auto ignore = _ignores.cbegin(); for (int i = 0; i < static_cast<int>(p1.mDataPoints.size()) && i < static_cast<int>(p2.mDataPoints.size()); ++i) { if (ignore == _ignores.end() || i != *ignore) { double diff = p1.mDataPoints[i] - p2.mDataPoints[i]; dist += sqrt(diff * diff); } if (ignore != _ignores.end()) ++ignore; } return dist; } void KMeansClustering::CalculateLimits() { _limits.resize(_dataframe.GetAttributeCount(), std::make_pair(std::numeric_limits<double>().max(), std::numeric_limits<double>().min())); auto& instances = _dataframe.GetInstances(); for (auto instance = instances.cbegin(); instance != instances.end(); ++instance) { DataPoint point = ToDataPoint(*instance); for (int i = 0; i < point.mDataPoints.size(); ++i) { if (_limits[i].first > point.mDataPoints[i]) _limits[i].first = point.mDataPoints[i]; if (_limits[i].second < point.mDataPoints[i]) _limits[i].second = point.mDataPoints[i]; } } _diffs.resize(_limits.size()); for (int i = 0, size = static_cast<int>(_limits.size()); i < size; ++i) _diffs[i] = _limits[i].second - _limits[i].first; } double KMeansClustering::Dot(const DataPoint & p1, const DataPoint & p2, const std::vector<int> & ignores, const std::vector<double> & diffs) { if (p1.mDataPoints.size() != p2.mDataPoints.size()) return 0.0; bool isDiffs = true; if (diffs.size() != p1.mDataPoints.size()) isDiffs = false; double dot = 0.0; auto ignore = ignores.cbegin(); for (int i = 0, size = static_cast<int>(p1.mDataPoints.size()); i < size; ++i) { if (ignore == ignores.end() || *ignore != i) { double temp = p1.mDataPoints[i] * p2.mDataPoints[i]; if (isDiffs) temp /= (diffs[i] * diffs[i]); dot += temp; } if (ignore != ignores.end()) ++ignore; } return dot; } double KMeansClustering::Length(const DataPoint & p, const std::vector<int> & ignores, const std::vector<double> & diffs, const bool Sqrt) { double length = 0.0; bool isDiffs = true; if (diffs.size() != p.mDataPoints.size()) isDiffs = false; auto ignore = ignores.cbegin(); for (int i = 0; i < p.mDataPoints.size(); ++i) { if (ignore == ignores.end() || *ignore != i) { double temp = (p.mDataPoints[i] * p.mDataPoints[i]); if (isDiffs) temp /= (diffs[i] * diffs[i]); length += temp; } if (ignore != ignores.end()) ++ignore; } return (Sqrt) ? sqrtl(length) : length; }
26.871264
98
0.598939
speed0606
e2ad1e63ef8826d66c3935972f84cf83ca29653d
3,957
hpp
C++
VirtuWorks/DateTime.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
VirtuWorks/DateTime.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
VirtuWorks/DateTime.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
// // Created by phoenixflower on 11/26/20. // #ifndef LANDESSDEVCORE_VW_DATETIME_HPP #define LANDESSDEVCORE_VW_DATETIME_HPP #include "Chrono/DateTime.h" #include "Primitives/General/StringView.hpp" #include "Primitives/General/ctre.hpp" #include "IO/FetchRequest.h" namespace LD { namespace VW { namespace Detail { static constexpr auto DateTimeRegularExpression = ctll::basic_fixed_string{"\"(\\d{4})-(\\d{1,2})-(\\d{1,2}) (\\d{1,2}):(\\d{1,2}):(\\d{1,2})\""}; static constexpr auto DateTimeRegularExpression1 = ctll::basic_fixed_string{"(\\d{4})-(\\d{1,2})-(\\d{1,2})"}; } class DateTime { private: LD::Date mDate; LD::Time mTime; public: DateTime() noexcept { } DateTime(LD::Date date, LD::Time time) noexcept:mDate{date},mTime{time} { } const LD::Date & Date() const noexcept { return this->mDate; } const LD::Time & Time() const noexcept { return this->mTime; } }; } } namespace LD { template<typename ... A> LD::QueryResult<LD::VW::DateTime(A...)> FromStringView(LD::Type<LD::VW::DateTime>, LD::StringView view, A && ... args) noexcept { //std::cout << "DateTime: " << view << std::endl; if (auto [whole, yearView, monthView, dayView,hourView,minuteView,secondView] = ctre::match<LD::VW::Detail::DateTimeRegularExpression>(view); whole) { //std::cout << "DateTime Year: " << yearView.view() << std::endl; LD::UInteger year = (yearView.view()[0]-'0')*1000 + (yearView.view()[1] - '0')*100 + (yearView.view()[2] - '0')*10 + (yearView.view()[3] - '0')*1; //std::cout << "DateTime Calculation: " << year << std::endl; LD::UInteger month = (monthView.view()[0]-'0')*10 + (monthView.view()[1] - '0')*1; LD::UInteger day = (dayView.view()[0] -'0')*10 + (dayView.view()[1]-'0')*1; LD::UInteger hour = (hourView.view()[0]-'0')*10 + (hourView.view()[1]-'0')*1; LD::UInteger minute = (minuteView.view()[0]-'0')*10 + (minuteView.view()[1]-'0')*1; LD::UInteger second = (secondView.view()[0]-'0')*10 + (secondView.view()[1] - '0')*1; return LD::MakeContext(LD::TransactionResult{},LD::VW::DateTime{LD::Date(LD::Year<LD::UInteger>{LD::UInteger{year}},LD::Month<LD::UInteger>{month},LD::Day<LD::UInteger>{day}),LD::Time(LD::Hour<LD::UInteger>{LD::UInteger (hour)},LD::Minute<LD::UInteger>{LD::UInteger (hour)},LD::Second<LD::UInteger>{LD::UInteger (hour)})},LD::Forward<A>(args)...); } else if (auto [whole, yearView, monthView, dayView] = ctre::match<LD::VW::Detail::DateTimeRegularExpression1>(view); whole) { //std::cout << "DateTime Year: " << yearView.view() << std::endl; LD::UInteger year = (yearView.view()[0]-'0')*1000 + (yearView.view()[1] - '0')*100 + (yearView.view()[2] - '0')*10 + (yearView.view()[3] - '0')*1; //std::cout << "DateTime Calculation: " << year << std::endl; LD::UInteger month = (monthView.view()[0]-'0')*10 + (monthView.view()[1] - '0')*1; LD::UInteger day = (dayView.view()[0] -'0')*10 + (dayView.view()[1]-'0')*1; std::cout << "Year : " << year << " , " << month << " , " << day << std::endl; return LD::MakeContext(LD::TransactionResult{},LD::VW::DateTime{LD::Date(LD::Year<LD::UInteger>{LD::UInteger{year}},LD::Month<LD::UInteger>{month},LD::Day<LD::UInteger>{day}),LD::Time(LD::Hour<LD::UInteger>{LD::UInteger (0)},LD::Minute<LD::UInteger>{LD::UInteger (0)},LD::Second<LD::UInteger>{LD::UInteger (0)})},LD::Forward<A>(args)...); } return LD::MakeContext(LD::TransactionError{},LD::Forward<A>(args)...); } } #endif //LANDESSDEVCORE_DATETIME_HPP
46.011628
359
0.551933
jlandess
e2b07fad535d2682c742dcb01b63c815359f0a2f
3,500
cpp
C++
decnumber_funcs128.cpp
hypnocode/decnumberxx
75a0626c97e53614d36de0e5a519514bb82cb1d4
[ "ICU" ]
3
2016-04-13T17:14:40.000Z
2021-10-05T00:47:03.000Z
decnumber_funcs128.cpp
hypnocode/decnumberxx
75a0626c97e53614d36de0e5a519514bb82cb1d4
[ "ICU" ]
null
null
null
decnumber_funcs128.cpp
hypnocode/decnumberxx
75a0626c97e53614d36de0e5a519514bb82cb1d4
[ "ICU" ]
null
null
null
/*------------------------------------------------------------------------------ decnumberxx Copyright (c) 2012, Hypnocode GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Hypnocode GmbH. 4. Neither the name of Hypnocode GmbH 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 HYPNOCODE GMBH ''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 HYPNOCODE GMBH 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. ------------------------------------------------------------------------------*/ #define DECNUMDIGITS (34) extern "C" { #include "decNumber/decQuad.h" #include "decNumber/decimal128.h" #include "decNumber/decNumber.h" } #include <cassert> extern "C" { void* decQuadFromExpSignedCoef (void* _0, int64_t _1, int32_t _2) noexcept { assert (false); return nullptr; } void* decQuadFromExpUnsignedCoef (void* _0, uint64_t _1, int32_t _2) noexcept { assert (false); return nullptr; } void* decQuadExp (void* _0, const void* _1, decContext* ctx) noexcept { decNumber _0num; decNumber _1num; decQuadToNumber (_1, &_1num); decNumberExp (&_0num, &_1num, ctx); return decQuadFromNumber (_0, &_0num, ctx); } void* decQuadLn (void* _0, const void* _1, decContext* ctx) noexcept { decNumber _0num; decNumber _1num; decQuadToNumber (_1, &_1num); decNumberLn (&_0num, &_1num, ctx); return decQuadFromNumber (_0, &_0num, ctx); } void* decQuadLog10 (void* _0, const void* _1, decContext* ctx) noexcept { decNumber _0num; decNumber _1num; decQuadToNumber (_1, &_1num); decNumberLog10 (&_0num, &_1num, ctx); return decQuadFromNumber (_0, &_0num, ctx); } void* decQuadPower (void* _0, const void* _1, const void* _2, decContext* ctx) noexcept { decNumber _0num; decNumber _1num; decNumber _2num; decQuadToNumber (_1, &_1num); decQuadToNumber (_2, &_2num); decNumberPower (&_0num, &_1num, &_2num, ctx); return decQuadFromNumber (_0, &_0num, ctx); } void* decQuadSquareRoot (void* _0, const void* _1, decContext* ctx) noexcept { decNumber _0num; decNumber _1num; decQuadToNumber (_1, &_1num); decNumberSquareRoot (&_0num, &_1num, ctx); return decQuadFromNumber (_0, &_0num, ctx); } } // extern "C"
28.688525
87
0.716571
hypnocode
e2b0894d87d0b1c8ff7e3bc137d4f78ee62eb941
6,460
hpp
C++
include/libgit2++/configuration.hpp
nabijaczleweli/libgit2pp
5aee94e708ad72ff347f7fb085d1a078fc87c861
[ "MIT" ]
1
2016-11-14T10:39:43.000Z
2016-11-14T10:39:43.000Z
include/libgit2++/configuration.hpp
nabijaczleweli/libgit2pp
5aee94e708ad72ff347f7fb085d1a078fc87c861
[ "MIT" ]
null
null
null
include/libgit2++/configuration.hpp
nabijaczleweli/libgit2pp
5aee94e708ad72ff347f7fb085d1a078fc87c861
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2016 nabijaczleweli // 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. #pragma once #include "guard.hpp" #include "transaction.hpp" #include <experimental/optional> #include <git2/config.h> #include <memory> #include <vector> namespace git2pp { enum class configuration_priority_level { system_wide = GIT_CONFIG_LEVEL_SYSTEM, xdg_compatible = GIT_CONFIG_LEVEL_XDG, global = GIT_CONFIG_LEVEL_GLOBAL, local = GIT_CONFIG_LEVEL_LOCAL, application = GIT_CONFIG_LEVEL_APP, highest = GIT_CONFIG_HIGHEST_LEVEL, }; class configuration_deleter { public: void operator()(git_config * config) const noexcept; }; struct configuration_entry; class configuration : public guard { public: // not `default` because it's a keyword configuration default_config() noexcept; void add_file(const char * path, configuration_priority_level priority, bool force = false) noexcept; void add_file(const std::string path, configuration_priority_level priority, bool force = false) noexcept; configuration open_level(configuration_priority_level priority) const noexcept; configuration open_global() noexcept; configuration_entry operator[](const char * name) const; configuration_entry operator[](const std::string & name) const; std::int32_t int32(const char * name) const noexcept; std::int32_t int32(const std::string & name) const noexcept; void int32(const char * name, std::int32_t value) noexcept; void int32(const std::string & name, std::int32_t value) noexcept; std::int64_t int64(const char * name) const noexcept; std::int64_t int64(const std::string & name) const noexcept; void int64(const char * name, std::int64_t value) noexcept; void int64(const std::string & name, std::int64_t value) noexcept; bool boolean(const char * name) const noexcept; bool boolean(const std::string & name) const noexcept; void boolean(const char * name, bool value) noexcept; void boolean(const std::string & name, bool value) noexcept; std::string path(const char * name) const; std::string path(const std::string & name) const; std::string string(const char * name) const; std::string string(const std::string & name) const; void string(const char * name, const char * value); void string(const std::string & name, const char * value); void string(const char * name, const std::string & value); void string(const std::string & name, const std::string & value); std::vector<configuration_entry> multivar(const char * name, const char * matching = nullptr) const; std::vector<configuration_entry> multivar(const std::string & name, std::experimental::optional<std::string> matching = std::experimental::nullopt) const; void multivar(const char * name, const char * value, const char * matching = nullptr); void multivar(const std::string & name, const std::string & value, std::experimental::optional<std::string> matching = std::experimental::nullopt); void multivar_delete(const char * name, const char * matching = nullptr); void multivar_delete(const std::string & name, std::experimental::optional<std::string> matching = std::experimental::nullopt); template <class F> void foreach(F && func) const; template <class F> void foreach_matching(const char * match, F && func) const; template <class F> void foreach_matching(const std::string & match, F && func) const; transaction lock() noexcept; configuration() noexcept; configuration(const char * path) noexcept; configuration(const std::string & path) noexcept; configuration(const configuration & other) noexcept; private: friend class repository; configuration(git_config * cfg) noexcept; std::unique_ptr<git_config, configuration_deleter> cfg; }; struct configuration_entry { public: std::string name; std::string value; configuration_priority_level priority_level; private: friend class configuration; configuration_entry(git_config_entry * ent); configuration_entry(const git_config_entry * ent); }; std::string global_configuration_path(); std::string xdg_configuration_path(); std::string system_configuration_path(); bool parse_configuration_boolean(const char * value) noexcept; bool parse_configuration_boolean(const std::string & value) noexcept; std::int32_t parse_configuration_int32(const char * value) noexcept; std::int32_t parse_configuration_int32(const std::string & value) noexcept; std::int64_t parse_configuration_int64(const char * value) noexcept; std::int64_t parse_configuration_int64(const std::string & value) noexcept; std::string parse_configuration_path(const char * value); std::string parse_configuration_path(const std::string & value); } template <class F> void git2pp::configuration::foreach(F && func) const { git_config_foreach(cfg.get(), [](const git_config_entry * entry, void * func) { (*reinterpret_cast<F *>(func))(configuration_entry(entry)); }, &func); } template <class F> void git2pp::configuration::foreach_matching(const char * match, F && func) const { git_config_foreach_match(cfg.get(), match, [](const git_config_entry * entry, void * func) { (*reinterpret_cast<F *>(func))(configuration_entry(entry)); }, &func); } template <class F> void git2pp::configuration::foreach_matching(const std::string & match, F && func) const { foreach_matching(match.c_str(), std::forward<F>(func)); }
38.224852
156
0.745975
nabijaczleweli
e2bcce6fbca3eab1127af8bd9af5449d04413d3d
33,298
cpp
C++
test/unit/argument_parser/format_parse_validators_test.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
test/unit/argument_parser/format_parse_validators_test.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
test/unit/argument_parser/format_parse_validators_test.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <fstream> #include <range/v3/view/remove_if.hpp> #include <range/v3/algorithm/equal.hpp> #include <seqan3/argument_parser/all.hpp> #include <seqan3/alphabet/all.hpp> #include <seqan3/io/stream/parse_condition.hpp> #include <seqan3/range/view/persist.hpp> #include <seqan3/std/filesystem> #include <seqan3/test/tmp_filename.hpp> using namespace seqan3; TEST(validator_test, fullfill_concept) { EXPECT_FALSE(validator_concept<int>); EXPECT_TRUE(validator_concept<detail::default_validator<int>>); EXPECT_TRUE(validator_concept<detail::default_validator<int> const>); EXPECT_TRUE(validator_concept<detail::default_validator<int> &>); EXPECT_TRUE(validator_concept<detail::default_validator<std::vector<int>>>); EXPECT_TRUE(validator_concept<arithmetic_range_validator>); EXPECT_TRUE(validator_concept<value_list_validator<double>>); EXPECT_TRUE(validator_concept<value_list_validator<std::string>>); EXPECT_TRUE(validator_concept<regex_validator>); EXPECT_TRUE(validator_concept<file_ext_validator>); EXPECT_TRUE(validator_concept<path_existence_validator>); EXPECT_TRUE(validator_concept<decltype(file_ext_validator{{"t"}} | regex_validator{".*"})>); } TEST(validator_test, no_file) { // file { std::filesystem::path p{"./sandbox.fasta"}; std::string s{"./stonebox.fasta"}; path_existence_validator my_validator{}; EXPECT_THROW(my_validator(p), parser_invalid_argument); EXPECT_THROW(my_validator(s), parser_invalid_argument); std::filesystem::path file_in_path; // option const char * argv[] = {"./argument_parser_test", "-i", "./sandbox.fasta"}; argument_parser parser("test_parser", 3, argv); parser.add_option(file_in_path, 'i', "int-option", "desc", option_spec::DEFAULT, path_existence_validator{}); EXPECT_THROW(parser.parse(), parser_invalid_argument); } // directory { std::filesystem::path p{"./sandbox/"}; std::string s{"./stonebox/"}; path_existence_validator my_validator{}; EXPECT_THROW(my_validator(p), parser_invalid_argument); EXPECT_THROW(my_validator(s), parser_invalid_argument); std::filesystem::path dir_in_path; // option const char * argv[] = {"./argument_parser_test", "-i", "./sandbox/"}; argument_parser parser("test_parser", 3, argv); parser.add_option(dir_in_path, 'i', "int-option", "desc", option_spec::DEFAULT, path_existence_validator{}); EXPECT_THROW(parser.parse(), parser_invalid_argument); } } TEST(validator_test, file_exists) { test::tmp_filename tmp_name{"testbox.fasta"}; // file { std::ofstream tmp_file(tmp_name.get_path()); path_existence_validator my_validator{}; EXPECT_NO_THROW(my_validator(tmp_name.get_path())); std::filesystem::path file_in_path; // option std::filesystem::path path = tmp_name.get_path(); const char * argv[] = {"./argument_parser_test", "-i", path.c_str()}; argument_parser parser("test_parser", 3, argv); parser.add_option(file_in_path, 'i', "int-option", "desc", option_spec::DEFAULT, path_existence_validator{}); EXPECT_NO_THROW(parser.parse()); } // directory { std::ofstream tmp_dir(tmp_name.get_path().parent_path()); path_existence_validator my_validator{}; EXPECT_NO_THROW(my_validator(tmp_name.get_path().parent_path())); std::filesystem::path dir_in_path; // option std::filesystem::path path = tmp_name.get_path().parent_path(); const char * argv[] = {"./argument_parser_test", "-i", path.c_str()}; argument_parser parser("test_parser", 3, argv); parser.add_option(dir_in_path, 'i', "int-option", "desc", option_spec::DEFAULT, path_existence_validator{}); EXPECT_NO_THROW(parser.parse()); } { // get help page message std::filesystem::path path; const char * argv[] = {"./argument_parser_test", "-h"}; argument_parser parser("test_parser", 2, argv); parser.add_positional_option(path, "desc", path_existence_validator{}); testing::internal::CaptureStdout(); EXPECT_EXIT(parser.parse(), ::testing::ExitedWithCode(EXIT_SUCCESS), ""); std::string my_stdout = testing::internal::GetCapturedStdout(); std::string expected = std::string("test_parser" "===========" "POSITIONAL ARGUMENTS" " ARGUMENT-1 (std::filesystem::path)" " desc The file or directory is checked for existence." "VERSION" " Last update: " " test_parser version: " " SeqAn version: ") + seqan3_version; EXPECT_TRUE(ranges::equal((my_stdout | std::view::filter(!is_space)), expected | std::view::filter(!is_space))); } } TEST(validator_test, file_ext_validator) { std::string option_value; std::vector<std::string> option_vector; file_ext_validator case_sensitive_file_ext_validator({"sAm", "FASTQ", "fasta" }, true); file_ext_validator case_insensitive_file_ext_validator({"sAm", "FASTQ", "fasta"}, false); file_ext_validator no_extension_file_ext_validator({""}); file_ext_validator default_file_ext_validator({"sAm", "FASTQ", "fasta"}); // check case insensitive validator => success { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.sam"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, case_insensitive_file_ext_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file.sam"); } // check case sensitive validator => failure { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.sam"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, case_sensitive_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } // check default (case insensitive) validator => success { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.FaStQ"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, default_file_ext_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file.FaStQ"); } // check case sensitive validator => success { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.FASTQ"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, case_sensitive_file_ext_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file.FASTQ"); } // check case insensitive validator => failure { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.bAm"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, case_insensitive_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } // check no file suffix => failure { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, case_sensitive_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } // check file suffix with no_ext_validator => failure { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.txt"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, no_extension_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } // check trailing dot with no_ext_validator => failure { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file."}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, no_extension_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } // check no file extension with no_ext_validator => success { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, no_extension_file_ext_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file"); } } TEST(validator_test, arithmetic_range_validator_success) { int option_value; std::vector<int> option_vector; // option const char * argv[] = {"./argument_parser_test", "-i", "10"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 'i', "int-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(1, 20)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, 10); // option - negative values const char * argv2[] = {"./argument_parser_test", "-i", "-10"}; argument_parser parser2("test_parser", 3, argv2); parser2.add_option(option_value, 'i', "int-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(-20, 20)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser2.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, -10); // positional option const char * argv3[] = {"./argument_parser_test", "10"}; argument_parser parser3("test_parser", 2, argv3); parser3.add_positional_option(option_value, "desc", arithmetic_range_validator(1, 20)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser3.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, 10); // positional option - negative values const char * argv4[] = {"./argument_parser_test", "--", "-10"}; argument_parser parser4("test_parser", 3, argv4); parser4.add_positional_option(option_value, "desc", arithmetic_range_validator(-20, 20)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser4.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, -10); // option - vector const char * argv5[] = {"./argument_parser_test", "-i", "-10", "-i", "48"}; argument_parser parser5("test_parser", 5, argv5); parser5.add_option(option_vector, 'i', "int-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(-50,50)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser5.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_vector[0], -10); EXPECT_EQ(option_vector[1], 48); // positional option - vector option_vector.clear(); const char * argv6[] = {"./argument_parser_test", "--", "-10", "1"}; argument_parser parser6("test_parser", 4, argv6); parser6.add_positional_option(option_vector, "desc", arithmetic_range_validator(-20,20)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser6.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_vector[0], -10); EXPECT_EQ(option_vector[1], 1); // get help page message option_vector.clear(); const char * argv7[] = {"./argument_parser_test", "-h"}; argument_parser parser7("test_parser", 2, argv7); parser7.add_positional_option(option_vector, "desc", arithmetic_range_validator(-20,20)); testing::internal::CaptureStdout(); EXPECT_EXIT(parser7.parse(), ::testing::ExitedWithCode(EXIT_SUCCESS), ""); std::string my_stdout = testing::internal::GetCapturedStdout(); std::string expected = std::string("test_parser" "===========" "POSITIONAL ARGUMENTS" " ARGUMENT-1 (List of signed 32 bit integer's)" " desc Value must be in range [-20,20]." "VERSION" " Last update: " " test_parser version: " " SeqAn version: ") + seqan3_version; EXPECT_TRUE(ranges::equal((my_stdout | std::view::filter(!is_space)), expected | std::view::filter(!is_space))); // option - double value double double_option_value; const char * argv8[] = {"./argument_parser_test", "-i", "10.9"}; argument_parser parser8("test_parser", 3, argv8); parser8.add_option(double_option_value, 'i', "double-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(1, 20)); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser8.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_FLOAT_EQ(double_option_value, 10.9); } TEST(validator_test, arithmetic_range_validator_error) { int option_value; std::vector<int> option_vector; // option - above max const char * argv[] = {"./argument_parser_test", "-i", "30"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 'i', "int-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(1, 20)); EXPECT_THROW(parser.parse(), validation_failed); // option - below min const char * argv2[] = {"./argument_parser_test", "-i", "-21"}; argument_parser parser2("test_parser", 3, argv2); parser2.add_option(option_value, 'i', "int-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(-20, 20)); EXPECT_THROW(parser2.parse(), validation_failed); // positional option - above max const char * argv3[] = {"./argument_parser_test", "30"}; argument_parser parser3("test_parser", 2, argv3); parser3.add_positional_option(option_value, "desc", arithmetic_range_validator(1, 20)); EXPECT_THROW(parser3.parse(), validation_failed); // positional option - below min const char * argv4[] = {"./argument_parser_test", "--", "-21"}; argument_parser parser4("test_parser", 3, argv4); parser4.add_positional_option(option_value, "desc", arithmetic_range_validator(-20, 20)); EXPECT_THROW(parser4.parse(), validation_failed); // option - vector const char * argv5[] = {"./argument_parser_test", "-i", "-100"}; argument_parser parser5("test_parser", 3, argv5); parser5.add_option(option_vector, 'i', "int-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(-50, 50)); EXPECT_THROW(parser5.parse(), validation_failed); // positional option - vector option_vector.clear(); const char * argv6[] = {"./argument_parser_test", "--", "-10", "100"}; argument_parser parser6("test_parser", 4, argv6); parser6.add_positional_option(option_vector, "desc", arithmetic_range_validator(-20, 20)); EXPECT_THROW(parser6.parse(), validation_failed); // option - double value double double_option_value; const char * argv7[] = {"./argument_parser_test", "-i", "0.9"}; argument_parser parser7("test_parser", 3, argv7); parser7.add_option(double_option_value, 'i', "double-option", "desc", option_spec::DEFAULT, arithmetic_range_validator(1, 20)); EXPECT_THROW(parser7.parse(), validation_failed); } TEST(validator_test, value_list_validator_success) { std::string option_value; int option_value_int; std::vector<std::string> option_vector; std::vector<int> option_vector_int; // option const char * argv[] = {"./argument_parser_test", "-s", "ba"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, value_list_validator({"ha", "ba", "ma"})); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "ba"); // option with integers const char * argv2[] = {"./argument_parser_test", "-i", "-21"}; argument_parser parser2("test_parser", 3, argv2); parser2.add_option(option_value_int, 'i', "int-option", "desc", option_spec::DEFAULT, value_list_validator<int>({0, -21, 10})); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser2.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value_int, -21); // positional option const char * argv3[] = {"./argument_parser_test", "ma"}; argument_parser parser3("test_parser", 2, argv3); parser3.add_positional_option(option_value, "desc", value_list_validator({"ha", "ba", "ma"})); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser3.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "ma"); // positional option - vector const char * argv4[] = {"./argument_parser_test", "ha", "ma"}; argument_parser parser4("test_parser", 3, argv4); parser4.add_positional_option(option_vector, "desc", value_list_validator({"ha", "ba", "ma"})); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser4.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_vector[0], "ha"); EXPECT_EQ(option_vector[1], "ma"); // option - vector const char * argv5[] = {"./argument_parser_test", "-i", "-10", "-i", "48"}; argument_parser parser5("test_parser", 5, argv5); parser5.add_option(option_vector_int, 'i', "int-option", "desc", option_spec::DEFAULT, value_list_validator<int>({-10,48,50})); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser5.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_vector_int[0], -10); EXPECT_EQ(option_vector_int[1], 48); // get help page message option_vector.clear(); const char * argv7[] = {"./argument_parser_test", "-h"}; argument_parser parser7("test_parser", 2, argv7); parser7.add_option(option_vector_int, 'i', "int-option", "desc", option_spec::DEFAULT, value_list_validator<int>({-10,48,50})); testing::internal::CaptureStdout(); EXPECT_EXIT(parser7.parse(), ::testing::ExitedWithCode(EXIT_SUCCESS), ""); std::string my_stdout = testing::internal::GetCapturedStdout(); std::string expected = std::string("test_parser" "===========" "OPTIONS" " -i, --int-option (List of signed 32 bit integer's)" " desc Value must be one of [-10,48,50]." "VERSION" " Last update: " " test_parser version: " " SeqAn version: ") + seqan3_version; EXPECT_TRUE(ranges::equal((my_stdout | std::view::filter(!is_space)), expected | std::view::filter(!is_space))); } TEST(validator_test, value_list_validator_error) { std::string option_value; int option_value_int; std::vector<std::string> option_vector; std::vector<int> option_vector_int; // option const char * argv[] = {"./argument_parser_test", "-s", "sa"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, value_list_validator({"ha", "ba", "ma"})); EXPECT_THROW(parser.parse(), validation_failed); // positional option const char * argv3[] = {"./argument_parser_test", "30"}; argument_parser parser3("test_parser", 2, argv3); parser3.add_positional_option(option_value_int, "desc", value_list_validator({0, 5, 10})); EXPECT_THROW(parser3.parse(), validation_failed); // positional option - vector const char * argv4[] = {"./argument_parser_test", "fo", "ma"}; argument_parser parser4("test_parser", 3, argv4); parser4.add_positional_option(option_vector, "desc", value_list_validator({"ha", "ba", "ma"})); EXPECT_THROW(parser4.parse(), validation_failed); // option - vector const char * argv5[] = {"./argument_parser_test", "-i", "-10", "-i", "488"}; argument_parser parser5("test_parser", 5, argv5); parser5.add_option(option_vector_int, 'i', "int-option", "desc", option_spec::DEFAULT, value_list_validator<int>({-10,48,50})); EXPECT_THROW(parser5.parse(), validation_failed); } TEST(validator_test, regex_validator_success) { std::string option_value; std::vector<std::string> option_vector; regex_validator email_validator("[a-zA-Z]+@[a-zA-Z]+\\.com"); regex_validator email_vector_validator("[a-zA-Z]+@[a-zA-Z]+\\.com"); // option const char * argv[] = {"./argument_parser_test", "-s", "ballo@rollo.com"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, email_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "ballo@rollo.com"); // positional option const char * argv2[] = {"./argument_parser_test", "chr1"}; argument_parser parser2("test_parser", 2, argv2); parser2.add_positional_option(option_value, "desc", regex_validator{"^chr[0-9]+"}); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser2.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "chr1"); // positional option - vector const char * argv3[] = {"./argument_parser_test", "rollo", "bollo", "lollo"}; argument_parser parser3("test_parser", 4, argv3); parser3.add_positional_option(option_vector, "desc", regex_validator{".*oll.*"}); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser3.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_vector[0], "rollo"); EXPECT_EQ(option_vector[1], "bollo"); EXPECT_EQ(option_vector[2], "lollo"); // option - vector option_vector.clear(); const char * argv4[] = {"./argument_parser_test", "-s", "rita@rambo.com", "-s", "tina@rambo.com"}; argument_parser parser4("test_parser", 5, argv4); parser4.add_option(option_vector, 's', "string-option", "desc", option_spec::DEFAULT, email_vector_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser4.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_vector[0], "rita@rambo.com"); EXPECT_EQ(option_vector[1], "tina@rambo.com"); // get help page message option_vector.clear(); const char * argv7[] = {"./argument_parser_test", "-h"}; argument_parser parser7("test_parser", 2, argv7); parser7.add_option(option_vector, 's', "string-option", "desc", option_spec::DEFAULT, email_vector_validator); testing::internal::CaptureStdout(); EXPECT_EXIT(parser7.parse(), ::testing::ExitedWithCode(EXIT_SUCCESS), ""); std::string my_stdout = testing::internal::GetCapturedStdout(); std::string expected = std::string("test_parser" "===========" "OPTIONS" " -s, --string-option (List of std::string's)" " desc Value must match the pattern '[a-zA-Z]+@[a-zA-Z]+\\.com'." "VERSION" " Last update: " " test_parser version: " " SeqAn version: ") + seqan3_version; EXPECT_TRUE(ranges::equal((my_stdout | ranges::view::remove_if(is_space)), expected | ranges::view::remove_if(is_space))); } TEST(validator_test, regex_validator_error) { std::string option_value; std::vector<std::string> option_vector; // option const char * argv[] = {"./argument_parser_test", "--string-option", "sally"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, '\0', "string-option", "desc", option_spec::DEFAULT, regex_validator("tt")); EXPECT_THROW(parser.parse(), validation_failed); // positional option const char * argv2[] = {"./argument_parser_test", "jessy"}; argument_parser parser2("test_parser", 2, argv2); parser2.add_positional_option(option_value, "desc", regex_validator("[0-9]")); EXPECT_THROW(parser2.parse(), validation_failed); // positional option - vector const char * argv3[] = {"./argument_parser_test", "rollo", "bttllo", "lollo"}; argument_parser parser3("test_parser", 4, argv3); parser3.add_positional_option(option_vector, "desc", regex_validator{".*oll.*"}); EXPECT_THROW(parser3.parse(), validation_failed); // option - vector option_vector.clear(); const char * argv4[] = {"./argument_parser_test", "-s", "gh", "-s", "tt"}; argument_parser parser4("test_parser", 5, argv4); parser4.add_option(option_vector, 's', "", "desc", option_spec::DEFAULT, regex_validator("tt")); EXPECT_THROW(parser4.parse(), validation_failed); } TEST(validator_test, chaining_validators) { std::string option_value; std::vector<std::string> option_vector; regex_validator absolute_path_validator("(/[^/]+)+/.*\\.[^/\\.]+$"); file_ext_validator my_file_ext_validator({"sa", "so"}); // option { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.sa"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, absolute_path_validator | my_file_ext_validator); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file.sa"); } { const char * argv[] = {"./argument_parser_test", "-s", "relative/path/file.sa"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, absolute_path_validator | my_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } { const char * argv[] = {"./argument_parser_test", "-s", "/absoulte/path/file.notValidExtension"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, absolute_path_validator | my_file_ext_validator); EXPECT_THROW(parser.parse(), validation_failed); } // with temporary validators { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.sa"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, regex_validator{"(/[^/]+)+/.*\\.[^/\\.]+$"} | file_ext_validator{"sa", "so"}); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file.sa"); } // three validators { const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.sa"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, regex_validator{"(/[^/]+)+/.*\\.[^/\\.]+$"} | file_ext_validator{"sa", "so"} | regex_validator{".*"}); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_value, "/absolute/path/file.sa"); } // help page message { const char * argv[] = {"./argument_parser_test", "-h"}; argument_parser parser("test_parser", 2, argv); parser.add_option(option_value, 's', "string-option", "desc", option_spec::DEFAULT, regex_validator{"(/[^/]+)+/.*\\.[^/\\.]+$"} | file_ext_validator{"sa", "so"} | regex_validator{".*"}); testing::internal::CaptureStdout(); EXPECT_EXIT(parser.parse(), ::testing::ExitedWithCode(EXIT_SUCCESS), ""); std::string my_stdout = testing::internal::GetCapturedStdout(); std::string expected = std::string("test_parser" "===========" "OPTIONS" " -s, --string-option (std::string)" " desc Value must match the pattern '(/[^/]+)+/.*\\.[^/\\.]+$'. " " File name extension must be one of [sa,so]." " Value must match the pattern '.*'." "VERSION" " Last update: " " test_parser version: " " SeqAn version: ") + seqan3_version; EXPECT_TRUE(ranges::equal((my_stdout | ranges::view::remove_if(is_space)), expected | ranges::view::remove_if(is_space))); } // chaining with a container option value type { std::vector<std::string> option_list_value{}; const char * argv[] = {"./argument_parser_test", "-s", "/absolute/path/file.sa"}; argument_parser parser("test_parser", 3, argv); parser.add_option(option_list_value, 's', "string-option", "desc", option_spec::DEFAULT, regex_validator{"(/[^/]+)+/.*\\.[^/\\.]+$"} | file_ext_validator{"sa", "so"}); testing::internal::CaptureStderr(); EXPECT_NO_THROW(parser.parse()); EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty()); EXPECT_EQ(option_list_value[0], "/absolute/path/file.sa"); } }
42.635083
120
0.610847
Clemapfel
e2bdd1d34ba3370b78cc3c9b27fcbd2ec664264b
622
cpp
C++
git_C++/SET IV/Tema SET 4/11/main.cpp
sorinmiroiu97/old-CPP-stuff
d6f7b3573c1f81597795cea75c5f76fd95c4395b
[ "MIT" ]
1
2021-11-28T14:36:35.000Z
2021-11-28T14:36:35.000Z
git_C++/SET IV/Tema SET 4/11/main.cpp
sorinmiroiu97/old-CPP-stuff
d6f7b3573c1f81597795cea75c5f76fd95c4395b
[ "MIT" ]
null
null
null
git_C++/SET IV/Tema SET 4/11/main.cpp
sorinmiroiu97/old-CPP-stuff
d6f7b3573c1f81597795cea75c5f76fd95c4395b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int n,i,x[100],y[100],a=1,b; int main() { cout <<"Introduceti numarul de elemente n="; cin>>n; cout<<"Introduceti elementele vectorului x"<<endl; for(i=1;i<=n;i++) { cout<<"x["<<i<<"]="; cin>>x[i]; } cout<<"Introduceti elementele vectorului y"<<endl; for(i=1;i<=n;i++) { cout<<"y["<<i<<"]="; cin>>y[i]; } for(i=1;i<=n;i++) { a=a*(x[i]+y[i]); b=b+x[i]*y[i]; } cout<<"a)"<<endl<<"e="<<a<<endl; cout<<"b)"<<endl<<"e="<<b; return 0; }
20.733333
55
0.42283
sorinmiroiu97
e2cb0e179d9942ec0888cfced6f69dbc7896cc33
1,149
cpp
C++
hydrogen-runtime/hydrogen/main.cpp
quadnix/hydrogen-cpp
872768ae1a62b12b8a6dca0d8d33305172b9628d
[ "MIT" ]
null
null
null
hydrogen-runtime/hydrogen/main.cpp
quadnix/hydrogen-cpp
872768ae1a62b12b8a6dca0d8d33305172b9628d
[ "MIT" ]
null
null
null
hydrogen-runtime/hydrogen/main.cpp
quadnix/hydrogen-cpp
872768ae1a62b12b8a6dca0d8d33305172b9628d
[ "MIT" ]
null
null
null
// // main.cpp // hydrogen // // Created by Patrick Kage on 4/10/15. // Copyright (c) 2015 Patrick Kage. All rights reserved. // #include <iostream> #include <unistd.h> #include "errors.h" #include "errorstack.h" #include "fextractor.h" #include "directivebundle.h" #include "reference.h" #include "value.h" #include "context.h" #include "directiveprocessor.h" #include "dpspooler.h" #include "functiondict.h" #include "dpspooler_req.h" #include "nativeprovider.h" #include "interpreter.h" string getworkingdir() { char cwd_tmp[256]; getcwd(cwd_tmp, 256); string cwd(cwd_tmp); return cwd; } int main(int argc, const char * argv[]) { //cout << "running at" << getworkingdir() << "\n"; if (argc != 2) { cout << "no file to run!\n"; return -1; } string fn = argv[1]; hyd::Interpreter interpreter; interpreter.loadFromFile(fn); interpreter.setBinaryLocation("/usr/local/hydrogen/lib"); while (!interpreter.done()) { if (interpreter.hasErrors()) { break; } interpreter.tick(); } cout << interpreter.getErrorReport(); return 0; }
20.157895
61
0.628372
quadnix
e2cb58df563f204d1cdf6c833d6ea160d91ced7b
236
cpp
C++
BaiTap-Loop/songhicdao/main.cpp
namanhishere/cpp
109988fb91e10c986cd1111cd2c543a056f4e560
[ "MIT" ]
1
2021-09-25T14:40:33.000Z
2021-09-25T14:40:33.000Z
BaiTap-Loop/songhicdao/main.cpp
namanhishere/cpp
109988fb91e10c986cd1111cd2c543a056f4e560
[ "MIT" ]
null
null
null
BaiTap-Loop/songhicdao/main.cpp
namanhishere/cpp
109988fb91e10c986cd1111cd2c543a056f4e560
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int inp; cin >> inp; int n = inp; int out = 0; while(n / 10 != 0){ out = out*10+n%10; n = n /10; } cout << out*10+n/10; return 0; }
13.111111
26
0.457627
namanhishere
e2cd932023abd07d5da02773b90938c4a897fa44
1,546
cpp
C++
fictional-fiesta/world/src/Phenotype.cpp
deStagiaire/fictional-fiesta
689e374885774b6eb7b8c11b1224204d7893ca07
[ "MIT" ]
null
null
null
fictional-fiesta/world/src/Phenotype.cpp
deStagiaire/fictional-fiesta
689e374885774b6eb7b8c11b1224204d7893ca07
[ "MIT" ]
null
null
null
fictional-fiesta/world/src/Phenotype.cpp
deStagiaire/fictional-fiesta
689e374885774b6eb7b8c11b1224204d7893ca07
[ "MIT" ]
null
null
null
/// @file Phenotype.cpp Implementation of the Phenotype class. #include "fictional-fiesta/world/itf/Phenotype.h" #include "fictional-fiesta/utils/itf/XmlNode.h" #include <sstream> namespace fictionalfiesta { namespace { constexpr char XML_ENERGY_NAME[]{"Energy"}; } // anonymous namespace Phenotype::Phenotype(double initialEnergy): _energy(initialEnergy) { } Phenotype::Phenotype(const XmlNode& node): _energy(node.getChildNodeTextAs<double>(XML_ENERGY_NAME)) { } double Phenotype::getEnergy() const { return _energy; } void Phenotype::feed(double energyConsumed, const Genotype& genotype) { // Currently the phenotype is just energy, so we just increase it in the same ammount than the // resource units aquired. _energy += energyConsumed; } Phenotype Phenotype::split(const Genotype& genotype) { _energy *= 0.5; return Phenotype{_energy}; } std::string Phenotype::str(unsigned int indentLevel) const { std::stringstream result; result << indent(indentLevel) << "Energy: " << _energy << "\n"; return result.str(); } void Phenotype::doSave(XmlNode& node) const { auto energy_node = node.appendChildNode(XML_ENERGY_NAME); energy_node.setText(_energy); } std::string Phenotype::getDefaultXmlName() const { return XML_MAIN_NODE_NAME; } bool operator==(const Phenotype& lhs, const Phenotype& rhs) { if (lhs._energy != rhs._energy) { return false; } return true; } bool operator!=(const Phenotype& lhs, const Phenotype& rhs) { return !(lhs == rhs); } } // namespace fictionalfiesta
19.08642
96
0.725744
deStagiaire
e2ce37baf40e88509fc348ad8717f9866fbddeb4
416
cpp
C++
C++/maximum-distance-between-a-pair-of-values.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/maximum-distance-between-a-pair-of-values.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/maximum-distance-between-a-pair-of-values.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n + m) // Space: O(1) class Solution { public: int maxDistance(vector<int>& nums1, vector<int>& nums2) { int result = 0, i = 0, j = 0; while (i < size(nums1) && j < size(nums2)) { if (nums1[i] > nums2[j]) { ++i; } else { result = max(result, j - i); ++j; } } return result; } };
21.894737
61
0.391827
Priyansh2
e2cf2e4a6fe60b74226959062f564b961d1678a6
582
cpp
C++
CodingNinjas/IsoscelesStarPattern.cpp
Sidharth-S-S/MyCppRepository
e03589b64ed65127b4a14a87e4c4054d9e4d8cc9
[ "MIT" ]
2
2022-02-03T02:43:32.000Z
2022-03-23T05:56:10.000Z
CodingNinjas/IsoscelesStarPattern.cpp
Sidharth-S-S/MyCppRepository
e03589b64ed65127b4a14a87e4c4054d9e4d8cc9
[ "MIT" ]
null
null
null
CodingNinjas/IsoscelesStarPattern.cpp
Sidharth-S-S/MyCppRepository
e03589b64ed65127b4a14a87e4c4054d9e4d8cc9
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ /* Read input as specified in the question. * Print output as specified in the question. */ int n ; cin >> n ; for (int i=1;i<=n;i++) { // print the spaces 1st ; in ith row i-1 spaces to print for (int j = 1 ; j<=n-i;j++) { cout << " " ; } // Now print the star . As stars can be printed at a go hence we have to print ith row : 2i -1 no of stars for (int k = 1; k <= 2*i-1 ; k++) { cout << "*" ; } cout << endl; } }
24.25
114
0.484536
Sidharth-S-S
e2cfa6ee1464ee2f8e7106095f33a292af806968
2,570
cpp
C++
build/source/NxOgreUtil.cpp
betajaen/nxogre
ab2fb93754fa5876191de2e27a416b501f480180
[ "MIT" ]
22
2015-03-11T20:32:30.000Z
2022-03-05T23:16:10.000Z
build/source/NxOgreUtil.cpp
betajaen/nxogre
ab2fb93754fa5876191de2e27a416b501f480180
[ "MIT" ]
1
2021-07-03T14:13:14.000Z
2021-07-03T14:13:14.000Z
build/source/NxOgreUtil.cpp
betajaen/nxogre
ab2fb93754fa5876191de2e27a416b501f480180
[ "MIT" ]
13
2015-02-09T14:30:24.000Z
2020-03-20T11:51:55.000Z
/** This file is part of NxOgre. Copyright (c) 2009 Robin Southern, http://www.nxogre.org 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 "NxOgreStable.h" #include "NxOgreUtil.h" #include "NxOgreSimple.h" #include "NxOgreFunctions.h" #include "NxOgreRay.h" #include "NxPhysics.h" namespace NxOgre { namespace Util { bool NxOgrePublicFunction RayPlaneIntersect(const Ray& ray, const SimplePlane& simplePlane, Real& distance, Vec3& pointOnPlane) { NxPlane plane; plane.d = simplePlane.mDistance; plane.normal = simplePlane.mNormal.as<NxVec3>(); NxRay inRay; inRay.dir = ray.mDirection.as<NxVec3>(); inRay.orig = ray.mOrigin.as<NxVec3>(); NxVec3 physxPointOnPlane; bool result = NxGetUtilLib()->NxRayPlaneIntersect(inRay, plane, distance, physxPointOnPlane); pointOnPlane.from<NxVec3>(physxPointOnPlane); return result; } } } // namespace NxOgre
34.266667
127
0.563035
betajaen
e2d8cd90935e0fba1ac9c349b08023737111dc01
10,767
cpp
C++
src/sim/search/ExpertKnowledge.cpp
gamerpuppy/sts_lightspeed
dc3ac7c05cf759987da6c95bca70592d987101b0
[ "MIT" ]
12
2021-09-06T19:29:12.000Z
2022-03-17T02:16:59.000Z
src/sim/search/ExpertKnowledge.cpp
gamerpuppy/sts_lightspeed
dc3ac7c05cf759987da6c95bca70592d987101b0
[ "MIT" ]
1
2022-01-27T14:24:54.000Z
2022-01-27T14:24:54.000Z
src/sim/search/ExpertKnowledge.cpp
gamerpuppy/sts_lightspeed
dc3ac7c05cf759987da6c95bca70592d987101b0
[ "MIT" ]
1
2022-01-20T07:09:45.000Z
2022-01-20T07:09:45.000Z
// // Created by keega on 9/19/2021. // #include "sim/search/ExpertKnowledge.h" using namespace sts; int sts::search::Expert::getPlayOrdering(CardId id) { switch (id) { case CardId::NORMALITY: return -30; case CardId::PAIN: return -25; case CardId::APOTHEOSIS: case CardId::APPARITION: return -20; case CardId::ARMAMENTS: return -15; case CardId::CORRUPTION: return -10; case CardId::PANACHE: case CardId::RUPTURE: return -5; case CardId::DARK_EMBRACE: case CardId::FEEL_NO_PAIN: case CardId::BLOODLETTING: case CardId::SPOT_WEAKNESS: case CardId::OFFERING: return -2; case CardId::BARRICADE: case CardId::BERSERK: case CardId::DEMON_FORM: return 0; case CardId::EVOLVE: case CardId::MAYHEM: case CardId::BRUTALITY: case CardId::FIRE_BREATHING: case CardId::METALLICIZE: return 3; case CardId::MASTER_OF_STRATEGY: return 4; case CardId::SADISTIC_NATURE: case CardId::PANACEA: case CardId::SECRET_TECHNIQUE: case CardId::SECRET_WEAPON: return 5; case CardId::DARK_SHACKLES: case CardId::FINESSE: case CardId::BATTLE_TRANCE: case CardId::DISARM: case CardId::ENLIGHTENMENT: case CardId::INFLAME: case CardId::COMBUST: case CardId::INTIMIDATE: case CardId::BLIND: case CardId::IMPERVIOUS: case CardId::LIMIT_BREAK: case CardId::TRIP: case CardId::SHOCKWAVE: case CardId::SEEING_RED: return 10; case CardId::JUGGERNAUT: case CardId::MADNESS: case CardId::POWER_THROUGH: case CardId::RAGE: case CardId::TRANSMUTATION: return 15; case CardId::PANIC_BUTTON: case CardId::MAGNETISM: case CardId::JACK_OF_ALL_TRADES: case CardId::BURNING_PACT: case CardId::DOUBLE_TAP: case CardId::DUAL_WIELD: case CardId::CHRYSALIS: case CardId::DEEP_BREATH: case CardId::DISCOVERY: case CardId::INFERNAL_BLADE: case CardId::METAMORPHOSIS: case CardId::HAVOC: case CardId::FORETHOUGHT: case CardId::WARCRY: case CardId::SECOND_WIND: case CardId::THINKING_AHEAD: case CardId::SHRUG_IT_OFF: case CardId::JAX: return 20; case CardId::EXHUME: case CardId::IMPATIENCE: case CardId::TRUE_GRIT: case CardId::THE_BOMB: return 22; case CardId::BASH: case CardId::UPPERCUT: case CardId::THUNDERCLAP: return 25; case CardId::SEVER_SOUL: case CardId::WHIRLWIND: case CardId::GOOD_INSTINCTS: case CardId::GHOSTLY_ARMOR: case CardId::VIOLENCE: case CardId::SWIFT_STRIKE: return 27; case CardId::IMMOLATE: case CardId::CLASH: case CardId::BLOOD_FOR_BLOOD: case CardId::BLUDGEON: case CardId::CARNAGE: case CardId::REAPER: case CardId::DRAMATIC_ENTRANCE: return 30; case CardId::SEARING_BLOW: case CardId::RAMPAGE: case CardId::POMMEL_STRIKE: case CardId::HAND_OF_GREED: case CardId::PERFECTED_STRIKE: case CardId::HEMOKINESIS: case CardId::HEAVY_BLADE: case CardId::WILD_STRIKE: case CardId::SWORD_BOOMERANG: return 35; case CardId::DROPKICK: case CardId::FIEND_FIRE: case CardId::CLEAVE: case CardId::RECKLESS_CHARGE: case CardId::FLAME_BARRIER: case CardId::FLASH_OF_STEEL: case CardId::FEED: case CardId::RITUAL_DAGGER: return 40; case CardId::PUMMEL: case CardId::TWIN_STRIKE: case CardId::CLOTHESLINE: case CardId::ANGER: case CardId::BITE: case CardId::BANDAGE_UP: case CardId::BODY_SLAM: case CardId::MIND_BLAST: return 50; case CardId::SENTINEL: case CardId::IRON_WAVE: case CardId::ENTRENCH: case CardId::PURITY: return 52; case CardId::STRIKE_RED: case CardId::DEFEND_RED: case CardId::HEADBUTT: return 55; case CardId::BURN: case CardId::DECAY: case CardId::CLUMSY: case CardId::WOUND: case CardId::DAZED: case CardId::VOID: return 60; case CardId::REGRET: case CardId::SHAME: case CardId::DOUBT: return 65; case CardId::SLIMED: case CardId::NECRONOMICURSE: case CardId::WRITHE: case CardId::PRIDE: case CardId::PARASITE: case CardId::ASCENDERS_BANE: case CardId::CURSE_OF_THE_BELL: case CardId::INJURY: return 70; case CardId::INVALID: default: return 10000; } } int search::Expert::getBossRelicOrdering(RelicId id) { switch (id) { case RelicId::RUNIC_DOME: return -1; case RelicId::ECTOPLASM: case RelicId::COFFEE_DRIPPER: case RelicId::FUSION_HAMMER: return 0; case RelicId::PANDORAS_BOX: case RelicId::BUSTED_CROWN: case RelicId::CURSED_KEY: case RelicId::SOZU: return 1; case RelicId::VELVET_CHOKER: case RelicId::SNECKO_EYE: case RelicId::SLAVERS_COLLAR: case RelicId::MARK_OF_PAIN: return 2; case RelicId::BLACK_BLOOD: return 3; case RelicId::TINY_HOUSE: case RelicId::ASTROLABE: case RelicId::CALLING_BELL: return 5; case RelicId::RUNIC_CUBE: case RelicId::PHILOSOPHERS_STONE: return 5; case RelicId::SACRED_BARK: case RelicId::RUNIC_PYRAMID: case RelicId::BLACK_STAR: return 10; default: return 100; } } int search::Expert::getObtainWeight(CardId id) { switch (id) { case CardId::APOTHEOSIS: case CardId::APPARITION: case CardId::CORRUPTION: return 100; case CardId::IMPERVIOUS: case CardId::DEMON_FORM: return 95; case CardId::BARRICADE: case CardId::FEEL_NO_PAIN: return 85; case CardId::MASTER_OF_STRATEGY: return 70; case CardId::RITUAL_DAGGER: case CardId::BRUTALITY: case CardId::FIEND_FIRE: case CardId::SECRET_TECHNIQUE: case CardId::BLUDGEON: case CardId::IMMOLATE: case CardId::OFFERING: case CardId::FLEX: case CardId::SPOT_WEAKNESS: return 65; case CardId::LIMIT_BREAK: return 40; case CardId::BERSERK: case CardId::WHIRLWIND: return 35; case CardId::REAPER: case CardId::DARK_EMBRACE: case CardId::MAYHEM: case CardId::PANACEA: case CardId::SECRET_WEAPON: case CardId::INFLAME: case CardId::CARNAGE: case CardId::DRAMATIC_ENTRANCE: case CardId::JAX: return 30; case CardId::RUPTURE: case CardId::FEED: return 25; case CardId::BLOOD_FOR_BLOOD: case CardId::ARMAMENTS: case CardId::DARK_SHACKLES: case CardId::FINESSE: case CardId::BATTLE_TRANCE: case CardId::DISARM: case CardId::BLIND: case CardId::TRIP: case CardId::SHOCKWAVE: case CardId::PERFECTED_STRIKE: case CardId::EVOLVE: return 20; case CardId::UPPERCUT: case CardId::POWER_THROUGH: case CardId::SECOND_WIND: case CardId::FLAME_BARRIER: return 18; case CardId::SEVER_SOUL: case CardId::INTIMIDATE: case CardId::JUGGERNAUT: case CardId::MADNESS: case CardId::RAGE: case CardId::TRANSMUTATION: case CardId::HAND_OF_GREED: case CardId::SHRUG_IT_OFF: return 15; case CardId::CLOTHESLINE: case CardId::ENTRENCH: case CardId::ENLIGHTENMENT: case CardId::FLASH_OF_STEEL: return 12; case CardId::FIRE_BREATHING: case CardId::COMBUST: case CardId::CLEAVE: case CardId::PANACHE: case CardId::EXHUME: case CardId::SEEING_RED: case CardId::SADISTIC_NATURE: case CardId::PANIC_BUTTON: case CardId::BURNING_PACT: case CardId::DOUBLE_TAP: case CardId::DUAL_WIELD: case CardId::CHRYSALIS: case CardId::DISCOVERY: case CardId::INFERNAL_BLADE: case CardId::METAMORPHOSIS: case CardId::HAVOC: case CardId::SENTINEL: case CardId::HEMOKINESIS: case CardId::HEAVY_BLADE: return 8; case CardId::METALLICIZE: case CardId::ANGER: case CardId::THINKING_AHEAD: case CardId::MAGNETISM: case CardId::JACK_OF_ALL_TRADES: case CardId::DEEP_BREATH: case CardId::IMPATIENCE: case CardId::TRUE_GRIT: case CardId::THE_BOMB: case CardId::WARCRY: case CardId::GHOSTLY_ARMOR: case CardId::WILD_STRIKE: case CardId::POMMEL_STRIKE: return 6; case CardId::BLOODLETTING: case CardId::GOOD_INSTINCTS: case CardId::VIOLENCE: case CardId::SWIFT_STRIKE: case CardId::FORETHOUGHT: case CardId::HEADBUTT: return 5; case CardId::CLASH: case CardId::PUMMEL: return 4; case CardId::THUNDERCLAP: case CardId::RAMPAGE: case CardId::SWORD_BOOMERANG: return 3; case CardId::DROPKICK: case CardId::RECKLESS_CHARGE: case CardId::IRON_WAVE: case CardId::TWIN_STRIKE: return 2; case CardId::BITE: case CardId::BANDAGE_UP: case CardId::BASH: case CardId::BODY_SLAM: return 1; case CardId::MIND_BLAST: case CardId::PURITY: case CardId::SEARING_BLOW: case CardId::STRIKE_RED: case CardId::DEFEND_RED: return 0; default: return 0; } } int search::Expert::getObtainWeight(CardId id, bool upgraded) { if (upgraded) { return getObtainWeight(id) * 1.5; } else { return getObtainWeight(id); } }
25.393868
63
0.568032
gamerpuppy
e2dbbfc80bcb616a0299dbc11876660fa990a83e
177
cpp
C++
PETCS/Intermediate/helloworld.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
PETCS/Intermediate/helloworld.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
PETCS/Intermediate/helloworld.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { cin.sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << "Hello, World!" << "\n"; return 0; }
19.666667
37
0.542373
dl4us
e2e04a43c7fad8002d8ef31c22871c95a062cf10
62,712
cpp
C++
dp/gl/src/Texture.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
217
2015-01-06T09:26:53.000Z
2022-03-23T14:03:18.000Z
dp/gl/src/Texture.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
10
2015-01-25T12:42:05.000Z
2017-11-28T16:10:16.000Z
dp/gl/src/Texture.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
44
2015-01-13T01:19:41.000Z
2022-02-21T21:35:08.000Z
// Copyright (c) 2014-2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 <dp/gl/Texture.h> #include <dp/gl/inc/TextureBind.h> #include <dp/gl/inc/TextureDSA.h> namespace dp { namespace gl { namespace { inline ITexture * getGLInterface() { static TextureBind glInterfaceBind; static TextureDSA glInterfaceDSA; static ITexture* glInterface = GLEW_EXT_direct_state_access ? static_cast<ITexture*>(&glInterfaceDSA) : static_cast<ITexture*>(&glInterfaceBind); return( glInterface ); } // Wrapper class for nD uploads for textures. // It can handle TexSubImage and TexImage as well as compressed data class TexGLTransfer { public: TexGLTransfer( GLenum texture, GLenum target, GLint level, GLenum internalFormat, GLenum dataFormat, GLenum dataType , const void *dataPtr, GLsizei width, GLsizei height = 1, GLsizei depth = 1, GLsizei dataSize = 0 ); typedef void (TexGLTransfer::*PNFTEXGLUPLOAD)(); GLenum m_target; GLint m_level; GLenum m_internalFormat; GLenum m_dataFormat; GLenum m_dataType; const void *m_dataPtr; GLsizei m_width; GLsizei m_height; GLsizei m_depth; size_t m_dataSize; GLsizei m_xOffset; GLsizei m_yOffset; GLsizei m_zOffset; void Create1D(); void Create2D(); void Create3D(); void Update1D(); void Update2D(); void Update3D(); void Create1DCompressed(); void Create2DCompressed(); void Create3DCompressed(); void Update1DCompressed(); void Update2DCompressed(); void Update3DCompressed(); // uses "compressed" path when m_dataSize is != 0 void doTransfer(int dimension, bool update ); static PNFTEXGLUPLOAD getTransferFunction(int dimension, bool update, bool compressed ); private: GLenum m_texture; }; typedef TexGLTransfer::PNFTEXGLUPLOAD TexGLUploadFunc; TexGLTransfer::TexGLTransfer( GLenum texture, GLenum target, GLint level, GLenum internalFormat, GLenum dataFormat, GLenum dataType, const void *dataPtr, GLsizei width, GLsizei height, GLsizei depth, GLsizei dataSize ) : m_texture(texture) , m_target(target) , m_level(level) , m_internalFormat(internalFormat) , m_dataFormat(dataFormat) , m_dataType(dataType) , m_dataPtr(dataPtr) , m_width(width) , m_height(height) , m_depth(depth) , m_dataSize(dataSize) , m_xOffset(0) , m_yOffset(0) , m_zOffset(0) { } void TexGLTransfer::Create1D() { getGLInterface()->setImage1D( m_texture, m_target, m_level, m_internalFormat, m_width, 0, m_dataFormat, m_dataType, m_dataPtr ); } void TexGLTransfer::Create2D() { getGLInterface()->setImage2D( m_texture, m_target, m_level, m_internalFormat, m_width, m_height, 0, m_dataFormat, m_dataType, m_dataPtr ); } void TexGLTransfer::Create3D() { getGLInterface()->setImage3D( m_texture, m_target, m_level, m_internalFormat, m_width, m_height, m_depth, 0, m_dataFormat, m_dataType, m_dataPtr ); } void TexGLTransfer::Update1D() { getGLInterface()->setSubImage1D( m_texture, m_target, m_level, m_xOffset, m_width, m_dataFormat, m_dataType, m_dataPtr ); } void TexGLTransfer::Update2D() { getGLInterface()->setSubImage2D( m_texture, m_target, m_level, m_xOffset, m_yOffset, m_width, m_height, m_dataFormat, m_dataType, m_dataPtr ); } void TexGLTransfer::Update3D() { getGLInterface()->setSubImage3D( m_texture, m_target, m_level, m_xOffset, m_yOffset, m_zOffset, m_width, m_height, m_depth, m_dataFormat, m_dataType, m_dataPtr ); } void TexGLTransfer::Create1DCompressed() { getGLInterface()->setCompressedImage1D( m_texture, m_target, m_level, m_internalFormat, m_width, 0, (GLsizei)m_dataSize, m_dataPtr ); } void TexGLTransfer::Create2DCompressed() { getGLInterface()->setCompressedImage2D( m_texture, m_target, m_level, m_internalFormat, m_width, m_height, 0, (GLsizei)m_dataSize, m_dataPtr ); } void TexGLTransfer::Create3DCompressed() { getGLInterface()->setCompressedImage3D( m_texture, m_target, m_level, m_internalFormat, m_width, m_height, m_depth, 0, (GLsizei)m_dataSize, m_dataPtr ); } void TexGLTransfer::Update1DCompressed() { getGLInterface()->setCompressedSubImage1D( m_texture, m_target, m_level, m_xOffset, m_width, m_internalFormat, (GLsizei)m_dataSize, m_dataPtr ); } void TexGLTransfer::Update2DCompressed() { getGLInterface()->setCompressedSubImage2D( m_texture, m_target, m_level, m_xOffset, m_yOffset, m_width, m_height, m_internalFormat, (GLsizei)m_dataSize, m_dataPtr ); } void TexGLTransfer::Update3DCompressed() { getGLInterface()->setCompressedSubImage3D( m_texture, m_target, m_level, m_xOffset, m_yOffset, m_zOffset, m_width, m_height, m_depth, m_internalFormat, (GLsizei)m_dataSize, m_dataPtr ); } TexGLTransfer::PNFTEXGLUPLOAD TexGLTransfer::getTransferFunction( int dimension, bool update, bool compressed ) { DP_ASSERT( 1 <= dimension && dimension <= 3 ); static const TexGLTransfer::PNFTEXGLUPLOAD funcs[] = { &TexGLTransfer::Create1D, &TexGLTransfer::Create2D, &TexGLTransfer::Create3D, &TexGLTransfer::Update1D, &TexGLTransfer::Update2D, &TexGLTransfer::Update3D, &TexGLTransfer::Create1DCompressed, &TexGLTransfer::Create2DCompressed, &TexGLTransfer::Create3DCompressed, &TexGLTransfer::Update1DCompressed, &TexGLTransfer::Update2DCompressed, &TexGLTransfer::Update3DCompressed, }; return funcs[ (compressed ? 6 : 0) + (update ? 3 : 0) + (dimension - 1) ]; } inline void TexGLTransfer::doTransfer( int dimension, bool update ) { ((*this).*getTransferFunction( dimension, update, m_dataSize != 0 ))(); } inline unsigned int numberOfMipmaps(unsigned int w, unsigned int h, unsigned int d) { unsigned int bits = dp::math::max( w, h, d ); unsigned int i=1; while (bits >>= 1) { ++i; } return i; } bool isCompressedSizeKnown( GLenum format ) { switch (format) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB: case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB: case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: case GL_COMPRESSED_RED_RGTC1: case GL_COMPRESSED_SIGNED_RED_RGTC1: case GL_COMPRESSED_RG_RGTC2: case GL_COMPRESSED_SIGNED_RG_RGTC2: case GL_COMPRESSED_LUMINANCE_LATC1_EXT: case GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT: case GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: case GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT: return true; } return false; } void getTexImage( const Texture *texGL, GLenum target, void *data, GLuint mipLevel ) { DP_ASSERT( texGL ); DP_ASSERT( texGL->getInternalFormat() != ~0 ); if ( isCompressedFormat( texGL->getFormat() ) ) { getGLInterface()->getCompressedImage( texGL->getGLId(), target, mipLevel, data ); } else { getGLInterface()->getImage( texGL->getGLId(), target, mipLevel, texGL->getFormat(), texGL->getType(), data ); } } GLsizei getMipMapSize( GLsizei sz, GLuint level ) { sz = (sz >> level); return sz ? sz : 1; } bool sizeValid( GLenum target, GLsizei w, GLsizei h, GLsizei d, GLsizei layers ) { // init to zero so comparison at bottom will fail on unknown texture GLsizei maxw = 0; GLsizei maxh = 0; GLsizei maxd = 0; GLsizei maxl = 0; bool powerOfTwoCheck = true; switch( target ) { case GL_TEXTURE_1D: maxw = Texture1D::getMaximumSize(); maxh = 1; maxd = 1; maxl = 0; break; case GL_TEXTURE_2D: maxw = Texture2D::getMaximumSize(); maxh = maxw; maxd = 1; maxl = 0; break; case GL_TEXTURE_RECTANGLE_ARB: maxw = TextureRectangle::getMaximumSize(); maxh = maxw; maxd = 1; powerOfTwoCheck = false; maxl = 0; break; case GL_TEXTURE_3D: maxw = Texture3D::getMaximumSize(); maxh = maxw; maxd = maxh; maxl = 0; break; case GL_TEXTURE_CUBE_MAP: maxw = TextureCubemap::getMaximumSize(); maxh = maxw; maxd = 1; maxl = 0; break; case GL_TEXTURE_1D_ARRAY_EXT: maxw = Texture1DArray::getMaximumSize(); maxh = 1; maxd = 1; maxl = Texture1DArray::getMaximumLayers(); if (!layers) { return false; } break; case GL_TEXTURE_2D_ARRAY_EXT: maxw = Texture2DArray::getMaximumSize(); maxh = maxw; maxd = 1; maxl = Texture2DArray::getMaximumLayers(); if (!layers) { return false; } break; case GL_TEXTURE_CUBE_MAP_ARRAY: maxw = TextureCubemapArray::getMaximumSize(); maxh = maxw; maxd = 1; maxl = TextureCubemapArray::getMaximumLayers(); if (!layers || (layers % 6 != 0)) { return false; } break; case GL_TEXTURE_BUFFER: maxw = TextureBuffer::getMaximumSize(); maxh = 1; maxd = 1; maxl = 0; break; case GL_TEXTURE_2D_MULTISAMPLE: maxw = Texture2DMultisample::getMaximumSize(); maxh = maxw; maxd = 1; maxl = 0; break; case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: maxw = Texture2DMultisampleArray::getMaximumSize(); maxh = maxw; maxd = 1; maxl = Texture2DMultisampleArray::getMaximumLayers(); break; default: DP_ASSERT( !"texture target unknown!" ); break; } // either we dont require a check, or we are only valid // when extension exists, or we are power of two powerOfTwoCheck = powerOfTwoCheck ? (!!GLEW_ARB_texture_non_power_of_two || (dp::math::isPowerOfTwo(w) && dp::math::isPowerOfTwo(h) && dp::math::isPowerOfTwo(d))) : true; return ( w <= maxw && h <= maxh && d <= maxd && layers <= maxl) && powerOfTwoCheck; } } // namespace size_t getCompressedSize( GLenum format, GLsizei w, GLsizei h, GLsizei d, GLsizei layers /*= 0 */ ) { // http://www.opengl.org/registry/specs/NV/texture_compression_vtc.txt // blocks = ceil(w/4) * ceil(h/4) * d; layers = std::max( 1, layers ); size_t blocks = ( (w + 3) / 4) * ( (h + 3) / 4 ) * d; // written against OpenGL 4.1 compatibility profile size_t bytesPerBlock = 0; switch ( format ) { case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: case GL_COMPRESSED_LUMINANCE_LATC1_EXT: case GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT: case GL_COMPRESSED_RED_RGTC1: case GL_COMPRESSED_SIGNED_RED_RGTC1: // these formats use 8 bytes per block bytesPerBlock = 8; break; case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: case GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: case GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT: case GL_COMPRESSED_RG_RGTC2: case GL_COMPRESSED_SIGNED_RG_RGTC2: case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB: case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB: // these formats use 16 bytes per block bytesPerBlock = 16; break; } return( bytesPerBlock * blocks * layers ); } size_t getImageDataSize( GLenum format, GLenum type, GLsizei w, GLsizei h, GLsizei d, GLsizei layers /*= 0 */ ) { size_t size = getCompressedSize( format, w, h, d, layers ); if ( size ) { return size; } // written against OpenGL 4.1 compatibility profile size_t formatSize = 0; bool isIntegerFormat = false; switch ( format ) { case GL_RED_INTEGER: case GL_GREEN_INTEGER: case GL_BLUE_INTEGER: case GL_ALPHA_INTEGER: isIntegerFormat = true; case GL_RED: case GL_GREEN: case GL_BLUE: case GL_ALPHA: case GL_LUMINANCE: formatSize = 1; break; case GL_RG_INTEGER: isIntegerFormat = true; case GL_RG: case GL_LUMINANCE_ALPHA: case GL_DEPTH_STENCIL: formatSize = 2; break; case GL_RGB_INTEGER: case GL_BGR_INTEGER: isIntegerFormat = true; case GL_RGB: case GL_BGR: formatSize = 3; break; case GL_RGBA_INTEGER: case GL_BGRA_INTEGER: isIntegerFormat = true; case GL_RGBA: case GL_BGRA: formatSize = 4; break; } size_t typeSize = 0; switch( type ) { case GL_UNSIGNED_BYTE: case GL_BYTE: typeSize = 1; break; case GL_HALF_FLOAT: DP_ASSERT( !isIntegerFormat ); case GL_UNSIGNED_SHORT: case GL_SHORT: typeSize = 2; break; case GL_FLOAT: DP_ASSERT( !isIntegerFormat ); case GL_UNSIGNED_INT: case GL_INT: typeSize = 4; break; case GL_UNSIGNED_BYTE_3_3_2: case GL_UNSIGNED_BYTE_2_3_3_REV: DP_ASSERT( format == GL_RGB || format == GL_RGB_INTEGER ); typeSize = 1; formatSize = 1; break; case GL_UNSIGNED_SHORT_5_6_5: case GL_UNSIGNED_SHORT_5_6_5_REV: case GL_UNSIGNED_SHORT_4_4_4_4: case GL_UNSIGNED_SHORT_4_4_4_4_REV: case GL_UNSIGNED_SHORT_5_5_5_1: case GL_UNSIGNED_SHORT_1_5_5_5_REV: DP_ASSERT( formatSize == 4 ); typeSize = 2; formatSize = 1; break; case GL_UNSIGNED_INT_8_8_8_8: case GL_UNSIGNED_INT_8_8_8_8_REV: case GL_UNSIGNED_INT_10_10_10_2: case GL_UNSIGNED_INT_2_10_10_10_REV: DP_ASSERT( formatSize == 4 ); typeSize = 4; formatSize = 1; break; case GL_UNSIGNED_INT_10F_11F_11F_REV: case GL_UNSIGNED_INT_5_9_9_9_REV: DP_ASSERT( format == GL_RGB ); DP_ASSERT( !isIntegerFormat ); typeSize = 4; formatSize = 1; break; case GL_UNSIGNED_INT_24_8: DP_ASSERT( format == GL_DEPTH_STENCIL ); typeSize = 4; formatSize = 1; break; case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: DP_ASSERT( format == GL_DEPTH_STENCIL ); typeSize = 8; formatSize = 1; break; } layers = std::max( 1, layers ); return( w * h * d * layers * formatSize * typeSize ); } GLenum getTargetForSamplerType( GLenum samplerType ) { switch ( samplerType ) { case GL_SAMPLER_1D: case GL_SAMPLER_1D_SHADOW: case GL_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_1D: return GL_TEXTURE_1D; case GL_SAMPLER_2D: case GL_SAMPLER_2D_SHADOW: case GL_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D: return GL_TEXTURE_2D; case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: return GL_TEXTURE_3D; case GL_SAMPLER_CUBE: case GL_SAMPLER_CUBE_SHADOW: case GL_UNSIGNED_INT_SAMPLER_CUBE: case GL_INT_SAMPLER_CUBE: return GL_TEXTURE_CUBE_MAP; case GL_SAMPLER_1D_ARRAY: case GL_SAMPLER_1D_ARRAY_SHADOW: case GL_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: return GL_TEXTURE_1D_ARRAY; case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: return GL_TEXTURE_2D_ARRAY; case GL_SAMPLER_2D_MULTISAMPLE: case GL_INT_SAMPLER_2D_MULTISAMPLE: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: return GL_TEXTURE_2D_MULTISAMPLE; case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: return GL_TEXTURE_2D_MULTISAMPLE_ARRAY; case GL_SAMPLER_BUFFER: case GL_INT_SAMPLER_BUFFER: case GL_UNSIGNED_INT_SAMPLER_BUFFER: return GL_TEXTURE_BUFFER; case GL_SAMPLER_2D_RECT: case GL_SAMPLER_2D_RECT_SHADOW : case GL_INT_SAMPLER_2D_RECT: case GL_UNSIGNED_INT_SAMPLER_2D_RECT: return GL_TEXTURE_RECTANGLE; default: DP_ASSERT(!"please support me"); } return GL_NONE; } bool isCompressedFormat( GLenum format ) { bool ok = false; switch ( format ) { case GL_COMPRESSED_RG : case GL_COMPRESSED_RGB : case GL_COMPRESSED_RGBA : case GL_COMPRESSED_ALPHA : case GL_COMPRESSED_LUMINANCE : case GL_COMPRESSED_LUMINANCE_ALPHA : case GL_COMPRESSED_INTENSITY : case GL_COMPRESSED_SLUMINANCE : case GL_COMPRESSED_SLUMINANCE_ALPHA : case GL_COMPRESSED_SRGB : case GL_COMPRESSED_SRGB_ALPHA : case GL_COMPRESSED_RGB_S3TC_DXT1_EXT : case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT : case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT : case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT : case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT : case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB : case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB : case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB : case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB : case GL_COMPRESSED_RED_RGTC1 : case GL_COMPRESSED_SIGNED_RED_RGTC1 : case GL_COMPRESSED_RG_RGTC2 : case GL_COMPRESSED_SIGNED_RG_RGTC2 : case GL_COMPRESSED_LUMINANCE_LATC1_EXT : case GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT : case GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT : case GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT : ok = true; break; } return( ok ); } bool isIntegerInternalFormat( GLenum format ) { bool ok = false; switch (format) { // http://www.opengl.org/registry/specs/ARB/texture_rg.txt case GL_R8I : case GL_R8UI : case GL_R16I : case GL_R16UI : case GL_R32I : case GL_R32UI : case GL_RG8I : case GL_RG8UI : case GL_RG16I : case GL_RG16UI : case GL_RG32I : case GL_RG32UI : // http://www.opengl.org/registry/specs/EXT/texture_integer.txt case GL_RGBA32UI_EXT : case GL_RGB32UI_EXT : case GL_ALPHA32UI_EXT : case GL_INTENSITY32UI_EXT : case GL_LUMINANCE32UI_EXT : case GL_LUMINANCE_ALPHA32UI_EXT: case GL_RGBA16UI_EXT : case GL_RGB16UI_EXT : case GL_ALPHA16UI_EXT : case GL_INTENSITY16UI_EXT : case GL_LUMINANCE16UI_EXT : case GL_LUMINANCE_ALPHA16UI_EXT: case GL_RGBA8UI_EXT : case GL_RGB8UI_EXT : case GL_ALPHA8UI_EXT : case GL_INTENSITY8UI_EXT : case GL_LUMINANCE8UI_EXT : case GL_LUMINANCE_ALPHA8UI_EXT : case GL_RGBA32I_EXT : case GL_RGB32I_EXT : case GL_ALPHA32I_EXT : case GL_INTENSITY32I_EXT : case GL_LUMINANCE32I_EXT : case GL_LUMINANCE_ALPHA32I_EXT : case GL_RGBA16I_EXT : case GL_RGB16I_EXT : case GL_ALPHA16I_EXT : case GL_INTENSITY16I_EXT : case GL_LUMINANCE16I_EXT : case GL_LUMINANCE_ALPHA16I_EXT : case GL_RGBA8I_EXT : case GL_RGB8I_EXT : case GL_ALPHA8I_EXT : case GL_INTENSITY8I_EXT : case GL_LUMINANCE8I_EXT : case GL_LUMINANCE_ALPHA8I_EXT : ok = true; break; } return( ok ); } bool isValidInternalFormat( GLenum format ) { bool ok = false; switch( format ) { case GL_RGB32F: case GL_RGB32I: case GL_RGB32UI: ok = !!GLEW_ARB_texture_buffer_object_rgb32; break; case GL_R8: case GL_R16: case GL_R16F: case GL_R32F: case GL_R8I: case GL_R16I: case GL_R32I: case GL_R8UI: case GL_R16UI: case GL_R32UI: case GL_RG8: case GL_RG16: case GL_RG16F: case GL_RG32F: case GL_RG8I: case GL_RG16I: case GL_RG32I: case GL_RG8UI: case GL_RG16UI: case GL_RG32UI: ok = !!GLEW_ARB_texture_rg; break; case GL_ALPHA8: case GL_ALPHA16: case GL_ALPHA16F_ARB: case GL_ALPHA32F_ARB: case GL_ALPHA8I_EXT: case GL_ALPHA16I_EXT: case GL_ALPHA32I_EXT: case GL_ALPHA8UI_EXT: case GL_ALPHA16UI_EXT: case GL_ALPHA32UI_EXT: case GL_LUMINANCE8: case GL_LUMINANCE16: case GL_LUMINANCE16F_ARB: case GL_LUMINANCE32F_ARB: case GL_LUMINANCE8I_EXT: case GL_LUMINANCE16I_EXT: case GL_LUMINANCE32I_EXT: case GL_LUMINANCE8UI_EXT: case GL_LUMINANCE16UI_EXT: case GL_LUMINANCE32UI_EXT: case GL_LUMINANCE8_ALPHA8: case GL_LUMINANCE16_ALPHA16: case GL_LUMINANCE_ALPHA16F_ARB: case GL_LUMINANCE_ALPHA32F_ARB: case GL_LUMINANCE_ALPHA8I_EXT: case GL_LUMINANCE_ALPHA16I_EXT: case GL_LUMINANCE_ALPHA32I_EXT: case GL_LUMINANCE_ALPHA8UI_EXT: case GL_LUMINANCE_ALPHA16UI_EXT: case GL_LUMINANCE_ALPHA32UI_EXT: case GL_INTENSITY8: case GL_INTENSITY16: case GL_INTENSITY16F_ARB: case GL_INTENSITY32F_ARB: case GL_INTENSITY8I_EXT: case GL_INTENSITY16I_EXT: case GL_INTENSITY32I_EXT: case GL_INTENSITY8UI_EXT: case GL_INTENSITY16UI_EXT: case GL_INTENSITY32UI_EXT: case GL_RGBA8: case GL_RGBA16: case GL_RGBA16F_ARB: case GL_RGBA32F_ARB: case GL_RGBA8I_EXT: case GL_RGBA16I_EXT: case GL_RGBA32I_EXT: case GL_RGBA8UI_EXT: case GL_RGBA16UI_EXT: case GL_RGBA32UI_EXT: ok = true; break; default: DP_ASSERT( !"unknown internal Format encountered!" ); break; } return( ok ); } bool isLayeredTarget( GLenum target ) { bool ok = false; switch( target ) { case GL_TEXTURE_1D_ARRAY_EXT : case GL_TEXTURE_2D_ARRAY_EXT : case GL_TEXTURE_CUBE_MAP_ARRAY : case GL_TEXTURE_2D_MULTISAMPLE_ARRAY : ok = true; break; } return( ok ); } bool isImageType( GLenum type ) { bool ok = false; switch( type ) { case GL_IMAGE_1D : case GL_IMAGE_2D : case GL_IMAGE_3D : case GL_IMAGE_2D_RECT : case GL_IMAGE_CUBE : case GL_IMAGE_BUFFER : case GL_IMAGE_1D_ARRAY : case GL_IMAGE_2D_ARRAY : case GL_IMAGE_CUBE_MAP_ARRAY : case GL_IMAGE_2D_MULTISAMPLE : case GL_IMAGE_2D_MULTISAMPLE_ARRAY : case GL_INT_IMAGE_1D : case GL_INT_IMAGE_2D : case GL_INT_IMAGE_3D : case GL_INT_IMAGE_2D_RECT : case GL_INT_IMAGE_CUBE : case GL_INT_IMAGE_BUFFER : case GL_INT_IMAGE_1D_ARRAY : case GL_INT_IMAGE_2D_ARRAY : case GL_INT_IMAGE_CUBE_MAP_ARRAY : case GL_INT_IMAGE_2D_MULTISAMPLE : case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY : case GL_UNSIGNED_INT_IMAGE_1D : case GL_UNSIGNED_INT_IMAGE_2D : case GL_UNSIGNED_INT_IMAGE_3D : case GL_UNSIGNED_INT_IMAGE_2D_RECT : case GL_UNSIGNED_INT_IMAGE_CUBE : case GL_UNSIGNED_INT_IMAGE_BUFFER : case GL_UNSIGNED_INT_IMAGE_1D_ARRAY : case GL_UNSIGNED_INT_IMAGE_2D_ARRAY : case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY : case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE : case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY : ok = true; break; } return( ok ); } bool isSamplerType( GLenum type ) { bool ok = false; switch( type ) { case GL_SAMPLER_1D: case GL_SAMPLER_2D: case GL_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_SAMPLER_2D_RECT: case GL_SAMPLER_2D_MULTISAMPLE: case GL_SAMPLER_1D_ARRAY: case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_CUBE_MAP_ARRAY: case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_SAMPLER_BUFFER: case GL_INT_SAMPLER_1D: case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_3D: case GL_INT_SAMPLER_CUBE: case GL_INT_SAMPLER_2D_RECT: case GL_INT_SAMPLER_2D_MULTISAMPLE: case GL_INT_SAMPLER_1D_ARRAY: case GL_INT_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_CUBE_MAP_ARRAY: case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_INT_SAMPLER_BUFFER: case GL_UNSIGNED_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_2D_RECT: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_UNSIGNED_INT_SAMPLER_BUFFER: case GL_SAMPLER_1D_SHADOW: case GL_SAMPLER_2D_SHADOW: case GL_SAMPLER_CUBE_SHADOW: case GL_SAMPLER_2D_RECT_SHADOW: case GL_SAMPLER_1D_ARRAY_SHADOW: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW: ok = true; break; } return( ok ); } /***************/ /* Texture */ /***************/ Texture::Texture( GLenum target, GLenum internalFormat, GLenum format, GLenum type, GLsizei border ) : m_target( target ) , m_internalFormat( internalFormat ) , m_format( format ) , m_type( type ) , m_definedLevels( 0 ) , m_maxLevel( 0 ) { GLuint id; glGenTextures( 1, &id ); setGLId( id ); GLenum filter = isIntegerInternalFormat( m_internalFormat ) ? GL_NEAREST : GL_LINEAR; switch (m_target) { case GL_TEXTURE_1D: case GL_TEXTURE_2D: case GL_TEXTURE_3D: case GL_TEXTURE_RECTANGLE: case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_CUBE_MAP_ARRAY: // default to linear/nearest filtering for those // as it will mean texture is always complete independent // of current mipmap state and internal format setFilterParameters( filter, filter ); break; default: break; } } Texture::~Texture( ) { if ( getGLId() ) { if ( getShareGroup() ) { DEFINE_PTR_TYPES( CleanupTask ); class CleanupTask : public ShareGroupTask { public: static CleanupTaskSharedPtr create( GLuint id ) { return( std::shared_ptr<CleanupTask>( new CleanupTask( id ) ) ); } virtual void execute() { glDeleteTextures( 1, &m_id ); } protected: CleanupTask( GLuint id ) : m_id( id ) {} private: GLuint m_id; }; // make destructor exception safe try { getShareGroup()->executeTask( CleanupTask::create( getGLId() ) ); } catch (...) {} } else { GLuint id = getGLId(); glDeleteTextures(1, &id ); } } } void Texture::bind() const { glBindTexture( m_target, getGLId() ); } void Texture::unbind() const { glBindTexture( m_target, 0 ); } void Texture::generateMipMap() { DP_ASSERT( m_maxLevel ); getGLInterface()->generateMipMap( getGLId(), m_target ); m_definedLevels = (1 << (m_maxLevel + 1)) - 1; } void Texture::setBorderColor( float color[4] ) { getGLInterface()->setParameter( getGLId(), m_target, GL_TEXTURE_BORDER_COLOR, color ); } void Texture::setBorderColor( int color[4] ) { getGLInterface()->setParameterUnmodified( getGLId(), m_target, GL_TEXTURE_BORDER_COLOR, color ); } void Texture::setBorderColor( unsigned int color[4] ) { getGLInterface()->setParameterUnmodified( getGLId(), m_target, GL_TEXTURE_BORDER_COLOR, color ); } void Texture::setCompareParameters( GLenum mode, GLenum func ) { getGLInterface()->setCompareParameters( getGLId(), m_target, mode, func ); } void Texture::setFilterParameters( GLenum minFilter, GLenum magFilter ) { getGLInterface()->setFilterParameters( getGLId(), m_target, minFilter, magFilter ); } void Texture::setFormat( GLenum format ) { if ( m_format != format ) { m_format = format; m_definedLevels = 0; } } void Texture::setLODParameters( float minLOD, float maxLOD, float LODBias ) { // must not set lod parameters on a texture rectangle (invalid operation) if ( m_target != GL_TEXTURE_RECTANGLE ) { getGLInterface()->setLODParameters( getGLId(), m_target, minLOD, maxLOD, LODBias ); } } void Texture::setMaxAnisotropy( float anisotropy ) { getGLInterface()->setParameter( getGLId(), m_target, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy ); } void Texture::setType( GLenum type ) { if ( m_type != type ) { m_type = type; m_definedLevels = 0; } } void Texture::setWrapParameters( GLenum wrapS, GLenum wrapT, GLenum wrapR ) { getGLInterface()->setWrapParameters( getGLId(), m_target, wrapS, wrapT, wrapR ); } void Texture::addDefinedLevel( GLuint level ) { m_definedLevels |= ( 1 << level ); } void Texture::resetDefinedLevels() { m_definedLevels = 1; } void Texture::setMaxLevel( GLuint level ) { m_maxLevel = level; } /***************/ /* Texture1D */ /***************/ Texture1DSharedPtr Texture1D::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width ) { return( std::shared_ptr<Texture1D>( new Texture1D( internalFormat, format, type, width ) ) ); } Texture1D::Texture1D( GLenum internalFormat, GLenum format, GLenum type, GLsizei width ) : Texture( GL_TEXTURE_1D, internalFormat, format, type ) , m_width( 0 ) { resize( width ); } void Texture1D::setData( const void *data, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( isMipMapLevelValid( mipLevel) ); TexGLTransfer upload( getGLId(), getTarget(), mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize(m_width, mipLevel)); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, 1, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); upload.doTransfer( 1, isMipMapLevelDefined(mipLevel) ); addDefinedLevel( mipLevel ); } void Texture1D::getData( void *data, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, getTarget(), data, mipLevel ); } void Texture1D::resize( GLsizei width ) { if ( m_width != width ) { DP_ASSERT( width <= getMaximumSize() ); m_width = width; getGLInterface()->setImage1D( getGLId(), getTarget(), 0, getInternalFormat(), width, 0, getFormat(), getType(), nullptr ); resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), 1 , 1 ) ); } } GLsizei Texture1D::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } /********************/ /* Texture1DArray */ /********************/ Texture1DArraySharedPtr Texture1DArray::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei layers ) { return( std::shared_ptr<Texture1DArray>( new Texture1DArray( internalFormat, format, type, width, layers ) ) ); } Texture1DArray::Texture1DArray( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei layers ) : Texture( GL_TEXTURE_1D_ARRAY_EXT, internalFormat, format, type ) , m_width( 0 ) , m_layers( 0 ) { resize( width, layers ); } void Texture1DArray::setData( const void *data, GLint layer, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( isMipMapLevelValid( mipLevel) ); DP_ASSERT( layer < getLayers() ); TexGLTransfer upload( getGLId(), getTarget(), mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize(m_width, mipLevel), 1); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, 1, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); if ( !isMipMapLevelDefined(mipLevel) ) { TexGLTransfer uploadCreate = upload; dp::gl::bind( GL_PIXEL_UNPACK_BUFFER, BufferSharedPtr() ); // make sure, GL_PIXEL_UNPACK_BUFFER is unbound ! uploadCreate.m_dataSize *= m_layers; uploadCreate.m_height = m_layers; uploadCreate.m_dataPtr = nullptr; uploadCreate.doTransfer( 2, false ); addDefinedLevel( mipLevel ); } upload.m_yOffset = layer; upload.doTransfer( 2, true ); } void Texture1DArray::getData( void *data, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, getTarget(), data, mipLevel ); } void Texture1DArray::resize( GLsizei width, GLsizei layers ) { if ( m_width != width || m_layers != layers) { DP_ASSERT( width <= getMaximumSize() && layers <= getMaximumLayers() ); m_width = width; m_layers = layers; getGLInterface()->setImage2D( getGLId(), getTarget(), 0, getInternalFormat(), width, layers, 0, getFormat(), getType(), 0 ); resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), 1 , 1 ) ); } } GLsizei Texture1DArray::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } GLsizei Texture1DArray::getMaximumLayers() { GLsizei size; glGetIntegerv( GL_MAX_ARRAY_TEXTURE_LAYERS_EXT, &size ); return size; } bool Texture1DArray::isSupported() { return !!GLEW_EXT_texture_array; } /***************/ /* Texture2D */ /***************/ Texture2DSharedPtr Texture2D::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height ) { return( std::shared_ptr<Texture2D>( new Texture2D( internalFormat, format, type, width, height ) ) ); } Texture2D::Texture2D( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height ) : Texture( GL_TEXTURE_2D, internalFormat, format, type ) , m_width( 0 ) , m_height( 0 ) { resize( width, height ); } void Texture2D::setData( const void *data, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( isMipMapLevelValid( mipLevel) ); TexGLTransfer upload( getGLId(), getTarget(), mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize( m_width, mipLevel ), getMipMapSize( m_height, mipLevel ) ); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, upload.m_height, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); upload.doTransfer( 2, isMipMapLevelDefined( mipLevel ) ); addDefinedLevel( mipLevel ); } void Texture2D::getData( void *data, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, getTarget(), data, mipLevel ); } void Texture2D::resize( GLsizei width, GLsizei height ) { if ( m_width != width || m_height != height) { DP_ASSERT( width <= getMaximumSize() && height <= getMaximumSize() ); m_width = width; m_height = height; getGLInterface()->setImage2D( getGLId(), getTarget(), 0, getInternalFormat(), width, height, 0, getFormat(), getType(), nullptr ); resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), getWidth() , 1 ) ); } } GLsizei Texture2D::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } /************************/ /* TextureRectangle */ /************************/ TextureRectangleSharedPtr TextureRectangle::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height ) { return( std::shared_ptr<TextureRectangle>( new TextureRectangle( internalFormat, format, type, width, height ) ) ); } TextureRectangle::TextureRectangle( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height ) : Texture( GL_TEXTURE_RECTANGLE, internalFormat, format, type ) , m_width( 0 ) , m_height( 0 ) { resize( width, height ); } void TextureRectangle::setData( const void *data ) { TexGLTransfer upload( getGLId(), getTarget(), 0, getInternalFormat(), getFormat(), getType(), data, m_width, m_height ); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, upload.m_height, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); upload.doTransfer( 2, isMipMapLevelDefined( 0 ) ); resetDefinedLevels(); } void TextureRectangle::getData( void *data ) const { DP_ASSERT( data ); getTexImage( this, getTarget(), data, 0 ); } void TextureRectangle::resize( GLsizei width, GLsizei height ) { if ( m_width != width || m_height != height) { DP_ASSERT( width <= getMaximumSize() && height <= getMaximumSize() ); m_width = width; m_height = height; getGLInterface()->setImage2D( getGLId(), getTarget(), 0, getInternalFormat(), width, height, 0, getFormat(), getType(), 0 ); resetDefinedLevels(); setMaxLevel( 0 ); // rectangle textures must not have mipmaps } } GLsizei TextureRectangle::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &size ); return size; } /*********************/ /* Texture2DArray */ /*********************/ Texture2DArraySharedPtr Texture2DArray::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height, GLsizei layers ) { return( std::shared_ptr<Texture2DArray>( new Texture2DArray( internalFormat, format, type, width, height, layers ) ) ); } Texture2DArray::Texture2DArray( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height, GLsizei layers ) : Texture( GL_TEXTURE_2D_ARRAY, internalFormat, format, type ) , m_width( 0 ) , m_height( 0 ) , m_layers( 0 ) { resize( width, height, layers ); } void Texture2DArray::setData( const void *data, GLint layer, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( isMipMapLevelValid( mipLevel) ); DP_ASSERT( layer < getLayers() ); TexGLTransfer upload( getGLId(), getTarget(), mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize( m_width, mipLevel ), getMipMapSize( m_height, mipLevel ) ); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, upload.m_height, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); if ( !isMipMapLevelDefined(mipLevel) ) { TexGLTransfer uploadCreate = upload; dp::gl::bind( GL_PIXEL_UNPACK_BUFFER, BufferSharedPtr() ); // make sure, GL_PIXEL_UNPACK_BUFFER is unbound ! uploadCreate.m_dataSize *= m_layers; uploadCreate.m_depth = m_layers; uploadCreate.m_dataPtr = nullptr; uploadCreate.doTransfer( 3, false ); addDefinedLevel( mipLevel ); } upload.m_zOffset = layer; upload.doTransfer( 3, true ); addDefinedLevel( mipLevel ); } void Texture2DArray::getData( void *data, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, getTarget(), data, mipLevel ); } void Texture2DArray::resize( GLsizei width, GLsizei height, GLsizei layers ) { if ( m_width != width || m_height != height || m_layers != layers) { DP_ASSERT( width <= getMaximumSize() && height <= getMaximumSize() && layers <= getMaximumLayers() ); m_width = width; m_height = height; m_layers = layers; getGLInterface()->setImage3D( getGLId(), getTarget(), 0, getInternalFormat(), width, height, layers, 0, getFormat(), getType(), 0 ); resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), getWidth() , 1 ) ); } } GLsizei Texture2DArray::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } GLsizei Texture2DArray::getMaximumLayers() { GLsizei size; glGetIntegerv( GL_MAX_ARRAY_TEXTURE_LAYERS_EXT, &size ); return size; } bool Texture2DArray::isSupported() { return !!GLEW_EXT_texture_array; } /***************/ /* Texture3D */ /***************/ Texture3DSharedPtr Texture3D::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height, GLsizei depth ) { return( std::shared_ptr<Texture3D>( new Texture3D( internalFormat, format, type, width, height, depth ) ) ); } Texture3D::Texture3D( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height, GLsizei depth ) : Texture( GL_TEXTURE_3D, internalFormat, format, type ) , m_width( 0 ) , m_height( 0 ) , m_depth( 0 ) { resize( width, height, depth ); } void Texture3D::setData( const void *data, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( isMipMapLevelValid( mipLevel) ); TexGLTransfer upload( getGLId(), getTarget(), mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize( m_width, mipLevel ), getMipMapSize( m_height, mipLevel ), getMipMapSize( m_depth, mipLevel ) ); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, upload.m_height, upload.m_depth ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); upload.doTransfer( 3, isMipMapLevelDefined(mipLevel) ); addDefinedLevel( mipLevel ); } void Texture3D::getData( void *data, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, getTarget(), data, mipLevel ); } void Texture3D::resize( GLsizei width, GLsizei height, GLsizei depth ) { if ( m_width != width || m_height != height || m_depth != depth) { DP_ASSERT( width <= getMaximumSize() && height <= getMaximumSize() && depth <= getMaximumSize() ); m_width = width; m_height = height; m_depth = depth; getGLInterface()->setImage3D( getGLId(), getTarget(), 0, getInternalFormat(), width, height, depth, 0, getFormat(), getType(), 0 ); resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), getWidth(), getDepth() ) ); } } GLsizei Texture3D::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_3D_TEXTURE_SIZE, &size ); return size; } /********************/ /* TextureCubemap */ /********************/ TextureCubemapSharedPtr TextureCubemap::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height ) { return( std::shared_ptr<TextureCubemap>( new TextureCubemap( internalFormat, format, type, width, height ) ) ); } TextureCubemap::TextureCubemap( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height ) : Texture( GL_TEXTURE_CUBE_MAP, internalFormat, format, type ) , m_width( 0 ) , m_height( 0 ) { resize( width, height ); } void TextureCubemap::setData( const void *data, int face, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( 0 <= face && face <= 6); DP_ASSERT( isMipMapLevelValid( mipLevel ) ); TexGLTransfer upload( getGLId(), GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize( m_width, mipLevel ), getMipMapSize( m_height, mipLevel ) ); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, upload.m_height, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); if ( !isMipMapLevelDefined(mipLevel) ) { TexGLTransfer uploadCreate = upload; dp::gl::bind( GL_PIXEL_UNPACK_BUFFER, BufferSharedPtr() ); // make sure, GL_PIXEL_UNPACK_BUFFER is unbound ! uploadCreate.m_dataPtr = nullptr; for (unsigned int f = 0; f < 6; ++f) { uploadCreate.m_target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + f; uploadCreate.doTransfer( 2, false ); } addDefinedLevel( mipLevel ); } upload.doTransfer( 2, true ); } void TextureCubemap::getData( void *data, int face, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( 0 <= face && face <= 6); DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, data, mipLevel ); } void TextureCubemap::resize( GLsizei width, GLsizei height ) { if ( m_width != width || m_height != height) { DP_ASSERT( width <= getMaximumSize() ); DP_ASSERT( width == height ); m_width = width; m_height = height; for ( unsigned int face = 0;face < 6;++face ) { getGLInterface()->setImage2D( getGLId(), GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, getInternalFormat(), width, height, 0, getFormat(), getType(), nullptr ); } resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), getWidth(), 1 ) ); } } GLsizei TextureCubemap::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_CUBE_MAP_TEXTURE_SIZE, &size ); return size; } /**************************/ /* TextureCubemapArray */ /**************************/ TextureCubemapArraySharedPtr TextureCubemapArray::create( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height, GLsizei layers ) { return( std::shared_ptr<TextureCubemapArray>( new TextureCubemapArray( internalFormat, format, type, width, height, layers ) ) ); } TextureCubemapArray::TextureCubemapArray( GLenum internalFormat, GLenum format, GLenum type, GLsizei width, GLsizei height, GLsizei layers ) : Texture( GL_TEXTURE_CUBE_MAP_ARRAY, internalFormat, format, type ) , m_width( 0 ) , m_height( 0 ) , m_layers( 0 ) { resize( width, height, layers ); } void TextureCubemapArray::setData( const void *data, GLint layer, GLuint mipLevel /*= 0 */ ) { DP_ASSERT( isMipMapLevelValid( mipLevel) ); DP_ASSERT( layer < getLayers() ); TexGLTransfer upload( getGLId(), getTarget(), mipLevel, getInternalFormat(), getFormat(), getType(), data, getMipMapSize( m_width, mipLevel ), getMipMapSize( m_height, mipLevel ) ); // set m_dataSize for compressed format upload.m_dataSize = getCompressedSize( getFormat(), upload.m_width, upload.m_height, 1 ); // format must match if compressed DP_ASSERT( !upload.m_dataSize || getFormat() == getInternalFormat() ); if ( !isMipMapLevelDefined(mipLevel) ) { TexGLTransfer uploadCreate = upload; dp::gl::bind( GL_PIXEL_UNPACK_BUFFER, BufferSharedPtr() ); // make sure, GL_PIXEL_UNPACK_BUFFER is unbound ! uploadCreate.m_dataSize *= m_layers; uploadCreate.m_depth = m_layers; uploadCreate.m_dataPtr = nullptr; uploadCreate.doTransfer( 3, false ); addDefinedLevel( mipLevel ); } upload.m_zOffset = layer; upload.doTransfer( 3, true ); } void TextureCubemapArray::getData( void *data, GLuint mipLevel /*= 0 */ ) const { DP_ASSERT( isMipMapLevelDefined( mipLevel ) ); DP_ASSERT( data ); getTexImage( this, getTarget(), data, mipLevel ); } void TextureCubemapArray::resize( GLsizei width, GLsizei height, GLsizei layers ) { if ( m_width != width || m_height != height || m_layers != layers) { DP_ASSERT( width <= getMaximumSize() && layers <= getMaximumLayers() && layers%6 == 0); DP_ASSERT( width == height ); m_width = width; m_height = height; m_layers = layers; getGLInterface()->setImage3D( getGLId(), getTarget(), 0, getInternalFormat(), width, height, layers , 0, getFormat(), getType(), 0 ); resetDefinedLevels(); setMaxLevel( numberOfMipmaps( getWidth(), getWidth() , 1 ) ); } } GLsizei TextureCubemapArray::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_CUBE_MAP_TEXTURE_SIZE, &size ); return size; } GLsizei TextureCubemapArray::getMaximumLayers() { GLsizei size; glGetIntegerv( GL_MAX_ARRAY_TEXTURE_LAYERS_EXT, &size ); return size; } bool TextureCubemapArray::isSupported() { return !!GLEW_ARB_texture_cube_map_array; } /***************************/ /* Texture2DMultisample */ /***************************/ Texture2DMultisampleSharedPtr Texture2DMultisample::create( GLenum internalFormat, GLsizei samples, GLsizei width, GLsizei height, bool fixedLocations ) { return( std::shared_ptr<Texture2DMultisample>( new Texture2DMultisample( internalFormat, samples, width, height, fixedLocations ) ) ); } Texture2DMultisample::Texture2DMultisample( GLenum internalFormat, GLsizei width, GLsizei height, GLsizei samples, bool fixedLocations ) : Texture( GL_TEXTURE_2D_MULTISAMPLE, internalFormat, GL_INVALID_ENUM, GL_INVALID_ENUM ) , m_samples( 1 ) , m_width( 0 ) , m_height( 0 ) , m_fixedLocations( fixedLocations ) { resize( width, height ); setSamples( samples ); } void Texture2DMultisample::resize( GLsizei width, GLsizei height ) { DP_ASSERT( getInternalFormat() != ~0 ); DP_ASSERT( m_samples ); if ( width != m_width || height != m_height ) { DP_ASSERT( width <= getMaximumSize() && height <= getMaximumSize() ); m_width = width; m_height = height; TextureBinding tb( getTarget(), getGLId() ); glTexImage2DMultisample( getTarget(), m_samples, getInternalFormat(), m_width, m_height, m_fixedLocations ); } } void Texture2DMultisample::setSamples( GLsizei samples ) { DP_ASSERT( getInternalFormat() != ~0 ); DP_ASSERT( m_width && m_height ); if ( samples != m_samples ) { m_samples = samples; TextureBinding tb( getTarget(), getGLId() ); glTexImage2DMultisample( getTarget(), m_samples, getInternalFormat(), m_width, m_height, m_fixedLocations ); } } GLsizei Texture2DMultisample::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } GLsizei Texture2DMultisample::getMaximumSamples() { GLsizei size; glGetIntegerv( GL_MAX_SAMPLES, &size ); return size; } GLsizei Texture2DMultisample::getMaximumIntegerSamples() { GLsizei size; glGetIntegerv( GL_MAX_INTEGER_SAMPLES, &size ); return size; } GLsizei Texture2DMultisample::getMaximumColorSamples() { GLsizei size; glGetIntegerv( GL_MAX_COLOR_TEXTURE_SAMPLES, &size ); return size; } GLsizei Texture2DMultisample::getMaximumDepthSamples() { GLsizei size; glGetIntegerv( GL_MAX_DEPTH_TEXTURE_SAMPLES, &size ); return size; } bool Texture2DMultisample::isSupported() { return !!GLEW_ARB_texture_multisample; } /********************************/ /* Texture2DMultisampleArray */ /********************************/ Texture2DMultisampleArraySharedPtr Texture2DMultisampleArray::create( GLenum internalFormat, GLsizei samples, GLsizei width, GLsizei height, GLsizei layers, bool fixedLocations ) { return( std::shared_ptr<Texture2DMultisampleArray>( new Texture2DMultisampleArray( internalFormat, samples, width, height, layers, fixedLocations ) ) ); } Texture2DMultisampleArray::Texture2DMultisampleArray( GLenum internalFormat, GLsizei samples, GLsizei width, GLsizei height, GLsizei layers, bool fixedLocations ) : Texture( GL_TEXTURE_2D_MULTISAMPLE_ARRAY, internalFormat, GL_INVALID_ENUM, GL_INVALID_ENUM ) , m_samples( 1 ) , m_width( 0 ) , m_height( 0 ) , m_fixedLocations( fixedLocations ) { resize( width, height, layers ); setSamples( samples ); } void Texture2DMultisampleArray::resize( GLsizei width, GLsizei height, GLsizei layers ) { DP_ASSERT( getInternalFormat() != ~0 ); DP_ASSERT( m_samples ); if ( width != m_width || height != m_height || layers != m_layers) { DP_ASSERT( width <= getMaximumSize() && height <= getMaximumSize() ); DP_ASSERT( layers <= getMaximumLayers() ); m_width = width; m_height = height; m_layers = layers; TextureBinding tb( getTarget(), getGLId() ); glTexImage3DMultisample( getTarget(), m_samples, getInternalFormat(), m_width, m_height, m_layers, m_fixedLocations ); } } void Texture2DMultisampleArray::setSamples( GLsizei samples ) { DP_ASSERT( getInternalFormat() != ~0 ); DP_ASSERT( m_width && m_height && m_layers ); if ( samples != m_samples ) { DP_ASSERT( samples <= getMaximumSamples() ); m_samples = samples; TextureBinding tb( getTarget(), getGLId() ); glTexImage3DMultisample( getTarget(), m_samples, getInternalFormat(), m_width, m_height, m_layers, m_fixedLocations ); } } GLsizei Texture2DMultisampleArray::getMaximumSize() { GLsizei size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } GLsizei Texture2DMultisampleArray::getMaximumSamples() { GLsizei size; glGetIntegerv( GL_MAX_SAMPLES, &size ); return size; } GLsizei Texture2DMultisampleArray::getMaximumColorSamples() { GLsizei size; glGetIntegerv( GL_MAX_COLOR_TEXTURE_SAMPLES, &size ); return size; } GLsizei Texture2DMultisampleArray::getMaximumDepthSamples() { GLsizei size; glGetIntegerv( GL_MAX_DEPTH_TEXTURE_SAMPLES, &size ); return size; } GLsizei Texture2DMultisampleArray::getMaximumLayers() { GLsizei size; glGetIntegerv( GL_MAX_ARRAY_TEXTURE_LAYERS_EXT, &size ); return size; } GLsizei Texture2DMultisampleArray::getMaximumIntegerSamples() { GLsizei size; glGetIntegerv( GL_MAX_INTEGER_SAMPLES, &size ); return size; } bool Texture2DMultisampleArray::isSupported() { return !!GLEW_ARB_texture_multisample; } /********************/ /* TextureBuffer */ /********************/ TextureBufferSharedPtr TextureBuffer::create( GLenum internalFormat, BufferSharedPtr const& buffer ) { return( std::shared_ptr<TextureBuffer>( new TextureBuffer( internalFormat, buffer ) ) ); } TextureBufferSharedPtr TextureBuffer::create(GLenum internalFormat, unsigned int size, GLvoid const* data, GLenum usage) { dp::gl::BufferSharedPtr buffer = dp::gl::Buffer::create(dp::gl::Buffer::CORE, usage, GL_TEXTURE_BUFFER); buffer->setSize(size); buffer->update(data); return( std::shared_ptr<TextureBuffer>(new TextureBuffer(internalFormat, buffer))); } TextureBuffer::TextureBuffer( GLenum internalFormat, BufferSharedPtr const& buffer ) : Texture( GL_TEXTURE_BUFFER, internalFormat, GL_INVALID_ENUM, GL_INVALID_ENUM ) { setBuffer( buffer ); } TextureBuffer::~TextureBuffer() { } BufferSharedPtr const& TextureBuffer::getBuffer() const { return( m_buffer ); } void TextureBuffer::setBuffer( BufferSharedPtr const& buffer ) { if ( m_buffer != buffer ) { m_buffer = buffer; getGLInterface()->attachBuffer( getGLId(), GL_TEXTURE_BUFFER, getInternalFormat(), m_buffer ? m_buffer->getGLId() : 0 ); } } GLint TextureBuffer::getMaximumSize() { GLint size; glGetIntegerv( GL_MAX_TEXTURE_BUFFER_SIZE, &size ); return( size ); } bool TextureBuffer::isSupported() { return( !!GLEW_ARB_texture_buffer_object || !!GLEW_EXT_texture_buffer_object ); } } // namespace gl } // namespace dp
31.785099
193
0.621619
asuessenbach
e2e0804841ec19cbc0bf85186298cd3c95446a24
604
hpp
C++
src/Domain/Creators/Factory1D.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Domain/Creators/Factory1D.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Domain/Creators/Factory1D.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> #include "Domain/Creators/AlignedLattice.hpp" #include "Domain/Creators/Factory.hpp" #include "Domain/Creators/Interval.hpp" #include "Domain/Creators/RotatedIntervals.hpp" #include "Utilities/TMPL.hpp" namespace DomainCreators_detail { template <> struct domain_creators<1> { using type = tmpl::list<domain::creators::AlignedLattice<1>, domain::creators::Interval, domain::creators::RotatedIntervals>; }; } // namespace DomainCreators_detail
27.454545
62
0.708609
macedo22
e2eb6fe227e20b8bd23c67a933f019a2c3856811
1,797
cpp
C++
src/examples/eag_control/eag_control_main.cpp
JGSuw/Firmware
c68a333795fb03034ab612ac0612aa736c9a28dc
[ "BSD-3-Clause" ]
null
null
null
src/examples/eag_control/eag_control_main.cpp
JGSuw/Firmware
c68a333795fb03034ab612ac0612aa736c9a28dc
[ "BSD-3-Clause" ]
null
null
null
src/examples/eag_control/eag_control_main.cpp
JGSuw/Firmware
c68a333795fb03034ab612ac0612aa736c9a28dc
[ "BSD-3-Clause" ]
null
null
null
#include "EAGControl.h" #include <px4_log.h> #include <cstring> #include <cstdlib> EAGControl *controller = NULL; /** * Print the correct usage. */ static void usage(const char *reason); static void usage(const char *reason) { if (reason) { warnx("%s\n", reason); } warnx("usage: eag_control {start|stop|status} [-p <additional params>]\n\n"); } static bool command_is_good(char* command); static bool command_is_good(char* command) { if(!strcmp(command,"start")) return true; if(!strcmp(command,"stop")) return true; if(!strcmp(command,"status")) return true; return false; } extern "C" __EXPORT int eag_control_main(int argc, char* argv[]); int eag_control_main(int argc, char* argv[]) { if(argc < 2){ usage("at least one argument required"); return -1; } if(!command_is_good(argv[1])){ usage("invalid command argument"); return -1; } // if this is the first time this has been called, // allocate the controller if(NULL == controller){ controller = new EAGControl(); } if(!strcmp(argv[1], "start")){ if(controller->is_running()){ warnx("Controller is already running"); } else controller->start(); } else if(!strcmp(argv[1],"stop")){ if(controller->is_running()){ controller->stop(); } else warnx("Controller is not running"); } else if(!strcmp(argv[1],"status")){ if(controller->is_running()){ warnx("EAG Control is running"); } else { warnx("EAG Control is not running"); } if(controller->eag_publisher_alive()){ warnx("EAG Publisher is running"); } else { warnx("EAG Publisher is not running"); } if(controller->eag_scrubber_alive()) { warnx("EAG Scrubber is running"); } else { warnx("EAG Scrubber is not running"); } } return 0; }
20.420455
78
0.643851
JGSuw
e2f8a2b90b6fe84d131f620a2ae86b27c0b8b701
4,411
cpp
C++
sources/calibn/tmp/helpers.cpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
null
null
null
sources/calibn/tmp/helpers.cpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
null
null
null
sources/calibn/tmp/helpers.cpp
SimonsRoad/seq2map
cc8cd20842b3c6db01f73d2e6ecf543189e56891
[ "BSD-3-Clause" ]
1
2018-11-01T13:11:39.000Z
2018-11-01T13:11:39.000Z
#include <sstream> #include <fstream> #include <iomanip> #include <ctime> #include <calibn/helpers.hpp> using namespace cv; std::vector<String> split(const String &s, char delim) { std::vector<String> elems; split(s, delim, elems); return elems; } std::vector<String>& split(const String &s, char delim, Strings &elems) { std::stringstream ss(s); String item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } bool replace(String& str, const String& from, const String& to) { size_t start_pos = str.find(from); if(start_pos == String::npos) return false; str.replace(start_pos, from.length(), to); return true; } String toString(int i) { std::stringstream ss; ss << i; return ss.str(); } String toString(const Mat& X) { Stringstream ss; ss << "["; for (int i = 0; i < X.rows; i++) { for (int j = 0; j < X.cols; j++) { ss << setw(2) << setprecision(5) << X.at<double>(i,j) << (j < X.cols - 1 ? ", " : "; "); } } ss << "]"; return ss.str(); } String toString(const Colour& colour) { std::vector<size_t> x; x.push_back(colour.Red); x.push_back(colour.Green); x.push_back(colour.Blue); Stringstream ss; ss << '#'; for(std::vector<size_t>::const_iterator i = x.begin(); i != x.end(); i++) ss << uppercase << hex << setfill('0') << setw(2) << *i; return ss.str(); } bool fileExists(const String& path) { return boost::filesystem::exists(path); } /* String fullPath(String path, String filename) { boost::filesystem::path p(path); p /= filename; return p.String(); } */ bool mkdir(const String& path) { return boost::filesystem::create_directories(path); } bool initLogFile(const Path& path) { try { logging::core::get()->add_global_attribute("TimeStamp", logging::attributes::local_clock()); logging::add_file_log(path, logging::keywords::format = "[%TimeStamp%] %Message%"); logging::add_console_log(std::cout); } catch (std::exception& ex) { std::cerr << "error logging to file \"" << path.string() << "\"" << std::endl; std::cerr << ex.what() << std::endl; return false; } return true; } double rmse(const Mat& e) { assert(e.rows > 0 && e.cols == 1); // e must be a column std::vector Mat ete = e.t() * e; double e2 = ete.at<double>(0,0); return sqrt(e2 / e.rows); } void drawLabel(Mat& im, const String& label, const Point& pt, int fontFace, double fontScale, const Scalar& frontColour, const Scalar& backColour) { int baseline = 0; Size text = getTextSize(label, fontFace, fontScale, 1.0, &baseline); rectangle(im, pt + Point(0, baseline), pt + Point(text.width, -text.height), backColour, FILLED); putText(im, label, pt, fontFace, fontScale, frontColour, 1, 8); } void drawEpipolarLines(Mat& im, size_t lines, const Scalar& colour) { int step = (int)((double)im.rows / (double)lines); for (int y = 0; y < im.rows; y+= step) { line(im, Point(0,y), Point(im.cols,y), colour); } } void drawCrosshair(Mat& im, const Point2f& pt, int markerSize, const Scalar& colour) { line(im, Point2f(pt.x - markerSize, pt.y), Point2f(pt.x + markerSize, pt.y), colour, 1); line(im, Point2f(pt.x, pt.y - markerSize), Point2f(pt.x, pt.y + markerSize), colour, 1); } void drawCrosshair(Mat& im, const std::vector<Point2f>& pts, int markerSize, const Scalar& colour) { for (std::vector<Point2f>::const_iterator pt = pts.begin(); pt != pts.end(); pt++) { drawCrosshair(im, *pt, markerSize, colour); } } void drawLineStripes(Mat& im, const std::vector<Point2f>& pts, const Scalar& colour, bool closed) { for (size_t i = 0; i < pts.size(); i++) { bool lastPts = !(i < pts.size() - 1); if (lastPts && !closed) { return; } Point2f p1 = pts[i]; Point2f p2 = !lastPts ? pts[i+1] : pts[0]; line(im, p1, p2, colour); } } std::vector<Colour> makeHsvColourMap(size_t n) { std::vector<Colour> colours(n); Mat hsv(n, 1, CV_32FC3), rgb; for (size_t i = 0; i < n; i++) { hsv.at<Vec3f>(i,0) = Vec3f(360.f * i / n, 1.0f, 1.0f); // Vec3f(H,S,V) } cvtColor(hsv, rgb, COLOR_HSV2RGB); for (size_t i = 0; i < n; i++) { Vec3f c = rgb.at<Vec3f>(i,0); colours[i] = Colour(c(0), c(1), c(2)); } return colours; } String now() { time_t t; time(&t); char buff[80]; struct tm* timeinfo = localtime (&t); strftime (buff, 80, "%c",timeinfo); return String(buff); }
21.945274
146
0.619814
SimonsRoad
e2fae44f646ad661d1a508788c2d764a0603039d
839
cpp
C++
Find (Kth element) Second Minimum number in an Array.cpp
Faiquekhan15/C-C-conceptual-Questions
a75141bd5a58c32e2446f695e66ffbf979b8c8af
[ "MIT" ]
null
null
null
Find (Kth element) Second Minimum number in an Array.cpp
Faiquekhan15/C-C-conceptual-Questions
a75141bd5a58c32e2446f695e66ffbf979b8c8af
[ "MIT" ]
null
null
null
Find (Kth element) Second Minimum number in an Array.cpp
Faiquekhan15/C-C-conceptual-Questions
a75141bd5a58c32e2446f695e66ffbf979b8c8af
[ "MIT" ]
null
null
null
//****************************************************************************** // C++ // Find Second Minimum number in an Array //*******************************************************************************/ #include<iostream> #include <limits.h> using namespace std; void kthSmallest(int a[],int n) { int min1=0; int min2=0; min1=min2=INT_MAX; for ( int i=0; i < n; i++ ) { if (a[i]<min1 ) { min2=min1; min1 = a[i]; } else if (a[i]< min2&&a[i]!=min1) { min2 = a[i] ; } } cout<<"kth smallest element ="<<min2; } int main() { int arr[100]; int n=0; cout<<"Enter size of array"<<endl; cin>>n; cout<<"Enter elements in array"<<endl; for ( int i=0; i < n; i++ ) { cin>>arr[i]; } kthSmallest(arr, n); cout <<"\n"; return 0; }
19.97619
82
0.402861
Faiquekhan15
e2fb0903f0d4dd71bd7651f14cca93146eab1e9d
2,628
cpp
C++
app/parser/Reader.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
2
2019-07-15T05:01:57.000Z
2019-09-25T20:23:04.000Z
app/parser/Reader.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
null
null
null
app/parser/Reader.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
null
null
null
#include "Reader.h" #include "GenExams.h" #include "Log.h" #include "Parser.h" #include <algorithm> namespace bsp = boost::spirit::classic; Reader::Reader(std::istream &examScript) : messages_{} , input_{examScript} , examScriptText_{} , pBuilder_{nullptr} { } void Reader::clear() { examScriptText_.clear(); messages_.clear(); } void Reader::read() { input_ >> std::noskipws; copy(std::istream_iterator<char>(input_), std::istream_iterator<char>(), back_inserter(examScriptText_)); examScriptText_.push_back('\0'); LOGI("------ Reading ready"); } std::vector<std::shared_ptr<GenExams>> Reader::parse() { messages_.clear(); ExamBuilder pb(messages_); skipparser skip; ExamSpecParser parser(pb); LOGI("------ Parsing started"); try { const static std::string LINE(75, '-'); std::cout << "\n- Parsing started" << std::endl; std::cout << LINE << "\n"; bsp::parse_info<> info = bsp::parse(&examScriptText_[0], parser, skip); if (info.full) { std::cout << LINE << "\n- Parsing ready\n" << LINE << "\n"; } else { auto lineFailure = std::count(static_cast<const char *>(&examScriptText_[0]), info.stop, '\n') + 1; std::cerr << "\n\n" << "*** Parsing failed at line: " << lineFailure << "\n" << "*** stopped at:\n" << info.stop << "\"\n\n"; messages_.push_back( message_t('E', 0, info.stop, "syntax error, parsing failed")); } } catch (std::exception &x) { std::cerr << "SYSTEM ERROR " << x.what() << std::endl; messages_.push_back(message_t('S', 0, 0, x.what())); } catch (...) { std::cerr << "SYSTEM CRASH " << std::endl; messages_.push_back(message_t('S', 0, 0, "")); } for (auto &msg : messages_) { int lineNumber = 0; /// \todo solve crash // if (std::get<2>(msg) != 0) { // lineNumber = std::count(static_cast<const char *>(&examScriptText_[0]), // std::get<2>(msg), '\n') + // 1; // } std::get<1>(msg) = lineNumber; } for (auto const &msg : messages_) { std::cout << std::get<0>(msg) << " line " << std::get<1>(msg) << ": " << std::get<3>(msg) << std::endl; if (std::get<0>(msg) == 'E') { pb.Product.clear(); } } LOGI("------ Parsing ready"); return pb.getProduct(); }
26.816327
84
0.495434
josokw
e2fcc7f87f57c6506bb31da97aa8ea8832d846a7
3,338
cpp
C++
BlissGBA/Memory/MemoryBus.cpp
Mesiow/BlissGBA
45d8334a3e52917092b05b8d39e35b41b6344b4f
[ "MIT" ]
8
2021-07-26T01:21:39.000Z
2022-01-26T12:28:24.000Z
BlissGBA/Memory/MemoryBus.cpp
Mesiow/BlissGBA
45d8334a3e52917092b05b8d39e35b41b6344b4f
[ "MIT" ]
null
null
null
BlissGBA/Memory/MemoryBus.cpp
Mesiow/BlissGBA
45d8334a3e52917092b05b8d39e35b41b6344b4f
[ "MIT" ]
null
null
null
#include "MemoryBus.h" MemoryBus::MemoryBus() :genMem(), displayMem(), mmio(&genMem) { genMem.loadBios("roms/cult_bios.bin"); } void MemoryBus::loadGamePak(const std::string& file) { pak.load(file); } void MemoryBus::writeU8(u32 address, u8 value) { if (address < GENERAL_MEM_END) { genMem.writeU8(address, value); } else if (address >= GENERAL_MEM_END && address <= DISPLAY_MEM_END) { displayMem.writeU8(address, value); } else if (address >= EXTERNAL_MEM_START && address <= EXTERNAL_MEM_END) { pak.writeU8(address, value); } } void MemoryBus::writeU16(u32 address, u16 value) { if (!isAlignedU16(address)) { std::cerr << "--Unaligned memory write U16 attempted--" << std::endl; return; } if (address < GENERAL_MEM_END) { genMem.writeU16(address, value); } else if (address >= GENERAL_MEM_END && address <= DISPLAY_MEM_END) { displayMem.writeU16(address, value); } else if (address >= EXTERNAL_MEM_START && address <= EXTERNAL_MEM_END) { pak.writeU16(address, value); } } void MemoryBus::writeU32(u32 address, u32 value) { if (!isAlignedU32(address)) { std::cerr << "--Unaligned memory write U32 attempted--" << std::endl; return; } if (address < GENERAL_MEM_END) { genMem.writeU32(address, value); } else if (address >= GENERAL_MEM_END && address <= DISPLAY_MEM_END) { displayMem.writeU32(address, value); } else if (address >= EXTERNAL_MEM_START && address <= EXTERNAL_MEM_END) { pak.writeU32(address, value); } if (address >= 0x80000000) { printf("--Open Bus writeU32-- at address: 0x%08X", address); } //Open bus if (address >= 0x10000000) { printf("--Open Bus readU32-- at address: 0x%08X", address); } } u8 MemoryBus::readU8(u32 address) { if (address < GENERAL_MEM_END) { return genMem.readU8(address); } else if (address >= GENERAL_MEM_END && address <= DISPLAY_MEM_END) { return displayMem.readU8(address); } else if (address >= EXTERNAL_MEM_START && address <= EXTERNAL_MEM_END) { return pak.readU8(address); } } u16 MemoryBus::readU16(u32 address) { if (!isAlignedU16(address)) { std::cerr << "--Unaligned memory read U16 attempted--" << std::endl; return 0; } if (address < GENERAL_MEM_END) { return genMem.readU16(address); } else if (address >= GENERAL_MEM_END && address <= DISPLAY_MEM_END) { return displayMem.readU16(address); } else if (address >= EXTERNAL_MEM_START && address <= EXTERNAL_MEM_END) { return pak.readU16(address); } } u32 MemoryBus::readU32(u32 address) { if (!isAlignedU32(address)) { std::cerr << "--Unaligned memory read U32 attempted--" << std::endl; return 0; } if (address < GENERAL_MEM_END) { return genMem.readU32(address); } else if (address >= GENERAL_MEM_END && address <= DISPLAY_MEM_END) { return displayMem.readU32(address); } else if (address >= EXTERNAL_MEM_START && address <= EXTERNAL_MEM_END) { return pak.readU32(address); } //Open bus hardcode pass for test 362 if (address >= 0x80000000) { printf("--Open Bus readU32-- at address: 0x%08X", address); return 0x1A000002; } ////Open bus if (address >= 0x10000000) { printf("--Open Bus readU32-- at address: 0x%08X", address); return 0; } } bool MemoryBus::isAlignedU16(u32 address) { return ((address % 2) == 0); } bool MemoryBus::isAlignedU32(u32 address) { return ((address % 4) == 0); }
23.507042
73
0.682744
Mesiow
c3b657a02abddd3725cca1f939e78d2088c1821a
128
cpp
C++
code-examples/retval-retvoid/usage_example.cpp
dawidpilarski/CodeDive-coroutines
732111f48116bbfea963abf21afd88cca6b9c18e
[ "Apache-2.0" ]
1
2020-06-08T03:55:13.000Z
2020-06-08T03:55:13.000Z
code-examples/retval-retvoid/usage_example.cpp
dawidpilarski/CodeDive-coroutines
732111f48116bbfea963abf21afd88cca6b9c18e
[ "Apache-2.0" ]
null
null
null
code-examples/retval-retvoid/usage_example.cpp
dawidpilarski/CodeDive-coroutines
732111f48116bbfea963abf21afd88cca6b9c18e
[ "Apache-2.0" ]
null
null
null
task<int> foo(){ co_return 42; } task<void> start(){ std::cout << (co_await foo()) << std::endl; // implicit co_return; }
16
45
0.59375
dawidpilarski
c3bd03be16660bba412a89b26ca5de691e016124
1,823
cpp
C++
src/database/overlay/SoXipMenuStyleElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/database/overlay/SoXipMenuStyleElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/database/overlay/SoXipMenuStyleElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "SoXipMenuStyleElement.h" SO_ELEMENT_SOURCE( SoXipMenuStyleElement ); SoXipMenuStyleElement::~SoXipMenuStyleElement() { } void SoXipMenuStyleElement::initClass() { SO_ELEMENT_INIT_CLASS( SoXipMenuStyleElement, SoReplacedElement ); } void SoXipMenuStyleElement::init( SoState* ) { mMenuStyle = SbXipMenuStyle(); } void SoXipMenuStyleElement::set( SoState* state, SoNode* node, const SbXipMenuStyle& style ) { SoXipMenuStyleElement* elt = (SoXipMenuStyleElement *) getElement( state, classStackIndex, node ); if( elt ) elt->mMenuStyle = style; } SbBool SoXipMenuStyleElement::matches( const SoElement* elt ) const { return mMenuStyle == ((const SoXipMenuStyleElement *) elt)->mMenuStyle; } SoElement* SoXipMenuStyleElement::copyMatchInfo() const { SoXipMenuStyleElement* result = (SoXipMenuStyleElement *) getTypeId().createInstance(); if( result ) { result->mMenuStyle = mMenuStyle; return result; } return NULL; } SbXipMenuStyle SoXipMenuStyleElement::get( SoState* state ) { const SoXipMenuStyleElement* elt = (const SoXipMenuStyleElement*) getConstElement( state, classStackIndex ); return elt ? elt->mMenuStyle : SbXipMenuStyle(); }
23.675325
91
0.767965
OpenXIP
c3d126ac145c3e6d5ccc2b21526827f27d71c334
1,479
cpp
C++
q/src/video/GLES/GLES_Vertex_Buffer.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
q/src/video/GLES/GLES_Vertex_Buffer.cpp
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
q/src/video/GLES/GLES_Vertex_Buffer.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
#include "QStdAfx.h" #include "video/GLES/GLES_Vertex_Buffer.h" #include "video/GLES/GLES_Interface.h" #include "video/Renderer.h" using namespace q; using namespace video; GLES_Vertex_Buffer::GLES_Vertex_Buffer() : m_buffer(GLES_Buffer_Impl::Type::VERTEX) { } GLES_Vertex_Buffer::~GLES_Vertex_Buffer() { } bool GLES_Vertex_Buffer::allocate(size_t size, Usage usage) { return m_buffer.allocate(size, usage); } size_t GLES_Vertex_Buffer::get_size() const { return m_buffer.get_size(); } Buffer::Usage GLES_Vertex_Buffer::get_usage() const { return m_buffer.get_usage(); } bool GLES_Vertex_Buffer::is_locked_for_reading() const { return m_buffer.is_locked_for_reading(); } uint8_t const* GLES_Vertex_Buffer::lock_for_reading() { return m_buffer.lock_for_reading(); } void GLES_Vertex_Buffer::unlock_for_reading() { m_buffer.unlock_for_reading(); } bool GLES_Vertex_Buffer::is_locked_for_writing() const { return m_buffer.is_locked_for_writing(); } uint8_t* GLES_Vertex_Buffer::lock_for_writing() { return m_buffer.lock_for_writing(); } void GLES_Vertex_Buffer::unlock_for_writing() { m_buffer.unlock_for_writing(); } bool GLES_Vertex_Buffer::is_locked_for_consuming() const { return m_buffer.is_locked_for_consuming(); } GLES_Buffer_Impl& GLES_Vertex_Buffer::get_buffer() { return m_buffer; } GLES_Buffer_Impl const& GLES_Vertex_Buffer::get_buffer() const { return m_buffer; }
19.207792
63
0.747803
jeanleflambeur
c3d94a01fc234fa24b3da7725a56a6ead220a328
1,391
cpp
C++
net/acceptor.cpp
bihuchao/small_rpc
8722031b72c4575a8ad52bc8bcb580a1bfecc58c
[ "BSD-2-Clause" ]
1
2022-03-13T23:44:39.000Z
2022-03-13T23:44:39.000Z
net/acceptor.cpp
bihuchao/small_rpc
8722031b72c4575a8ad52bc8bcb580a1bfecc58c
[ "BSD-2-Clause" ]
null
null
null
net/acceptor.cpp
bihuchao/small_rpc
8722031b72c4575a8ad52bc8bcb580a1bfecc58c
[ "BSD-2-Clause" ]
null
null
null
// Use of this source code is governed by a BSD-style license. // // Author: Huchao Bi (bihuchao at qq dot com) #include "acceptor.h" #include "base/logging.h" #include "socket.h" #include "eventloop.h" #include "tcpconnection.h" namespace small_rpc { // Acceptor Acceptor::Acceptor(EventLoop* el, const char* addr, unsigned short port) { _fd = listen_socket(addr, port); _event = EPOLLIN; _el = el; _el->update_channel(static_cast<Channel*>(this)); } // handle_events void Acceptor::handle_events(int events) { if (events & EPOLLIN) { handler_new_connection(); } } // handler_new_connection void Acceptor::handler_new_connection() { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); int conn = ::accept(_fd, reinterpret_cast<struct sockaddr*>(&client_addr), &client_addr_len); if (conn == -1) { if (errno == EAGAIN // nonblocking || errno == EWOULDBLOCK // same as EAGAIN || errno == ECONNABORTED // get a RST connection || errno == EINTR) { // interrupt by signal PLOG_DEBUG << "Acceptor accept -1"; return ; } else { PLOG_FATAL << "Acceptor failed to invoke ::accept"; } } if (_new_connection_callback) { _new_connection_callback(conn); } } }; // namespace small_rpc
27.27451
78
0.629763
bihuchao
c3e58cf1abc09feb5b8686f6107393581dee948f
1,946
cpp
C++
Source/Engine/Source/ING/Rendering/Engine/Engine.cpp
vinoxphucs/ING
cb0123847fb225b65bb5cddb1e4456cd562fd43e
[ "MIT" ]
1
2022-03-01T07:30:58.000Z
2022-03-01T07:30:58.000Z
Source/Engine/Source/ING/Rendering/Engine/Engine.cpp
vinoxphucs/ING
cb0123847fb225b65bb5cddb1e4456cd562fd43e
[ "MIT" ]
null
null
null
Source/Engine/Source/ING/Rendering/Engine/Engine.cpp
vinoxphucs/ING
cb0123847fb225b65bb5cddb1e4456cd562fd43e
[ "MIT" ]
null
null
null
#include "Engine.h" /** * Include System */ #include <ING\Rendering/System/System.h> /** * Include Shader Manager */ #include <ING\Rendering/Shader/Manager/Manager.h> /** * Include Material Manager */ #include <ING\Rendering/Material/Manager/Manager.h> /** * Include Mesh Manager */ #include <ING\Rendering/Mesh/Manager/Manager.h> /** * Include Scene Manager */ #include <ING\Rendering/Scene/Manager/Manager.h> /** * Include API */ #include <ING\Rendering/API/Manager/Manager.h> /** * Include ScreenManager */ #include <ING\Screen/Manager/Manager.h> /** * Include Screen */ #include <ING\Screen/Screen.h> /** * Include WindowManager */ #include <ING\Window/Manager/Manager.h> /** * Include Window */ #include <ING\Window/Window.h> /** * Include SwapChain */ #include <ING/Rendering/API/SwapChain/SwapChain.h> /** * Include Device */ #include <ING/Rendering/API/Device/Device.h> /** * Include Device Context */ #include <ING/Rendering/API/Device/Context/Context.h> /** * Include Camera */ #include <ING/Camera/Camera.h> namespace ING { namespace Rendering { /** * Constructors And Destructor */ Engine::Engine() { /** * Add Squares */ /* API Manager */ AddSquare<APIManager>(); /* Shader Manager */ AddSquare<ShaderManager>(); /* Material Manager */ AddSquare<MaterialManager>(); /* Mesh Manager */ AddSquare<MeshManager>(); /* Scene Manager */ AddSquare<SceneManager>(); /* System */ AddSquare<System>(); } Engine::~Engine() { } /** * Init, Run, Release Methods */ bool Engine::Init() { return Board<Engine>::Init(); } bool Engine::Run() { return Board<Engine>::Run(); } bool Engine::Release() { return Board<Engine>::Release(); } /** * Methods */ void Engine::FrameUpdate() { Rendering::System::GetInstance()->FrameUpdate(); } } }
10.932584
53
0.613566
vinoxphucs
c3eadb28b8704f97adf6521a9743003877697216
1,541
cpp
C++
PhotoChopper/utils/statistics.cpp
SteaveP/PhotoChopper
7a96d389b5c77bfee9d212a679fb999dc87a4856
[ "MIT" ]
null
null
null
PhotoChopper/utils/statistics.cpp
SteaveP/PhotoChopper
7a96d389b5c77bfee9d212a679fb999dc87a4856
[ "MIT" ]
1
2017-03-27T16:32:08.000Z
2017-03-27T16:32:08.000Z
PhotoChopper/utils/statistics.cpp
SteaveP/PhotoChopper
7a96d389b5c77bfee9d212a679fb999dc87a4856
[ "MIT" ]
null
null
null
#include "statistics.h" namespace pc { namespace utils { Statistics::Statistics() { Reset(); } Statistics::Info::Info(const std::string& file, const std::string& msg) : filename(file), message(msg) {} Statistics::Info::Info() {} void Statistics::Reset() { m_success.clear(); m_warning.clear(); m_fail.clear(); } void Statistics::AddSuccess(const Info& file) { m_success.push_back(file); } void Statistics::AddWarning(const Info& file) { m_warning.push_back(file); } void Statistics::AddFail(const Info& file, FailType type) { m_fail[type].push_back(file); } int Statistics::GetTotalProcessedCount() { return GetSuccessCount() + GetTotalFailCount(); } int Statistics::GetSuccessCount() { return m_success.size(); } int Statistics::GetWarningsCount() { return m_warning.size(); } int Statistics::GetTotalFailCount() { int count = 0; for each(const auto& t in m_fail) { count += t.second.size(); } return count; } int Statistics::GetFailCount(FailType failType) { TFailedInfos::const_iterator it = m_fail.find(failType); if (it != m_fail.end()) return it->second.size(); else return 0; } const Statistics::TInfoVec& Statistics::GetFails(FailType failType) { TFailedInfos::const_iterator it = m_fail.find(failType); if (it != m_fail.end()) return it->second; else throw std::invalid_argument("elements for specified failType not found"); } const Statistics::TFailedInfos& Statistics::GetFails() { return m_fail; } float Statistics::GetTotalTime() { // not implemented yet return -1.f; } } }
15.565657
75
0.711875
SteaveP
c3f1427415057d66a5e13f874fc98025f3373f53
2,873
cpp
C++
proto_server/test/test_net_parse_routines.cpp
tseyler/proto-server
e3a45dc64e8081deaad5a8a59560878c2b0bfdc1
[ "MIT" ]
null
null
null
proto_server/test/test_net_parse_routines.cpp
tseyler/proto-server
e3a45dc64e8081deaad5a8a59560878c2b0bfdc1
[ "MIT" ]
null
null
null
proto_server/test/test_net_parse_routines.cpp
tseyler/proto-server
e3a45dc64e8081deaad5a8a59560878c2b0bfdc1
[ "MIT" ]
null
null
null
/* Copyright 2015 Terry Seyler. All rights reserved. */ #include <core/protocol/net_parse_routines.hpp> #include <gtest/gtest.h> using namespace proto_net::protocol; TEST(NetParseRoutinesTest, search_pattern_test) { std::string str("This is a test"); std::string pat("is"); EXPECT_TRUE( search_pattern(str, pat) ); } TEST(NetParseRoutinesTest, search_pattern_count_test) { std::string str("This is a test"); std::string pat("is"); size_t expected = 2; size_t actual; search_pattern(str, pat, actual); EXPECT_EQ( expected, actual ); } TEST(NetParseRoutinesTest, search_pattern_matches_test) { std::string str("This is a test"); std::string pat(".s"); matches_t matches; search_pattern(str, pat, matches); size_t expected = 3; EXPECT_EQ( expected, matches.size() ); if (matches.size() == 3) // test contents { std::string expected_string("es"); EXPECT_EQ( expected_string, matches[2] ); } } TEST(NetParseRoutinesTest, match_pattern_test) { std::string str(" This is a test"); std::string pat("^\\s+.*"); EXPECT_TRUE( match_pattern(str, pat) ); } TEST(NetParseRoutinesTest, match_pattern_matches_test) { std::string str(" This is a test"); std::string pat("^\\s+(.*)"); matches_t matches; match_pattern(str, pat, matches); size_t expected = 2; EXPECT_EQ( expected, matches.size() ); if (matches.size() == 2) // test contents { std::string expected_string("This is a test"); EXPECT_EQ( expected_string, matches[1] ); } } TEST(NetParseRoutinesTest, replace_pattern_test) { std::string str("This is a test"); std::string pat("This"); std::string rep_str("That"); std::string expected("That is a test"); EXPECT_EQ( expected, replace_pattern(str, pat, rep_str) ); } TEST(NetParseRoutinesTest, trim_front_test) { std::string actual(" This is a test"); std::string expected("This is a test"); EXPECT_EQ( expected, trim_front(actual) ); } TEST(NetParseRoutinesTest, trim_back_test) { std::string actual("This is a test "); std::string expected("This is a test"); EXPECT_EQ( expected, trim_back(actual) ); } TEST(NetParseRoutinesTest, trim_test) { std::string actual(" This is a test "); std::string expected("This is a test"); EXPECT_EQ( expected, trim(actual) ); } TEST(NetParseRoutinesTest, split_test) { std::string str("This is a test"); matches_t matches; split(str, matches); std::string expected("test"); EXPECT_EQ( expected, matches[3] ); } TEST(NetParseRoutinesTest, split_sep_test) { std::string str("http://www.google.com"); std::string sep(":/"); matches_t matches; split(str, sep, matches); std::string expected("www.google.com"); EXPECT_EQ( expected, matches[1] ); }
25.201754
62
0.651584
tseyler
c3f5d5caa3eb0a1570057d44944c33d97044c029
50,091
cpp
C++
src/eval_impl_jit.cpp
jarikomppa/sassy
0802c4ef13e5d9b6079cbee60cbf753ae26179f2
[ "MIT" ]
32
2022-03-11T17:54:09.000Z
2022-03-25T08:07:06.000Z
src/eval_impl_jit.cpp
jarikomppa/sassy
0802c4ef13e5d9b6079cbee60cbf753ae26179f2
[ "MIT" ]
null
null
null
src/eval_impl_jit.cpp
jarikomppa/sassy
0802c4ef13e5d9b6079cbee60cbf753ae26179f2
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "eval.h" #include "xbyak/xbyak.h" using namespace EvalFunc; namespace jit_kludge { double log(double v) { return std::log((float)v); // no "double log(double)" exists } double log10(double v) { return std::log10((float)v); // no "double log10(double)" exists } double tan(double v) { return std::tan((float)v); // no "double tan(double)" exists } double notetofreq(double v) { if ((int)v >= 0 && (int)v < 128) return note_to_freq[(int)v]; return 0; } double freqtonote(double v) { return 12 * log(32 * POW_2_3_4TH * (v / 440)) / log(2); } double even(double v) { return ((int)v & 1) ? 0.0 : 1.0; } double odd(double v) { return ((int)v & 1) ? 1.0 : 0.0; } double sign(double v) { return (v < 0.0) ? -1.0 : 1.0; } double smoothstep(double v) { return v * v * (3 - 2 * v); } double smootherstep(double v) { return v * v * v * (v * (v * 6 - 15) + 10); } double notetofreqslow(double v) { return pow(2, (v - 69) / 12.0) * 440; } double quantize(double v) { double t = 12 * log(32 * POW_2_3_4TH * (v) / 440) / log(2); int i = (int)t; if (i >= 0 && i < 128) return note_to_freq[i]; return v; } double minfunc(double a, double b) { return (b < a) ? b : a; } double maxfunc(double a, double b) { return (b > a) ? b : a; } double clamp(double a, double b, double c) { return (a < b) ? b : (a > c) ? c : a; } double mix(double a, double b, double c) { return b + a * (c - b); } double map(double a, double b, double c, double d, double e) { return ((a - b) / (c - b)) * (e - d) + d; } double pinknoise(int cell, int memofs) { return paranoise(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, cell, memofs); } double brownnoise(int cell, int memofs) { return paranoise(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, cell, memofs); } double bluenoise(int cell, int memofs) { return paranoise(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, cell, memofs); } } void store_xmm0(Xbyak::CodeGenerator& code, bool& first) { if (first) { first = false; return; } using namespace Xbyak::util; code.sub(rsp, 16); // push xmm0 to stack code.movq(qword[rsp + 32], xmm0); } void jit_init(Xbyak::CodeGenerator& code) { using namespace Xbyak::util; code.resetSize(); code.sub(rsp, 16 * 10); code.movdqu(xword[rsp + 16 * 0], xmm6); code.movdqu(xword[rsp + 16 * 1], xmm7); code.movdqu(xword[rsp + 16 * 2], xmm8); code.movdqu(xword[rsp + 16 * 3], xmm9); code.movdqu(xword[rsp + 16 * 4], xmm10); code.movdqu(xword[rsp + 16 * 5], xmm11); code.movdqu(xword[rsp + 16 * 6], xmm12); code.movdqu(xword[rsp + 16 * 7], xmm13); code.movdqu(xword[rsp + 16 * 8], xmm14); code.movdqu(xword[rsp + 16 * 9], xmm15); code.push(rbx); code.push(rbp); code.push(rdi); code.push(r12); code.push(r13); code.push(r14); code.push(r15); code.sub(rsp, 32); // reserve stack for func calls code.mov(r14, rcx); // read var ptr code.mov(r15, rdx); // write var ptr } int jit_addcode(Op* bc, int cell, Xbyak::CodeGenerator& code, char *stringstore) { using namespace Xbyak::util; union double_64int { double f; unsigned long long i64; }; double_64int one, epsilon; one.f = 1; epsilon.f = EPSILON; // Assumption: // Top of stack == xmm0. // rsp is kept at -32 bytes offset so we don't need to muck with it doing calls. int memofs = 0; int stack = 0; bool first = 1; if (bc->mOpcode == 0) return 0; while (bc->mOpcode) { switch (bc->mOpcode) { case 'C': // numeric constant { store_xmm0(code, first); if (bc->mArg.f64) { code.mov(rax, bc->mArg.f64); // move constant to xmm0 code.movq(xmm0, rax); } else { code.xorpd(xmm0, xmm0); } stack++; bc++; } break; case 'A': // area { double_64int t; store_xmm0(code, first); t.f = bc->mArg.i.i; code.mov(rax, t.i64); // move constant to xmm0 code.movq(xmm0, rax); code.sub(rsp, 16); // push xmm0 to stack code.movq(qword[rsp + 32], xmm0); t.f = bc->mArg.i.j; code.mov(rax, t.i64); // move constant to xmm0 code.movq(xmm0, rax); stack += 2; bc++; } break; case '+': { stack--; // Pop two values off stack code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.addsd(xmm0, xmm1); bc++; } break; case '-': { stack--; // Pop two values off stack code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.subsd(xmm1, xmm0); // arguments are swapped, but don't matter code.movsd(xmm0, xmm1); bc++; } break; case '*': { stack--; // Pop two values off stack code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.mulsd(xmm0, xmm1); // arguments are swapped, but don't matter bc++; } break; case '/': { stack--; // Pop two values off stack code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.divsd(xmm1, xmm0); // order matters! code.movsd(xmm0, xmm1); bc++; } break; case '>': { stack--; // Compare is swapped because parameters are in wrong regs code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.cmpsd(xmm0, xmm1, 1); code.mov(rax, one.i64); code.movq(xmm1, rax); code.andpd(xmm0, xmm1); bc++; } break; case '<': { stack--; // Compare is swapped because parameters are in wrong regs code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.cmpsd(xmm0, xmm1, 5); code.mov(rax, one.i64); code.movq(xmm1, rax); code.andpd(xmm0, xmm1); bc++; } break; case '=': // TODO: no threshold check { stack--; // Pop two values off stack code.movq(xmm1, qword[rsp + 32]); code.add(rsp, 16); code.cmpsd(xmm0, xmm1, 0); // leads to empty or full mask (Arguments are swapped but don't matter) code.mov(rax, one.i64); code.movq(xmm1, rax); code.andpd(xmm0, xmm1); // anding pattern of 1.0 to either 0.0 or 1.0 bc++; } break; case 'V': // variable { store_xmm0(code, first); code.movq(xmm0, qword[r14 + (bc->mArg.i.i - 1) * 8]); stack++; bc++; } break; case 'T': // text { store_xmm0(code, first); long long v = ((intptr_t)stringstore + bc->mArg.i.i); code.mov(rax, v); code.movq(xmm0, rax); stack++; bc++; } break; case 'F': // function call { #define CALLFUNC1(x) \ code.mov(rax, (size_t)static_cast<double(*)(double)>(x)); \ code.call(rax); int func = bc->mArg.i.i; bc++; switch (func) { case FUNC_SIN: CALLFUNC1(sin); break; case FUNC_OUT: CALLFUNC1(output); break; case FUNC_TRUNC: CALLFUNC1(trunc); break; case FUNC_FRACT: // this is overly complicated, should calc trunc/fract without func call code.movsd(xmm1, xmm0); CALLFUNC1(trunc); code.movsd(xmm2, xmm0); code.movsd(xmm0, xmm1); code.subsd(xmm0, xmm2); //stack[sp - 1] = stack[sp - 1] - trunc(stack[sp - 1]); break; case FUNC_SIN1: CALLFUNC1(sin1); break; case FUNC_TRIANGLE: CALLFUNC1(triangle); break; case FUNC_SQUARE: CALLFUNC1(square); break; case FUNC_SQUAREQ: CALLFUNC1(squareq); break; case FUNC_SAW: CALLFUNC1(saw); break; case FUNC_SAWQ: CALLFUNC1(sawq); break; case FUNC_SQRT: CALLFUNC1(sqrt); break; case FUNC_LOG: CALLFUNC1(jit_kludge::log); break; case FUNC_COS: CALLFUNC1(cos); break; case FUNC_TAN: CALLFUNC1(jit_kludge::tan); break; case FUNC_ACOS: CALLFUNC1(acos); break; case FUNC_ASIN: CALLFUNC1(asin); break; case FUNC_ATAN: CALLFUNC1(atan); break; case FUNC_COSH: CALLFUNC1(cosh); break; case FUNC_SINH: CALLFUNC1(sinh); break; case FUNC_TANH: CALLFUNC1(tanh); break; case FUNC_EXP: CALLFUNC1(exp); break; case FUNC_LOG10: CALLFUNC1(jit_kludge::log10); break; case FUNC_FLOOR: CALLFUNC1(floor); break; case FUNC_ABS: CALLFUNC1(abs); break; case FUNC_OPL1: CALLFUNC1(opl1); break; case FUNC_OPL2: CALLFUNC1(opl2); break; case FUNC_OPL3: CALLFUNC1(opl3); break; case FUNC_B_NOT: CALLFUNC1(b_not); break; case FUNC_NOTETOFREQ: CALLFUNC1(jit_kludge::notetofreq); break; case FUNC_FREQTONOTE: CALLFUNC1(jit_kludge::freqtonote); break; case FUNC_EVEN: CALLFUNC1(jit_kludge::even); break; case FUNC_ODD: CALLFUNC1(jit_kludge::odd); break; case FUNC_SIGN: CALLFUNC1(jit_kludge::sign); break; case FUNC_SMOOTHSTEP: CALLFUNC1(jit_kludge::smoothstep); break; case FUNC_SMOOTHERSTEP: CALLFUNC1(jit_kludge::smootherstep); break; case FUNC_NOTETOFREQSLOW: CALLFUNC1(jit_kludge::notetofreqslow); break; case FUNC_QUANTIZE: CALLFUNC1(jit_kludge::quantize); break; case FUNC_MIDIOUTPITCH: CALLFUNC1(midioutpitch); break; case FUNC_MIDIOUTPROG: CALLFUNC1(midioutprog); break; case FUNC_IN2: CALLFUNC1(in2); break; case FUNC_MIDIVALV: CALLFUNC1(midivalv); break; case FUNC_MIDINOTEV: CALLFUNC1(midinotev); break; case FUNC_MIDIVELV: CALLFUNC1(midivelv); break; case FUNC_MIDIONV: CALLFUNC1(midionv); break; case FUNC_MIDICHANNEL: CALLFUNC1(midichannel); break; case FUNC_DISTORT: CALLFUNC1(distort); break; case FUNC_LEN: CALLFUNC1(len); break; case FUNC_CHANNELS: CALLFUNC1(channels); break; #define CALLFUNC2(x) \ stack--; \ code.movsd(xmm1, xmm0); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(rax, (size_t)static_cast<double(*)(double, double)>(x)); \ code.call(rax); case FUNC_OUT2: CALLFUNC2(output2); break; case FUNC_PULSE: CALLFUNC2(pulse); break; case FUNC_POW: CALLFUNC2(pow); break; case FUNC_ATAN2: CALLFUNC2(atan2); break; case FUNC_SQUAREF: CALLFUNC2(squaref); break; case FUNC_SAWF: CALLFUNC2(sawf); break; case FUNC_SQUARESAW: CALLFUNC2(squaresaw); break; case FUNC_B_AND: CALLFUNC2(b_and); break; case FUNC_B_OR: CALLFUNC2(b_or); break; case FUNC_B_XOR: CALLFUNC2(b_xor); break; case FUNC_B_NAND: CALLFUNC2(b_nand); break; case FUNC_B_NOR: CALLFUNC2(b_nor); break; case FUNC_B_SHLEFT: CALLFUNC2(b_shleft); break; case FUNC_B_SHRIGHT: CALLFUNC2(b_shright); break; case FUNC_B_TEST: CALLFUNC2(b_test); break; case FUNC_B_SET: CALLFUNC2(b_set); break; case FUNC_B_CLEAR: CALLFUNC2(b_clear); break; case FUNC_LOOKUP: CALLFUNC2(lookup); break; case FUNC_AREAMIN: CALLFUNC2(tablemin); break; case FUNC_AREAMAX: CALLFUNC2(tablemax); break; case FUNC_AVERAGE: CALLFUNC2(tableaverage); break; case FUNC_SUM: CALLFUNC2(tablesum); break; case FUNC_PRODUCT: CALLFUNC2(tableproduct); break; case FUNC_COUNT: CALLFUNC2(tablecount); break; case FUNC_MOD: CALLFUNC2(fmod); break; case FUNC_MIN: CALLFUNC2(jit_kludge::minfunc); break; case FUNC_MAX: CALLFUNC2(jit_kludge::maxfunc); break; case FUNC_MIDIOUT: CALLFUNC2(midiout); break; case FUNC_MIDIOUTPOT: CALLFUNC2(midioutpot); break; case FUNC_PROBEC: CALLFUNC2(probe); break; case FUNC_BITCRUNCH: CALLFUNC2(bitcrunch); break; case FUNC_MIDIVALC: CALLFUNC2(midivalc); break; case FUNC_MIDINOTEC: CALLFUNC2(midinotec); break; case FUNC_MIDIVELC: CALLFUNC2(midivelc); break; case FUNC_MICIONC: CALLFUNC2(midionc); break; case FUNC_SCALE: CALLFUNC2(scale); break; case FUNC_SAMPLE: CALLFUNC2(sample); break; case FUNC_SAMPLEFAST: CALLFUNC2(samplefast); break; case FUNC_MIDIOUTPITCHC: CALLFUNC2(midioutpitchc); break; case FUNC_MIDIOUTPROGC: CALLFUNC2(midioutprogc); break; case FUNC_AKWF: CALLFUNC2(akwf); break; #define PUSH_CONST(x) \ {\ store_xmm0(code, first); \ double_64int t; t.f = x; \ stack++; \ code.mov(rax, t.i64); /* move constant to xmm0 */ \ code.movq(xmm0, rax); \ } case FUNC_PI: PUSH_CONST(M_PI); break; case FUNC_NAN: PUSH_CONST(nan("0")); break; case FUNC_TRUE: PUSH_CONST(1.0); break; case FUNC_FALSE: PUSH_CONST(0.0); break; case FUNC_DT: PUSH_CONST(dt()); break; #define CALLFUNC0(x) \ stack++; \ store_xmm0(code, first); \ code.mov(rax, (size_t)static_cast<double(*)()>(x)); \ code.call(rax); case FUNC_TIME: CALLFUNC0(gettime); break; case FUNC_MIDIVAL: CALLFUNC0(midival); break; case FUNC_MIDINOTE: CALLFUNC0(midinote); break; case FUNC_MIDIVEL: CALLFUNC0(midivel); break; case FUNC_MIDION: CALLFUNC0(midion); break; case FUNC_MIDIPITCH: CALLFUNC0(midipitch); break; case FUNC_MIDIPROG: CALLFUNC0(midiprog); break; case FUNC_NOISE: CALLFUNC0(noise); break; case FUNC_IN: CALLFUNC0(in); break; case FUNC_CPU: CALLFUNC0(cpu); break; #define CALLFUNC1M(x) \ code.mov(rdx, cell); /* set up memory params */ \ code.mov(r8, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(double,int,int)>(x)); \ code.call(rax); case FUNC_GRAPH: CALLFUNC1M(graph); break; case FUNC_FFT: CALLFUNC1M(fft); break; case FUNC_TIMEGATE: CALLFUNC1M(timegate); break; case FUNC_BAR: CALLFUNC1M(bar); break; case FUNC_PIE: CALLFUNC1M(pie); break; case FUNC_SLIDERV: CALLFUNC1M(slider); break; case FUNC_TOGGLEV: CALLFUNC1M(toggle); break; case FUNC_STEP: CALLFUNC1M(step); break; case FUNC_DC: CALLFUNC1M(dc); break; case FUNC_PLOTXY: CALLFUNC1M(plotxy); break; case FUNC_BUFFER: CALLFUNC1M(buffer); break; case FUNC_ENCODERV: CALLFUNC1M(encoder); break; #define CALLFUNC1MT(x) \ code.movq(rcx, xmm0); \ code.mov(rdx, cell); /* set up memory params */ \ code.mov(r8, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(char*,int,int)>(x)); \ code.call(rax); case FUNC_LOADWAV: CALLFUNC1MT(loadwav); break; case FUNC_KLATT: CALLFUNC1MT(klatt); break; case FUNC_LABEL: CALLFUNC1MT(label); break; #define CALLFUNC2M(x) \ stack--; \ code.movsd(xmm1, xmm0); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(r8, cell); /* set up memory params */ \ code.mov(r9, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(double,double,int,int)>(x)); \ code.call(rax); case FUNC_DELAY: CALLFUNC2M(delay); break; case FUNC_HOLD: CALLFUNC2M(hold); break; case FUNC_LATCH: CALLFUNC2M(latch); break; case FUNC_MIDIPOTV: CALLFUNC2M(midipot); break; case FUNC_TRIGGERM: CALLFUNC2M(trigger); break; case FUNC_RUBBERBAND: CALLFUNC2M(rubberband); break; case FUNC_SLIDERPOTV: CALLFUNC2M(sliderpot); break; case FUNC_DRUNKARDSWALK: CALLFUNC2M(drunkardswalk); break; case FUNC_TOGGLEPOTV: CALLFUNC2M(togglepot); break; case FUNC_STEPG: CALLFUNC2M(stepg); break; case FUNC_PLOTXY2: CALLFUNC2M(plotxy2); break; case FUNC_BARA: CALLFUNC2M(bara); break; case FUNC_PIEA: CALLFUNC2M(piea); break; case FUNC_PLAY: CALLFUNC2M(play); break; case FUNC_SLEWLIMIT: CALLFUNC2M(slewlimit); break; case FUNC_BBD: CALLFUNC2M(bbd); break; #define CALLFUNC2MT(x) \ stack--; \ code.movsd(xmm1, xmm0); \ code.mov(rcx, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(r8, cell); /* set up memory params */ \ code.mov(r9, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(char*,double,int,int)>(x)); \ code.call(rax); case FUNC_LOADWAVC: CALLFUNC2MT(loadwavc); break; #define CALLFUNC3M(x) \ stack -= 2; \ code.movsd(xmm2, xmm0); \ code.movq(xmm1, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(r9, cell); /* set up memory params */ \ code.sub(rsp, 8); /* 16 byte align*/ \ code.sub(rsp, 8); \ code.mov(dword[rsp + 32], memofs); /* push memofs to stack */ \ code.mov(rax, (size_t)static_cast<double(*)(double, double, double, int, int)>(x)); \ code.call(rax); \ code.add(rsp, 16); /* memofs + align off stack */ case FUNC_HOLDL: CALLFUNC3M(holdl); break; case FUNC_PLAYLOOP: CALLFUNC3M(playloop); break; case FUNC_SIDVOICE: CALLFUNC3M(sidvoice); break; case FUNC_SLEWLIMITUD: CALLFUNC3M(slewlimitud); break; case FUNC_BBDEFF: CALLFUNC3M(bbdeff); break; #define CALLFUNC3TM(x) \ stack -= 2; \ code.movq(xmm2, xmm0); \ code.movq(xmm1, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(rcx, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(r9, cell); /* set up memory params */ \ code.sub(rsp, 8); /* 16 byte align*/ \ code.sub(rsp, 8); \ code.mov(dword[rsp + 32], memofs); /* push memofs to stack */ \ code.mov(rax, (size_t)static_cast<double(*)(char*, double, double, int, int)>(x)); \ code.call(rax); \ code.add(rsp, 16); /* memofs + align off stack */ case FUNC_IMG: CALLFUNC3TM(img); break; #define CALLFUNC3(x) \ stack -= 2; \ code.movsd(xmm2, xmm0); \ code.movq(xmm1, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(rax, (size_t)static_cast<double(*)(double, double, double)>(x)); \ code.call(rax); case FUNC_B_ROTLEFTV: CALLFUNC3(b_rotleft); break; case FUNC_B_ROTRIGHTV: CALLFUNC3(b_rotright); break; case FUNC_HILIGHTV: CALLFUNC3(hilight); break; case FUNC_RGB: CALLFUNC3(rgb); break; case FUNC_REPLACE: CALLFUNC3(replace); break; case FUNC_SUPERSAW: CALLFUNC3(supersaw); break; case FUNC_SUPERSQUARE: CALLFUNC3(supersquare); break; case FUNC_SUPERSIN: CALLFUNC3(supersin); break; case FUNC_SELECT: CALLFUNC3(tableselect); break; case FUNC_SELECTV: CALLFUNC3(tableselectv); break; case FUNC_FIND: CALLFUNC3(tablefind); break; case FUNC_FINDV: CALLFUNC3(tablefindv); break; case FUNC_CLAMP: CALLFUNC3(jit_kludge::clamp); break; case FUNC_MIX: CALLFUNC3(jit_kludge::mix); break; case FUNC_MIDIOUTC: CALLFUNC3(midioutc); break; case FUNC_MIDIOUTPOTC: CALLFUNC3(midioutpotc); break; case FUNC_SQUARESAWD: CALLFUNC3(squaresawd); break; #define CALLFUNC4(x) \ stack -= 3; \ code.movsd(xmm3, xmm0); \ code.movq(xmm2, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm1, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double)>(x)); \ code.call(rax); case FUNC_MIDIOUTRAW: CALLFUNC4(midioutraw); break; case FUNC_WRITE: CALLFUNC4(write); break; #define CALLFUNC4M(x) \ stack -= 3; \ code.movsd(xmm3, xmm0); \ code.movq(xmm2, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm1, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.sub(rsp, 8); \ code.mov(dword[rsp + 32], memofs); \ code.sub(rsp, 8); \ code.mov(dword[rsp + 32], cell); \ code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, int, int)>(x)); \ code.call(rax); \ code.add(rsp, 8 + 8); case FUNC_GRAIN: CALLFUNC4M(grain); break; case FUNC_SIDFILTER: CALLFUNC4M(sidfilter); break; #define CALLFUNC0M(x) \ stack++; \ store_xmm0(code, first); \ code.mov(rcx, cell); /* set up memory params */ \ code.mov(rdx, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(int,int)>(x)); \ code.call(rax); case FUNC_BUTTON: CALLFUNC0M(button); break; #define CALLFUNC0MC(x,c) \ stack++; \ store_xmm0(code, first); \ code.mov(rax, (size_t)c); /* store constant */ \ code.movq(xmm0, rax); \ code.mov(rdx, cell); /* set up memory params */ \ code.mov(r8, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(double,int,int)>(x)); \ code.call(rax); case FUNC_TOGGLE: CALLFUNC0MC(toggle, 0); break; case FUNC_SLIDER: CALLFUNC0MC(slider, 0); break; case FUNC_ENCODER: CALLFUNC0MC(encoder, 0); break; #define CALLFUNC1MC2(x,c) \ if (c) { \ code.mov(rax, c); /* store constant */ \ code.movq(xmm1, rax); \ } else { \ code.xorpd(xmm1, xmm1); \ } \ code.mov(r8, cell); /* set up memory params */ \ code.mov(r9, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(double,double,int,int)>(x)); \ code.call(rax); case FUNC_TRIGGER: { double_64int t; t.f = 0; CALLFUNC1MC2(trigger, t.i64); } break; #define CALLFUNC1MC(x,c) \ code.movsd(xmm1, xmm0); \ code.mov(rax, (size_t)c); /* store constant */ \ code.movq(xmm0, rax); \ code.mov(r8, cell); /* set up memory params */ \ code.mov(r9, memofs); \ code.mov(rax, (size_t)static_cast<double(*)(double,double,int,int)>(x)); \ code.call(rax); \ case FUNC_MIDIPOT: { double_64int t; t.f = 0; CALLFUNC1MC(midipot, t.i64); } break; case FUNC_SLIDERPOT: { double_64int t; t.f = 0; CALLFUNC1MC(sliderpot, t.i64); } break; case FUNC_TOGGLEPOT: { double_64int t; t.f = 0; CALLFUNC1MC(togglepot, t.i64); } break; #define CALLFUNC2C(x,c) \ stack--; \ code.movsd(xmm1, xmm0); \ code.mov(rax, (size_t)c); /* store constant */ \ code.movq(xmm2, rax); \ code.movq(xmm0, qword[rsp+32]); /* pop from stack */ \ code.add(rsp, 16); \ code.mov(rax, (size_t)static_cast<double(*)(double, double, double)>(x)); \ code.call(rax); case FUNC_B_ROTLEFT: { double_64int t; t.f = 32; CALLFUNC2C(b_rotleft, t.i64); } break; case FUNC_B_ROTRIGHT: { double_64int t; t.f = 32; CALLFUNC2C(b_rotright, t.i64); } break; case FUNC_HILIGHT: { double_64int t; t.f = rgb(0.1f, 0.3f, 0.1f); CALLFUNC2C(hilight, t.i64); } break; case FUNC_DEGREES: { double_64int t; t.f = (180 / M_PI); code.mov(rax, t.i64); code.movq(xmm1, rax); code.mulsd(xmm0, xmm1); } break; case FUNC_RADIANS: { double_64int t; t.f = (M_PI / 180); code.mov(rax, t.i64); code.movq(xmm1, rax); code.mulsd(xmm0, xmm1); } break; case FUNC_ISNAN: code.mov(rax, one.i64); code.movq(xmm1, rax); code.cmppd(xmm0, xmm0, 3); // check for nan:s, result all 0 or all 1 code.andpd(xmm0, xmm1); // and mask with pattern of 1.0 break; case FUNC_NANKILL: code.movq(xmm1, xmm0); code.cmppd(xmm0, xmm0, 7); // check for not nan:s, result all 0 or all 1 code.andpd(xmm0, xmm1); // and mask with pattern of original value break; case FUNC_IF: stack -= 2; code.movq(xmm2, xmm0); code.movq(xmm1, qword[rsp + 32]); // pop from stack code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); // pop from stack code.add(rsp, 16); code.mov(rax, epsilon.i64); code.movq(xmm3, rax); code.cmppd(xmm0, xmm3, 5); // xmm0 > xmm3; xmm0 is all 0:s or all 1:s code.andpd(xmm1, xmm0); // xmm1 is 0 or 'then' code.andnpd(xmm0, xmm2); // xmm0 is 0 or 'else' code.orpd(xmm0, xmm1); // xmm0 is 'then' or 'else' break; case FUNC_AND: stack--; // params are swapped but that doesn't matter code.movq(xmm1, qword[rsp + 32]); // pop from stack code.add(rsp, 16); code.mov(rax, epsilon.i64); code.movq(xmm3, rax); code.cmppd(xmm0, xmm3, 5); // all 0:s or all 1:s code.cmppd(xmm1, xmm3, 5); // all 0:s or all 1:s code.andpd(xmm0, xmm1); code.mov(rax, one.i64); // finally and with pattern of 1.0 code.movq(xmm3, rax); code.andpd(xmm0, xmm3); break; case FUNC_OR: stack--; // params are swapped but that doesn't matter code.movq(xmm1, qword[rsp + 32]); // pop from stack code.add(rsp, 16); code.mov(rax, epsilon.i64); code.movq(xmm3, rax); code.cmppd(xmm0, xmm3, 5); // all 0:s or all 1:s code.cmppd(xmm1, xmm3, 5); // all 0:s or all 1:s code.orpd(xmm0, xmm1); code.mov(rax, one.i64); // finally and with pattern of 1.0 code.movq(xmm3, rax); code.andpd(xmm0, xmm3); break; case FUNC_XOR: stack--; // params are swapped but that doesn't matter code.movq(xmm1, qword[rsp + 32]); // pop from stack code.add(rsp, 16); code.mov(rax, epsilon.i64); code.movq(xmm3, rax); code.cmppd(xmm0, xmm3, 5); // all 0:s or all 1:s code.cmppd(xmm1, xmm3, 5); // all 0:s or all 1:s code.xorpd(xmm0, xmm1); code.mov(rax, one.i64); // finally and with pattern of 1.0 code.movq(xmm3, rax); code.andpd(xmm0, xmm3); break; case FUNC_NOT: code.mov(rax, epsilon.i64); code.movq(xmm3, rax); code.cmppd(xmm0, xmm3, 1); // all 0:s or all 1:s; comparison is swapped code.mov(rax, one.i64); // finally and with pattern of 1.0 code.movq(xmm3, rax); code.andpd(xmm0, xmm3); break; case FUNC_PROBE: code.movsd(xmm1, xmm0); code.xorpd(xmm0, xmm0); code.mov(rax, (size_t)static_cast<double(*)(double, double)>(probe)); code.call(rax); break; case FUNC_ADSR: stack -= 4; code.movsd(xmm5, xmm0); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm5 has 5th. code.sub(rsp, 8); // 16 byte align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 5th to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(adsr)); code.call(rax); code.add(rsp, 8 + 8 * 2 + 8); // 5th, cell, memofs, align off stack break; case FUNC_CATMULLROM: stack -= 4; code.movsd(xmm5, xmm0); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm5 has 5th. code.sub(rsp, 8); // 16 byte align code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 5th to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double)>(catmullrom)); code.call(rax); code.add(rsp, 8 + 8); // 5th, cell, memofs, align off stack break; case FUNC_HEXWAVE: stack -= 4; code.movsd(xmm5, xmm0); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm5 has 5th. code.sub(rsp, 8); // 16 byte align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 5th to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(hexwave)); code.call(rax); code.add(rsp, 8 + 8 * 2 + 8); // 5th, cell, memofs, align off stack break; case FUNC_ALLPASS: stack -= 2; code.movsd(xmm2, xmm0); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.mov(r9, cell); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); // 16 byte align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, int, int)>(allpass)); code.call(rax); code.add(rsp, 8 + 8); // memofs, align off stack break; case FUNC_COMB: stack -= 3; code.movsd(xmm3, xmm0); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, int, int)>(comb)); code.call(rax); code.add(rsp, 8 + 8); // memofs, cell off stack break; case FUNC_REVERB: stack -= 3; code.movsd(xmm3, xmm0); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, int, int)>(reverb)); code.call(rax); code.add(rsp, 8 + 8); // memofs, cell off stack break; case FUNC_FILTER: stack -= 3; code.movsd(xmm3, xmm0); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2 and 3 have fist 4 params, count, cell and memofs goes to stack code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(rax, one.i64); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // align, count, memofs, cell off stack break; case FUNC_LPF: stack -= 2; code.movsd(xmm2, xmm0); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.xorpd(xmm3, xmm3); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(rax, one.i64); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // memofs, cell off stack break; case FUNC_HPF: stack -= 2; code.movsd(xmm2, xmm0); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.mov(rax, one.i64); code.movq(xmm3, rax); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(rax, one.i64); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // memofs, cell off stack break; case FUNC_BPF: stack -= 2; code.movsd(xmm2, xmm0); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); { double_64int t; t.f = 2.0; code.mov(rax, t.i64); } code.movq(xmm3, rax); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(rax, one.i64); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // memofs, cell off stack break; case FUNC_MAP: stack -= 4; code.movsd(xmm5, xmm0); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm5 has 5th. code.sub(rsp, 8); // 16 byte align code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 5th to stack code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double)>(jit_kludge::map)); code.call(rax); code.add(rsp, 8 + 8); // 5th, align off stack break; #define CALLFUNC5M(x) \ stack -= 4; \ code.movq(rax, xmm0); \ code.movq(xmm3, qword[rsp + 32]); \ code.add(rsp, 16); \ code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ \ code.add(rsp, 16); \ code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ \ code.add(rsp, 16); \ code.sub(rsp, 8); /* align*/ \ code.sub(rsp, 8); \ code.mov(dword[rsp + 32], memofs); /* push memofs to stack*/ \ code.sub(rsp, 8); \ code.mov(dword[rsp + 32], cell); /* push cell to stack*/ \ code.sub(rsp, 8); \ code.mov(qword[rsp + 32], rax); \ code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(x)); \ code.call(rax); \ code.add(rsp, 8 + 8 + 8 + 8); case FUNC_FILTERC: CALLFUNC5M(filter); break; case FUNC_PLAYLOOPP: CALLFUNC5M(playloopp); break; case FUNC_PLAYLOOPX: CALLFUNC5M(playloopx); break; case FUNC_SIDENVELOPE: CALLFUNC5M(sidenvelope); break; case FUNC_LPFC: stack -= 3; code.movq(rax, xmm0); code.movq(xmm2, qword[rsp + 32]); code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.xorpd(xmm3, xmm3); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // memofs, cell off stack break; case FUNC_HPFC: stack -= 3; code.movq(rax, xmm0); code.movq(xmm2, qword[rsp + 32]); code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.mov(rbx, one.i64); code.movq(xmm3, rbx); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // memofs, cell off stack break; case FUNC_BPFC: stack -= 3; code.movq(rax, xmm0); code.movq(xmm2, qword[rsp + 32]); code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); { double_64int t; t.f = 2.0; code.mov(rbx, t.i64); } code.movq(xmm3, rbx); // At this point xmm0,1,2 and r9 have fist 4 params, memofs is the last and goes to stack code.sub(rsp, 8); code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.mov(qword[rsp + 32], rax); code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, int, int)>(filter)); code.call(rax); code.add(rsp, 8 + 8 + 8 + 8); // memofs, cell off stack break; case FUNC_PARANOISE: stack -= 9; // what was I thinking.. code.movsd(xmm9, xmm0); code.movq(xmm8, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm7, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm6, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm5, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm4, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm4-9 has 5th-10th. code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm9); // push 10 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm8); // push 9 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm7); // push 8 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm6); // push 7 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 6 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm4); // push 5 code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, double, double, double, double, double, int, int)>(paranoise)); code.call(rax); code.add(rsp, 8 * 8); // 5-10th, memofs and cell off stack break; case FUNC_PADSYNTH: stack -= 10; code.movsd(xmm10, xmm0); code.movq(xmm9, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm8, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm7, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm6, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm5, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm4, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm4-10 has 5th-11th. code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm10); // push 11 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm9); // push 10 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm8); // push 9 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm7); // push 8 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm6); // push 7 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 6 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm4); // push 5 code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, double, double, double, double, double, double, int, int)>(padsynth)); code.call(rax); code.add(rsp, 10 * 8); // align, 5-11th, memofs and cell off stack break; case FUNC_PADSYNTH22: stack -= 10; code.movsd(xmm10, xmm0); code.movq(xmm9, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm8, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm7, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm6, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm5, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm4, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm4-10 has 5th-11th. code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm10); // push 11 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm9); // push 10 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm8); // push 9 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm7); // push 8 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm6); // push 7 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 6 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm4); // push 5 code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, double, double, double, double, double, double, int, int)>(padsynth22)); code.call(rax); code.add(rsp, 10 * 8); // align, 5-11th, memofs and cell off stack break; case FUNC_AY: stack -= 10; code.movsd(xmm10, xmm0); code.movq(xmm9, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm8, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm7, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm6, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm5, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm4, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm4-10 has 5th-11th. code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm10); // push 11 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm9); // push 10 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm8); // push 9 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm7); // push 8 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm6); // push 7 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 6 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm4); // push 5 code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, double, double, double, double, double, double, int, int)>(ay)); code.call(rax); code.add(rsp, 10 * 8); // align, 5-11th, memofs and cell off stack break; case FUNC_BIQUAD: stack -= 6; code.movsd(xmm6, xmm0); code.movq(xmm5, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm4, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm3, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm2, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm1, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); code.movq(xmm0, qword[rsp + 32]); /* pop from stack */ code.add(rsp, 16); // At this point xmm0,1,2,3 have fist 4 params and xmm4-6 has 5th-7th. code.sub(rsp, 8); // align code.sub(rsp, 8); code.mov(dword[rsp + 32], memofs); // push memofs to stack code.sub(rsp, 8); code.mov(dword[rsp + 32], cell); // push cell to stack code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm6); // push 7 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm5); // push 6 code.sub(rsp, 8); code.movq(qword[rsp + 32], xmm4); // push 5 code.mov(rax, (size_t)static_cast<double(*)(double, double, double, double, double, double, double, int, int)>(biquad)); code.call(rax); code.add(rsp, 6 * 8); // align, 5-7th, memofs and cell off stack break; case FUNC_PINKNOISE: CALLFUNC0M(jit_kludge::pinknoise); break; case FUNC_BROWNNOISE: CALLFUNC0M(jit_kludge::brownnoise); break; case FUNC_BLUENOISE: CALLFUNC0M(jit_kludge::bluenoise); break; case FUNC_NOP: PUSH_CONST(0.0); break; case FUNC_NOP1: stack--; code.add(rsp, 16); PUSH_CONST(0.0); break; case FUNC_NOP2: stack -= 2; code.add(rsp, 16*2); PUSH_CONST(0.0); break; case FUNC_NOP3: stack -= 3; code.add(rsp, 16*3); PUSH_CONST(0.0); break; case FUNC_NOP4: stack -= 4; code.add(rsp, 16*4); PUSH_CONST(0.0); break; case FUNC_NOP5: stack -= 5; code.add(rsp, 16*5); PUSH_CONST(0.0); break; case FUNC_NOP6: stack -= 6; code.add(rsp, 16*6); PUSH_CONST(0.0); break; case FUNC_NOP7: stack -= 7; code.add(rsp, 16*7); PUSH_CONST(0.0); break; case FUNC_NOP8: stack -= 8; code.add(rsp, 16*8); PUSH_CONST(0.0); break; case FUNC_NOP9: stack -= 9; code.add(rsp, 16*9); PUSH_CONST(0.0); break; case FUNC_NOP10: stack -= 10; code.add(rsp, 16*10); PUSH_CONST(0.0); break; default: return 1; } memofs += gFunc[func].mMemory + gFunc[func].mSamplerateMemory * gSamplerate; } break; default: return 1; } } if (stack != 1) return 1; // last item is in xmm0, write out code.movq(qword[r15 + cell * 8], xmm0); return 0; } jitfunc jit_finish(Xbyak::CodeGenerator& code) { using namespace Xbyak::util; code.add(rsp, 32); // undo function call stack trick code.pop(r15); code.pop(r14); code.pop(r13); code.pop(r12); code.pop(rdi); code.pop(rbp); code.pop(rbx); code.movdqu(xmm6, xword[rsp + 16 * 0]); code.movdqu(xmm7, xword[rsp + 16 * 1]); code.movdqu(xmm8, xword[rsp + 16 * 2]); code.movdqu(xmm9, xword[rsp + 16 * 3]); code.movdqu(xmm10, xword[rsp + 16 * 4]); code.movdqu(xmm11, xword[rsp + 16 * 5]); code.movdqu(xmm12, xword[rsp + 16 * 6]); code.movdqu(xmm13, xword[rsp + 16 * 7]); code.movdqu(xmm14, xword[rsp + 16 * 8]); code.movdqu(xmm15, xword[rsp + 16 * 9]); code.add(rsp, 16 * 10); code.ret(); code.readyRE(); return code.getCode<double(*)(double*, double*)>(); } jitfunc jit(Op* bc, int cell, Xbyak::CodeGenerator &code, char *stringstore) { jit_init(code); if (jit_addcode(bc, cell, code, stringstore)) return 0; return jit_finish(code); }
26.800963
160
0.596754
jarikomppa
c3f9787d916eb81fbdd07a3a6702a3d06b514c0e
75,981
cpp
C++
p/mpgt/MultiPartiteGraph.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/mpgt/MultiPartiteGraph.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/mpgt/MultiPartiteGraph.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
#include "MultiPartiteGraph.h" #include "Defs.h" using namespace cv; using namespace std; MultiPartiteGraph::MultiPartiteGraph(int n_window) { number_of_graphs = 0; window_size = n_window; position_weight = 0.07; histogram_weight = 0.001; contour_weight = 0.001; area_weight = 0.00025; enable_oclusion_solver = 1; min_area = 9999999.9; max_area = 0.0; total_blobs = 0; } void MultiPartiteGraph::InsertGraph(int graph_id) { mpg[graph_id]; number_of_graphs++; } void MultiPartiteGraph::InsertGraph(int graph_id, Graph graph) { mpg[graph_id] = graph; number_of_graphs++; } void MultiPartiteGraph::InsertNode(int graph_id, Node node) { ///Revisar cuantos grafos tienen el multi y si existe el graph con el id if((mpg.size()) > window_size) cout << "Multi graph is full, unable to add node." << endl; else if(!mpg.count(graph_id) && (mpg.size() <= window_size)){ ///Create graph if doesnt exist. //cout << "Creating graph " << graph_id << " and inserting first node" << endl; Graph tmp_graph; tmp_graph.push_back(node); InsertGraph(graph_id, tmp_graph); total_blobs++; } else{ //cout << "Inserting node " << node.blob_id << endl; mpg[graph_id].push_back(node); total_blobs++; } } void MultiPartiteGraph::ShowMultiGraphInfo(void) { cout << "\nMultiPartiteGraph info:" << endl; cout << "Number of graphs = " << mpg.size() << "\n" << endl; for(unsigned int i=1;i<=mpg.size();i++){ cout << "\t Info for graph number: " << i << endl; cout << "\t Number of nodes = " << mpg[i-1].size() << "\n" << endl; } } Graph MultiPartiteGraph::GetGraph(int graph_id) { //cout << "Tag set size of first element at GetGraph = " << mpg[graph_id].at(0).player_tag_set.size() << " with player tag = " << mpg[graph_id].at(0).player_tag << endl; return mpg[graph_id]; } Node MultiPartiteGraph::GetNode(int graph_id, int blob_id) { Graph gph = GetGraph(graph_id); //cout << "Tag set size of first element at GetNode = " << gph.at(0).player_tag_set.size() << " with player tag = " << gph.at(0).player_tag << endl; Node nd; for(unsigned int vnit = 0 ; vnit < gph.size(); ++vnit){ if(gph[vnit].blob_id == blob_id){ //cout << "Tag set size of requested element "<< vnit <<" at GetNode = " << gph.at(vnit).player_tag_set.size() << " with player tag = " << gph.at(vnit).player_tag << endl; nd = gph[vnit]; } } return nd; //return mpg[graph_id].at(node_id); } Node MultiPartiteGraph::DeleteNode(int graph_id, int blob_id) { Node nd; nd = GetNode(graph_id,blob_id); mpg[graph_id].erase(mpg[graph_id].begin()+blob_id); return nd; } double MultiPartiteGraph::CompareNodes(Node node1, Node node2) { double delta_position=ComparePointsDistance(node1.centroid, node2.centroid);// cout << "Delta posicion = " << delta_position << endl; double delta_histogram=CompareHistograms(node1.histogram, node2.histogram);// cout << "Delta histogram = " << delta_histogram << endl; double delta_shape=CompareContours(node1.contorno, node2.contorno);// cout << "Delta contornos = " << delta_shape << endl; double delta_area=CompareAreas(node1.area, node2.area); double limit= (double) max_speed * (double) position_weight; if(delta_position > limit){ //31.75 //cout << " dif pos = " << delta_position << " limit = " << limit <<" max_speed = " << max_speed << " position_weight = " << position_weight<<endl; delta_position = 9999999; } double weight = delta_position*position_weight+ delta_histogram*histogram_weight+ delta_shape*contour_weight+ delta_area*area_weight; return weight; } std::map<std::string,double> MultiPartiteGraph::CompareNodesProperties(Node node1, Node node2) { double delta_position=ComparePointsDistance(node1.centroid, node2.centroid); double delta_histogram=CompareHistograms(node1.histogram, node2.histogram); double delta_shape=CompareContours(node1.contorno, node2.contorno); double delta_area=CompareAreas(node1.area, node2.area); std::map<std::string,double> deltas; deltas["position"]= delta_position; deltas["histogram"]= delta_histogram; deltas["contour"]= delta_shape; deltas["area"]= delta_area; return deltas; } std::vector<Edge> MultiPartiteGraph::CompareGraphs(int graphid1, int graphid2) { Node nodeu, nodev; std::vector<Edge> edges; int ubid = 0; int vbid = 0; Graph graph1,graph2; graph1 = GetGraph(graphid1); graph2 = GetGraph(graphid2); for(unsigned int u=0; u < graph1.size(); u++){ double minval = 9999999999; Edge uvedge; int converge = NO; for(unsigned int v=0; v < graph2.size(); v++){ nodeu = graph1[u]; nodev = graph2[v]; /* cout << "Comparing blob player " << nodeu.blob_id << " of frame " << nodeu.blob_frame_number << " with blob player " << nodev.blob_id << " of frame " << nodev.blob_frame_number; */ // double retval = CompareNodes(nodeu,nodev); std::map<std::string,double> deltas; deltas = CompareNodesProperties(nodeu,nodev); double limit= (double) max_speed * (double) position_weight; double retval = deltas["position"]*position_weight+ deltas["histogram"]*histogram_weight+ deltas["shape"]*contour_weight+ deltas["area"]*area_weight; // cout << " Function value = " << retval << endl; //minval = (minval < retval) ? minval : retval; if(minval < retval){ minval = minval; ubid = nodeu.blob_id; vbid = nodev.blob_id; //cout << "No min value of "<< minval <<" between ubid = " << uvedge.ubid << " and vbid = " << uvedge.vbid << endl; } else if(deltas["position"] < limit){ minval = retval; ubid = nodeu.blob_id; vbid = nodev.blob_id; uvedge.ubid=ubid; uvedge.vbid=vbid; uvedge.uframe=graphid1; uvedge.vframe=graphid2; uvedge.weight=minval; converge = YES; //cout << "Min value found of "<< minval <<" between ubid = " << uvedge.ubid << " and vbid = " << uvedge.vbid << endl; //cout << "Delta position = " << deltas["position"] << " weight = " << minval << " limit = " << limit << endl; } } if(converge==YES){ /* ubid = nodeu.blob_id;// + " / " + std::to_string(nodeu.blob_frame_number); vbid = nodev.blob_id;// + " / " + std::to_string(nodev.blob_frame_number); cout << "Min value of "<< uvedge.weight <<" between ubid = " << uvedge.ubid << " and vbid = " << uvedge.vbid; cout << " Graph1 size = " << graph1.size() << " Graph2 size = " << graph2.size() << endl; */ edges.push_back(uvedge); converge = NO; } } return edges; } std::vector<Edge> MultiPartiteGraph::CompareGraphs(Graph graph1, Graph graph2) { Node nodeu, nodev; std::vector<Edge> edges; int ubid = 0; int vbid = 0; for(unsigned int u=0; u < graph1.size(); u++){ double minval = 9999999999; Edge uvedge; int converge = NO; for(unsigned int v=0; v < graph2.size(); v++){ nodeu = graph1[u]; nodev = graph2[v]; /* cout << "Comparing blob player " << nodeu.blob_id << " of frame " << nodeu.blob_frame_number << " with blob player " << nodev.blob_id << " of frame " << nodev.blob_frame_number; */ // double retval = CompareNodes(nodeu,nodev); std::map<std::string,double> deltas; deltas = CompareNodesProperties(nodeu,nodev); double limit= (double) max_speed * (double) position_weight; double retval = deltas["position"]*position_weight+ deltas["histogram"]*histogram_weight+ deltas["shape"]*contour_weight+ deltas["area"]*area_weight; // cout << " Function value = " << retval << endl; //minval = (minval < retval) ? minval : retval; if(minval < retval){ minval = minval; ubid = nodeu.blob_id; vbid = nodev.blob_id; //cout << "No min value of "<< minval <<" between ubid = " << uvedge.ubid << " and vbid = " << uvedge.vbid << endl; } else if(deltas["position"] < limit){ minval = retval; ubid = nodeu.blob_id; vbid = nodev.blob_id; uvedge.ubid=ubid; uvedge.vbid=vbid; uvedge.uframe=graph1[u].blob_frame_number;; uvedge.vframe=graph2[v].blob_frame_number; uvedge.weight=minval; converge = YES; //cout << "Min value found of "<< minval <<" between ubid = " << uvedge.ubid << " and vbid = " << uvedge.vbid << endl; //cout << "Delta position = " << deltas["position"] << " weight = " << minval << " limit = " << limit << endl; } } if(converge==YES){ /* ubid = nodeu.blob_id;// + " / " + std::to_string(nodeu.blob_frame_number); vbid = nodev.blob_id;// + " / " + std::to_string(nodev.blob_frame_number); cout << "Min value of "<< uvedge.weight <<" between ubid = " << uvedge.ubid << " and vbid = " << uvedge.vbid; cout << " Graph1 size = " << graph1.size() << " Graph2 size = " << graph2.size() << endl; */ edges.push_back(uvedge); converge = NO; } } return edges; } std::vector<Edge> MultiPartiteGraph::GenerateEdgesFromGraphs(Graph graph1, Graph graph2) { Node nodeu, nodev; Edge uvedge; //double minval = INF; std::vector<Edge> edges; for(unsigned int u=0; u < graph1.size(); u++){ for(unsigned int v=0; v < graph2.size(); v++){ nodeu = graph1[u]; nodev = graph2[v]; double retval = CompareNodes(nodeu,nodev); int uid = nodeu.blob_id; int vid = nodev.blob_id; //uvedge[std::make_pair(uid, vid)] = retval; uvedge.ubid=uid; uvedge.vbid=vid; uvedge.weight=retval; edges.push_back(uvedge); } } return edges; } void MultiPartiteGraph::AddNodePlayertag(int graph_id, int node_id, int tag) { mpg[graph_id].at(node_id).player_tag_set.insert(tag); } void MultiPartiteGraph::SetNodePlayertag(int graph_id, int node_id, int tag) { mpg[graph_id].at(node_id).player_tag=tag; //cout << "Previous on set node tag set size = " << mpg[graph_id].at(node_id).player_tag_set.size() << endl; mpg[graph_id].at(node_id).player_tag_set.clear(); mpg[graph_id].at(node_id).player_tag_set.insert(tag); //cout << "After on set node insert tag set size = " << mpg[graph_id].at(node_id).player_tag_set.size() << endl; } void MultiPartiteGraph::AddTagAndCentroid(int graph_id, int node_id, int tag, Point2f mcentroid) { mpg[graph_id].at(node_id).merged_centroids.insert(std::make_pair(tag, mcentroid)); } void MultiPartiteGraph::SetTagAndCentroid(int graph_id, int node_id, int tag, Point2f mcentroid) { mpg[graph_id].at(node_id).merged_centroids.clear(); mpg[graph_id].at(node_id).merged_centroids.insert(std::make_pair(tag, mcentroid)); } void MultiPartiteGraph::DeleteTagAndCentroid(int graph_id, int node_id, int tag) { for (std::map< int,Point2f >::iterator tcit=mpg[graph_id].at(node_id).merged_centroids.begin(); tcit!=mpg[graph_id].at(node_id).merged_centroids.end(); ++tcit) if(tcit->first == tag) mpg[graph_id].at(node_id).merged_centroids.erase(tcit); } void MultiPartiteGraph::ClearTagAndCentroids(int graph_id, int node_id) { mpg[graph_id].at(node_id).merged_centroids.clear(); } void MultiPartiteGraph::ClearTagSet(int graph_id, int node_id) { mpg[graph_id].at(node_id).player_tag_set.clear(); } void MultiPartiteGraph::SetNodePlayerCluster(int graph_id, int node_id, int cluster) { mpg[graph_id].at(node_id).cluster=cluster; //cout << "Cluster " << cluster << " set to node " << node_id << " from graph " << graph_id << endl; } void MultiPartiteGraph::SetNodeType(int graph_id, int node_id, int type) { mpg[graph_id].at(node_id).blob_type=type; } void MultiPartiteGraph::CopyNodePlayerTagSet(int graph_id, int node_id, set< int > tags_set) { mpg[graph_id].at(node_id).player_tag_set=tags_set; } void MultiPartiteGraph::CopyMergedCentroidsMap(int graph_id, int node_id, map< int,Point2f > cp_merged_centroids) { mpg[graph_id].at(node_id).merged_centroids.clear(); mpg[graph_id].at(node_id).merged_centroids=cp_merged_centroids; } void MultiPartiteGraph::CopyNodePlayerPositionHistory(int graph_id, int node_id, std::array<Point2f,5> cp_position_history) { /* cout << "Previous node position history: " << endl; for(unsigned int pni=0;pni<5;pni++) cout << "Position " << pni << " point x = " << mpg[graph_id].at(node_id).position_history[pni].x << " y = " << mpg[graph_id].at(node_id).position_history[pni].y << endl; cout << "Passed node position history: " << endl; for(unsigned int cni=0;cni<5;cni++) cout << "Position " << cni << " point x = " << cp_position_history[cni].x << " y = " << cp_position_history[cni].y << endl; */ for(unsigned int pcni=0;pcni<5;pcni++) mpg[graph_id].at(node_id).position_history[pcni]=cp_position_history[pcni]; /* cout << "After copy"<< endl; for(unsigned int pni=0;pni<5;pni++) cout << "Position " << pni << " point x = " << mpg[graph_id].at(node_id).position_history[pni].x << " y = " << mpg[graph_id].at(node_id).position_history[pni].y << endl; */ } void MultiPartiteGraph::UpdateNodeSpeed(int graph_id, int node_id) { mpg[graph_id].at(node_id).UpdateSpeed(); } void MultiPartiteGraph::UpdateNodeSpeed(int graph_id, int node_id, int frames) { mpg[graph_id].at(node_id).UpdateSpeed(frames); } void MultiPartiteGraph::UpdateNodeDirection(int graph_id, int node_id) { mpg[graph_id].at(node_id).UpdateDirection(); } void MultiPartiteGraph::ChangeNodeStartPointHistory(int graph_id, int node_id, Point2f new_start_point) { mpg[graph_id].at(node_id).ChangeBlobStartPointHistory(new_start_point); } void MultiPartiteGraph::SetNodePlayertagFromCoincidence(int graph_id, int node_id) { map<int, int> m = mpg[graph_id].at(node_id).player_tags; ///Lambda, use c++11 auto x = std::max_element(m.begin(), m.end(), [](const pair<int, int>& p1, const pair<int, int>& p2) { return p1.second < p2.second; }); SetNodePlayertag(graph_id, node_id, x->first); } void MultiPartiteGraph::IncrementNodePlayertag(int graph_id, int node_id, int tag) { if (mpg[graph_id].at(node_id).player_tags.count(tag)>1) mpg[graph_id].at(node_id).player_tags[tag]+=1; else mpg[graph_id].at(node_id).player_tags[tag]=1; } void MultiPartiteGraph::InsertNodePlayertagToBlob(int graph_id, int blob_id, int tag) { Graph gph = GetGraph(graph_id); int node_id=505; ///Determine the node_id searching the blob_id because node_id is ///the position in the node vector, which is the blob_id for(unsigned int vnit = 0 ; vnit < gph.size(); ++vnit){ if(gph[vnit].blob_id == blob_id) node_id=vnit; } mpg[graph_id].at(node_id).player_tag_set.insert(tag); } void MultiPartiteGraph::InsertNodePlayerTagCentroidToBlob(int graph_id, int blob_id, int tag, Point2f mcentroid) { Graph gph = GetGraph(graph_id); int node_id=505; ///Determine the node_id searching the blob_id because node_id is ///the position in the node vector, which is the blob_id for(unsigned int vnit = 0 ; vnit < gph.size(); ++vnit){ if(gph[vnit].blob_id == blob_id) node_id=vnit; } mpg[graph_id].at(node_id).merged_centroids.insert(std::make_pair(tag, mcentroid)); } void MultiPartiteGraph::ChangeBlobState(int graph_id, int blob_id, int state) { Graph gph = GetGraph(graph_id); int node_id=504; ///Determine the node_id searching the blob_id because node_id is ///the position in the node vector, which is the blob_id for(unsigned int vnit = 0 ; vnit < gph.size(); ++vnit){ if(gph[vnit].blob_id == blob_id) node_id=vnit; } mpg[graph_id].at(node_id).blob_type=state; } int MultiPartiteGraph::RemoveNodePlayertagFromBlob(int graph_id, int blob_id, int tag) { Graph gph = GetGraph(graph_id); int node_id=503; cout << "Removing blob " << blob_id << " from frame " << graph_id << " with tag " << tag << endl; ///Determine the node_id searching the blob_id because node_id is ///the position in the node vector, which is the blob_id for(unsigned int vnit = 0 ; vnit < gph.size(); ++vnit){ if(gph[vnit].blob_id == blob_id) node_id=vnit; } int retval = mpg[graph_id].at(node_id).player_tag_set.erase(tag); return retval; } int MultiPartiteGraph::RemoveTagFromPlayerTagSet(int graph_id, int node_id, int tag) { int retval = mpg[graph_id].at(node_id).player_tag_set.erase(tag); return retval; } void MultiPartiteGraph::MVSimpleSolver(std::map<std::string,double> weights, std::map<std::string,int> mpgtparms, int step) { position_weight = weights["position"]; histogram_weight = weights["histogram"]; contour_weight = weights["contour"]; area_weight = weights["area"]; max_speed = weights["max_speed"]; max_merge_distance = mpgtparms["max_merge_distance"]; enable_boundary_blob_remover = mpgtparms["enable_boundary_blob_remover"]; oclusion_memoir.InitMemoir(mpgtparms,weights); D(cout << "Doing a simple solver on mpg." << endl;) /*Reduce number of borders*/ for(unsigned int i=0; i< window_size-1; i++){ int frame_number = i+step; Graph graphn1,graphn2; graphn1 = GetGraph(frame_number); graphn2 = GetGraph(frame_number+1); D(cout << "\nEvents between " << frame_number << " and " << frame_number+1 << endl;) std::vector<Edge> back_min_edges=CompareGraphs(frame_number,frame_number+1); D(cout << " -Merges" << endl;) AnalyzeEdges(back_min_edges,BACK); /* for(unsigned int iedge = 0; iedge < back_min_edges.size(); iedge++){ cout << "Source blob = " << back_min_edges[iedge].ubid << " destination blob = " << back_min_edges[iedge].vbid; cout << " Weight = " << back_min_edges[iedge].weight << endl; } */ /// std::vector<Edge> front_min_edges=CompareGraphs(frame_number+1,frame_number); cout << " -Splits" << endl; /// AnalyzeEdges(front_min_edges,FRONT); ///Propagate player tag for(unsigned int en = 0; en < back_min_edges.size(); en++){ Node nodeu, nodev; Edge single_edge = back_min_edges[en]; /* cout << "Node U id = " << single_edge.ubid << " and node V id = " << single_edge.vbid << " for edge " << en << " with weight = " << single_edge.weight <<endl; */ for(unsigned int u=0; u < graphn1.size(); u++){ for(unsigned int v=0; v < graphn2.size(); v++){ nodeu=graphn1[u]; nodev=graphn2[v]; if((nodeu.blob_id==single_edge.ubid) && (nodev.blob_id==single_edge.vbid)){ //nodev.player_tag=nodeu.player_tag; //nodev.blob_labels=nodeu.blob_labels; //mpg[frame_number+1].at(v).player_tag=nodeu.player_tag; SetNodePlayertag(frame_number+1,v,nodeu.player_tag); /* cout << "Found pair for a border between blob u " << nodeu.blob_id << "\t with player tag " << nodeu.player_tag << "\t and blob v " << nodev.blob_id << "\t with player tag " << nodev.player_tag << endl; */ } } } } } } void MultiPartiteGraph::MVExtendedSimpleSolver(std::map<std::string,double> weights, std::map<std::string,int> mpgtparms, int step) { position_weight = weights["position"]; histogram_weight = weights["histogram"]; contour_weight = weights["contour"]; area_weight = weights["area"]; max_speed = weights["max_speed"]; max_merge_distance = mpgtparms["max_merge_distance"]; enable_boundary_blob_remover = mpgtparms["enable_boundary_blob_remover"]; enable_oclusion_solver = mpgtparms["enable_oclusion_solver"]; oclusion_memoir.InitMemoir(mpgtparms,weights); abduction_memoir.InitMemoir(mpgtparms,weights); D(cout << "Doing a extended simple solver on mpg." << endl;) /*Reduce number of borders*/ for(unsigned int i=0; i< window_size-1; i++){ int frame_number = i+step; Graph graphn1,graphn2; graphn1 = GetGraph(frame_number); graphn2 = GetGraph(frame_number+1); cout << "\n--- Events between " << frame_number << " and " << frame_number+1 << " ---" << endl; std::vector<Edge> back_min_edges=CompareGraphs(frame_number,frame_number+1); D(cout << " -Merges" << endl;) ///Propagate player tag for(unsigned int en = 0; en < back_min_edges.size(); en++){ Node nodeu, nodev; Edge single_edge = back_min_edges[en]; for(unsigned int u=0; u < graphn1.size(); u++){ for(unsigned int v=0; v < graphn2.size(); v++){ nodeu=graphn1[u]; nodev=graphn2[v]; if((nodeu.blob_id==single_edge.ubid) && (nodev.blob_id==single_edge.vbid)){ //Node nodevtmp=GetNode(frame_number+1,v); //cout << "Previous tag set size = " << nodevtmp.player_tag_set.size() << endl; //nodevtmp=GetNode(frame_number+1,v); //cout << "After tag set size = " << nodevtmp.player_tag_set.size() << endl; CopyNodePlayerTagSet(frame_number+1,v,nodeu.player_tag_set); ///To propagate the players contained on a blob if(nodeu.merged_centroids.size()==1) CopyMergedCentroidsMap(frame_number+1,v,nodeu.merged_centroids); SetNodePlayertag(frame_number+1,v,nodeu.player_tag); ///Set the player id AddTagAndCentroid(frame_number+1,v, nodeu.player_tag,nodeu.centroid); ///Set the player id and the centroid (mostly for mergerd blobs) CopyNodePlayerPositionHistory(frame_number+1,v,nodeu.position_history); ///To update position history, used to compute the direction UpdateNodeDirection(frame_number+1,v); ///Update player direction depending on previous positions UpdateNodeSpeed(frame_number+1,v); } } } } ///Abduction solver if(mpgtparms["enable_abduction_finder"]){ AnalyzeAbductions(back_min_edges,frame_number,BACK); abduction_memoir.DegradeMemoirs(); } ///Oclusion solver if(mpgtparms["enable_oclusion_solver"]==VERSION1){ AnalyzeEdges(back_min_edges,BACK); ///Check and solve merges } else if(mpgtparms["enable_oclusion_solver"]==VERSION2){ AnalyzeEdgesv2(back_min_edges,BACK); ///Check and solve merges } else if(mpgtparms["enable_oclusion_solver"]==VERSION3){ AnalyzeEdgesv3(back_min_edges,BACK); ///Check and solve merges } else if(mpgtparms["enable_oclusion_solver"]==VERSION4){ AnalyzeEdgesv4(back_min_edges,mpgtparms,BACK); ///Check and solve merges } std::vector<Edge> front_min_edges=CompareGraphs(frame_number+1,frame_number); D(cout << " -Splits" << endl;) if(mpgtparms["enable_oclusion_solver"]==VERSION1){ AnalyzeEdges(front_min_edges,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } else if(mpgtparms["enable_oclusion_solver"]==VERSION2){ AnalyzeEdgesv2(front_min_edges,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } else if(mpgtparms["enable_oclusion_solver"]==VERSION3){ AnalyzeEdgesv3(front_min_edges,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } else if(mpgtparms["enable_oclusion_solver"]==VERSION4){ AnalyzeEdgesv4(front_min_edges,mpgtparms,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } if(mpgtparms["enable_abduction_finder"]){ AnalyzeAbductions(front_min_edges,frame_number,FRONT); abduction_memoir.DegradeMemoirs(); } } } void MultiPartiteGraph::MVMPSolver(std::map<std::string,double> weights, int step) { position_weight = weights["position"]; histogram_weight = weights["histogram"]; contour_weight = weights["contour"]; area_weight = weights["area"]; max_speed = weights["max_speed"]; D(cout << "Doing a multipartite solver using a max coincidence criterion on mpg." << endl;) /*All against all*/ for(unsigned int i=0; i< window_size; i++){ for(unsigned int j=1+i; j< window_size; j++){ Graph graphu,graphv; graphu = GetGraph(step+i); graphv = GetGraph(step+j); ///Generate the edges between all frames std::vector<Edge> min_edges=CompareGraphs(graphu,graphv); ///Create a propagation histogram for(unsigned int en = 0; en < min_edges.size(); en++){ Node nodeu, nodev; Edge single_edge = min_edges[en]; for(unsigned int u=0; u < graphu.size(); u++){ for(unsigned int v=0; v < graphv.size(); v++){ nodeu=graphu[u]; nodev=graphv[v]; if((nodeu.blob_id==single_edge.ubid) && (nodev.blob_id==single_edge.vbid)){ SetNodePlayertag(step+j,v,nodeu.player_tag); IncrementNodePlayertag(step+j,v,nodeu.player_tag); /* cout << "Found pair for a border between blob u " << nodeu.blob_id << "\t with player tag " << nodeu.player_tag << "\t and blob v " << nodev.blob_id << "\t with player tag " << nodev.player_tag << endl; */ } } } } } } ///Scan all nodes to assign player tag depending on number of coincidences for(unsigned int i=1; i< window_size; i++){ Graph graphn; graphn = GetGraph(step+i); for(unsigned int node=0; node < graphn.size(); node++){ SetNodePlayertagFromCoincidence(step+i, node); } } } void MultiPartiteGraph::MVMPAssignFromFirstGraph(std::map<std::string,double> weights, int step) { position_weight = weights["position"]; histogram_weight = weights["histogram"]; contour_weight = weights["contour"]; area_weight = weights["area"]; max_speed = weights["max_speed"]; D(cout << "Doing a multipartite assigner from the first graph with the rest on the MPG." << endl;) /*All against all*/ for(unsigned int j=1; j< window_size; j++){ Graph graphu,graphv; graphu = GetGraph(step); graphv = GetGraph(step+j); ///Generate the edges between all frames with the first graph std::vector<Edge> min_edges=CompareGraphs(graphu,graphv); ///Create a coincidence matrix for(unsigned int en = 0; en < min_edges.size(); en++){ Node nodeu, nodev; Edge single_edge = min_edges[en]; for(unsigned int u=0; u < graphu.size(); u++){ for(unsigned int v=0; v < graphv.size(); v++){ nodeu=graphu[u]; nodev=graphv[v]; if((nodeu.blob_id==single_edge.ubid) && (nodev.blob_id==single_edge.vbid)){ SetNodePlayertag(step+j,v,nodeu.player_tag); AddTagAndCentroid(step+j,v,nodeu.player_tag,nodev.centroid); } } } } } } void MultiPartiteGraph::SolveBorderBPG(std::map<std::string,double> weights, int step, Graph previous_graph) { position_weight = weights["position"]; histogram_weight = weights["histogram"]; contour_weight = weights["contour"]; area_weight = weights["area"]; max_speed = weights["max_speed"]; /*Reduce number of borders*/ int frame_number = step; //cout << "Solving bipartite graph between borders" << endl; Graph second_graph; second_graph = GetGraph(frame_number); cout << "\nSolving bipartite graph between borders: " << previous_graph[0].blob_frame_number << " - " << second_graph[0].blob_frame_number << endl; std::vector<Edge> min_edges=CompareGraphs(previous_graph,second_graph); /* for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ cout << "Source blob = " << min_edges[iedge].ubid << " destination blob = " << min_edges[iedge].vbid; cout << " Weight = " << min_edges[iedge].weight << endl; } */ for(unsigned int en = 0; en < min_edges.size(); en++){ Node nodeu, nodev; Edge single_edge = min_edges[en]; /* cout << "Node U id = " << single_edge.ubid << " and node V id = " << single_edge.vbid << " for edge " << en << " with weight = " << single_edge.weight <<endl; */ for(unsigned int u=0; u < previous_graph.size(); u++){ for(unsigned int v=0; v < second_graph.size(); v++){ nodeu=previous_graph[u]; nodev=second_graph[v]; if((nodeu.blob_id==single_edge.ubid) && (nodev.blob_id==single_edge.vbid)){ //nodev.player_tag=nodeu.player_tag; //nodev.blob_labels=nodeu.blob_labels; //mpg[frame_number+1].at(v).player_tag=nodeu.player_tag; ///SetNodePlayertag(frame_number,v,nodeu.player_tag); /* cout << "Found pair for a border between blob u " << nodeu.blob_id << "\t with player tag " << nodeu.player_tag << "\t and blob v " << nodev.blob_id << "\t with player tag " << nodev.player_tag << endl; */ } } } } AnalyzeEdges(min_edges,BACK); ///Check for merges } void MultiPartiteGraph::SolveExtendedBorderBPG(std::map<std::string,double> weights,std::map<std::string,int> mpgtparms,int step, Graph previous_graph) { position_weight = weights["position"]; histogram_weight = weights["histogram"]; contour_weight = weights["contour"]; area_weight = weights["area"]; max_speed = weights["max_speed"]; max_merge_distance = mpgtparms["max_merge_distance"]; enable_boundary_blob_remover = mpgtparms["enable_boundary_blob_remover"]; enable_oclusion_solver = mpgtparms["enable_oclusion_solver"]; oclusion_memoir.InitMemoir(mpgtparms,weights); abduction_memoir.InitMemoir(mpgtparms,weights); /*Reduce number of borders*/ int frame_number = step; InsertGraph(frame_number-1, previous_graph); Graph graphn1,graphn2; graphn1 = GetGraph(frame_number-1); graphn2 = GetGraph(frame_number); cout << "\nSolving with extended bipartite graph between borders: " << graphn1[0].blob_frame_number << " - " << graphn2[0].blob_frame_number << endl; //cout << "previous graph size = " << previous_graph.size() << " second graph size = " << second_graph.size() << endl; //std::vector<Edge> back_min_edges=CompareGraphs(previous_graph,second_graph); //cout << "back min edges size: " << back_min_edges.size() << endl; std::vector<Edge> back_min_edges=CompareGraphs(frame_number-1,frame_number); //std::vector<Edge> front_min_edges=CompareGraphs(second_graph,previous_graph); //cout << "front min edges size: " << front_min_edges.size() << endl; std::vector<Edge> front_min_edges=CompareGraphs(frame_number,frame_number-1); /* cout << "Inspecting border merge edges" << endl; PrintEdges(back_min_edges); cout << "Inspecting border split edges" << endl; PrintEdges(front_min_edges); */ for(unsigned int en = 0; en < back_min_edges.size(); en++){ Node nodeu, nodev; Edge single_edge = back_min_edges[en]; for(unsigned int u=0; u < graphn1.size(); u++){ for(unsigned int v=0; v < graphn2.size(); v++){ nodeu=graphn1[u]; nodev=graphn2[v]; if((nodeu.blob_id==single_edge.ubid) && (nodev.blob_id==single_edge.vbid)){ CopyNodePlayerTagSet(frame_number,v,nodeu.player_tag_set); if(nodeu.merged_centroids.size()==1) CopyMergedCentroidsMap(frame_number,v, nodeu.merged_centroids); SetNodePlayertag(frame_number,v,nodeu.player_tag); AddTagAndCentroid(frame_number,v, nodeu.player_tag,nodeu.centroid); CopyNodePlayerPositionHistory(frame_number,v,nodeu.position_history); UpdateNodeDirection(frame_number,v); ///Update player direction depending on previous positions UpdateNodeSpeed(frame_number,v); } } } } ///Abduction solver if(mpgtparms["enable_abduction_finder"]){ AnalyzeAbductions(back_min_edges,frame_number,BACK); abduction_memoir.DegradeMemoirs(); } ///Oclusion solver if(mpgtparms["enable_oclusion_solver"]==VERSION1){ AnalyzeEdges(back_min_edges,BACK); ///Check and solve merges } else if(mpgtparms["enable_oclusion_solver"]==VERSION2){ AnalyzeEdgesv2(back_min_edges,BACK); ///Check and solve merges } else if(mpgtparms["enable_oclusion_solver"]==VERSION3){ AnalyzeEdgesv3(back_min_edges,BACK); ///Check and solve merges } else if(mpgtparms["enable_oclusion_solver"]==VERSION4){ AnalyzeEdgesv4(back_min_edges,mpgtparms,BACK); ///Check and solve merges } if(mpgtparms["enable_abduction_finder"]){ AnalyzeAbductions(front_min_edges,frame_number,FRONT); abduction_memoir.DegradeMemoirs(); } if(mpgtparms["enable_oclusion_solver"]==VERSION1){ AnalyzeEdges(front_min_edges,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } else if(mpgtparms["enable_oclusion_solver"]==VERSION2){ AnalyzeEdgesv2(front_min_edges,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } else if(mpgtparms["enable_oclusion_solver"]==VERSION3){ AnalyzeEdgesv3(front_min_edges,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } else if(mpgtparms["enable_oclusion_solver"]==VERSION4){ AnalyzeEdgesv4(front_min_edges,mpgtparms,FRONT); ///Check and solve splits oclusion_memoir.DegradeMemoirs(); } } void MultiPartiteGraph::AnalyzeEdges(std::vector<Edge> min_edges, int direction) { ///Figure it out if there is any event std::map< int, std::set<int> > oclusion_map; //In the form of destination to a list of sources ///Create an event/oclusion map for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ int source_blob_id = min_edges[iedge].ubid; int destination_blob_id = min_edges[iedge].vbid; //cout << "Source blob = " << source_blob_id << " destination blob = " << destination_blob_id; //cout << " Weight = " << min_edges[iedge].weight << endl; oclusion_map[destination_blob_id].insert(source_blob_id); } ///Inspect merge/split oclusion map std::map<int,std::set<int>>::iterator omit; for (omit=oclusion_map.begin(); omit!=oclusion_map.end(); ++omit){ if(omit->second.size()>1){///Process only detected merges/splits if(direction==BACK){///Merges std::cout << "--Merge v1--" << endl; std::cout << "From " ; for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << "to " << omit->first << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit;; double best_blob_fit_weight=9999999; for (auto sourcev : omit->second) ///Sweep through the sources of the merge event for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){///Search on borders to match the sourcev id if(min_edges[iedge].ubid==sourcev){ cout << "Trying to remember blob " << min_edges[iedge].ubid << " from frame " << min_edges[iedge].uframe << endl; Node to_remember = GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); cout << "Tag set size of node to remenber = " << to_remember.player_tag_set.size() << " with tag = " << to_remember.player_tag << " and blobid = " << to_remember.blob_id << endl; //oclusion_memoir.Remember(to_remember); //Add node to short term memory, both single and merged if(to_remember.player_tag_set.size()<=1){///If is a individual blob thats is going to merge oclusion_memoir.Remember(to_remember);//Remember only single blobs cout << "Inserting single player tag " << to_remember.player_tag << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. } else{///If the blob is already a merged blob, copy their tags to the new merged blob, in the if append the new single blob oclusion_memoir.Remember(to_remember); ///Coment to avoid remembering merged blobs, but this helps to recover splits without merges cout << "Node is a merged one with "<< to_remember.player_tag_set.size() << " tags, inserting player tags to the next merged blob"<<endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. for (std::set<int>::iterator tsit=to_remember.player_tag_set.begin(); tsit!=to_remember.player_tag_set.end(); ++tsit){ //cout << "Inserting player tag " << *tsit << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,*tsit); } } ChangeBlobState(min_edges[iedge].vframe,min_edges[iedge].vbid,MULTI_PLAYER); ///Assign to the merged blob the id of the most likely blob if(min_edges[iedge].weight < best_blob_fit_weight){ best_blob_fit_weight=min_edges[iedge].weight; SetNodePlayertag(min_edges[iedge].vframe, min_edges[iedge].vbid, to_remember.player_tag); AddTagAndCentroid(min_edges[iedge].vframe,min_edges[iedge].vbid, to_remember.player_tag,to_remember.centroid); cout << "SetNodePlayertag of " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << " to " << to_remember.player_tag << " with weight " << min_edges[iedge].weight << endl; } } } } else if(direction==FRONT){///Splits std::cout << "--Split v1--" << endl; std::cout << "From " << omit->first << " to "; for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit; //double best_blob_fit_weight=9999999; for (auto sourcev : omit->second) for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ if(min_edges[iedge].ubid==sourcev){ cout << "Trying to recover blob " << min_edges[iedge].ubid << " from oclusion memoir." << endl; //Search in oclusion memoir nodes with player tags Node to_recover=GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); /* ///Assign to the best fit split blob the id of the merged blob - to solve splits without merges Node origin_merged_blob=GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); if(min_edges[iedge].weight < best_blob_fit_weight){ best_blob_fit_weight=min_edges[iedge].weight; SetNodePlayertag(min_edges[iedge].uframe,min_edges[iedge].ubid,origin_merged_blob.player_tag); cout << "SetNodePlayertag of " << min_edges[iedge].ubid << " from frame " << min_edges[iedge].uframe << " with origin tag " << origin_merged_blob.player_tag << " and weight " << min_edges[iedge].weight << endl; } */ if(oclusion_memoir.vector_memoir.size()>0){///Is only possible to recover something lost //Node likely_node=oclusion_memoir.ExtractClosestMemoir(to_recover); Node merged = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); ///This is the merged blob ChangeNodeStartPointHistory(min_edges[iedge].uframe,min_edges[iedge].ubid,merged.centroid); ///Aca cambio el start point a to_recover para que tenga el centroide del merged por si sigue la misma direccion Node likely_node=oclusion_memoir.GetClosestMemoir(to_recover);///Return the node that resembles more to the split node cout << "Assign for blob " << to_recover.blob_id << " of frame " << to_recover.blob_frame_number << " from memorized blob " << likely_node.blob_id << " of frame " << likely_node.blob_frame_number << " with tag " << likely_node.player_tag << endl; if(merged.player_tag_set.count(likely_node.player_tag)>0){ ///Buscar si el player tag ya fue removido sino haga lo que sigue, para que funcione debo transferir tambien el set de tags cout << "El blob compuesto tiene el id del nodo por recuperar, en total tiene " << merged.player_tag_set.size() << " ids." << endl; ///Copy player tag from likely to recover and remove player tag from set //if(to_recover.player_tag_set.size()<=1){ cout << "Tag set size from blob to recover = " << to_recover.player_tag_set.size() << endl; SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, likely_node.player_tag); AddTagAndCentroid(to_recover.blob_frame_number,min_edges[iedge].ubid, likely_node.player_tag,likely_node.centroid); RemoveNodePlayertagFromBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,likely_node.player_tag); oclusion_memoir.Forget(to_recover); ///Aca esta borrando, esto es un problema si es un merged xq borra el tag heredado /*} else{ for (std::set<int>::iterator trit=to_recover.player_tag_set.begin(); trit!=to_recover.player_tag_set.end(); ++trit){ SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, *trit); } } */ } } } } } } } } void MultiPartiteGraph::AnalyzeEdgesv2(std::vector<Edge> min_edges, int direction) { ///Figure it out if there is any event std::map< int, std::set<int> > oclusion_map; //In the form of destination to a list of sources ///Create an event/oclusion map for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ int source_blob_id = min_edges[iedge].ubid; int destination_blob_id = min_edges[iedge].vbid; //cout << "Source blob = " << source_blob_id << " destination blob = " << destination_blob_id; //cout << " Weight = " << min_edges[iedge].weight << endl; oclusion_map[destination_blob_id].insert(source_blob_id); } ///Inspect merge/split oclusion map std::map<int,std::set<int>>::iterator omit; for (omit=oclusion_map.begin(); omit!=oclusion_map.end(); ++omit){ //cout << "Merge size v2 for blob " << omit->first << " is " << omit->second.size() << endl; if(omit->second.size()>1){///Process only detected merges/splits if(direction==BACK){///Merges std::cout << "--Merge v2--" << endl; std::cout << "From " ; for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << "to " << omit->first << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit;; double best_blob_fit_weight=9999999; for (auto sourcev : omit->second) ///Sweep through the sources of the merge event for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){///Search on borders to match the sourcev id if(min_edges[iedge].ubid==sourcev){ cout << "Trying to remember blob " << min_edges[iedge].ubid << " from frame " << min_edges[iedge].uframe << endl; Node to_remember = GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); cout << "Tag set size of node to remenber = " << to_remember.player_tag_set.size() << " with tag = " << to_remember.player_tag << " and blobid = " << to_remember.blob_id << endl; //oclusion_memoir.Remember(to_remember); //Add node to short term memory, both single and merged if(to_remember.player_tag_set.size()<=1){///If is a individual blob thats is going to merge oclusion_memoir.Remember(to_remember);//Remember only single blobs cout << "Inserting single player tag " << to_remember.player_tag << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. } else{///If the blob is already a merged blob, copy their tags to the new merged blob, in the if append the new single blob oclusion_memoir.Remember(to_remember); ///Coment to avoid remembering merged blobs, but this helps to recover splits without merges cout << "Node is a merged one with "<< to_remember.player_tag_set.size() << " tags, inserting player tags to the next merged blob"<<endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. for (std::set<int>::iterator tsit=to_remember.player_tag_set.begin(); tsit!=to_remember.player_tag_set.end(); ++tsit){ //cout << "Inserting player tag " << *tsit << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,*tsit); } } ChangeBlobState(min_edges[iedge].vframe,min_edges[iedge].vbid,MULTI_PLAYER); ///Assign to the merged blob the id of the most likely blob if(min_edges[iedge].weight < best_blob_fit_weight){ best_blob_fit_weight=min_edges[iedge].weight; SetNodePlayertag(min_edges[iedge].vframe, min_edges[iedge].vbid, to_remember.player_tag); AddTagAndCentroid(min_edges[iedge].vframe, min_edges[iedge].vbid, to_remember.player_tag, to_remember.centroid); cout << "SetNodePlayertag of " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << " to " << to_remember.player_tag << " with weight " << min_edges[iedge].weight << endl; } } } } else if(direction==FRONT){///Splits std::cout << "--Split v2--" << endl; std::cout << "From " << omit->first << " to "; for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit; for (auto sourcev : omit->second) for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ if(min_edges[iedge].ubid==sourcev){ cout << "Trying to recover blob " << min_edges[iedge].ubid << " from oclusion memoir." << endl; //Search in oclusion memoir nodes with player tags Node to_recover=GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); if(oclusion_memoir.vector_memoir.size()>0){///Is only possible to recover something lost //Node likely_node=oclusion_memoir.ExtractClosestMemoir(to_recover); Node merged = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); ///This is the merged blob ChangeNodeStartPointHistory(min_edges[iedge].uframe,min_edges[iedge].ubid,merged.centroid); ///Aca cambio el start point a to_recover para que tenga el centroide del merged por si sigue la misma direccion Node likely_node=oclusion_memoir.GetMemoirByTags(to_recover,merged.player_tag_set);///Return the node that resembles more to the split node cout << "Assign for blob " << to_recover.blob_id << " of frame " << to_recover.blob_frame_number << " from memorized blob " << likely_node.blob_id << " of frame " << likely_node.blob_frame_number << " with tag " << likely_node.player_tag << " and tag set size " << likely_node.player_tag_set.size() << endl; if(merged.player_tag_set.count(likely_node.player_tag)>0){ ///Buscar si el player tag ya fue removido sino haga lo que sigue, para que funcione debo transferir tambien el set de tags cout << "El blob compuesto tiene el id del nodo por recuperar, en total tiene " << merged.player_tag_set.size() << " ids." << endl; ///Copy player tag from likely to recover and remove player tag from set //if(to_recover.player_tag_set.size()<=1){ cout << "Tag set size from blob to recover = " << to_recover.player_tag_set.size() << endl; SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, likely_node.player_tag); AddTagAndCentroid(to_recover.blob_frame_number, min_edges[iedge].ubid, likely_node.player_tag, likely_node.centroid); RemoveNodePlayertagFromBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,likely_node.player_tag);///Quitar el tag del merged tag set oclusion_memoir.Forget(to_recover); ///Aca esta borrando, esto es un problema si es un merged xq borra el tag heredado /*} else{ for (std::set<int>::iterator trit=to_recover.player_tag_set.begin(); trit!=to_recover.player_tag_set.end(); ++trit){ SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, *trit); } } */ } /* ///Ahora hay que limpiar el tag set del split/to recover blob for (std::set<int>::iterator trit=to_recover.player_tag_set.begin(); trit!=to_recover.player_tag_set.end(); ++trit){ if(!oclusion_memoir.TagIsInMemoir(*trit)) cout << "Tag " << *trit << " not found on the oclusion memoir thats on the tag set from blob id " << min_edges[iedge].ubid << " of frame " << to_recover.blob_frame_number << endl; RemoveNodePlayertagFromBlob(to_recover.blob_frame_number,min_edges[iedge].ubid,*trit);///Quitar el tag del split tag set } */ } } } } } } } void MultiPartiteGraph::AnalyzeEdgesv3(std::vector<Edge> min_edges, int direction) { ///Figure it out if there is any event std::map< int, std::set<int> > oclusion_map; //In the form of destination to a list of sources ///Create an event/oclusion map for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ int source_blob_id = min_edges[iedge].ubid; int destination_blob_id = min_edges[iedge].vbid; //cout << "Source blob = " << source_blob_id << " destination blob = " << destination_blob_id; //cout << " Weight = " << min_edges[iedge].weight << endl; oclusion_map[destination_blob_id].insert(source_blob_id); } ///Inspect merge/split oclusion map std::map<int,std::set<int>>::iterator omit; for (omit=oclusion_map.begin(); omit!=oclusion_map.end(); ++omit){ if(omit->second.size()>1){///Process only detected merges/splits if(direction==BACK){///Merges std::cout << "--Merge v3--" << endl; std::cout << "From " ; for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << "to " << omit->first << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit;; double best_blob_fit_weight=9999999; for (auto sourcev : omit->second) ///Sweep through the sources of the merge event for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){///Search on borders to match the sourcev id if(min_edges[iedge].ubid==sourcev){ cout << "Trying to remember blob " << min_edges[iedge].ubid << " from frame " << min_edges[iedge].uframe << endl; Node to_remember = GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); cout << "Tag set size of node to remenber = " << to_remember.player_tag_set.size() << " with tag = " << to_remember.player_tag << " and blobid = " << to_remember.blob_id << endl; //oclusion_memoir.Remember(to_remember); //Add node to short term memory, both single and merged if(to_remember.player_tag_set.size()<=1){///If is a individual blob thats is going to merge oclusion_memoir.Remember(to_remember);//Remember only single blobs cout << "Inserting single player tag " << to_remember.player_tag << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. } else{///If the blob is already a merged blob, copy their tags to the new merged blob //oclusion_memoir.Remember(to_remember); ///Coment to avoid remembering merged blobs, but this helps to recover splits without merges cout << "Node is a merged one with "<< to_remember.player_tag_set.size() << " tags, inserting player tags to the next merged blob"<<endl; //InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. for (std::set<int>::iterator tsit=to_remember.player_tag_set.begin(); tsit!=to_remember.player_tag_set.end(); ++tsit){ //cout << "Inserting player tag " << *tsit << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,*tsit); } } ChangeBlobState(min_edges[iedge].vframe,min_edges[iedge].vbid,MULTI_PLAYER); ///Assign to the merged blob the id of the most likely blob if(min_edges[iedge].weight < best_blob_fit_weight){ best_blob_fit_weight=min_edges[iedge].weight; SetNodePlayertag(min_edges[iedge].vframe, min_edges[iedge].vbid, to_remember.player_tag); cout << "SetNodePlayertag of " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << " to " << to_remember.player_tag << " with weight " << min_edges[iedge].weight << endl; } } } } else if(direction==FRONT){///Splits std::cout << "--Split v3--" << endl; std::cout << "From " << omit->first << " to "; for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit; for (auto sourcev : omit->second) for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ if(min_edges[iedge].ubid==sourcev){ cout << "Trying to recover blob " << min_edges[iedge].ubid << " from oclusion memoir." << endl; //Search in oclusion memoir nodes with player tags Node to_recover=GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); if(oclusion_memoir.vector_memoir.size()>0){///Is only possible to recover something lost //Node likely_node=oclusion_memoir.ExtractClosestMemoir(to_recover); Node merged = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); ///This is the source merged blob ChangeNodeStartPointHistory(min_edges[iedge].uframe,min_edges[iedge].ubid,merged.centroid); ///Aca cambio el start point a to_recover para que tenga el centroide del merged por si sigue la misma direccion Node likely_node=oclusion_memoir.GetMemoirByTags(to_recover,merged.player_tag_set);///Return the node that resembles more to the split node cout << "Assign for blob " << to_recover.blob_id << " with tag set size " << to_recover.player_tag_set.size() << " of frame " << to_recover.blob_frame_number << " from memorized blob " << likely_node.blob_id << " of frame " << likely_node.blob_frame_number << " with tag " << likely_node.player_tag << " and tag set size " << likely_node.player_tag_set.size() << endl; if(merged.player_tag_set.count(likely_node.player_tag)>0){ ///Buscar si el player tag ya fue removido sino haga lo que sigue, para que funcione debo transferir tambien el set de tags cout << "El blob compuesto tiene el id del nodo por recuperar, en total tiene " << merged.player_tag_set.size() << " ids." << endl; ///Copy player tag from likely to recover and remove player tag from set //if(to_recover.player_tag_set.size()<=1){ //cout << "Single blob to recover with tag set size = " << to_recover.player_tag_set.size() << endl; SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, likely_node.player_tag); RemoveNodePlayertagFromBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,likely_node.player_tag); oclusion_memoir.Forget(to_recover); ///Aca esta borrando, esto es un problema si es un merged xq borra el tag heredado //} /* else{ cout << "The blob to recover is a merged, not recovering from memoir, tag size = " << to_recover.player_tag_set.size() << endl; for (std::set<int>::iterator trit=to_recover.player_tag_set.begin(); trit!=to_recover.player_tag_set.end(); ++trit){ SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, *trit); } } */ } } } } } } } } void MultiPartiteGraph::AnalyzeEdgesv4(std::vector<Edge> min_edges, std::map<std::string,int> mpgtparms,int direction) { int match_method = mpgtparms["match_method"]; int match_threshold = mpgtparms["match_threshold"]; int merged_blob_area_threshold = mpgtparms["merged_blob_area_threshold"]; int min_blob_area_threshold = mpgtparms["min_blob_area_threshold"]; //cout << "Umbral para considerar blob como merged = " << merged_blob_area_threshold << endl; //cout << "Umbral para considerar blob como parcial o bola = " << min_blob_area_threshold << endl; ///Figure it out if there is any event std::map< int, std::set<int> > oclusion_map; //In the form of destination to a list of sources //cout << "Analyze events between " << min_edges[0].uframe << " and " << min_edges[0].vframe << " with direction " << direction << endl; /* if(direction == BACK){ cout << "Inspecting border merge edges" << endl; PrintEdges(min_edges); } else{ cout << "Inspecting border split edges" << endl; PrintEdges(min_edges); } */ ///Create an event/oclusion map for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ int source_blob_id = min_edges[iedge].ubid; int destination_blob_id = min_edges[iedge].vbid; //cout << "Source blob = " << source_blob_id << " destination blob = " << destination_blob_id; //cout << " Weight = " << min_edges[iedge].weight << endl; oclusion_map[destination_blob_id].insert(source_blob_id); } ///Inspect merge/split oclusion map std::map<int,std::set<int>>::iterator omit; for (omit=oclusion_map.begin(); omit!=oclusion_map.end(); ++omit){ //cout << "Merge size " << omit->second.size() << endl; if(omit->second.size()>1){///Process only detected merges/splits if(direction==BACK){///Merges std::cout << "--Merge v4--" << endl; std::cout << "From " ; ///Imprimir las correspondencias de varios nodos a un nodo for (auto sourcev : omit->second) std::cout << sourcev << " "; std::cout << "to " << omit->first << endl; for (auto sourcev : omit->second) ///Sweep through the sources of the merge event for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){///Search on borders to match the sourcev id if(min_edges[iedge].ubid==sourcev){ cout << "Trying to remember blob " << min_edges[iedge].ubid << " from frame " << min_edges[iedge].uframe << endl; Node to_remember = GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); Node merged_blob = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); cout << "Tag set size of node to remenber = " << to_remember.player_tag_set.size() << " with tag = " << to_remember.player_tag << " and blobid = " << to_remember.blob_id << endl; ///Para detectar que es un blob con varios jugadores juntos if(to_remember.area > ( prom_area * merged_blob_area_threshold/100.0)) to_remember.SetBlobType(MULTI_PLAYER); else to_remember.SetBlobType(SINGLE_PLAYER); ///Para descartar partes de jugadores o la bola if(to_remember.area < ( prom_area * min_blob_area_threshold/100.0)) to_remember.SetBlobType(NON_PLAYER); //oclusion_memoir.Remember(to_remember); //Add node to short term memory, both single and merged if((to_remember.merged_centroids.size()<=1) && (to_remember.blob_type == SINGLE_PLAYER ) ){///If is a individual blob thats is going to merge (filtering small blobs such as the ball and partial parts of a player) oclusion_memoir.Remember(to_remember);//Remember only single blobs cout << "Inserting single player tag " << to_remember.player_tag << " with centroid to merged centroids on destiny blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; ///Search on the destiny blob for the centroid of the merged blob with template matching if((to_remember.contourRegion.cols <= merged_blob.contourRegion.cols) && (to_remember.contourRegion.rows <= merged_blob.contourRegion.rows)){ double match_value; cv::Point new_centroid = MatchBlobTemplate(merged_blob.contourRegion, merged_blob.centroid, to_remember.contourRegion, match_method, &match_value); //cout << "Match value of " << match_value << " with the matching method " << match_method << endl; if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ){//min if(match_value <= match_threshold) InsertNodePlayerTagCentroidToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag,new_centroid); //Add player tag and centroid to destiny blob list. } else{//max if(match_value >= match_threshold) InsertNodePlayerTagCentroidToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag,new_centroid); //Add player tag and centroid to destiny blob list. } InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_remember.player_tag); //Add player tag to list. } //else // cout << "Unable to search merged blob within new blob because of oversize template dimension." << endl; } else if((to_remember.merged_centroids.size()>1) && (to_remember.area > prom_area * min_blob_area_threshold/100.0 )){///If the blob is already a merged blob, copy their tags to the new merged blob, in the if append the new single blob //oclusion_memoir.Remember(to_remember); ///Coment to avoid remembering merged blobs, but this helps to recover splits without merges cout << "Node is a merged one with "<< to_remember.merged_centroids.size() << " merged centroids, inserting player tag and centroid to the next merged blob"<<endl; ///Copy source merged centroids and player tags to destiny blob for (map< int,Point2f >::iterator mipit=to_remember.merged_centroids.begin(); mipit!=to_remember.merged_centroids.end(); ++mipit){ //cout << "Inserting player tag " << *tsit.first << " to set and changing state to blob " << min_edges[iedge].vbid << " from frame " << min_edges[iedge].vframe << endl; ///Search for the merged centroid on the oclusion memoir for(unsigned int omvi = 0; omvi < oclusion_memoir.vector_memoir.size(); omvi++){ Node to_search = oclusion_memoir.vector_memoir[omvi].info; if(mipit->first == to_search.player_tag){ if((to_search.contourRegion.cols <= merged_blob.contourRegion.cols) && (to_search.contourRegion.rows <= merged_blob.contourRegion.rows)){ ///Search on the destiny blob for the centroid of the merged blob with template matching double match_value; cv::Point new_centroid = MatchBlobTemplate(merged_blob.contourRegion, merged_blob.centroid, to_search.contourRegion, match_method, &match_value); //cout << "Match value of " << match_value << " with the matching method " << match_method << endl; if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ){//min if(match_value <= match_threshold) InsertNodePlayerTagCentroidToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_search.player_tag,new_centroid); } else{//max if(match_value >= match_threshold) InsertNodePlayerTagCentroidToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,to_search.player_tag,new_centroid); } InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,mipit->first); } } } } } } } } else if(direction==FRONT){///Splits std::cout << "--Split v4--" << endl; std::cout << "From " << omit->first << " to "; for (auto destv : omit->second) std::cout << destv << " "; std::cout << endl; ///Search the frame number for source blob id std::vector<Edge>::iterator edgesit; for (auto destv : omit->second) for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ if(min_edges[iedge].ubid==destv){ cout << "Trying to recover blob " << min_edges[iedge].ubid << " from oclusion memoir." << endl; //Search in oclusion memoir nodes with player tags Node to_recover=GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); //cout << "To recover blob area = " << to_recover.area << endl; //cout << "Prom area = " << prom_area << " merged_blob_area_threshold size = " << prom_area * merged_blob_area_threshold/100.0 << endl; ///Para detectar que es un blob con varios jugadores juntos if(to_recover.area > ( prom_area * merged_blob_area_threshold/100.0)) to_recover.SetBlobType(MULTI_PLAYER); else to_recover.SetBlobType(SINGLE_PLAYER); ///Para descartar partes de jugadores o la bola if(to_recover.area < ( prom_area * min_blob_area_threshold/100.0)) to_recover.SetBlobType(NON_PLAYER); if(oclusion_memoir.vector_memoir.size()>0){///Is only possible to recover something lost //Node likely_node=oclusion_memoir.ExtractClosestMemoir(to_recover); Node merged = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); ///This is the merged blob ChangeNodeStartPointHistory(min_edges[iedge].uframe,min_edges[iedge].ubid,merged.centroid); ///Aca cambio el start point a to_recover para que tenga el centroide del merged por si sigue la misma direccion //Node likely_node=oclusion_memoir.GetMemoirByTags(to_recover,merged.player_tag_set); Node likely_node=oclusion_memoir.GetMemoirByTagsAndTM1(to_recover,merged.player_tag_set,merged.merged_centroids);///Return the node that resembles more to the split node cout << "Assign for blob " << to_recover.blob_id << " of frame " << to_recover.blob_frame_number << " from memorized blob " << likely_node.blob_id << " of frame " << likely_node.blob_frame_number << " with tag " << likely_node.player_tag << " and tag set size " << likely_node.player_tag_set.size() << endl; if((merged.merged_centroids.count(likely_node.player_tag)>0) && (to_recover.blob_type == SINGLE_PLAYER)){ //if((merged.merged_centroids.count(likely_node.player_tag)>0) ){ cout << "El blob compuesto tiene el id del nodo por recuperar, en total tiene " << merged.merged_centroids.size() << " merged centroids." << endl; ///Copy player tag from likely to recover and remove player tag from set //if(to_recover.player_tag_set.size()<=1){ cout << "Merged centroids size from blob to recover = " << to_recover.merged_centroids.size() << endl; ClearTagSet(to_recover.blob_frame_number, min_edges[iedge].ubid); ClearTagAndCentroids(to_recover.blob_frame_number, min_edges[iedge].ubid); SetNodePlayertag(to_recover.blob_frame_number, min_edges[iedge].ubid, likely_node.player_tag); SetTagAndCentroid(to_recover.blob_frame_number, min_edges[iedge].ubid, likely_node.player_tag, to_recover.centroid); RemoveNodePlayertagFromBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,likely_node.player_tag);///Quitar el tag del merged tag set oclusion_memoir.Forget(likely_node); //DeleteTagAndCentroid(min_edges[iedge].vframe,min_edges[iedge].vbid,likely_node.player_tag); } else if(to_recover.blob_type == NON_PLAYER){///Es muy pequeno, se descarta cout << "The blob to recover is too small." << endl; } else{//Es un merged blob, buscar cuales blobs no se han separado y transferirlos al nuevo cout << "The blob to recover is a merged blob" << endl; ClearTagAndCentroids(min_edges[iedge].uframe,min_edges[iedge].ubid); ClearTagSet(min_edges[iedge].uframe,min_edges[iedge].ubid); Node merged = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); //Node likely_node=oclusion_memoir.GetMemoirByTagsAndTM1(to_recover,merged.player_tag_set,merged.merged_centroids); CopyNodePlayerTagSet(min_edges[iedge].uframe,min_edges[iedge].ubid,merged.player_tag_set); CopyMergedCentroidsMap(min_edges[iedge].uframe,min_edges[iedge].ubid,merged.merged_centroids); SetNodeType(min_edges[iedge].uframe,min_edges[iedge].ubid,MULTI_PLAYER); } } } } } //} }//if only detected merge else if(omit->second.size()==1){///Process one to one blob coincidence but only the merged blobs if(direction==BACK){ auto sourcev = omit->second; //auto destu = omit->first; for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){///Search on borders to match the sourcev id std::set<int>::iterator srcit = omit->second.begin(); if((*srcit == min_edges[iedge].ubid) && (omit->first == min_edges[iedge].vbid)){///el second es la fuente, el first es el destino Node sourcen = GetNode(min_edges[iedge].uframe,min_edges[iedge].ubid); Node destn = GetNode(min_edges[iedge].vframe,min_edges[iedge].vbid); ///Buscar los tags que estan en el merged centroid del source para hacer el template matching en el siguiente y asignar los nuevos centroides if(sourcen.merged_centroids.size()>1){ //cout << "Blob " << sourcen.blob_id << " en " << sourcen.blob_frame_number << " con " << sourcen.merged_centroids.size()<< " merged centroids" << endl; //cout << "Blob fuente en " << sourcen.centroid.x << " x " << sourcen.centroid.y << endl; //cout << "Blob destino en " << destn.centroid.x << " x " << destn.centroid.y << endl; std::map< int,Point2f >::iterator srcmcit; for (srcmcit = sourcen.merged_centroids.begin(); srcmcit!=sourcen.merged_centroids.end(); ++srcmcit) { Node templ_blob = oclusion_memoir.GetMemoirByTag(srcmcit->first); //cout << "Blob template en " << templ_blob.centroid.x << " x " << templ_blob.centroid.y << " con tag " << templ_blob.player_tag << " desde frame " << templ_blob.blob_frame_number << endl; if((templ_blob.contourRegion.cols <= destn.contourRegion.cols) && (templ_blob.contourRegion.rows <= destn.contourRegion.rows) && (templ_blob.contourRegion.cols>0 && templ_blob.contourRegion.rows>0)){ double match_value; cv::Point new_centroid = MatchBlobTemplate(destn.contourRegion, destn.centroid, templ_blob.contourRegion, match_method, &match_value); //cout << "Nuevo centroide de Blob template en " << new_centroid.x << " x " << new_centroid.y << endl; //cout << "Match value of " << match_value << " with the matching method " << match_method << endl; if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ){//min if(match_value <= match_threshold) InsertNodePlayerTagCentroidToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,templ_blob.player_tag,new_centroid); //Add player tag and centroid to destiny blob list. } else{//max if(match_value >= match_threshold) InsertNodePlayerTagCentroidToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,templ_blob.player_tag,new_centroid); //Add player tag and centroid to destiny blob list. } InsertNodePlayertagToBlob(min_edges[iedge].vframe,min_edges[iedge].vbid,templ_blob.player_tag); //Add player tag to list. } //else // cout << "Unable to search merged blob within new blob because of oversize template dimension." << endl; } } } } } } }//for loop } void MultiPartiteGraph::AnalyzeAbductions(std::vector<Edge> min_edges, int source_frame_number, int direction) { int frame_number = source_frame_number; Graph source_gph; source_gph = GetGraph(frame_number); ///Identify nodes without a destination node if(direction==BACK){///Remember blob if disappears cout << "--Inspecting for lost blobs" << endl; for(unsigned int unit = 0 ; unit < source_gph.size(); ++unit){///Look only on source blobs, if theres no match consider a abduction Node source_node; source_node = source_gph[unit]; //cout << "---Inspecting blob id = " << source_node.blob_id << " from frame " << source_node.blob_frame_number << endl; bool found=false; for(unsigned int iedge = 0; iedge < min_edges.size() and not found; iedge++){ int source_blob_id = min_edges[iedge].ubid; int source_frame_id = min_edges[iedge].uframe; //cout << "Edge blob id = " << source_blob_id << " from frame " << source_frame_id << endl; if((source_node.blob_id==source_blob_id) && (source_node.blob_frame_number==source_frame_id)) found=true; } if(not found){///Solo existen los bordes que convergen, esto es que existe alguna asociacion, sino quiere decir que desaparecio cout << "Blob " << source_node.blob_id << " from frame " << source_node.blob_frame_number << " with tag " << source_node.player_tag << " abduced." << endl; abduction_memoir.Remember(source_node); cout << "Abduction memory size = " << abduction_memoir.vector_memoir.size() << endl; } } } if(direction==FRONT){///Recover blob if reapears cout << "--Inspecting for abducted blobs" << endl; Graph destination_gph; destination_gph = GetGraph(frame_number+1); ///Identify nodes without a source node for(unsigned int unit = 0; unit < destination_gph.size(); ++unit){///Look only on destination blobs, if theres no match consider a reborn :P Node destination_node; destination_node = destination_gph[unit]; bool found=false; for(unsigned int iedge = 0; iedge < min_edges.size(); iedge++){ int destination_blob_id = min_edges[iedge].ubid; int destination_frame_id = min_edges[iedge].uframe; if((destination_node.blob_id==destination_blob_id) and (destination_node.blob_frame_number==destination_frame_id)) found=true; } if(not found and abduction_memoir.vector_memoir.size()>0){ Node reborn_node = abduction_memoir.GetClosestMemoir(destination_node); //Node reborn_node = abduction_memoir.GetClosestMemoir(destination_node); cout << "Blob " << destination_node.blob_id << " from frame " << destination_node.blob_frame_number << " with tag " << destination_node.player_tag << " untracked, trying to recover from abduction memory." << endl; if(reborn_node.player_tag != 0){///Esto porque si no encuentra es igual a cero cout << "Recovering with blob " << reborn_node.blob_id << " from frame " << reborn_node.blob_frame_number << " with tag " << reborn_node.player_tag << endl; cout << "Abduction memory size = " << abduction_memoir.vector_memoir.size() << endl; abduction_memoir.Forget(reborn_node); SetNodePlayertag(destination_node.blob_frame_number,destination_node.blob_id,reborn_node.player_tag); CopyNodePlayerTagSet(destination_node.blob_frame_number,destination_node.blob_id,reborn_node.player_tag_set); CopyMergedCentroidsMap(destination_node.blob_frame_number,destination_node.blob_id,reborn_node.merged_centroids); } } } } } std::vector<Memoir> MultiPartiteGraph::GetOclusionMemories(void) { return oclusion_memoir.vector_memoir; } std::vector<Memoir> MultiPartiteGraph::GetAbductionMemories(void) { return abduction_memoir.vector_memoir; } void MultiPartiteGraph::SetOclusionMemories(std::vector<Memoir> om) { oclusion_memoir.vector_memoir = om; } void MultiPartiteGraph::SetAbductionMemories(std::vector<Memoir> am) { abduction_memoir.vector_memoir = am; } void MultiPartiteGraph::PrintEdges(std::vector<Edge> edges) { for(unsigned int iedge = 0; iedge < edges.size(); iedge++){ int source_blob_id = edges[iedge].ubid; int destination_blob_id = edges[iedge].vbid; cout << "Source blob = " << source_blob_id << " ------- destination blob = " << destination_blob_id; cout << " Weight = " << edges[iedge].weight << endl; } } MultiPartiteGraph::~MultiPartiteGraph() { }
44.175
240
0.670905
jose-lp
c3f9cfb939b0a918f7a75a9fa3437d84495ba561
10,329
hpp
C++
include/mc2lib/codegen/cats.hpp
melver/mc2lib
c67b3884217a1ff6cd5f0e67eb92525245488d8e
[ "BSD-3-Clause" ]
5
2016-09-26T04:03:11.000Z
2021-12-02T06:59:14.000Z
include/mc2lib/codegen/cats.hpp
melver/mc2lib
c67b3884217a1ff6cd5f0e67eb92525245488d8e
[ "BSD-3-Clause" ]
1
2021-09-10T08:33:23.000Z
2021-09-13T09:03:28.000Z
include/mc2lib/codegen/cats.hpp
melver/mc2lib
c67b3884217a1ff6cd5f0e67eb92525245488d8e
[ "BSD-3-Clause" ]
3
2016-07-07T04:02:38.000Z
2019-01-30T18:23:40.000Z
/* * Copyright (c) 2014-2016, Marco Elver * 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 software 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. */ #ifndef MC2LIB_CODEGEN_CATS_HPP_ #define MC2LIB_CODEGEN_CATS_HPP_ #include <cassert> #include <cstddef> #include <limits> #include <sstream> #include <stdexcept> #include <unordered_map> #include "../memconsistency/cats.hpp" #include "compiler.hpp" namespace mc2lib { namespace codegen { // Workaround for Wtype-limits warning. template <class T1, class T2> constexpr bool lt__(T1 a, T2 b) { return a < b; } /** * @brief Interface to memconsistency::cats data structures. * * This class serves as a helper to interface with data structures in * memconsistency::cats. Its primary function is the creation of new events by * Operations. * * Furthermore, as this is the interface to the consistency model descriptions * and checker, we can encode efficient support for virtual address synonyms * here by transforming the address used to construct events (see * EvtStateCats::set_addr_mask). As described in [1], if we are working at the * virtual address level, we are checking VAMC (Virtual Address * Memory Consistency). Here we only consider the problem of synonym sets of * virtual addresses mapping to the same physical address, and add simple * support for it. * * [1] <a href="http://dx.doi.org/10.1145/1736020.1736057"> * Bogdan F. Romanescu, Alvin R. Lebeck, Daniel J. Sorin, "Specifying and * dynamically verifying address translation-aware memory consistency", * 2010.</a> */ class EvtStateCats { public: // 1 Op can at most emit 2 write Events static constexpr std::size_t kMaxOpSize = sizeof(types::WriteID) * 2; static constexpr std::size_t kMaxOpEvents = kMaxOpSize / sizeof(types::WriteID); static constexpr types::Poi kMinOther = static_cast<types::Poi>(1) << (sizeof(types::Poi) * 8 - 1); static constexpr types::Poi kMaxOther = std::numeric_limits<types::Poi>::max() - (kMaxOpEvents - 1); static constexpr types::WriteID kInitWrite = std::numeric_limits<types::WriteID>::min(); static constexpr types::WriteID kMinWrite = kInitWrite + 1; static constexpr types::WriteID kMaxWrite = (lt__(std::numeric_limits<types::WriteID>::max(), kMinOther) ? std::numeric_limits<types::WriteID>::max() : kMinOther - 1) - (kMaxOpEvents - 1); static_assert(kMinOther > kMaxWrite, "Invalid read/write ID limits!"); explicit EvtStateCats(mc::cats::ExecWitness *ew, mc::cats::Architecture *arch) : ew_(ew), arch_(arch), addr_mask_(~0) {} void Reset() { last_write_id_ = kMinWrite - 1; last_other_id = kMinOther - 1; writes_.clear(); ew_->Clear(); arch_->Clear(); } bool Exhausted() const { return last_write_id_ >= kMaxWrite || last_other_id >= kMaxOther; } template <std::size_t max_size_bytes, class Func> EventPtrs<max_size_bytes> MakeEvent(types::Pid pid, mc::Event::Type type, std::size_t size, Func mkevt) { static_assert(max_size_bytes <= kMaxOpSize, "Invalid size!"); static_assert(sizeof(types::WriteID) <= max_size_bytes, "Invalid size!"); static_assert(max_size_bytes % sizeof(types::WriteID) == 0, "Invalid size!"); assert(size <= max_size_bytes); assert(sizeof(types::WriteID) <= size); assert(size % sizeof(types::WriteID) == 0); // Initialize to avoid uninitialized warning with some older compilers. EventPtrs<max_size_bytes> result{{nullptr}}; for (std::size_t i = 0; i < size / sizeof(types::WriteID); ++i) { result[i] = mkevt(i * sizeof(types::WriteID)); } return result; } mc::Event MakeOther(types::Pid pid, mc::Event::Type type, types::Addr addr) { assert(!Exhausted()); addr &= addr_mask_; return mc::Event(type, addr, mc::Iiid(pid, ++last_other_id)); } template <std::size_t max_size_bytes = sizeof(types::WriteID)> EventPtrs<max_size_bytes> MakeRead(types::Pid pid, mc::Event::Type type, types::Addr addr, std::size_t size = max_size_bytes) { assert(!Exhausted()); addr &= addr_mask_; ++last_other_id; return MakeEvent<max_size_bytes>(pid, type, size, [&](types::Addr offset) { const mc::Event event = mc::Event(type, addr + offset, mc::Iiid(pid, last_other_id)); return &ew_->events.Insert(event, true); }); } template <std::size_t max_size_bytes = sizeof(types::WriteID)> EventPtrs<max_size_bytes> MakeWrite(types::Pid pid, mc::Event::Type type, types::Addr addr, types::WriteID *data, std::size_t size = max_size_bytes) { assert(!Exhausted()); addr &= addr_mask_; ++last_write_id_; return MakeEvent<max_size_bytes>(pid, type, size, [&](types::Addr offset) { const types::WriteID write_id = last_write_id_; const mc::Event event = mc::Event(type, addr + offset, mc::Iiid(pid, write_id)); *(data + offset) = write_id; return (writes_[write_id] = &ew_->events.Insert(event, true)); }); } template <std::size_t max_size_bytes = sizeof(types::WriteID)> EventPtrs<max_size_bytes> GetWrite(const EventPtrs<max_size_bytes> &after, types::Addr addr, const types::WriteID *from_id, std::size_t size = max_size_bytes) { static_assert(max_size_bytes <= kMaxOpSize, "Invalid size!"); static_assert(sizeof(types::WriteID) <= max_size_bytes, "Invalid size!"); static_assert(max_size_bytes % sizeof(types::WriteID) == 0, "Invalid size!"); assert(size <= max_size_bytes); assert(sizeof(types::WriteID) <= size); assert(size % sizeof(types::WriteID) == 0); addr &= addr_mask_; EventPtrs<max_size_bytes> result; result.fill(nullptr); // init for (std::size_t i = 0; i < size / sizeof(types::WriteID); ++i) { WriteID_EventPtr::const_iterator write; const bool valid = from_id[i] != kInitWrite && (write = writes_.find(from_id[i])) != writes_.end() && write->second->addr == addr && write->second->iiid != after[i]->iiid; if (valid) { result[i] = write->second; } else { if (from_id[i] != kInitWrite) { // While the checker works even if memory is not 0'ed out // completely, as the chances of reading a write-id from a // previous test that has already been used in this test is // low and doesn't necessarily cause a false positive, it is // recommended that memory is 0'ed out for every new test. // // This does also provides limited checking for single-copy // atomicity violations where sizeof(WriteID) > 1. std::ostringstream oss; oss << __func__ << ": Invalid write!" << " A=" << std::hex << addr << " S=" << size; if (write != writes_.end()) { oss << ((write->second->addr != addr) ? " (addr mismatch)" : "") << ((write->second->iiid == after[i]->iiid) ? " (same iiid)" : ""); } throw std::logic_error(oss.str()); } auto initial = mc::Event(mc::Event::kWrite, addr, mc::Iiid(-1, addr)); result[i] = &ew_->events.Insert(initial); } addr += sizeof(types::WriteID); } return result; } mc::cats::ExecWitness *ew() { return ew_; } const mc::cats::ExecWitness *ew() const { return ew_; } mc::cats::Architecture *arch() { return arch_; } const mc::cats::Architecture *arch() const { return arch_; } /** * When using virtual addresses, this can be used to mask test memory * addresses, s.t. synonyms map to the same address used by the checker. * Although we could modify the checker to permit sets of addresses, this * would be much more expensive in terms of storage and hash-map lookup by * the checker. Assumes that synonym range start addresses are multiples of * 2**n (the size of memory). */ void set_addr_mask(types::Addr val) { addr_mask_ = val; } types::Addr addr_mask() const { return addr_mask_; } private: typedef std::unordered_map<types::WriteID, const mc::Event *> WriteID_EventPtr; mc::cats::ExecWitness *ew_; mc::cats::Architecture *arch_; WriteID_EventPtr writes_; types::WriteID last_write_id_; types::Poi last_other_id; types::Addr addr_mask_; }; } // namespace codegen } // namespace mc2lib #endif /* MC2LIB_CODEGEN_CATS_HPP_ */ /* vim: set ts=2 sts=2 sw=2 et : */
37.021505
80
0.643044
melver
c3ff5e6ef96be4df90b879d1da31b3d9e25091c6
3,204
cpp
C++
tests/IncDFS_Exp_IO.cpp
shahbazk/IncDFS-Experimental
84970b3e23905b6af4611c8dbfbf4806f6ed0c9e
[ "BSD-2-Clause" ]
null
null
null
tests/IncDFS_Exp_IO.cpp
shahbazk/IncDFS-Experimental
84970b3e23905b6af4611c8dbfbf4806f6ed0c9e
[ "BSD-2-Clause" ]
null
null
null
tests/IncDFS_Exp_IO.cpp
shahbazk/IncDFS-Experimental
84970b3e23905b6af4611c8dbfbf4806f6ed0c9e
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * tests/IncDFS_Exp_IO.cpp * Evaluation of algorithms on Random Graphs in two versions: VarN and VarM * Initialization code * * Part of Project: Incremental-DFS-Experimental: * https://github.com/shahbazk/IncDFS-Experimental * * Copyright (C) 2017 Shahbaz Khan <shahbazk@cse.iitk.ac.in> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ // No. of edges in graph of sparsity i // 1- 2n // 2- nlogn // 3- n\sqrt{n} // 4- complete int edgSpars(int n,int i) { int ans =0; if(i==1) ans = 2*n; if(i==2) ans = n*log2(n); if(i==3) ans = n*sqrt(n); #if defined(DIRECTED) if(i>3) ans = n*(n-1); if(ans> n*(n-1)) return n*(n-1); else return ans; #else if(i>3) ans = n*(n-1)/2; if(ans> (n*(n-1)/2)) return (n*(n-1)/2); else return ans; #endif } #ifdef DAG int *perm=NULL; #endif int (*edgS)[2]=NULL; void randomEinit(int n) { int i,j,c=0; if (edgS!=NULL){ free(edgS); } edgS = (int (*)[2])calloc(n*n,sizeof(edgS)); #ifdef DAG if(perm!= NULL) {free(perm);} perm = (int *)calloc(n+1,sizeof(perm)); for(i=0;i<=n;i++) perm[i]=i; i--; while(i>1) { j = rand()%(i)+1; c = perm[i]; perm[i] = perm[j]; perm[j] = c; i--; } #endif c=0; for(i=1;i<=n;i++) { #if defined(DIRECTED) for(j=1;j<=n;j++) #else for(j=i+1;j<=n;j++) #endif { if(i==j) continue; #ifdef DAG edgS[c][0]=perm[i]; edgS[c][1]=perm[j]; #else edgS[c][0]=i; edgS[c][1]=j; #endif c++; } } int e1,e2; while(c) { i = rand()%(c); e1 = edgS[c-1][0]; e2 = edgS[c-1][1]; edgS[c-1][0] = edgS[i][0]; edgS[c-1][1] = edgS[i][1]; edgS[i][0] = e1; edgS[i][1] = e2; c--; } } /* Generate the connected graph G(n,p=m/n*n) m = 0 for star graph. */ void initGraph(Graph &G, int n, int m) { int i,j; #if defined(DIRECTED) || defined(DAG) G = Graph(n+1,1); #else G = Graph(n+1,0); #endif for(i=1;i<=n;i++) { G.addEdge(0,i); #ifdef SHWGRPH printf("Graph: (%d,%d)\n",0,i); #endif for(j=i+1;j<=n;j++) { if(rand()%(n*n)<m) { #ifdef SHWGRPH printf("Graph: (%d,%d)\n",i,j); #endif G.addEdge(i,j); } } } } ///////////////////////////////////////// ///////////// ARGUMENTS ///////////////// ///////////////////////////////////////// //#if defined(Static_DFS) || defined(DIRECTED) || defined(ADFS) #if defined(Static_DFS) || defined(ADFS) #define GET_OPT(x) \ int OPT=4; \ if(argc>x) OPT= atoi(argv[x]); #else #define GET_OPT(x) {} #endif #ifdef REAL #define GET_ARGS() \ int DP=1000; \ if(argc>1) DP = atoi(argv[1]);\ GET_OPT(2) #else // RANDOM #define GET_ARGS() \ int N=100,DP=100,TST=10,SPARS=4;\ if(argc>1) N= atoi(argv[1]);\ if(argc>2) SPARS= atoi(argv[2]);\ if(argc>3) DP= atoi(argv[3]);\ if(argc>4) TST= atoi(argv[4]);\ GET_OPT(5) #endif ////////////////////////////////////////// ///////// INIT n,m,t ///////////////////// ////////////////////////////////////////// #ifdef REAL #define INIT_NM() \ assert(scanf("%d%d",&n_max,&m_max)==2); #else #define INIT_NM() \ n_max = N, m_max = edgSpars(N,SPARS);\ int t=TST; #endif
18.204545
80
0.501873
shahbazk
7f03f8db52088f189c4791f9c9f3db02cf0a1d12
16,686
hpp
C++
include/rome/delegate.hpp
rmettler/cpp_delegates
8557a1731eccbad9608f3111c5599f666b74750e
[ "BSL-1.0" ]
4
2020-01-30T19:17:57.000Z
2020-04-02T13:03:13.000Z
include/rome/delegate.hpp
rmettler/cpp_delegates
8557a1731eccbad9608f3111c5599f666b74750e
[ "BSL-1.0" ]
null
null
null
include/rome/delegate.hpp
rmettler/cpp_delegates
8557a1731eccbad9608f3111c5599f666b74750e
[ "BSL-1.0" ]
null
null
null
// // Project: C++ delegates // File content: // - delegate<Ret(Args...), Behavior> // - fwd_delegate<void(Args...), Behavior> // - event_delegate<void(Args...)> // - command_delegate<void(Args...)> // See the documentation for more information. // // The rome::delegate implementation is based on the article of // Sergey Ryazanov: "The Impossibly Fast C++ Delegates", 18 Jul 2005 // https://www.codeproject.com/articles/11015/the-impossibly-fast-c-delegates // // Copyright Roger Mettler 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // https://www.boost.org/LICENSE_1_0.txt) // #pragma once #include <algorithm> #include <cstddef> #include <type_traits> #include <utility> #include "detail/delegate_base.hpp" namespace rome { // Used as template argument for delegates to declare that it invoking an empty delegate is valid // behavior. struct target_is_optional; // Used as template argument for delegates to declare that an assigned target is expected when the // delegate is invoked and leads to an exception otherwise. struct target_is_expected; // Used as template argument for delegates to declare that an assigned target is mandatory when the // delegate is invoked and thus the design ensures that always a delegate is assigned. struct target_is_mandatory; namespace detail { struct ok {}; template<typename...> struct wrong_t : std::false_type {}; template<typename... T> constexpr bool wrong = wrong_t<T...>::value; struct bad_delegate_template_param {}; template<typename Ret, typename Behavior> struct bad_delegate_template_param_ : bad_delegate_template_param { constexpr bad_delegate_template_param_() noexcept { static_assert(wrong<Ret, Behavior>, "Invalid template parameter. The second template parameter 'Behavior' must " "either be empty or contain one of the types 'rome::target_is_optional', " "'rome::target_is_expected' or 'rome::target_is_mandatory', where " "'rome::target_is_optional' is only valid if the return type 'Ret' is 'void'."); } }; template<typename Ret, typename Behavior> struct delegate_helper { template<typename... Args> using delegate_base_type = delegate_base::delegate_base<Ret(Args...), delegate_base::invalid_invoker>; using assert_template_params = bad_delegate_template_param_<Ret, Behavior>; }; template<> struct delegate_helper<void, target_is_optional> { template<typename... Args> using delegate_base_type = delegate_base::delegate_base<void(Args...), delegate_base::no_call_invoker>; using assert_template_params = ok; }; template<typename Ret> struct delegate_helper<Ret, target_is_expected> { template<typename... Args> using delegate_base_type = delegate_base::delegate_base<Ret(Args...), delegate_base::exception_call_invoker>; using assert_template_params = ok; }; } // namespace detail template<typename Signature, typename Behavior = target_is_expected> class delegate; template<typename Ret, typename... Args, typename Behavior> class delegate<Ret(Args...), Behavior> : private detail::delegate_helper<Ret, Behavior>::assert_template_params { private: using delegate_base_type = typename detail::delegate_helper<Ret, Behavior>::template delegate_base_type<Args...>; delegate_base_type target_ = {}; delegate(delegate_base_type&& target) noexcept : target_{std::move(target)} { } public: constexpr delegate() noexcept = default; delegate(const delegate&) noexcept = delete; delegate(delegate&&) noexcept = default; ~delegate() = default; constexpr delegate(std::nullptr_t) noexcept : delegate{} { } delegate& operator=(const delegate&) noexcept = delete; delegate& operator=(delegate&&) noexcept = default; constexpr delegate& operator=(std::nullptr_t) noexcept { target_ = nullptr; return *this; } constexpr explicit operator bool() const noexcept { return target_.operator bool(); } void swap(delegate& other) noexcept { target_.swap(other.target_); } Ret operator()(Args... args) const { return target_.operator()(static_cast<Args>(args)...); } // Creates a new delegate targeting the passed function or static member function. template<Ret (*pFunction)(Args...)> static constexpr delegate create() noexcept { return delegate{delegate_base_type::template create<pFunction>()}; } // Creates a new delegate targeting the passed non-static member function. template<typename C, Ret (C::*pMethod)(Args...)> static delegate create(C& obj) noexcept { return delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new delegate targeting the passed non-static const member function. template<typename C, Ret (C::*pMethod)(Args...) const> static delegate create(const C& obj) noexcept { return delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new delegate targeting the passed functor and taking ownership of it. template<typename T> static delegate create(T&& functor) noexcept( noexcept(delegate_base_type::create(std::forward<T>(functor)))) { return delegate{delegate_base_type::template create(std::forward<T>(functor))}; } }; template<typename Ret, typename... Args> class delegate<Ret(Args...), target_is_mandatory> { private: using delegate_base_type = detail::delegate_base::delegate_base<Ret(Args...), detail::delegate_base::exception_call_invoker>; delegate_base_type target_ = {}; delegate(delegate_base_type&& target) noexcept : target_{std::move(target)} { } public: constexpr delegate() noexcept = delete; delegate(const delegate&) noexcept = delete; delegate(delegate&&) noexcept = default; ~delegate() = default; delegate& operator=(const delegate&) noexcept = delete; delegate& operator=(delegate&&) noexcept = default; constexpr explicit operator bool() const noexcept { return target_.operator bool(); } void swap(delegate& other) noexcept { target_.swap(other.target_); } Ret operator()(Args... args) const { return target_.operator()(static_cast<Args>(args)...); } // Creates a new delegate targeting the passed function or static member function. template<Ret (*pFunction)(Args...)> static constexpr delegate create() noexcept { return delegate{delegate_base_type::template create<pFunction>()}; } // Creates a new delegate targeting the passed non-static member function. template<typename C, Ret (C::*pMethod)(Args...)> static delegate create(C& obj) noexcept { return delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new delegate targeting the passed non-static const member function. template<typename C, Ret (C::*pMethod)(Args...) const> static delegate create(const C& obj) noexcept { return delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new delegate targeting the passed functor and taking ownership of it. template<typename T> static delegate create(T&& functor) noexcept( noexcept(delegate_base_type::create(std::forward<T>(functor)))) { return delegate{delegate_base_type::template create(std::forward<T>(functor))}; } }; template<typename Sig, typename Behavior> constexpr bool operator==(const delegate<Sig, Behavior>& lhs, std::nullptr_t) { return !lhs; } template<typename Sig, typename Behavior> constexpr bool operator==(std::nullptr_t, const delegate<Sig, Behavior>& rhs) { return !rhs; } template<typename Sig, typename Behavior> constexpr bool operator!=(const delegate<Sig, Behavior>& lhs, std::nullptr_t) { return static_cast<bool>(lhs); } template<typename Sig, typename Behavior> constexpr bool operator!=(std::nullptr_t, const delegate<Sig, Behavior>& rhs) { return static_cast<bool>(rhs); } namespace detail { struct bad_delegate_template_param_with_mutable_arguments {}; template<typename... Args> struct bad_delegate_template_param_with_mutable_arguments_ : bad_delegate_template_param_with_mutable_arguments { constexpr bad_delegate_template_param_with_mutable_arguments_() noexcept { static_assert(wrong<Args...>, "Invalid template parameter. The first template parameter 'Signature' must be " "of type 'void(Args...)' and all arguments 'Args...' must be of immutable type. " "E.g.: 'fwd_delegate<void (int, int&&, const std::array<int,10>&, const " "int*)>'"); } }; template<typename T> constexpr bool is_value() { return std::is_null_pointer<T>::value || std::is_integral<T>::value || std::is_floating_point<T>::value || std::is_enum<T>::value || std::is_union<T>::value || std::is_class<T>::value; } template<typename T> constexpr bool is_referenced_type_a_const_value() { if (is_value<T>()) { return std::is_const<T>::value; } if (std::is_pointer<T>::value) { using TT = typename std::remove_pointer<T>::type; return is_referenced_type_a_const_value<TT>(); } return false; } template<typename T> constexpr bool is_copied_moved_or_const_referenced_value() { if (is_value<T>()) { return true; } if (std::is_rvalue_reference<T>::value) { using TT = typename std::remove_reference<T>::type; return is_copied_moved_or_const_referenced_value<TT>(); } if (std::is_lvalue_reference<T>::value) { using TT = typename std::remove_reference<T>::type; return is_referenced_type_a_const_value<TT>(); } return is_referenced_type_a_const_value<T>(); } struct fwd_delegate_params_ok {}; template<typename... Args> using fwd_delegate_assert_immutable_arguments = std::conditional_t< std::is_same< std::integer_sequence<bool, true, is_copied_moved_or_const_referenced_value<Args>()...>, std::integer_sequence<bool, is_copied_moved_or_const_referenced_value<Args>()..., true>>::value, fwd_delegate_params_ok, bad_delegate_template_param_with_mutable_arguments_<Args...>>; } // namespace detail // same as rome::delegate but restricts to void return and enforces immutable arguments template<typename Signature, typename Behavior = target_is_expected> class fwd_delegate; template<typename... Args, typename Behavior> class fwd_delegate<void(Args...), Behavior> : private detail::delegate_helper<void, Behavior>::assert_template_params, private detail::fwd_delegate_assert_immutable_arguments<Args...> { private: using delegate_base_type = typename detail::delegate_helper<void, Behavior>::template delegate_base_type<Args...>; delegate_base_type target_ = {}; fwd_delegate(delegate_base_type&& target) noexcept : target_{std::move(target)} { } public: constexpr fwd_delegate() noexcept = default; fwd_delegate(const fwd_delegate&) noexcept = delete; fwd_delegate(fwd_delegate&&) noexcept = default; ~fwd_delegate() = default; constexpr fwd_delegate(std::nullptr_t) noexcept : fwd_delegate{} { } fwd_delegate& operator=(const fwd_delegate&) noexcept = delete; fwd_delegate& operator=(fwd_delegate&&) noexcept = default; constexpr fwd_delegate& operator=(std::nullptr_t) noexcept { target_ = nullptr; return *this; } constexpr explicit operator bool() const noexcept { return target_.operator bool(); } void swap(fwd_delegate& other) noexcept { target_.swap(other.target_); } void operator()(Args... args) const { return target_.operator()(static_cast<Args>(args)...); } // Creates a new fwd_delegate targeting the passed function or static member function. template<void (*pFunction)(Args...)> static constexpr fwd_delegate create() noexcept { return fwd_delegate{delegate_base_type::template create<pFunction>()}; } // Creates a new fwd_delegate targeting the passed non-static member function. template<typename C, void (C::*pMethod)(Args...)> static fwd_delegate create(C& obj) noexcept { return fwd_delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new fwd_delegate targeting the passed non-static const member function. template<typename C, void (C::*pMethod)(Args...) const> static fwd_delegate create(const C& obj) noexcept { return fwd_delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new fwd_delegate targeting the passed functor and taking ownership of it. template<typename T> static fwd_delegate create(T&& functor) noexcept( noexcept(delegate_base_type::create(std::forward<T>(functor)))) { return fwd_delegate{delegate_base_type::template create(std::forward<T>(functor))}; } }; template<typename... Args> class fwd_delegate<void(Args...), target_is_mandatory> : private detail::fwd_delegate_assert_immutable_arguments<Args...> { private: using delegate_base_type = detail::delegate_base::delegate_base<void(Args...), detail::delegate_base::exception_call_invoker>; delegate_base_type target_ = {}; fwd_delegate(delegate_base_type&& target) noexcept : target_{std::move(target)} { } public: constexpr fwd_delegate() noexcept = delete; fwd_delegate(const fwd_delegate&) noexcept = delete; fwd_delegate(fwd_delegate&&) noexcept = default; ~fwd_delegate() = default; fwd_delegate& operator=(const fwd_delegate&) noexcept = delete; fwd_delegate& operator=(fwd_delegate&&) noexcept = default; constexpr explicit operator bool() const noexcept { return target_.operator bool(); } void swap(fwd_delegate& other) noexcept { target_.swap(other.target_); } void operator()(Args... args) const { return target_.operator()(static_cast<Args>(args)...); } // Creates a new fwd_delegate targeting the passed function or static member function. template<void (*pFunction)(Args...)> static constexpr fwd_delegate create() noexcept { return fwd_delegate{delegate_base_type::template create<pFunction>()}; } // Creates a new fwd_delegate targeting the passed non-static member function. template<typename C, void (C::*pMethod)(Args...)> static fwd_delegate create(C& obj) noexcept { return fwd_delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new fwd_delegate targeting the passed non-static const member function. template<typename C, void (C::*pMethod)(Args...) const> static fwd_delegate create(const C& obj) noexcept { return fwd_delegate{delegate_base_type::template create<C, pMethod>(obj)}; } // Creates a new fwd_delegate targeting the passed functor and taking ownership of it. template<typename T> static fwd_delegate create(T&& functor) noexcept( noexcept(delegate_base_type::create(std::forward<T>(functor)))) { return fwd_delegate{delegate_base_type::template create(std::forward<T>(functor))}; } }; template<typename Sig, typename Behavior> constexpr bool operator==(const fwd_delegate<Sig, Behavior>& lhs, std::nullptr_t) { return !lhs; } template<typename Sig, typename Behavior> constexpr bool operator==(std::nullptr_t, const fwd_delegate<Sig, Behavior>& rhs) { return !rhs; } template<typename Sig, typename Behavior> constexpr bool operator!=(const fwd_delegate<Sig, Behavior>& lhs, std::nullptr_t) { return static_cast<bool>(lhs); } template<typename Sig, typename Behavior> constexpr bool operator!=(std::nullptr_t, const fwd_delegate<Sig, Behavior>& rhs) { return static_cast<bool>(rhs); } template<typename Signature> using event_delegate = fwd_delegate<Signature, target_is_optional>; template<typename Signature> using command_delegate = fwd_delegate<Signature, target_is_mandatory>; } // namespace rome
36.672527
100
0.686504
rmettler
7f058842f1c4e283e9b8b11e3a6057ce904a0ffe
4,300
cpp
C++
tests/test_queue_mpsc_waitfree.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
4
2017-11-28T17:22:46.000Z
2022-03-17T07:47:19.000Z
tests/test_queue_mpsc_waitfree.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
10
2017-10-04T01:20:25.000Z
2017-11-23T06:15:23.000Z
tests/test_queue_mpsc_waitfree.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
1
2019-06-13T23:05:49.000Z
2019-06-13T23:05:49.000Z
#include "../stitch/queue_mpsc_waitfree.h" #include "../testing/testing.h" using namespace Stitch; using namespace std; static bool test() { Testing::Test test; test.assert("Lockfree.", Waitfree_MPSC_Queue<int>::is_lockfree()); Waitfree_MPSC_Queue<int> q (10); for (int rep = 0; rep < 3; ++rep) { for (int i = 0; i < 7; ++i) { test.assert("Not full.", !q.full()); bool ok = q.push(i); test.assert("Pushed.", ok); } for (int i = 0; i < 7; ++i) { test.assert("Not empty.", !q.empty()); int v; bool ok = q.pop(v); test.assert("Popped.", ok); if (ok) test.assert("Popped " + to_string(v), v == i); } } return test.success(); } static bool test_bulk() { Testing::Test test; Waitfree_MPSC_Queue<int> q(10); for (int rep = 0; rep < 6; ++rep) { int count = q.capacity() - 2; { vector<int> data(count); for(int i = 0; i < count; ++i) data[i] = i; bool pushed = q.push(count, data.begin()); test.assert("Pushed.", pushed); } test.assert("Queue is not empty.", !q.empty()); { vector<int> data(count); bool popped = q.pop(count, data.begin()); test.assert("Popped.", popped); for (int i = 0; i < count; ++i) test.assert("Got " + to_string(data[i]), data[i] == i); } test.assert("Queue is empty.", q.empty()); } { vector<int> data(q.capacity() + 1); test.assert("Can't pop when empty.", !q.pop(1, data.begin())); test.assert("Can't push more than capcity.", !q.push(q.capacity() + 1, data.begin())); } return test.success(); } static bool test_bulk_array() { Testing::Test test; Waitfree_MPSC_Queue<int> q(10); constexpr int N = 5; int input[N] = { 1, 3, 2, 4, 5 }; int output[N] = { 0, 0, 0, 0, 0 }; q.push(N, input); q.pop(N, output); for (int i = 0; i < N; ++i) { test.assert("Transferred: " + to_string(output[i]), output[i] == input[i]); } return test.success(); } static bool stress_test() { Testing::Test test; Waitfree_MPSC_Queue<int> q(50); atomic<bool> quit { false }; auto producer = ([&](bool first) { int v = 1; while(!quit) { while(!quit) { //printf("%s %d\n", first ? "1: " : "2: ", v); bool ok = q.push(first ? v : v + 1000); if (ok) v = (v + 1) & 0xFF; else break; } this_thread::yield(); } }); thread p1(producer, true); thread p2(producer, false); bool work = true; int v1 = 1; int v2 = 1; int v; auto start = chrono::steady_clock::now(); while(work) { this_thread::yield(); work &= chrono::steady_clock::now() - start < chrono::seconds(5); while(work && q.pop(v)) { work &= chrono::steady_clock::now() - start < chrono::seconds(5); if (v < 1000) { bool correct = v1 == v; test.assert("Stream 1 = " + to_string(v) + ", expected " + to_string(v1), correct); v1 = (v + 1) & 0xFF; //printf("1: Next: %d\n", v1); work &= correct; } else { v -= 1000; bool correct = v2 == v; test.assert("Stream 2 = " + to_string(v) + ", expected " + to_string(v2), correct); v2 = (v + 1) & 0xFF; //printf("2: Next: %d\n", v2); work &= correct; } } } quit = true; p1.join(); p2.join(); return test.success(); } Testing::Test_Set waitfree_mpsc_queue_tests() { return { { "test", test }, { "bulk", test_bulk }, { "bulk-array", test_bulk_array }, { "stress", stress_test }, }; }
22.279793
94
0.438605
adamelliot
7f08564026376b1358820e6ab41610ec0cf92fd0
383
cpp
C++
Baekjoon/5046.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/5046.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/5046.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(void) { int n, b, h, w, min, p, sum = 0; cin >> n >> b >> h >> w; min = b + 1; for (int i = 0; i < h; i++) { cin >> p; sum = 0; for (int k = 0, tmp; k < w; k++) { cin >> tmp; if (tmp >= n) sum = p*n; } if (min > sum && sum != 0) min = sum; } if (min > b) cout << "stay home"; else cout << min; }
14.730769
34
0.436031
Twinparadox
7f0bd84d407cb2b4463e5364a39c3a73d10ffa2f
800
cpp
C++
BZOJ/3668.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
BZOJ/3668.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
BZOJ/3668.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> using namespace std; inline bool is_num(char c){ return c>='0'&&c<='9'; } inline int ni(){ int i=0;char c; while(!is_num(c=getchar())); while(i=i*10-'0'+c,is_num(c=getchar())); return i; } const int N=100010; int f[2]; int main(){ int n=ni(),mx=ni(); f[0]=0; f[1]=0x7fffffff; char op[5]; for(int i=1,t;i<=n;i++){ scanf("%s%d",op,&t); switch(op[0]){ case 'A':{ f[0]&=t; f[1]&=t; break; } case 'O':{ f[0]|=t; f[1]|=t; break; } case 'X':{ f[0]^=t; f[1]^=t; break; } } } int ans=0; for(int i=0;i<32;i++){ if(mx&(1<<i)){ ans=max((f[0]&(1<<i))|((f[0]|f[1])&((1<<i)-1)),(f[1]&(1<<i))|ans); }else{ ans=(f[0]&(1<<i))|ans; } } printf("%d",ans); }
15.384615
69
0.48375
sshockwave
7f0cf40b3306f8444d7aa6ffc1de404d877d0d62
2,525
cpp
C++
src/osgEarthBuildings/Parapet.cpp
VTMAK/osgearth-buildings-pprabhu
b18c78ee5c8c0876a76ee8897070f1dbb55ccb7b
[ "MIT" ]
3
2017-12-05T06:38:28.000Z
2021-12-07T06:19:39.000Z
src/osgEarthBuildings/Parapet.cpp
VTMAK/osgearth-buildings-pprabhu
b18c78ee5c8c0876a76ee8897070f1dbb55ccb7b
[ "MIT" ]
null
null
null
src/osgEarthBuildings/Parapet.cpp
VTMAK/osgearth-buildings-pprabhu
b18c78ee5c8c0876a76ee8897070f1dbb55ccb7b
[ "MIT" ]
3
2017-12-03T09:48:04.000Z
2021-12-07T06:19:41.000Z
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2016 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "Parapet" #include "BuildContext" #define LC "[Parapet] " using namespace osgEarth; using namespace osgEarth::Symbology; using namespace osgEarth::Buildings; Parapet::Parapet() : _width( 0.0f ) { _numFloors = 1u; setTag("parapet"); } Parapet::Parapet(const Parapet& rhs) : Elevation( rhs ), _width ( rhs._width ) { } Elevation* Parapet::clone() const { return new Parapet(*this); } void Parapet::setWidth(float width) { _width = width; if ( width > 0.0f ) { _roof = new Roof(); _roof->setType( Roof::TYPE_FLAT ); _roof->setTag("parapet"); } else { _roof = 0L; } } bool Parapet::build(const Polygon* footprint, BuildContext& bc) { if ( getWidth() > 0.0f ) { // copy the outer ring of the footprint. Ignore any holes. osg::ref_ptr<Polygon> copy = dynamic_cast<Polygon*>(footprint->clone()); // apply a negative buffer to the outer ring: osg::ref_ptr<Geometry> hole; BufferParameters bp(BufferParameters::CAP_DEFAULT, BufferParameters::JOIN_MITRE); if ( copy->buffer(-getWidth(), hole, bp) ) { Ring* ring = dynamic_cast<Ring*>( hole.get() ); if ( ring ) { // rewind the new geometry CW and add it as a hole: ring->rewind(Geometry::ORIENTATION_CW); copy->getHoles().push_back( ring ); return Elevation::build( copy.get(), bc ); } } } return Elevation::build( footprint, bc ); } Config Parapet::getConfig() const { Config conf = Elevation::getConfig(); conf.add("type", "parapet"); conf.add("width", getWidth()); return conf; }
25.505051
89
0.63604
VTMAK
7f0f43fa28762e85079a025ac6f67c9ba0127615
7,473
cpp
C++
src/interface_model.cpp
ASLeonard/polyomino_interfaces
b281e4c50d0935b7145fc0d01b51d8ac83fad712
[ "MIT" ]
null
null
null
src/interface_model.cpp
ASLeonard/polyomino_interfaces
b281e4c50d0935b7145fc0d01b51d8ac83fad712
[ "MIT" ]
null
null
null
src/interface_model.cpp
ASLeonard/polyomino_interfaces
b281e4c50d0935b7145fc0d01b51d8ac83fad712
[ "MIT" ]
1
2019-04-13T12:42:11.000Z
2019-04-13T12:42:11.000Z
#include "interface_model.hpp" #include <functional> namespace simulation_params { uint8_t n_tiles=2,model_type=0,samming_threshold=10; double temperature=0,binding_threshold=1,mu_prob=1; } //weight binding strengths as the normalised hamming distance to some power T void InterfaceAssembly::SetBindingStrengths() { simulation_params::samming_threshold=static_cast<uint8_t>(interface_size*(1-simulation_params::binding_threshold)); for(size_t i=0;i<=simulation_params::samming_threshold;++i) binding_probabilities[i]=std::pow(1-double(i)/interface_size,simulation_params::temperature); } //helper function to print strengths (from strength = 1 to 0) void InterfaceAssembly::PrintBindingStrengths() { for(auto b : binding_probabilities) std::cout<<b<<std::endl; } //define interaction matrix for this genotype model, based on weighted hamming distance double InterfaceAssembly::InteractionMatrix(const interface_type face_1,const interface_type face_2) { return binding_probabilities[interface_model::SammingDistance(face_1,face_2)]; } //genotype can mutate through random bit flips given binomial weighting void InterfaceAssembly::Mutation(BGenotype& genotype) { for(interface_type& base : genotype) for(uint8_t nth_bit=0; nth_bit<interface_size; ++nth_bit) if(std::bernoulli_distribution(simulation_params::mu_prob/(interface_size*4*simulation_params::n_tiles))(RNG_Engine)) base ^= (interface_type(1) << nth_bit); } namespace interface_model { //reverse the order of bits so there is "head-to-tail" alignment in interactions interface_type ReverseBits(interface_type v) { interface_type s(interface_size), mask= ~0; while ((s >>= 1) > 0) { mask ^= (mask << s); v = ((v >> s) & mask) | ((v << s) & ~mask); } return v; } //count the number of set bits between an XOR operation, similar to the hamming distance uint8_t SammingDistance(interface_type face1,interface_type face2) { return __builtin_popcountll(face1 ^ ReverseBits(~face2)); } //main assembly code, takes in the genotype, phenotype table, and the pid and interactions to store the results double PolyominoAssemblyOutcome(BGenotype& binary_genome,FitnessPhenotypeTable* pt,Phenotype_ID& pid,std::set<InteractionPair>& pid_interactions) { //remove non-interacting monomers in genotype InterfaceAssembly::StripNoncodingGenotype(binary_genome); //get edges for the assembly graph const std::vector<std::pair<InteractionPair,double> > edges = InterfaceAssembly::GetActiveInterfaces(binary_genome); //set up objects to record repeated assemblies std::vector<Phenotype_ID> Phenotype_IDs; Phenotype_IDs.reserve(pt->phenotype_builds); std::map<Phenotype_ID, std::set<InteractionPair> > phenotype_interactions; //repeat assembly according to settings for(uint16_t nth=0;nth<pt->phenotype_builds;++nth) { //RAW assemble code from polyomino_core, extended for this model auto [assembly_information, interacting_indices] =InterfaceAssembly::AssemblePolyomino(edges); //if not unbound, add information if(assembly_information.size()>0) { Phenotype phen=GetPhenotypeFromGrid(assembly_information); Phenotype_IDs.emplace_back(pt->GetPhenotypeID(phen)); phenotype_interactions[Phenotype_IDs.back()].insert(interacting_indices.begin(),interacting_indices.end()); } //unbound, add null pid else Phenotype_IDs.emplace_back(0,0); } //relabel information in case new pid found pt->RelabelPIDs(Phenotype_IDs); pt->RelabelMaps(phenotype_interactions,true); pt->UpdateFitnesses(); //get frequency of each polyomino and set phenotype to most common one std::map<Phenotype_ID,uint16_t> ID_counter=pt->PhenotypeFrequencies(Phenotype_IDs); if(!ID_counter.empty()) pid=std::max_element(ID_counter.begin(),ID_counter.end(),[] (const auto & p1, const auto & p2) {return p1.second < p2.second;})->first; else pid=NULL_pid; //update values and calculate fitness depending on model pid_interactions=phenotype_interactions[pid]; if(simulation_params::model_type==1) return pt->SingleFitness(pid,ID_counter[pid]); if(simulation_params::model_type==2) for(auto kv : ID_counter) if(kv.first!=NULL_pid && kv.first!=pid) pid_interactions.merge(phenotype_interactions[kv.first]); return pt->GenotypeFitness(ID_counter); } } //helper function to generate an assembly graph randomly given the edge locations and total size BGenotype GenerateTargetGraph(std::map<uint8_t,std::vector<uint8_t>> edge_map,uint8_t graph_size) { const uint8_t total_edges=std::accumulate(edge_map.begin(),edge_map.end(),0,[](uint8_t size,const auto & p1) {return size+p1.second.size();}); BGenotype graph(graph_size); //helper objects std::uniform_int_distribution<uint8_t> delta_ser(0,simulation_params::samming_threshold); std::vector<uint8_t> bits(interface_size); std::iota(bits.begin(),bits.end(),0); constexpr uint8_t shift_r=interface_size/2; do { InterfaceAssembly::RandomiseGenotype(graph); for(auto edge : edge_map) { graph[edge.first]=InterfaceAssembly::GenRandomSite(); for(uint8_t connector : edge.second) { //make perfectly self-interacting if(edge.first!=connector) graph[connector]=interface_model::ReverseBits(~graph[edge.first]); else graph[connector]=(interface_model::ReverseBits(~(graph[edge.first]>>shift_r))>>shift_r) | ((graph[edge.first]>>shift_r)<<shift_r); //randomly flip bits to give random edge strength std::shuffle(bits.begin(),bits.end(),RNG_Engine); const uint8_t delta_s = delta_ser(RNG_Engine)/((edge.first==connector) ? 2 : 1); for(uint8_t b=0; b<delta_s;++b) graph[connector] ^=(interface_type(1)<<bits[b]); } } //if wrong number of edges, start again }while(InterfaceAssembly::GetActiveInterfaces(graph).size()!=total_edges); return graph; } //helper method to swap subunits if only edge is on second subunit void EnsureNeutralDisconnections(BGenotype& genotype) { BGenotype temp_genotype(genotype); uint8_t edges = InterfaceAssembly::GetActiveInterfaces(temp_genotype).size(); //no edges, so no need to swap anything if(edges==0) return; InterfaceAssembly::StripNoncodingGenotype(temp_genotype); //not disconnected, no need to swap if(temp_genotype.size()==genotype.size()) return; uint8_t new_edges=InterfaceAssembly::GetActiveInterfaces(temp_genotype).size(); //disjointed with internal edge on 2nd tile if(new_edges==0) std::swap_ranges(genotype.begin(),genotype.begin()+4,genotype.begin()+4); else { //disjointed with internal edges on both if(new_edges!=edges) { do { std::generate(genotype.begin()+4,genotype.end(),InterfaceAssembly::GenRandomSite); }while(InterfaceAssembly::GetActiveInterfaces(genotype).size()!=new_edges); //established disjointed tile with internal tile on first, neutral 2nd tile do { temp_genotype.assign(genotype.begin()+4,genotype.end()); InterfaceAssembly::Mutation(temp_genotype); }while(!InterfaceAssembly::GetActiveInterfaces(temp_genotype).empty()); //don't allow new internal edges on 2nd tile, but can allow external edge std::swap_ranges(genotype.begin()+4, genotype.end(), temp_genotype.begin()); } } }
41.748603
151
0.729024
ASLeonard
7f1321df478137cfa4268a2e577d9f987f670b7e
7,315
cpp
C++
cpp/04-Fraction.cpp
ljcbaby/Program-Practice
e999c07b595fcf3e70c8da462304e3cc0a292bac
[ "Unlicense" ]
null
null
null
cpp/04-Fraction.cpp
ljcbaby/Program-Practice
e999c07b595fcf3e70c8da462304e3cc0a292bac
[ "Unlicense" ]
null
null
null
cpp/04-Fraction.cpp
ljcbaby/Program-Practice
e999c07b595fcf3e70c8da462304e3cc0a292bac
[ "Unlicense" ]
null
null
null
#include <cstdio> #include <iostream> #include <numeric> // Fraction in integers of integers class Fraction { int numerator; int denominator; void simplify(); public: Fraction(int, int); void set(int, int); double toDouble() const; // operators Fraction operator+(const int&) const; Fraction operator+(const Fraction&) const; friend Fraction operator+(const int&, const Fraction&); Fraction operator-(const int&) const; Fraction operator-(const Fraction&) const; friend Fraction operator-(const int&, const Fraction&); Fraction operator*(const int&) const; Fraction operator*(const Fraction&) const; friend Fraction operator*(const int&, const Fraction&); Fraction operator/(const int&) const; Fraction operator/(const Fraction&) const; friend Fraction operator/(const int&, const Fraction&); Fraction& operator++(); Fraction& operator++(int); Fraction& operator--(); Fraction& operator--(int); Fraction& operator+=(const int&); Fraction& operator+=(const Fraction&); Fraction& operator-=(const int&); Fraction& operator-=(const Fraction&); Fraction& operator*=(const int&); Fraction& operator*=(const Fraction&); Fraction& operator/=(const int&); Fraction& operator/=(const Fraction&); Fraction& operator=(const int&); Fraction& operator=(const Fraction&); // comparison operators bool operator==(const Fraction&) const; bool operator!=(const Fraction&) const; bool operator<(const Fraction&) const; bool operator>(const Fraction&) const; bool operator<=(const Fraction&) const; bool operator>=(const Fraction&) const; // IO operators // iostream friend std::istream& operator>>(std::istream&, Fraction&); friend std::ostream& operator<<(std::ostream&, const Fraction&); // stdio void Input(const char*); void Output() const; }; void Fraction::simplify() { if (denominator == 0) { std::cerr << "Error for denominator 0." << std::endl; exit(-1); } if (denominator < 0) { denominator = -denominator; numerator = -numerator; } int p = std::gcd(numerator, denominator); numerator /= p; denominator /= p; } Fraction::Fraction(int n = 0, int d = 1) { numerator = n; denominator = d; simplify(); } void Fraction::set(int n, int d) { numerator = n; denominator = d; simplify(); } double Fraction::toDouble() const { return (double)numerator / denominator; } Fraction Fraction::operator+(const int& rhs) const { return Fraction(numerator + rhs * denominator, denominator); } Fraction Fraction::operator+(const Fraction& rhs) const { return Fraction(numerator * rhs.denominator + rhs.numerator * denominator, denominator * rhs.denominator); } Fraction operator+(const int& lhs, const Fraction& rhs) { return Fraction(lhs * rhs.denominator + rhs.numerator, rhs.denominator); } Fraction Fraction::operator-(const int& rhs) const { return Fraction(numerator - rhs * denominator, denominator); } Fraction Fraction::operator-(const Fraction& rhs) const { return Fraction(numerator * rhs.denominator - rhs.numerator * denominator, denominator * rhs.denominator); } Fraction operator-(const int& lhs, const Fraction& rhs) { return Fraction(lhs * rhs.denominator - rhs.numerator, rhs.denominator); } Fraction Fraction::operator*(const int& rhs) const { return Fraction(numerator * rhs, denominator); } Fraction Fraction::operator*(const Fraction& rhs) const { return Fraction(numerator * rhs.numerator, denominator * rhs.denominator); } Fraction operator*(const int& lhs, const Fraction& rhs) { return Fraction(lhs * rhs.numerator, rhs.denominator); } Fraction Fraction::operator/(const int& rhs) const { return Fraction(numerator, denominator * rhs); } Fraction Fraction::operator/(const Fraction& rhs) const { return Fraction(numerator * rhs.denominator, denominator * rhs.numerator); } Fraction operator/(const int& lhs, const Fraction& rhs) { return Fraction(lhs * rhs.denominator, rhs.numerator); } Fraction& Fraction::operator++() { numerator += denominator; return *this; } Fraction& Fraction::operator--() { numerator -= denominator; return *this; } Fraction& Fraction::operator+=(const int& rhs) { numerator += rhs * denominator; return *this; } Fraction& Fraction::operator+=(const Fraction& rhs) { numerator *= rhs.denominator; numerator += rhs.numerator * denominator; denominator *= rhs.denominator; return *this; } Fraction& Fraction::operator-=(const int& rhs) { numerator -= rhs * denominator; return *this; } Fraction& Fraction::operator-=(const Fraction& rhs) { numerator *= rhs.denominator; numerator -= rhs.numerator * denominator; denominator *= rhs.denominator; return *this; } Fraction& Fraction::operator*=(const int& rhs) { numerator *= rhs; return *this; } Fraction& Fraction::operator*=(const Fraction& rhs) { numerator *= rhs.numerator; denominator *= rhs.denominator; return *this; } Fraction& Fraction::operator/=(const int& rhs) { denominator *= rhs; return *this; } Fraction& Fraction::operator/=(const Fraction& rhs) { numerator *= rhs.denominator; denominator *= rhs.numerator; return *this; } Fraction& Fraction::operator=(const int& rhs) { numerator = rhs; denominator = 1; return *this; } Fraction& Fraction::operator=(const Fraction& rhs) { numerator = rhs.numerator; denominator = rhs.denominator; return *this; } bool Fraction::operator==(const Fraction& rhs) const { return numerator == rhs.numerator && denominator == rhs.denominator; } bool Fraction::operator!=(const Fraction& rhs) const { return !(*this == rhs); } bool Fraction::operator<(const Fraction& rhs) const { return numerator * rhs.denominator < rhs.numerator* denominator; } bool Fraction::operator>(const Fraction& rhs) const { return rhs < *this; } bool Fraction::operator<=(const Fraction& rhs) const { return !(rhs < *this); } bool Fraction::operator>=(const Fraction& rhs) const { return !(*this < rhs); } std::istream& operator>>(std::istream& is, Fraction& rhs) { char c; is >> rhs.numerator >> c >> rhs.denominator; return is; } std::ostream& operator<<(std::ostream& os, const Fraction& rhs) { if (rhs.denominator == 1) { os << rhs.numerator; } else { os << rhs.numerator << '/' << rhs.denominator; } return os; } void Fraction::Input(const char* format = "%d/%d") { scanf(format, &numerator, &denominator); } void Fraction::Output() const { if (denominator == 1) printf("%d", numerator); else printf("%d/%d", numerator, denominator); } //Tester int main() { #ifndef ONLINE_JUDGE freopen("1.in", "r", stdin); freopen("1.out", "w", stdout); freopen("1.err", "w", stderr); #endif //Why need a tester? Fraction f1; std::cout << f1 << std::endl; Fraction f2(1, 2); std::cout << f2 << std::endl; f1 += 3*f2; std::cout << f1 << std::endl; f1 *= 3; std::cout << f1 << std::endl; // 不想测试了,直接丢了个测试包,没错误就交了。 #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); fclose(stderr); #endif return 0; }
28.913043
110
0.6581
ljcbaby
7f1d64b5c6477e4471dd1ae240bc8ae2ad873e30
237
hpp
C++
WarbandServerQuery/WarbandServerQuery/Hook.hpp
RaJiska/WarbandServerQuery
713a96de139961357731a72aeb7737d922228a87
[ "BSD-3-Clause" ]
null
null
null
WarbandServerQuery/WarbandServerQuery/Hook.hpp
RaJiska/WarbandServerQuery
713a96de139961357731a72aeb7737d922228a87
[ "BSD-3-Clause" ]
null
null
null
WarbandServerQuery/WarbandServerQuery/Hook.hpp
RaJiska/WarbandServerQuery
713a96de139961357731a72aeb7737d922228a87
[ "BSD-3-Clause" ]
null
null
null
#pragma once #define FREEZE_REGS pushad #define RESTORE_REGS popad namespace Hook { extern "C" void playerJoined(void); extern "C" void playerLeft(void); extern "C" void chatMessageSent(void); extern "C" void logEntryAdded(void); }
19.75
39
0.755274
RaJiska
7f1e18dbc65aa06e989421bc45da00db3c78f00e
1,875
cpp
C++
cognitics/src/flt/RoadPath.cpp
mikedig/cdb-productivity-api
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
[ "MIT" ]
null
null
null
cognitics/src/flt/RoadPath.cpp
mikedig/cdb-productivity-api
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
[ "MIT" ]
null
null
null
cognitics/src/flt/RoadPath.cpp
mikedig/cdb-productivity-api
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
[ "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2019 Cognitics, Inc. 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 "flt/RoadPath.h" namespace flt { RoadPath::~RoadPath(void) { } RoadPath::RoadPath(void) { } int RoadPath::getRecordType(void) { return FLT_ROADPATH; } std::string RoadPath::getRecordName(void) { return "RoadPath"; } void RoadPath::bind(ccl::BindStream &bs, int length, int revision) { /* 4 */ bs.bind(id, 8); /* 12 */ bs.bind(RESERVED12); /* 16 */ bs.bind(path, 120); /* 136 */ bs.bind(speedLimit); /* 144 */ bs.bind(noPassing); /* 148 */ bs.bind(vertexNormalType); /* 152 */ bs.bind(RESERVED152, 480); } }
32.327586
77
0.637867
mikedig
7f222111754b99236b1426197335443c12e8cc97
11,258
cc
C++
build/X86_MESI_Two_Level/python/m5/internal/param_Sinic.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
build/X86_MESI_Two_Level/python/m5/internal/param_Sinic.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86_MESI_Two_Level/python/m5/internal/param_Sinic.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" namespace { const uint8_t data_m5_internal_param_Sinic[] = { 120,156,189,89,235,83,27,201,17,159,89,189,16,32,16,111, 99,131,89,159,141,45,223,157,225,30,229,228,146,115,92,241, 43,201,85,157,177,75,92,149,109,114,149,173,101,119,36,45, 72,187,170,221,1,172,43,72,85,130,43,201,215,124,203,31, 145,111,249,3,47,221,61,59,203,32,16,184,42,17,2,181, 70,61,61,61,51,221,191,238,233,89,121,44,125,45,195,251, 183,54,99,201,45,139,49,31,254,57,219,101,172,205,217,150, 197,184,176,152,63,195,118,10,44,90,100,220,47,176,15,140, 109,229,152,200,177,99,104,228,217,31,115,44,252,90,73,205, 102,82,165,243,164,42,208,1,186,71,216,110,158,88,22,235, 141,50,81,96,91,69,246,38,156,97,121,81,98,59,163,44, 42,49,14,175,16,102,126,219,171,178,116,196,8,219,42,131, 212,10,72,141,146,212,12,73,165,189,101,236,165,17,126,153, 249,163,236,3,172,124,140,249,99,180,138,113,230,143,83,163, 194,252,10,53,38,152,63,65,141,73,173,190,202,182,166,116, 123,218,104,207,24,237,89,163,61,103,180,231,141,246,130,209, 190,102,180,23,141,246,117,163,125,195,104,47,25,237,101,163, 125,211,104,175,24,109,219,104,223,162,246,36,19,83,44,248, 132,5,183,89,112,135,53,56,243,171,184,77,240,192,187,173, 85,38,242,44,184,203,182,238,50,1,255,171,236,152,131,59, 166,140,17,247,104,196,116,54,162,70,35,238,179,173,251,76, 192,127,77,141,24,97,155,181,57,128,75,240,51,188,106,28, 90,114,28,200,190,136,147,32,10,157,32,108,68,129,133,253, 37,36,8,46,15,73,14,222,69,120,63,67,148,197,140,32, 6,107,7,148,29,129,6,206,96,140,111,225,12,126,142,45, 30,113,252,18,228,216,33,52,242,172,65,29,65,62,149,56, 2,220,76,177,67,208,94,96,135,196,217,124,19,46,179,188, 44,18,48,166,8,24,170,27,6,99,55,192,130,193,178,11, 48,237,6,173,91,226,186,215,104,117,180,122,167,235,198,110, 199,217,12,194,192,171,225,194,101,25,87,223,233,70,177,108, 7,219,114,4,101,156,208,237,8,199,145,163,240,37,134,1, 50,144,176,99,153,135,175,59,81,16,74,220,94,59,145,113, 208,149,149,108,180,211,137,252,189,182,144,99,192,249,142,56, 47,226,56,138,107,104,143,58,18,137,164,187,219,148,184,186, 14,78,81,195,101,17,73,94,1,89,111,69,29,1,36,108, 246,246,214,155,162,243,240,65,163,183,190,189,23,180,253,245, 183,223,252,194,121,249,98,243,59,231,135,131,200,249,94,236, 139,246,122,183,39,65,116,189,243,112,29,86,36,226,208,5, 214,201,222,214,160,123,26,21,31,4,77,39,93,96,75,180, 187,34,198,253,38,19,56,41,31,231,51,252,38,207,241,41, 62,193,131,162,118,32,90,165,162,29,248,239,212,129,86,154, 38,192,135,60,117,168,197,142,168,129,94,170,161,3,209,111, 57,116,23,236,16,156,209,228,236,216,98,63,230,80,224,8, 104,30,162,218,206,156,55,171,162,90,169,42,177,35,240,112, 1,253,247,211,18,169,26,33,85,22,59,4,10,174,205,179, 35,72,29,32,10,44,160,59,101,22,77,48,14,95,130,50, 66,152,135,0,216,183,135,69,112,125,62,115,189,130,44,238, 198,15,98,52,119,29,209,90,27,213,220,40,89,235,186,178, 85,175,104,223,128,153,200,199,27,81,168,220,216,8,66,95, 187,85,1,163,17,180,1,24,117,180,33,105,35,177,118,228, 102,98,232,91,175,29,37,130,192,69,186,235,147,40,136,210, 141,46,169,193,89,113,61,52,216,23,137,135,64,2,128,41, 141,184,2,212,54,92,112,212,49,24,102,81,249,117,130,66, 21,192,80,4,40,212,0,10,170,181,100,85,248,36,223,8, 208,138,94,33,13,234,188,198,197,127,152,242,5,103,59,22, 69,226,33,229,0,144,6,143,81,36,30,82,156,99,239,231, 140,75,43,229,67,168,131,99,145,59,13,99,8,45,0,27, 144,125,132,129,75,126,68,247,23,24,224,81,249,26,48,164, 192,65,30,47,224,8,84,101,225,20,121,214,93,0,229,35, 8,131,67,150,226,229,56,7,120,128,21,65,248,66,86,0, 246,60,204,251,87,2,90,154,25,200,253,178,21,36,209,129, 138,106,108,83,122,216,132,112,121,221,123,181,189,35,60,153, 172,0,227,93,180,103,123,110,24,70,210,118,125,223,118,37, 68,253,246,158,20,137,45,35,123,53,169,161,11,235,215,53, 130,50,125,189,174,168,83,67,193,198,15,60,9,249,100,134, 190,80,72,38,66,2,0,90,145,159,0,31,135,54,133,172, 87,113,4,154,57,162,5,16,62,28,20,197,105,65,14,163, 246,137,94,129,202,46,69,13,153,68,180,27,148,176,188,182, 155,36,14,174,128,248,4,52,220,245,190,219,222,19,164,61, 1,125,176,32,108,170,53,12,57,15,93,195,109,232,93,211, 86,194,40,244,123,176,178,192,251,26,39,189,70,16,172,64, 30,170,240,121,120,151,249,28,47,1,16,75,124,193,242,242, 41,236,178,51,101,30,183,204,200,223,60,117,57,192,240,24, 178,71,205,162,224,167,221,32,108,235,159,98,11,7,215,239, 32,89,69,114,23,201,61,189,225,225,237,186,210,191,235,103, 56,147,69,91,245,114,233,166,178,120,114,78,197,211,132,17, 79,199,24,23,135,116,110,6,57,35,38,114,184,241,104,76, 71,17,197,28,56,26,98,14,133,41,122,224,56,53,177,143, 147,110,212,23,113,25,183,128,220,91,77,238,217,10,105,118, 203,77,236,48,58,129,183,141,157,42,133,33,184,235,75,104, 115,3,190,77,3,190,117,27,37,16,187,245,219,72,242,131, 140,126,255,42,141,222,84,70,255,61,206,52,158,226,107,130, 112,53,198,61,4,7,122,162,164,205,191,9,141,222,2,154, 223,180,251,2,28,112,111,194,37,56,179,200,246,120,108,85, 212,177,69,103,159,42,67,117,14,11,10,186,81,68,15,52, 114,108,62,61,141,18,60,46,186,113,244,190,103,71,13,91, 50,189,164,71,171,201,218,106,242,45,164,17,251,241,137,173, 211,148,17,139,46,134,188,74,1,104,17,25,132,240,29,85, 189,120,239,9,58,48,232,155,227,168,136,87,229,138,147,30, 68,224,22,242,131,165,253,64,57,15,106,22,76,117,67,118, 194,104,230,4,220,196,107,156,102,148,60,144,227,11,16,227, 134,253,241,157,67,251,35,180,254,206,168,44,229,236,111,12, 173,11,54,76,3,154,162,69,71,204,12,138,99,157,114,200, 207,61,125,172,52,18,172,52,65,64,168,116,43,116,168,164, 167,17,20,30,255,48,178,71,118,90,228,210,226,197,140,152, 124,22,49,228,154,143,58,17,242,167,131,6,205,14,209,133, 98,20,30,170,30,188,115,58,19,81,165,146,163,44,46,135, 231,151,17,53,129,131,107,121,119,226,21,204,187,203,124,214, 82,168,32,192,252,18,201,55,89,184,114,205,27,202,178,86, 250,19,165,113,60,56,42,203,188,197,185,243,180,218,201,18, 229,33,26,237,60,123,245,253,171,141,77,231,185,216,15,60, 65,197,43,190,240,180,123,138,48,249,10,26,2,46,127,156, 9,74,155,31,168,150,69,106,161,179,143,45,14,23,87,168, 17,62,208,197,85,221,79,235,170,70,32,136,234,55,165,8, 76,45,167,146,178,97,175,204,221,202,147,72,222,15,57,200, 208,153,143,218,110,103,219,119,31,239,225,36,56,147,167,131, 202,210,171,174,154,171,198,112,224,3,22,78,95,191,213,171, 223,31,114,245,249,8,116,102,171,38,228,251,145,71,89,224, 135,150,176,59,162,179,13,183,204,86,208,181,27,109,183,73, 190,200,165,187,122,165,119,37,201,153,70,176,82,174,72,240, 200,223,136,108,47,10,33,217,237,121,50,138,109,95,64,33, 47,124,251,129,77,153,210,14,18,219,221,134,94,215,147,10, 218,167,227,146,202,38,55,110,38,84,33,237,30,96,243,10, 156,233,192,141,58,128,42,241,128,101,101,130,58,20,40,161, 96,157,68,245,159,138,20,56,77,224,42,39,123,42,55,61, 65,242,16,201,58,51,143,216,225,249,239,215,202,1,44,65, 19,21,249,13,171,108,209,81,69,2,175,81,54,57,27,142, 127,226,31,17,142,34,207,182,10,58,40,139,40,41,74,120, 29,68,90,198,108,190,53,170,153,99,68,199,137,89,209,204, 9,162,147,196,172,106,230,20,209,105,98,206,104,230,44,209, 57,98,206,107,230,2,209,107,196,92,212,204,235,68,111,16, 115,73,51,151,137,222,36,230,138,102,218,68,111,17,243,19, 205,188,77,244,14,49,87,53,243,46,209,123,196,172,105,230, 125,162,159,18,243,51,205,252,156,232,3,98,174,177,244,177, 220,58,49,191,96,91,95,50,191,72,156,175,48,117,149,254, 199,212,69,25,224,10,98,255,207,255,207,140,85,255,205,21, 47,186,254,152,165,53,203,160,108,197,205,29,85,84,176,4, 92,215,233,100,234,13,181,1,186,243,79,159,14,29,199,139, 133,43,133,242,200,157,161,111,142,242,156,154,242,47,39,201, 39,43,210,10,122,31,191,203,246,113,76,21,90,111,150,28, 165,159,223,225,67,67,122,110,43,169,24,198,106,185,170,158, 208,209,198,29,43,45,152,89,102,128,98,102,0,124,68,18, 138,3,199,48,130,42,134,81,196,237,118,69,232,215,191,64, 233,47,153,89,212,146,204,144,61,143,201,245,159,44,171,150, 198,161,138,157,133,138,233,108,148,97,158,54,54,71,206,171, 102,129,53,124,55,18,70,255,165,49,90,195,19,227,228,236, 168,63,69,66,167,69,118,80,212,95,100,246,191,222,7,64, 95,180,221,158,227,69,221,30,94,164,46,234,134,154,141,10, 254,19,150,180,251,164,227,247,78,35,104,68,78,59,58,112, 58,110,188,75,42,47,21,66,197,104,190,254,14,121,107,192, 72,217,138,69,210,138,218,62,233,191,92,10,39,152,50,38, 200,122,228,141,179,99,59,238,251,19,115,92,212,143,90,199, 148,86,205,27,36,15,126,140,47,210,71,253,125,250,144,119, 102,111,50,221,65,43,104,182,78,44,124,185,148,182,192,153, 158,129,99,47,182,241,89,169,254,25,6,219,88,94,98,99, 121,142,141,13,158,92,234,147,223,15,98,185,231,182,29,184, 163,41,35,95,40,128,26,233,199,13,131,41,151,7,140,240, 162,189,80,146,206,139,37,80,105,197,80,74,92,185,216,55, 230,39,17,71,39,219,30,220,139,218,240,190,159,113,228,205, 193,178,193,79,130,212,93,34,130,58,39,76,157,196,150,183, 7,142,58,237,255,143,145,195,41,102,78,77,145,245,81,106, 165,179,15,146,135,144,194,204,254,20,250,233,195,38,95,64, 177,30,245,28,135,46,211,14,102,31,199,185,138,42,23,159, 216,29,161,114,188,169,67,149,203,139,80,231,206,241,1,127, 86,185,88,230,116,141,232,251,89,204,224,21,51,30,222,83, 212,149,191,151,212,145,67,174,79,171,123,90,153,99,254,210, 70,207,235,85,174,166,159,16,116,253,143,105,157,96,177,225, 118,212,35,97,234,79,31,24,37,234,208,164,159,43,112,194, 250,103,72,30,100,167,192,175,112,52,98,164,243,112,77,27, 97,77,25,225,133,108,137,24,46,214,79,93,240,160,69,34, 4,247,193,146,112,5,167,168,61,43,241,218,11,210,254,197, 65,253,127,136,18,57,104,116,16,165,163,175,157,219,191,217, 75,164,232,156,25,44,194,189,142,243,82,116,162,184,247,50, 242,5,197,191,217,255,4,66,188,238,134,77,1,118,198,107, 34,101,179,83,2,233,29,81,233,208,82,246,185,107,56,45, 59,96,35,208,169,126,89,160,71,30,103,251,159,181,35,111, 87,248,169,204,249,198,38,153,231,81,199,5,254,249,179,108, 6,122,150,169,190,126,63,198,81,115,125,220,68,196,129,219, 198,176,63,95,223,243,142,155,154,31,129,165,59,41,108,207, 65,10,194,212,100,168,155,98,118,216,159,126,98,67,104,143, 69,51,0,7,198,164,209,28,154,150,129,24,132,228,121,51, 211,152,3,175,32,19,168,167,45,234,201,234,99,122,144,250, 35,144,42,254,84,49,82,230,37,252,156,132,79,11,138,67, 43,199,71,249,4,47,192,103,21,62,167,172,241,106,57,95, 46,131,220,216,56,191,236,111,5,50,200,168,181,178,84,230, 255,5,164,119,248,185, }; EmbeddedPython embedded_m5_internal_param_Sinic( "m5/internal/param_Sinic.py", "/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/m5/internal/param_Sinic.py", "m5.internal.param_Sinic", data_m5_internal_param_Sinic, 2806, 8625); } // anonymous namespace
58.331606
86
0.66415
hoho20000000
7f22212f5e2ec007001beba181c38fdebf7c669a
1,885
cpp
C++
src/types/int4.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
src/types/int4.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
src/types/int4.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#include "chokoengine.hpp" CE_BEGIN_NAMESPACE Int4::Int4(int v) : x(v), y(v), z(v), w(v) {} Int4::Int4(int x, int y, int z, int w) : x(x), y(y), z(z), w(w) {} Int4::Int4(Int2 a, Int2 b) : x(a.x), y(a.y), z(b.y), w(b.y) {} Int4::Int4(Int3 v, int w) : x(v.x), y(v.y), z(v.z), w(w) {} Int4::operator Int2() const { return Int2(x, y); } Int4::operator Int3() const { return Int3(x, y, z); } Int4::operator Vec4() const { return Vec4(x, y, z, w); } int& Int4::operator [](const int i) { return (&x)[i]; } Int4 Int4::operator -() const { return Int4(-x, -y, -z, -w); } Int4 Int4::operator +(const Int4& rhs) const { return Int4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); } Int4 Int4::operator -(const Int4& rhs) const { return Int4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); } Int4 Int4::operator *(const Int4& rhs) const { return Int4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w); } Int4 Int4::operator /(const Int4& rhs) const { return Int4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w); } bool Int4::operator ==(const Int4& rhs) const { return (x == rhs.x) && (y == rhs.y) && (z == rhs.z) && (w == rhs.w); } bool Int4::operator !=(const Int4& rhs) const { return (x != rhs.x) || (y != rhs.y) || (z != rhs.z) || (w != rhs.w); } Int4& Int4::operator +=(const Int4& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; w += rhs.w; return *this; } Int4& Int4::operator -=(const Int4& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; w -= rhs.w; return *this; } Int4& Int4::operator *=(const Int4& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; w *= rhs.w; return *this; } Int4& Int4::operator /=(const Int4& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; w /= rhs.w; return *this; } std::string Int4::str() const { return "iVector(" + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ", " + std::to_string(w) + ")"; } CE_END_NAMESPACE
20.053191
82
0.542175
chokomancarr
7f291dff83e1ee6229a4bfdb777ed4afd59d5363
1,696
cpp
C++
Source/IO.cpp
nmford20/Emu
efadff34fbc6d1a328d6df4330b35c3d67d82e87
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/IO.cpp
nmford20/Emu
efadff34fbc6d1a328d6df4330b35c3d67d82e87
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/IO.cpp
nmford20/Emu
efadff34fbc6d1a328d6df4330b35c3d67d82e87
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <AMReX_MultiFabUtil.H> #include <AMReX_PlotFileUtil.H> #include "FlavoredNeutrinoContainer.H" #include "IO.H" #include "Evolve.H" using namespace amrex; void WritePlotFile (const amrex::MultiFab& state, const FlavoredNeutrinoContainer& neutrinos, const amrex::Geometry& geom, amrex::Real time, int step, int write_plot_particles) { BL_PROFILE("WritePlotFile()"); BoxArray grids = state.boxArray(); grids.convert(IntVect()); const DistributionMapping& dmap = state.DistributionMap(); const std::string& plotfilename = amrex::Concatenate("plt", step); amrex::Print() << " Writing plotfile " << plotfilename << "\n"; amrex::WriteSingleLevelPlotfile(plotfilename, state, GIdx::names, geom, time, step); if (write_plot_particles == 1) { auto neutrino_varnames = neutrinos.get_attribute_names(); neutrinos.Checkpoint(plotfilename, "neutrinos", true, neutrino_varnames); } } void RecoverParticles (const std::string& dir, FlavoredNeutrinoContainer& neutrinos, amrex::Real& time, int& step) { BL_PROFILE("RecoverParticles()"); // load the metadata from this plotfile PlotFileData plotfile(dir); // get the time at which to restart time = plotfile.time(); // get the time step at which to restart const int lev = 0; step = plotfile.levelStep(lev); // initialize our particle container from the plotfile std::string file("neutrinos"); neutrinos.Restart(dir, file); // print the step/time for the restart amrex::Print() << "Restarting after time step: " << step-1 << " t = " << time << " s. ct = " << PhysConst::c * time << " cm" << std::endl; }
28.266667
140
0.673349
nmford20
7f2c2d8cee060dbba37104726d6008d1b0fbbb5b
1,864
cpp
C++
luogu/P2622.cpp
Leon-Francis/AlgorithmPractice
bfff066da64ebbb00ecd33d94ebbe5bcc382867c
[ "MIT" ]
1
2020-10-07T12:03:12.000Z
2020-10-07T12:03:12.000Z
luogu/P2622.cpp
Leon-Francis/AlgorithmPractice
bfff066da64ebbb00ecd33d94ebbe5bcc382867c
[ "MIT" ]
null
null
null
luogu/P2622.cpp
Leon-Francis/AlgorithmPractice
bfff066da64ebbb00ecd33d94ebbe5bcc382867c
[ "MIT" ]
null
null
null
/*** * @Author: Leon-Francis * @Date: 2021-04-14 21:46:51 * @Contact: leon_francis@163.com * @LastEditTime: 2021-04-14 22:58:22 * @LastEditors: Leon-Francis * @Description: 状压dp:关灯问题Ⅱ * @FilePath: /AlgorithmPractice/luogu/P2622.cpp * @(C)Copyright 2020-2021, Leon-Francis */ #include <iostream> #include <queue> #include <vector> using namespace std; int N, M; int swi[101][11]; queue<pair<int, int>> wait; vector<int> already; int change(int ori, int num) { int and_op = 0; int or_op = 0; for (int i = 0; i < N; i++) { if (swi[num][i] == 0) { and_op += (1 << i); } if (swi[num][i] == -1) { or_op += (1 << i); and_op += (1 << i); } } return (ori & and_op) | or_op; } bool is_in(int x) { for (int i = 0; i < already.size(); i++) { if (already[i] == x) { return true; } } return false; } int bfs() { if (wait.empty()) { return -1; } int now = wait.front().first; int now_num = wait.front().second; wait.pop(); for (int i = 0; i < M; i++) { int temp = change(now, i); if (temp == 0) { return now_num + 1; } else if (!is_in(temp)) { wait.push(pair<int, int>(temp, now_num + 1)); already.push_back(temp); } } return bfs(); } int main() { cin >> N >> M; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { cin >> swi[i][j]; } } int ori_lab = 1; int temp = 1; for (int i = 0; i < N; i++) { temp *= 2; ori_lab = temp - 1; } wait.push(pair<int, int>(ori_lab, 0)); already.push_back(ori_lab); cout << bfs() << endl; return 0; } // AC!!!!!!!!!!Yeah
18.828283
57
0.45279
Leon-Francis
7f2ca2b4bbcbf04c6d07dc102c2100ccf15451da
716
hpp
C++
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/MaterialMetalBridge.hpp
MonsterENT/EiRas
b29592da60b1a9085f5a2d8fa4ed01b43660f712
[ "MIT" ]
1
2019-12-24T10:12:16.000Z
2019-12-24T10:12:16.000Z
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/MaterialMetalBridge.hpp
MonsterENT/EiRas
b29592da60b1a9085f5a2d8fa4ed01b43660f712
[ "MIT" ]
null
null
null
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/MaterialMetalBridge.hpp
MonsterENT/EiRas
b29592da60b1a9085f5a2d8fa4ed01b43660f712
[ "MIT" ]
null
null
null
// // MaterialMetalBridge.hpp // EiRasMetalBuild // // Created by MonsterENT on 11/13/19. // Copyright © 2019 MonsterENT. All rights reserved. // #ifndef MaterialMetalBridge_hpp #define MaterialMetalBridge_hpp #include <Global/PlatformDependency/EiRasPlatformBridgeProtocol.h> #include <string> namespace Graphics { class GraphicsRenderState; } namespace MaterialSys { class Shader; class MaterialProp; class MaterialMetalBridge : public EiRasPlatformBridgeProtocol { public: MaterialMetalBridge(std::string name); void SetProperty(MaterialProp* prop, void* res); void UpdateRenderState(Graphics::GraphicsRenderState* renderState, Shader* shaderObj); }; } #endif /* MaterialMetalBridge_hpp */
21.058824
90
0.77933
MonsterENT
b52a337cc9972c676c2bd8b348128247c8b4b7af
1,231
cpp
C++
10423.cpp
programmer-k/Baekjoon-Online-Judge-Submission
f4ea98b7e3cd101250de9e495982f218e80c37fb
[ "Apache-2.0" ]
null
null
null
10423.cpp
programmer-k/Baekjoon-Online-Judge-Submission
f4ea98b7e3cd101250de9e495982f218e80c37fb
[ "Apache-2.0" ]
null
null
null
10423.cpp
programmer-k/Baekjoon-Online-Judge-Submission
f4ea98b7e3cd101250de9e495982f218e80c37fb
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; struct go { int x; int y; int z; }; typedef pair<int, pair<int, int> > pa; int n, m, k; int visit[1010]; vector<int> elc; vector<go> v; int parent[1010]; int Find(int x) { if (parent[x] == x) return x; return parent[x] = Find(parent[x]); } void Union(int x, int y) { x = Find(x); y = Find(y); if (x != y) parent[x] = y; } bool com(go a, go b) { if (a.z < b.z) return true; return false; } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < k; i++) { int x; scanf("%d", &x); elc.push_back(x); } for (int i = 1; i <= n; i++) { parent[i] = i; } priority_queue<pa, vector<pa>, greater<>> q; for (int i = 0; i < m; i++) { int x, y, z; scanf("%d%d%d", &x, &y, &z); v.push_back({ x,y,z }); } for (int i = 0; i < k - 1; i++) { int now = elc[i]; int next = elc[i + 1]; Union(now, next); } int ans = 0; sort(v.begin(), v.end(), com); for (int i = 0; i < v.size(); i++) { int now = v[i].x; int next = v[i].y; int dist = v[i].z; if (Find(now) != Find(next)) { ans += dist; Union(now, next); k++; } if (k == n) break; } cout << ans << endl; return 0; }
15.012195
45
0.509342
programmer-k
b52bd916c704fe938d1a91bfde963719d1de6501
620
cpp
C++
Ruken/Source/Src/Resource/Exceptions/ResourceProcessingFailure.cpp
Renondedju/Daemon
8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6
[ "MIT" ]
4
2020-06-11T00:35:03.000Z
2020-06-23T11:57:52.000Z
Ruken/Source/Src/Resource/Exceptions/ResourceProcessingFailure.cpp
Renondedju/Daemon
8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6
[ "MIT" ]
1
2020-03-17T13:34:16.000Z
2020-03-17T13:34:16.000Z
Ruken/Source/Src/Resource/Exceptions/ResourceProcessingFailure.cpp
Renondedju/Daemon
8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6
[ "MIT" ]
2
2020-03-19T12:20:17.000Z
2020-09-03T07:49:06.000Z
#include "Resource/ResourceProcessingFailure.hpp" USING_RUKEN_NAMESPACE ResourceProcessingFailure::ResourceProcessingFailure(EResourceProcessingFailureCode const in_code, RkBool const in_validity, RkChar const* in_description) noexcept: std::exception {in_description}, description {in_description}, resource_validity {in_validity}, code {in_code} {} ResourceProcessingFailure::operator std::string() const noexcept { return EnumToString(code) + ": " + description; } char const* ResourceProcessingFailure::what() const { return std::exception::what(); }
28.181818
164
0.732258
Renondedju
b52cdf5e8ef2ec0e126217e625965bcb15a82502
1,724
inl
C++
cusp/graph/detail/symmetric_rcm.inl
Raman-sh/cusplibrary
99dcde05991ef59cbc4546aeced6eb3bd49c90c9
[ "Apache-2.0" ]
270
2015-01-12T19:40:50.000Z
2022-03-28T00:58:21.000Z
cusp/graph/detail/symmetric_rcm.inl
njh19/cusplibrary
4f72f152804dee592fec86719049af2b5469295a
[ "Apache-2.0" ]
41
2015-01-08T18:07:42.000Z
2022-02-27T02:37:38.000Z
cusp/graph/detail/symmetric_rcm.inl
njh19/cusplibrary
4f72f152804dee592fec86719049af2b5469295a
[ "Apache-2.0" ]
106
2015-02-27T19:30:58.000Z
2022-03-29T13:55:53.000Z
/* * Copyright 2008-2014 NVIDIA 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 <cusp/detail/config.h> #include <thrust/system/detail/generic/select_system.h> #include <cusp/system/detail/adl/graph/symmetric_rcm.h> #include <cusp/system/detail/generic/graph/symmetric_rcm.h> namespace cusp { namespace graph { template <typename DerivedPolicy, typename MatrixType, typename PermutationType> void symmetric_rcm(const thrust::detail::execution_policy_base<DerivedPolicy>& exec, const MatrixType& G, PermutationType& P) { using cusp::system::detail::generic::symmetric_rcm; return symmetric_rcm(thrust::detail::derived_cast(thrust::detail::strip_const(exec)), G, P); } template<typename MatrixType, typename PermutationType> void symmetric_rcm(const MatrixType& G, PermutationType& P) { using thrust::system::detail::generic::select_system; typedef typename MatrixType::memory_space System1; typedef typename PermutationType::memory_space System2; System1 system1; System2 system2; cusp::graph::symmetric_rcm(select_system(system1,system2), G, P); } } // end namespace graph } // end namespace cusp
31.345455
96
0.738979
Raman-sh
b530c0f6bfd4ed95b5ac2581a25863a675307152
4,889
cpp
C++
src/Core/City.cpp
Lecrapouille/OpenGlassBox
664299285ca231e54fab5a7c8c63292bd39c755d
[ "MIT" ]
4
2020-10-14T01:42:56.000Z
2022-03-03T22:30:56.000Z
src/Core/City.cpp
Lecrapouille/OpenGlassBox
664299285ca231e54fab5a7c8c63292bd39c755d
[ "MIT" ]
null
null
null
src/Core/City.cpp
Lecrapouille/OpenGlassBox
664299285ca231e54fab5a7c8c63292bd39c755d
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) 2020 Quentin Quadrat. // https://github.com/Lecrapouille/OpenGlassBox // Based on https://github.com/federicodangelo/MultiAgentSimulation // Distributed under MIT License. //----------------------------------------------------------------------------- #include "Core/City.hpp" #include "Config.hpp" // ----------------------------------------------------------------------------- City::City(std::string const& name, Vector3f position, uint32_t gridSizeU, uint32_t gridSizeV) : m_name(name), m_position(position), m_gridSizeU(gridSizeU), m_gridSizeV(gridSizeV) { static City::Listener listener; setListener(listener); } // ----------------------------------------------------------------------------- City::City(std::string const& name, uint32_t gridSizeU, uint32_t gridSizeV) : City(name, Vector3f(0.0f, 0.0f, 0.0f), gridSizeU, gridSizeV) {} // ----------------------------------------------------------------------------- City::City(std::string const& name) : City(name, Vector3f(0.0f, 0.0f, 0.0f), 32u, 32u) {} // ----------------------------------------------------------------------------- void City::setListener(City::Listener& listener) { m_listener = &listener; } // ----------------------------------------------------------------------------- void City::update() { // Start from the last element for easy removing of the Agent size_t i = m_agents.size(); while (i--) { if (m_agents[i]->update(m_dijkstra)) { // Swap the position of the Agent with the last in the vector and // remove the last element of the vector. std::swap(m_agents[i], m_agents[m_agents.size() - 1u]); m_agents.pop_back(); } } i = m_units.size(); while (i--) { m_units[i]->executeRules(); } for (auto& map: m_maps) { map.second->executeRules(); } } // ----------------------------------------------------------------------------- // Since Units are attached to a Path Node // They are directly translated. void City::translate(Vector3f const direction) { m_position += direction; for (auto& it: m_maps) { it.second->translate(direction); } for (auto& it: m_paths) { it.second->translate(direction); } for (auto& it: m_agents) { it->translate(direction); } } // ----------------------------------------------------------------------------- void City::world2mapPosition(Vector3f worldPos, uint32_t& u, uint32_t& v) { float x = (worldPos.x - m_position.x) / config::GRID_SIZE; float y = (worldPos.y - m_position.y) / config::GRID_SIZE; if (x < 0.0f) u = 0u; else if (uint32_t(x) >= m_gridSizeU) u = m_gridSizeU - 1u; else u = uint32_t(x); if (y < 0.0f) v = 0u; else if (uint32_t(y) >= m_gridSizeV) v = m_gridSizeV - 1u; else v = uint32_t(y); } // ----------------------------------------------------------------------------- Map& City::addMap(MapType const& type) { Map& map = *(m_maps[type.name] = std::make_unique<Map>(type, *this)); m_listener->onMapAdded(map); return map; } // ----------------------------------------------------------------------------- Map& City::getMap(std::string const& id) { return *m_maps.at(id); } // ----------------------------------------------------------------------------- Path& City::addPath(PathType const& type) { Path& path = *(m_paths[type.name] = std::make_unique<Path>(type)); m_listener->onPathAdded(path); return path; } // ----------------------------------------------------------------------------- Path& City::getPath(std::string const& id) { return *m_paths.at(id); } // ----------------------------------------------------------------------------- Unit& City::addUnit(UnitType const& type, Node& node) { m_units.push_back(std::make_unique<Unit>(/*m_nextUnitId++,*/ type, node, *this)); Unit& unit = *(m_units.back()); m_listener->onUnitAdded(unit); return unit; } // ----------------------------------------------------------------------------- Unit& City::addUnit(UnitType const& type, Path& path, Way& way, float offset) { Node& newNode = path.splitWay(way, offset); return addUnit(type, newNode); } // ----------------------------------------------------------------------------- Agent& City::addAgent(AgentType const& type, Unit& owner, Resources const& resources, std::string const& searchTarget) { m_agents.push_back(std::make_unique<Agent>(m_nextAgentId++, type, owner, resources, searchTarget)); Agent& agent = *(m_agents.back()); m_listener->onAgentAdded(agent); return agent; }
30.179012
94
0.45449
Lecrapouille
b532581a6d06704a1db83b154026633c959684f0
1,785
hh
C++
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/PCXLate/Headers/Translater.hh
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/PCXLate/Headers/Translater.hh
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/PCXLate/Headers/Translater.hh
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */ #ifndef __Translater__ #define __Translater__ /* * $Header: /fuji/lewis/RCS/Translater.hh,v 1.3 1992/09/26 22:24:08 lewis Exp $ * * Description: * * A Translater is a wrapper on the C++ lexer that takes an input file, and * goes over each token in-turn, and passes it to a virtual method (HandleToken), and * this, by default, just writes the token to the output stream. But, you could do * some mapping action, or build a data structure sumarizing what you've seen * go by for later consumption. * * The dstFile in Translater::TranslateFile (const PathName& srcFile, const PathName& dstFile); * is allowed to be a badpathname, in which case output is ignored/not done. * * * * TODO: * * Notes: * * Changes: * $Log: Translater.hh,v $ * Revision 1.3 1992/09/26 22:24:08 lewis * Ported to A/UX and gcc 2.2.1. * * * * */ #include "Config-Foundation.hh" #include "CPlusLexer.hh" class istream; class ostream; class PathName; class Translater { public: Translater (); nonvirtual void TranslateFile (const PathName& srcFile, const PathName& dstFile); protected: virtual void HandleToken (const Token& t); nonvirtual void _HandleToken (const Token& t); nonvirtual istream& _GetIn () const; nonvirtual ostream& _GetOut () const; private: istream* fInFile; ostream* fOutFile; }; /* ******************************************************************************** ************************************ InLines *********************************** ******************************************************************************** */ // For gnuemacs: // Local Variables: *** // mode:C++ *** // tab-width:4 *** // End: *** #endif /*__Translater__*/
22.3125
97
0.592157
SophistSolutions
b5326cc2d376801751e37350f9675517d9a8eb6f
5,060
cpp
C++
src/web_server/session/handle_request/handle_request.cpp
X-rays5/web_server
c14e2c8e6e53797d2179cb5985a135e34173b3b9
[ "MIT" ]
2
2021-09-16T03:22:45.000Z
2021-11-09T11:45:07.000Z
src/web_server/session/handle_request/handle_request.cpp
X-rays5/web_server
c14e2c8e6e53797d2179cb5985a135e34173b3b9
[ "MIT" ]
null
null
null
src/web_server/session/handle_request/handle_request.cpp
X-rays5/web_server
c14e2c8e6e53797d2179cb5985a135e34173b3b9
[ "MIT" ]
null
null
null
// // Created by X-ray on 6/8/2021. // #pragma once #include "handle_request.hpp" namespace web_server { namespace session { namespace handle_request { std::string ErrorResponse(std::string title, std::string what, int error_code) { std::string body = "<!doctype html>\n<html>\n<head>\n<title>"+std::to_string(error_code)+" "+title+"</title>\n</head>\n<body>\n<h1>"+std::to_string(error_code)+" "+title+"</h1>\n<hr>\n<p>"+what+"</p>\n<hr>\n<p><i>Server: Boost.Beast/"+std::to_string(BOOST_BEAST_VERSION)+" Error: "+std::to_string(error_code)+"</i></p>\n</body>\n</html>\n"; return body; } std::map<std::string, std::string> ParseUrlParameters(std::string url) { if (url.find('?') != std::string::npos) { std::map<std::string, std::string> parameters; std::string parameterstring = url.substr(url.find('?') + 1, url.size()); while (parameterstring.find('=') != std::string::npos) { int ispos = parameterstring.find('='); int nextpos = parameterstring.find('&'); if (nextpos == std::string::npos) nextpos = parameterstring.size(); std::string kv = parameterstring.substr(0, nextpos); parameters.insert({kv.substr(0, ispos), kv.substr(ispos + 1, kv.size() - 1)}); if (nextpos != std::string::npos) { parameterstring.erase(0, nextpos + 1); } else { return parameters; } } return parameters; } else { return std::map<std::string, std::string>{}; } } boost::beast::http::message<false, boost::beast::http::basic_string_body<char>> handle_tools::HandleError(http_status status, std::string error) { auto handler = error_handlers.find(status); if (handler != error_handlers.end()) { return std::invoke(handler->second, error); } else { responsebuilder res(http_status::internal_server_error, "text/html"); res.SetBody(ErrorResponse("Internal Server Error", "Unable to handle error with code: " + std::to_string(static_cast<int>(status)), static_cast<int>(http_status::internal_server_error))); std::cout << "Unknown error occurred: " << static_cast<int>(status) << "\n"; return res.GetStringResponse(); } } void handle_tools::AddErrorHandler(http_status status, handle_tools::error_handler_t handler) { error_handlers[status] = std::move(handler); } void handle::RegisterErrorHandlers() { tools_.AddErrorHandler(http_status::bad_request, [=](std::string error) { responsebuilder res(http_status::bad_request, "text/html"); res.SetBody(ErrorResponse("Bad Request", std::move(error), static_cast<int>(http_status::bad_request))); return res.GetStringResponse(); }); tools_.AddErrorHandler(http_status::not_found, [=](std::string error) { responsebuilder res(http_status::not_found, "text/html"); res.SetBody(ErrorResponse("Not Found", std::move(error), static_cast<int>(http_status::not_found))); return res.GetStringResponse(); }); tools_.AddErrorHandler(http_status::internal_server_error, [=](std::string error) { responsebuilder res(http_status::internal_server_error, "text/html"); res.SetBody(ErrorResponse("Internal Server Error", std::move(error), static_cast<int>(http_status::internal_server_error))); return res.GetStringResponse(); }); tools_.AddErrorHandler(http_status::service_unavailable, [=](std::string error) { responsebuilder res(http_status::service_unavailable, "text/html"); res.SetBody(ErrorResponse("Service unavailable", std::move(error), static_cast<int>(http_status::service_unavailable))); return res.GetStringResponse(); }); tools_.AddErrorHandler(http_status::Im_a_teapot, [=](std::string error) { responsebuilder res(http_status::Im_a_teapot, "text/html"); res.SetBody(ErrorResponse("I'm a teapot", "I'm refusing to brew coffee because I'm, permanently, a teapot.", static_cast<int>(http_status::Im_a_teapot))); return res.GetStringResponse(); }); } } // handle_request } // session } // web_server
55
356
0.541897
X-rays5
b538d20a99fe761f63e38508824374a2fdf824b2
5,471
cpp
C++
Source/StdLib/ISCTYPE.cpp
FoxCutter/BootDebug
d40afa3a19d8a840788cbdb091cc121b01b36f7f
[ "BSD-2-Clause" ]
null
null
null
Source/StdLib/ISCTYPE.cpp
FoxCutter/BootDebug
d40afa3a19d8a840788cbdb091cc121b01b36f7f
[ "BSD-2-Clause" ]
1
2020-02-15T03:11:11.000Z
2020-02-15T03:11:11.000Z
Source/StdLib/ISCTYPE.cpp
FoxCutter/BootDebug
d40afa3a19d8a840788cbdb091cc121b01b36f7f
[ "BSD-2-Clause" ]
null
null
null
//========================================== // LIBCTINY - Matt Pietrek 2001 // MSDN Magazine, January 2001 //========================================== #include <ctype.h> const unsigned short pctype[256] = { _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _SPACE | _CONTROL, _SPACE | _CONTROL, _SPACE | _CONTROL, _SPACE | _CONTROL, _SPACE | _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _CONTROL, _SPACE | _BLANK, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _DIGIT | _HEX, // 0 _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, _DIGIT | _HEX, // 9 _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _UPPER | _HEX, // A _UPPER | _HEX, _UPPER | _HEX, _UPPER | _HEX, _UPPER | _HEX, _UPPER | _HEX, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, _UPPER, // Z _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _PUNCT, _LOWER | _HEX, // a _LOWER | _HEX, _LOWER | _HEX, _LOWER | _HEX, _LOWER | _HEX, _LOWER | _HEX, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, _LOWER, // z _PUNCT, _PUNCT, _PUNCT, _PUNCT, _CONTROL, }; extern "C" int __cdecl _isctype ( int c , int mask ) { /* c valid between -1 and 255 */ if (((unsigned)(c + 1)) <= 256) { return ( pctype[c] & mask ) ; } else return 0; } extern "C" int __cdecl toupper ( int c ) { if ( (c >= 'a') && (c <= 'z') ) c = c - ('a' - 'A'); return c; } extern "C" int __cdecl tolower ( int c ) { if ( (c >= 'A') && (c <= 'Z') ) c = c + ('a' - 'A'); return c; } extern "C" int __cdecl isalpha ( int c ) { return _isctype(c, _ALPHA); } extern "C" int __cdecl isupper ( int c ) { return _isctype(c, _UPPER); } extern "C" int __cdecl islower ( int c ) { return _isctype(c, _LOWER); } extern "C" int __cdecl isdigit ( int c ) { return _isctype(c, _DIGIT); } extern "C" int __cdecl isxdigit ( int c ) { return _isctype(c, _HEX); } extern "C" int __cdecl isspace ( int c ) { return _isctype(c, _SPACE); } extern "C" int __cdecl ispunct ( int c ) { return _isctype(c, _PUNCT); } extern "C" int __cdecl isalnum ( int c ) { return _isctype(c, _ALPHA | _DIGIT); } extern "C" int __cdecl isprint ( int c ) { return _isctype(c, _BLANK | _PUNCT| _ALPHA| _DIGIT); } extern "C" int __cdecl isgraph ( int c ) { return _isctype(c, _PUNCT| _ALPHA| _DIGIT); } extern "C" int __cdecl iscntrl ( int c ) { return _isctype(c, _CONTROL); }
24.981735
53
0.331749
FoxCutter
b53abd29cb90ede0c6d3a8f2895d511461da93cc
268
cpp
C++
src/DisplayHandler.cpp
ustisha/ArduinoComponents
9090a9408669c5ae9bd26ab66e7c916f9a459379
[ "MIT" ]
null
null
null
src/DisplayHandler.cpp
ustisha/ArduinoComponents
9090a9408669c5ae9bd26ab66e7c916f9a459379
[ "MIT" ]
null
null
null
src/DisplayHandler.cpp
ustisha/ArduinoComponents
9090a9408669c5ae9bd26ab66e7c916f9a459379
[ "MIT" ]
null
null
null
#include "../include/DisplayHandler.h" #include <../include/DisplayView.h> void DisplayHandler::addDisplayHandler(DisplayView *view) { displayView = view; } void DisplayHandler::render() { if (displayView != nullptr) { displayView->render(); } }
20.615385
59
0.675373
ustisha