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
2be19475ad2ab5415710e71a0674f69bf112b811
414
cpp
C++
string/reverse_str.cpp
Nilesh-Das/mustdogfg
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
[ "MIT" ]
null
null
null
string/reverse_str.cpp
Nilesh-Das/mustdogfg
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
[ "MIT" ]
null
null
null
string/reverse_str.cpp
Nilesh-Das/mustdogfg
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); char s[] = "nilesh"; int n = sizeof(s) / sizeof(s[0]); // n i l e s h \0 // | | // p q char *p = s; char *q = s+n-2; for(int i=0; i<n/2; i++) { char tmp = *p; *p = *q; *q = tmp; p++, q--; } cout << s << '\n'; return 0; }
12.9375
35
0.437198
Nilesh-Das
2be4c5c6a09c112e30d6970ea523b989fcfff30f
2,164
cpp
C++
CppSprtPkg/Library/CppSprtLib.cpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
CppSprtPkg/Library/CppSprtLib.cpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
CppSprtPkg/Library/CppSprtLib.cpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
/* ## @file # # Copyright (c) 2018 Loongson Technology Corporation Limited (www.loongson.cn). # All intellectual property rights(Copyright, Patent and Trademark) reserved. # # Any violations of copyright or other intellectual property rights of the Loongson Technology # Corporation Limited will be held accountable in accordance with the law, # if you (or any of your subsidiaries, corporate affiliates or agents) initiate # directly or indirectly any Intellectual Property Assertion or Intellectual Property Litigation: # (i) against Loongson Technology Corporation Limited or any of its subsidiaries or corporate affiliates, # (ii) against any party if such Intellectual Property Assertion or Intellectual Property Litigation arises # in whole or in part from any software, technology, product or service of Loongson Technology Corporation # Limited or any of its subsidiaries or corporate affiliates, or (iii) against any party relating to the Software. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR # 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). # # ## */ extern"C" { #include <Uefi.h> #include <Library/UefiBootServicesTableLib.h> } #undef NULL #define NULL 0 VOID *operator new(UINTN Size) throw() { VOID *RetVal; EFI_STATUS Status; if (Size == 0) { return NULL; } Status = gBS->AllocatePool(EfiLoaderData, (UINTN)Size, &RetVal); if (Status != EFI_SUCCESS) { RetVal = NULL; } return RetVal; } VOID *operator new[](UINTN cb) { VOID *res = operator new(cb); return res; } VOID operator delete(VOID *p) { if (p != NULL) { (VOID)gBS->FreePool(p); } } VOID operator delete[](VOID *p) { operator delete(p); } extern "C" VOID _Unwind_Resume(struct _Unwind_Exception *object) { } #include "CppCrt.cpp"
28.853333
127
0.738447
lvjianmin-loongson
2bede9ee1af5420271b4f1026fd3a0a900f59688
1,911
hpp
C++
src/autonomy/compiler/translator_exceptions.hpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
2
2015-05-31T20:26:51.000Z
2022-02-19T16:11:14.000Z
src/autonomy/compiler/translator_exceptions.hpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
null
null
null
src/autonomy/compiler/translator_exceptions.hpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
null
null
null
//! \file translator_exceptions.hpp //! \brief Exception classes that may be thrown by the translator. #ifndef AUTONOMY_COMPILER_TRANSLATOR_EXCEPTIONS_HPP #define AUTONOMY_COMPILER_TRANSLATOR_EXCEPTIONS_HPP #include <string> #include <exception> #include <autonomy/compiler/parser_ids.hpp> namespace autonomy { namespace compiler { //! \class translator_exception //! \brief Generic translator exception. class translator_exception : public std::exception { public: translator_exception(std::string const& msg); ~translator_exception() throw () {} virtual const char* what() const throw (); private: std::string _msg; }; //! \class corrupted_parse_tree //! \brief Exception for parse trees recognized as malformed. class corrupted_parse_tree : public translator_exception { public: corrupted_parse_tree(parser_id_t at_node, parser_id_t prev_node); ~corrupted_parse_tree() throw () {} }; //! \class undeclared_variable //! \brief Thrown when attempting to reference an undeclared variable. class undeclared_variable : public translator_exception { public: undeclared_variable(std::string const& symbol); ~undeclared_variable() throw () {} }; //! \class undefined_command //! \brief Thrown when attempting to access an unavailable command. class undefined_command : public translator_exception { public: undefined_command(std::string const& symbol); ~undefined_command() throw () {} }; } } #endif
27.3
81
0.574568
medlefsen
2bf728489b29051f8a13d5dd8d4c4903026421c8
3,332
hpp
C++
Vals.hpp
Galenika/csgo-offsets-finder
5fd13006bb5fe58bed4f0a35a99142fe5a279c72
[ "MIT" ]
2
2021-02-26T08:03:30.000Z
2021-07-14T23:28:41.000Z
Vals.hpp
RequestFX/csgo-offsets-finder
5fd13006bb5fe58bed4f0a35a99142fe5a279c72
[ "MIT" ]
null
null
null
Vals.hpp
RequestFX/csgo-offsets-finder
5fd13006bb5fe58bed4f0a35a99142fe5a279c72
[ "MIT" ]
4
2021-02-03T20:08:55.000Z
2021-07-06T17:13:14.000Z
// Made by RequestFX#1541 #pragma once namespace vals { namespace signatures { static long anim_overlays, clientstate_choked_commands, clientstate_delta_ticks, clientstate_last_outgoing_command, clientstate_net_channel, convar_name_hash_table, dwClientState, dwClientState_GetLocalPlayer, dwClientState_IsHLTV, dwClientState_Map, dwClientState_MapDirectory, dwClientState_MaxPlayer, dwClientState_PlayerInfo, dwClientState_State, dwClientState_ViewAngles, dwEntityList, dwForceAttack, dwForceAttack2, dwForceBackward, dwForceForward, dwForceJump, dwForceLeft, dwForceRight, dwGameDir, dwGameRulesProxy, dwGetAllClasses, dwGlobalVars, dwGlowObjectManager, dwInput, dwInterfaceLinkList, dwLocalPlayer, dwMouseEnable, dwMouseEnablePtr, dwPlayerResource, dwRadarBase, dwSensitivity, dwSensitivityPtr, dwSetClanTag, dwViewMatrix, dwWeaponTable, dwWeaponTableIndex, dwYawPtr, dwZoomSensitivityRatioPtr, dwbSendPackets, dwppDirect3DDevice9, find_hud_element, force_update_spectator_glow, interface_engine_cvar, is_c4_owner, m_bDormant, m_flSpawnTime, m_pStudioHdr, m_pitchClassPtr, m_yawClassPtr, model_ambient_min, set_abs_angles, set_abs_origin; } namespace netvars { static long cs_gamerules_data, m_ArmorValue, m_Collision, m_CollisionGroup, m_Local, m_MoveType, m_OriginalOwnerXuidHigh, m_OriginalOwnerXuidLow, m_SurvivalGameRuleDecisionTypes, m_SurvivalRules, m_aimPunchAngle, m_aimPunchAngleVel, m_angEyeAnglesX, m_angEyeAnglesY, m_bBombPlanted, m_bFreezePeriod, m_bGunGameImmunity, m_bHasDefuser, m_bHasHelmet, m_bInReload, m_bIsDefusing, m_bIsQueuedMatchmaking, m_bIsScoped, m_bIsValveDS, m_bSpotted, m_bSpottedByMask, m_bStartedArming, m_bUseCustomAutoExposureMax, m_bUseCustomAutoExposureMin, m_bUseCustomBloomScale, m_clrRender, m_dwBoneMatrix, m_fAccuracyPenalty, m_fFlags, m_flC4Blow, m_flCustomAutoExposureMax, m_flCustomAutoExposureMin, m_flCustomBloomScale, m_flDefuseCountDown, m_flDefuseLength, m_flFallbackWear, m_flFlashDuration, m_flFlashMaxAlpha, m_flLastBoneSetupTime, m_flLowerBodyYawTarget, m_flNextAttack, m_flNextPrimaryAttack, m_flSimulationTime, m_flTimerLength, m_hActiveWeapon, m_hMyWeapons, m_hObserverTarget, m_hOwner, m_hOwnerEntity, m_hViewModel, m_iAccountID, m_iClip1, m_iCompetitiveRanking, m_iCompetitiveWins, m_iCrosshairId, m_iEntityQuality, m_iFOV, m_iFOVStart, m_iGlowIndex, m_iHealth, m_iItemDefinitionIndex, m_iItemIDHigh, m_iMostRecentModelBoneCounter, m_iObserverMode, m_iShotsFired, m_iState, m_iTeamNum, m_iViewModelIndex, m_lifeState, m_nFallbackPaintKit, m_nFallbackSeed, m_nFallbackStatTrak, m_nForceBone, m_nModelIndex, m_nTickBase, m_rgflCoordinateFrame, m_szCustomName, m_szLastPlaceName, m_thirdPersonViewAngles, m_vecOrigin, m_vecVelocity, m_vecViewOffset, m_viewPunchAngle; } }
21.088608
38
0.722689
Galenika
920480b3726dbde0caf825b1285953e6ea6970b6
3,370
cpp
C++
EZOJ/1976.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
BZOJ/2286.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/1976.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> #include <cctype> #include <algorithm> using namespace std; typedef long long lint; #define ni (next_num<int>()) #define nl (next_num<lint>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool flag=c=='-'; flag?(c=getchar()):0; while(i=i*10-'0'+c,isdigit(c=getchar())); return flag?-i:i; } inline void apmin(int &a,const int &b){ if(a>b){ a=b; } } const int N=250010,logN=20,INF=0x7f7f7f7f; struct Tree{ static const int E=N*2; int to[E],bro[E],val[E],head[N],etop; }; struct Virtual:Tree{ Virtual(){ memset(tag,0,sizeof(tag)); memset(vis,0,sizeof(vis)); tim=0; } int tag[N],tim; inline void add_edge(int,int); int vis[N]; lint f[N]; void dfs(int x){ f[x]=0; for(int i=head[x],v;~i;i=bro[i]){ if(vis[v=to[i]]==tim){ f[x]+=val[i]; }else{ dfs(v); f[x]+=min(f[v],(lint)val[i]); } } } }V; int dfn[N]; inline bool dfncmp(const int &a,const int &b){ return dfn[a]<dfn[b]; } struct Actual:Tree{ int fa[N][logN],len[N][logN],dep[N],ldep[N]; inline void reset(){ memset(head,-1,sizeof(head)); memset(len,127,sizeof(len)); memset(fa,0,sizeof(fa)); etop=tim=dep[1]=ldep[1]=0; dep[0]=-1; } inline void add_edge(int u,int v,int w){ to[etop]=v; bro[etop]=head[u]; val[etop]=w; head[u]=etop++; } int tim; void dfs(int x,int f){ dfn[x]=++tim; fa[x][0]=f; for(int &j=ldep[x];fa[x][j+1]=fa[fa[x][j]][j];j++){ len[x][j+1]=min(len[x][j],len[fa[x][j]][j]); } for(int i=head[x],v;~i;i=bro[i]){ v=to[i]; if(v!=f){ dep[v]=dep[x]+1; len[v][0]=val[i]; dfs(v,x); } } } inline int lca(int u,int v){ if(dep[u]<dep[v]){ swap(u,v); } for(int j=ldep[u];j>=0;j--){ if(dep[fa[u][j]]>=dep[v]){ u=fa[u][j]; } } if(u==v){ return u; } for(int j=min(ldep[u],ldep[v]);j>=0;j--){ if(fa[u][j]!=fa[v][j]){ u=fa[u][j],v=fa[v][j]; } } assert(fa[u][0]==fa[v][0]); return fa[u][0]; } inline int dist(int u,int v){ int ans=INF; if(dep[u]<dep[v]){ swap(u,v); } for(int j=ldep[u];j>=0;j--){ if(dep[fa[u][j]]>=dep[v]){ apmin(ans,len[u][j]); u=fa[u][j]; } } if(u==v){ return ans; } for(int j=min(ldep[u],ldep[v]);j>=0;j--){ if(fa[u][j]!=fa[v][j]){ apmin(ans,min(len[u][j],len[v][j])); u=fa[u][j],v=fa[v][j]; } } assert(fa[u][0]==fa[v][0]); return ans; } int seq[N],stk[N]; inline lint work(int n){ V.tim++; V.etop=0; for(int i=0;i<n;i++){ V.vis[seq[i]=ni]=V.tim; } sort(seq,seq+n,dfncmp); int stop=0; stk[++stop]=1; for(int i=0;i<n;i++){ int x=seq[i],f=x; for(int v=stk[stop];v!=f&&dep[f=lca(x,v)]<dep[v];v=stk[stop]){ if(dep[f]>dep[stk[--stop]]){ stk[++stop]=f; } V.add_edge(stk[stop],v); } assert(stk[stop]==f); assert(stk[stop]!=x); stk[++stop]=x; } for(;stop>1;stop--){ V.add_edge(stk[stop-1],stk[stop]); } V.dfs(1); return V.f[1]; } }T; inline void Virtual::add_edge(int u,int v){ if(tag[u]<tim){ tag[u]=tim; head[u]=-1; } to[etop]=v; bro[etop]=head[u]; val[etop]=T.dist(u,v); head[u]=etop++; } int main(){ T.reset(); int n=ni; for(int i=1;i<n;i++){ int u=ni,v=ni,w=ni; T.add_edge(u,v,w); T.add_edge(v,u,w); } T.dfs(1,0); for(int tot=ni;tot--;){ printf("%lld\n",T.work(ni)); } }
18.618785
65
0.532938
sshockwave
92105c452e6afe0720afa7153119d93b67dffc75
9,483
cpp
C++
src/engine/logic/entity.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/engine/logic/entity.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/engine/logic/entity.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
namespace Logic { bool init_entity() { // This limits the memory to one arena, just to keep // tabs on the memory, if you trust this code switch it // to true to have UNLIMITED entities. _fog_es.memory = Util::request_arena(false); _fog_es.next_free = 0; _fog_es.entities = Util::create_list<Entity *>(100), _fog_es.max_entity = -1; _fog_es.num_entities = 0; _fog_es.num_removed = 0; _fog_es.defrag_limit = 100; _fog_global_type_table.arena = Util::request_arena(); return true; } const char *Entity::show() { char *buffer = Util::request_temporary_memory<char>(512); char *ptr = buffer; EMeta meta_info = _fog_global_entity_list[(u32) type()]; auto write = [&ptr](const char *c) { while (*c) *(ptr++) = *(c++); }; auto seek = [&ptr]() { // Seeks until a nullterminated character. while (*ptr) ptr++; }; write(type_name()); write("\n"); u8 *raw_address = (u8 *) this; for (u32 i = 0; i < meta_info.num_fields; i++) { write(" "); // Indentation, might remove later. const ETypeInfo *info = fetch_type(meta_info.fields[i].hash); if (info) write(info->name); else write("????"); write(" "); write(meta_info.fields[i].name); if (info && info->show) { write(" = "); info->show(ptr, raw_address + meta_info.fields[i].offset); seek(); } write("\n"); } *ptr = '\0'; return buffer; } EMeta meta_data_for(EntityType type) { ASSERT((u32) type < (u32) EntityType::NUM_ENTITY_TYPES, "Invalid type"); EMeta meta = _fog_global_entity_list[(u32) type]; ASSERT(meta.registered, "Entity is not registerd."); return _fog_global_entity_list[(u32) type]; } void *_entity_vtable(EntityType type) { meta_data_for(type); return _fog_global_entity_vtable[(u32) type](); } template <typename T> bool contains_type() { return fetch_type(typeid(T).hash_code()); } bool contains_type(u64 hash) { return fetch_type(hash); } void register_type(ETypeInfo info) { ETypeInfo **current = _fog_global_type_table.data + (info.hash % TypeTable::NUM_SLOTS); while (*current) { if ((*current)->hash == info.hash) ERR("Type hash collision (last added ->) '%s' '%s', " "adding the same type twice?", info.name, (*current)->name); current = &(*current)->next; } info.next = nullptr; *current = _fog_global_type_table.arena->push(info); } template <typename T> const ETypeInfo *fetch_type() { return fetch_type(typeid(T).hash_code()); } const ETypeInfo *fetch_entity_type(EntityType type) { return fetch_type(meta_data_for(type).hash); } const ETypeInfo *fetch_type(u64 hash) { ETypeInfo *current = _fog_global_type_table.data[hash % TypeTable::NUM_SLOTS]; while (current) { if (current->hash == hash) return current; current = current->next; } ERR("Invalid entity query %llu", hash); return current; } // ES EntityID generate_entity_id() { EntityID id; _fog_es.num_entities++; if (_fog_es.next_free < 0) { // Reusing id.slot = -_fog_es.next_free - 1; _fog_es.next_free = _fog_es.entities[id.slot]->id.slot; } else { id.slot = _fog_es.next_free++; id.gen = 0; } if ((s32) _fog_es.entities.capacity <= id.slot) { _fog_es.entities.resize(id.slot * 2); } id.gen++; _fog_es.max_entity = MAX(id.slot, _fog_es.max_entity); return id; } template<typename T> EntityID add_entity(T entity) { static_assert(std::is_base_of<Entity, T>(), "You supplied a class that isn't based on Logic::Entity"); EntityID id = generate_entity_id(); entity.id = id; Util::allow_allocation(); _fog_es.entities[id.slot] = _fog_es.memory->push(entity); ASSERT((u64) _fog_es.entities[id.slot] > 1000, "Invalid pointer in entity system."); Util::strict_allocation_check(); return id; } EntityID add_entity_ptr(Entity *entity) { EntityID id = generate_entity_id(); entity->id = id; u32 size = Logic::fetch_entity_type(entity->type())->size; Util::allow_allocation(); Entity *copy = (Entity *) _fog_es.memory->push<u8>(size); Util::strict_allocation_check(); Util::copy_bytes(entity, copy, size); _fog_es.entities[id.slot] = entity; ASSERT((u64) _fog_es.entities[id.slot] > 1000, "Invalid pointer in entity system."); return id; } void clear_entitysystem() { _fog_es.memory->clear(); _fog_es.next_free = 0; _fog_es.entities.clear(); _fog_es.max_entity = 0; _fog_es.num_entities = 0; _fog_es.num_removed = 0; } Entity *fetch_entity(EntityID id) { if (id.slot >= 0) { Entity *entity = _fog_es.entities[id.slot]; if (entity && id == entity->id) return entity; } return nullptr; } template <typename T> T *fetch_entity(EntityID id) { Entity *entity = fetch_entity(id); ASSERT(entity, "Cannot find entity"); //ASSERT(entity->type() == T::st_type(), "Types don't match!"); return (T *) entity; } bool valid_entity(EntityID id) { return fetch_entity(id) != nullptr; } bool remove_entity(EntityID id) { Entity *entity = fetch_entity(id); if (!entity) return false; _fog_es.num_entities--; _fog_es.num_removed++; s32 slot = entity->id.slot; entity->id.slot = _fog_es.next_free; _fog_es.next_free = -slot - 1; if (slot == _fog_es.max_entity) { while (_fog_es.entities[_fog_es.max_entity]->id.slot < 0 && 0 <= _fog_es.max_entity) _fog_es.max_entity--; } return true; } void for_entity_of_type(EntityType type, MapFunc f) { for (s32 i = _fog_es.max_entity; 0 <= i; i--) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (e->type() != type) continue; if (f(e)) break; } } void for_entity(MapFunc f) { for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (f(e)) break; } } EntityID fetch_first_of_type(EntityType type) { for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (e->type() == type) return e->id; } return {-1, 0}; } void update_es() { START_PERF(ENTITY_UPDATE); const f32 delta = Logic::delta(); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; e->update(delta); } STOP_PERF(ENTITY_UPDATE); } void draw_es() { START_PERF(ENTITY_DRAW); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; e->draw(); } STOP_PERF(ENTITY_DRAW); } // TODO(ed): Make this doable across multiple frames, so we // can spend 1ms on it everyframe or something like that... void defragment_entity_memory() { START_PERF(ENTITY_DEFRAG); if (_fog_es.num_removed < _fog_es.defrag_limit) { STOP_PERF(ENTITY_DEFRAG); return; } // This is kinda hacky... Util::allow_allocation(); Util::MemoryArena *target_arena = Util::request_arena(false); u64 memory = 0; ASSERT(offsetof(Entity, id) < 16, "Empty entity is quite large"); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; u32 size; if (e->id.slot != i) { size = offsetof(Entity, id) + sizeof(EntityID); } else { size = fetch_type(meta_data_for(e->type()).hash)->size; } memory += size; Util::allow_allocation(); u8 *target = target_arena->push<u8>(size); Util::copy_bytes(e, target, size); _fog_es.entities[i] = (Entity *) target; ASSERT((u64) _fog_es.entities[i] > 1000, "Invalid pointer in entity system."); } ASSERT(memory < Util::ARENA_SIZE_IN_BYTES, "Too large allocations"); _fog_es.memory->pop(); _fog_es.memory = target_arena; _fog_es.num_removed = 0; // We've not removed any now STOP_PERF(ENTITY_DEFRAG); } };
31.61
92
0.538226
FredTheDino
921a323c58434473c208cf3a837cbb195f53020e
7,058
cpp
C++
system-test/cache_distributed.cpp
ThomasDai/MaxScale
766afedbada386b4402b8dbb21805e7eaba52323
[ "BSD-3-Clause" ]
null
null
null
system-test/cache_distributed.cpp
ThomasDai/MaxScale
766afedbada386b4402b8dbb21805e7eaba52323
[ "BSD-3-Clause" ]
1
2021-02-12T10:08:58.000Z
2021-02-18T02:57:57.000Z
system-test/cache_distributed.cpp
ThomasDai/MaxScale
766afedbada386b4402b8dbb21805e7eaba52323
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2024-11-26 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <iostream> #include <string> #include <vector> #include <maxbase/string.hh> #include <maxtest/testconnections.hh> // This test checks // - that a failure to connect to redis/memcached does not stall the client and // - that when redis/memcached become available, they are transparently taken into use. using namespace std; namespace { const int PORT_RWS = 4006; const int PORT_RWS_REDIS = 4007; const int PORT_RWS_MEMCACHED = 4008; const int TIMEOUT = 10; // This should be bigger that the cache timeout in the config. bool restart_service(TestConnections& test, const char* zService) { bool rv = test.maxscales->ssh_node_f(0, true, "service %s restart", zService) == 0; sleep(1); // A short sleep to ensure connecting is possible. return rv; } bool start_service(TestConnections& test, const char* zService) { bool rv = test.maxscales->ssh_node_f(0, true, "service %s start", zService) == 0; sleep(1); // A short sleep to ensure connecting is possible. return rv; } bool stop_service(TestConnections& test, const char* zService) { return test.maxscales->ssh_node_f(0, true, "service %s stop", zService) == 0; } bool start_redis(TestConnections& test) { return start_service(test, "redis"); } bool stop_redis(TestConnections& test) { return stop_service(test, "redis"); } bool start_memcached(TestConnections& test) { return start_service(test, "memcached"); } bool stop_memcached(TestConnections& test) { return stop_service(test, "memcached"); } void drop(TestConnections& test) { MYSQL* pMysql = test.maxscales->conn_rwsplit[0]; test.try_query(pMysql, "DROP TABLE IF EXISTS cache_distributed"); test.maxscales->ssh_node_f(0, true, "redis-cli flushall"); restart_service(test, "memcached"); } void create(TestConnections& test) { drop(test); MYSQL* pMysql = test.maxscales->conn_rwsplit[0]; test.try_query(pMysql, "CREATE TABLE cache_distributed (f INT)"); } Connection connect(TestConnections& test, int port) { Connection c = test.maxscales->get_connection(port); bool connected = c.connect(); test.expect(connected, "Could not connect to %d.", port); return c; } void insert(TestConnections& test, Connection& c) { bool inserted = c.query("INSERT INTO cache_distributed values (1)"); test.expect(inserted, "Could not insert value."); } void select(TestConnections& test, const char* zName, Connection& c, size_t n) { Result rows = c.rows("SELECT * FROM cache_distributed"); test.expect(rows.size() == n, "%s: Expected %lu rows, but got %lu.", zName, n, rows.size()); } void install_and_start_redis_and_memcached(Maxscales& maxscales) { setenv("maxscale_000_keyfile", maxscales.sshkey(0), 0); setenv("maxscale_000_whoami", maxscales.user_name.c_str(), 0); setenv("maxscale_000_network", maxscales.ip4(0), 0); string path(test_dir); path += "/cache_install_and_start_storages.sh"; system(path.c_str()); } } int main(int argc, char* argv[]) { TestConnections::skip_maxscale_start(true); TestConnections test(argc, argv); auto maxscales = test.maxscales; install_and_start_redis_and_memcached(*maxscales); maxscales->start(); if (maxscales->connect_rwsplit() == 0) { create(test); sleep(1); Connection none = connect(test, PORT_RWS); insert(test, none); test.tprintf("Connecting with running redis/memcached."); test.set_timeout(TIMEOUT); Connection redis = connect(test, PORT_RWS_REDIS); Connection memcached = connect(test, PORT_RWS_MEMCACHED); // There has been 1 insert so we should get 1 in all cases. As redis and memcached // are running, the caches will be populated as well. test.set_timeout(TIMEOUT); select(test, "none", none, 1); select(test, "redis", redis, 1); select(test, "memcached", memcached, 1); test.stop_timeout(); test.tprintf("Stopping redis/memcached."); stop_redis(test); stop_memcached(test); test.tprintf("Connecting with stopped redis/memcached."); // Using a short timeout at connect-time ensure that if the async connecting // does not work, we'll get a quick failure. test.set_timeout(TIMEOUT); redis = connect(test, PORT_RWS_REDIS); memcached = connect(test, PORT_RWS_MEMCACHED); // There has still been only one insert, so in all cases we should get just one row. // As redis and memcached are not running, the result comes from the backend. test.set_timeout(TIMEOUT); select(test, "none", none, 1); select(test, "redis", redis, 1); select(test, "memcached", memcached, 1); test.stop_timeout(); // Lets add another row. insert(test, none); // There has been two inserts, and as redis/memcached are stopped, we should // get two in all cases. test.set_timeout(TIMEOUT); select(test, "none", none, 2); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); test.stop_timeout(); test.tprintf("Starting redis/memcached."); start_redis(test); start_memcached(test); sleep(1); // To allow things to stabalize. // As the caches are now running, they will now be taken into use. However, that // will be triggered by the fetching and hence the first result will be fetched from // the backend and possibly cached as well, if the connection to the cache is established // faster that what getting the result from the backend is. test.set_timeout(TIMEOUT); select(test, "none", none, 2); select(test, "redis", redis, 2); select(test, "memcache", memcached, 2); test.stop_timeout(); // To make sure the result ends up in the cache, we select again after having slept // for a short while. sleep(2); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); // Add another row, should not be visible from cached alternatives. insert(test, none); select(test, "none", none, 3); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); // Add yet another row, should not be visible from cached alternatives. insert(test, none); select(test, "none", none, 4); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); } else { ++test.global_result; } return test.global_result; }
30.034043
97
0.66081
ThomasDai
9220ba602ed16f5e80dd6083c04c278af0bf33c5
1,087
hpp
C++
include/xul/util/gzip.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/util/gzip.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/util/gzip.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include "zlib.h" namespace xul { int gzip_uncompress( Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) { z_stream stream; int err; int gzip = 1; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; if (gzip == 1) { err = inflateInit2(&stream, 47); } else { err = inflateInit(&stream); } if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } }
20.903846
79
0.594296
hindsights
92225a4239d3b912d52bdb714a4e60ea88887894
4,849
cpp
C++
z3/src/Macierz.cpp
KolodziejJakub/UkladRownan
522bec5390ed79c34194cb5b0e18eb2a5f2317c2
[ "MIT" ]
null
null
null
z3/src/Macierz.cpp
KolodziejJakub/UkladRownan
522bec5390ed79c34194cb5b0e18eb2a5f2317c2
[ "MIT" ]
null
null
null
z3/src/Macierz.cpp
KolodziejJakub/UkladRownan
522bec5390ed79c34194cb5b0e18eb2a5f2317c2
[ "MIT" ]
null
null
null
#include "Macierz.hh" Macierz::Macierz(Wektor a1, Wektor a2, Wektor a3) { Wektor a1,a2,a3; } double & Wektor::operator[](int index) { if(index > ROZMIAR || index < 0) { exit(1); } return tab[index]; } const double & Wektor::operator[](int index) const { if(index > ROZMIAR || index < 0) { exit(1); } return tab[index]; } void Macierz::transpozycja() { Macierz pomoc; for (int i=0; i<ROZMIAR; i++) { for(int j=0; j<ROZMIAR; j++) { pomoc[i][j]=tab[i][j]; } } for (int i=0; i<ROZMIAR; i++) { for(int j=0; j<ROZMIAR; j++) { tab[i][j]=pomoc[j][i]; } } } Wektor Macierz::operator *(Wektor W) { Wektor Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i]=Wynik[i] + (tab[i][j]*W[j]); } } return Wynik; } Macierz Macierz::operator *(Macierz W) { Macierz Wynik; W.transpozycja(); for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=Wynik[i][j] + (tab[i][j] * W[i][j]); } } return Wynik; } Macierz Macierz::operator +(Macierz W) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]+W[i][j]; } } return Wynik; } Macierz Macierz::operator -(Macierz W) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]-W[i][j]; } } return Wynik; } Macierz Macierz::operator * (double l) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]*l; } } return Wynik; } double Macierz::wyznacznikSarus () { double Wynik; Wynik = tab[0][0]*tab[1][1]*tab[2][2]+tab[1][0]*tab[2][1]*tab[0][2]+ tab[2][0]*tab[0][1]*tab[0][2]-tab[0][2]*tab[1][1]*tab[2][0]- tab[1][2]*tab[2][1]*tab[0][0]-tab[2][2]*tab[0][1]*tab[1][0]; return Wynik; } void Macierz::odwrotnosc() { int s; Macierz wyzn, pomoc; double mac2x2[4]; double wyznacznik; for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { wyzn[i][j]=tab[i][j]; pomoc[i][j]=tab[i][j]; } } wyznacznik = wyzn.wyznacznikSarus; for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { s=0; for (int k=0; k<ROZMIAR; k++) { for (int l=0; l<ROZMIAR; l++) { if (k != i && l != j) { mac2x2[s]=pomoc[k][l]; s++; } } } if ((i+j)%2 != 0) { wyzn[i][j]=-(Wyznacznik2x2(mac2x2)); } else { wyzn[i][j]=Wyznacznik2x2(mac2x2); } } } wyzn.transpozycja(); for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { tab[i][j]=(1/wyznacznik)*wyzn[i][j]; } } } double Macierz::Wyznacznik2x2 (double mac2x2[4]) { double Wynik; Wynik=mac2x2[0]*mac2x2[2]-mac2x2[1]*mac2x2[3]; return Wynik; } bool Macierz::operator == (const Macierz & W2)const { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { if (abs(tab[i][j]-W2[i][j]) >= 0.000001) { return false; } } } return true; } bool Macierz::operator != (const Macierz & W2)const { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { if (abs(tab[i][j]-W2[i][j]) >= 0.000001) { return true; } } } return false; } const Wektor & Macierz::zwroc_kolumne (int ind) { Wektor Wynik; for (int i=0; i<ROZMIAR; i++) { Wynik[i] = tab[ind][i]; } return Wynik; } void Macierz::zmien_kolumne(int ind, Wektor nowy) { for (int i=0; i<ROZMIAR; i++) { tab[ind][i] = nowy[i]; } } std::istream& operator >> (std::istream &Strm, Macierz &Mac) { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Strm>>Mac[i][j]; return Strm; } } Mac.transpozycja(); } std::ostream& operator << (std::ostream &Strm, Macierz &Mac) { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Strm<<Mac[i][j]; return Strm; } } }
18.026022
72
0.427717
KolodziejJakub
92234105f6f8264a51fffbcf71c5a638f309e984
6,947
hpp
C++
include/pfasst/interfaces.hpp
danielru/PFASST
d74a822f98fc84ae98232a61fed6f47f60341b08
[ "BSD-2-Clause" ]
null
null
null
include/pfasst/interfaces.hpp
danielru/PFASST
d74a822f98fc84ae98232a61fed6f47f60341b08
[ "BSD-2-Clause" ]
null
null
null
include/pfasst/interfaces.hpp
danielru/PFASST
d74a822f98fc84ae98232a61fed6f47f60341b08
[ "BSD-2-Clause" ]
null
null
null
/* * Interfaces for SDC/MLSDC/PFASST algorithms. */ #ifndef _PFASST_INTERFACES_HPP_ #define _PFASST_INTERFACES_HPP_ #include <cassert> #include <deque> #include <exception> #include <iterator> #include <memory> #include <string> #include "globals.hpp" using namespace std; namespace pfasst { using time_precision = double; // forward declare for ISweeper template<typename time> class Controller; /** * not implemented yet exception. * * Used by PFASST to mark methods that are required for a particular algorithm (SDC/MLSDC/PFASST) * that may not be necessary for all others. */ class NotImplementedYet : public exception { string msg; public: NotImplementedYet(string msg) : msg(msg) {} const char* what() const throw() { return (string("Not implemented/supported yet, required for: ") + this->msg).c_str(); } }; /** * value exception. * * Thrown when a PFASST routine is passed an invalid value. */ class ValueError : public exception { string msg; public: ValueError(string msg) : msg(msg) {} const char* what() const throw() { return (string("ValueError: ") + this->msg).c_str(); } }; class ICommunicator { public: virtual ~ICommunicator() { } virtual int size() = 0; virtual int rank() = 0; }; /** * abstract SDC sweeper. * @tparam time time precision * defaults to pfasst::time_precision */ template<typename time = time_precision> class ISweeper { protected: Controller<time>* controller; public: //! @{ virtual ~ISweeper() {} //! @} //! @{ /** * set the sweepers controller. */ void set_controller(Controller<time>* ctrl) { this->controller = ctrl; } Controller<time>* get_controller() { assert(this->controller); return this->controller; } //! @} //! @{ /** * setup (allocate etc) the sweeper. * @param[in] coarse * `true` if this sweeper exists on a coarsened MLSDC or PFASST level. * This implies that space for an FAS correction and "saved" solutions are necessary. */ virtual void setup(bool coarse = false) { UNUSED(coarse); } /** * perform a predictor sweep. * * Compute a provisional solution from the initial condition. * This is typically very similar to a regular SDC sweep, except that integral terms based on * previous iterations don't exist yet. * @param[in] initial * `true` if function values at the first node need to be computed. * `false` if functions values at the first node already exist (usually this is the case * when advancing from one time step to the next). */ virtual void predict(bool initial) = 0; /** * Perform one SDC sweep/iteration. * * Compute a correction and update solution values. Note that this function can assume that * valid function values exist from a previous pfasst::ISweeper::sweep() or * pfasst::ISweeper::predict(). */ virtual void sweep() = 0; /** * Advance from one time step to the next. * * Essentially this means copying the solution and function values from the last node to the * first node. */ virtual void advance() = 0; /** * Save states (and/or function values) at all nodes. * * This is typically done in MLSDC/PFASST immediately after a call to restrict. * The saved states are used to compute deltas during interpolation. * * @note This method must be implemented in derived sweepers. */ virtual void save(bool initial_only=false) { UNUSED(initial_only); throw NotImplementedYet("mlsdc/pfasst"); } virtual void spread() { throw NotImplementedYet("pfasst"); } //! @} //! @{ virtual void post(ICommunicator* comm, int tag) { UNUSED(comm); UNUSED(tag); }; virtual void send(ICommunicator* comm, int tag, bool blocking) { UNUSED(comm); UNUSED(tag); UNUSED(blocking); throw NotImplementedYet("pfasst"); } virtual void recv(ICommunicator* comm, int tag, bool blocking) { UNUSED(comm); UNUSED(tag); UNUSED(blocking); throw NotImplementedYet("pfasst"); } virtual void broadcast(ICommunicator* comm) { UNUSED(comm); throw NotImplementedYet("pfasst"); } //! @} }; /** * abstract time/space transfer (restrict/interpolate) class. * @tparam time time precision * defaults to pfasst::time_precision */ template<typename time = time_precision> class ITransfer { public: //! @{ virtual ~ITransfer() {} //! @} //! @{ /** * Interpolate initial condition from the coarse sweeper to the fine sweeper. */ virtual void interpolate_initial(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) { UNUSED(dst); UNUSED(src); throw NotImplementedYet("pfasst"); } /** * Interpolate, in time and space, from the coarse sweeper to the fine sweeper. * @param[in] interp_initial * `true` if a delta for the initial condtion should also be computed (PFASST). */ virtual void interpolate(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src, bool interp_initial = false) = 0; /** * Restrict initial condition from the fine sweeper to the coarse sweeper. * @param[in] restrict_initial * `true` if the initial condition should also be restricted. */ virtual void restrict_initial(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) { UNUSED(dst); UNUSED(src); throw NotImplementedYet("pfasst"); } /** * Restrict, in time and space, from the fine sweeper to the coarse sweeper. * @param[in] restrict_initial * `true` if the initial condition should also be restricted. */ virtual void restrict(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src, bool restrict_initial = false) = 0; /** * Compute FAS correction between the coarse and fine sweepers. */ virtual void fas(time dt, shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) = 0; //! @} }; } // ::pfasst #endif
25.921642
99
0.579531
danielru
9227a459875871befbe049779c58d71e0167cca8
2,375
cpp
C++
src/SchemaLex.cpp
eXtremal-ik7/config4cpp
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
[ "MIT" ]
null
null
null
src/SchemaLex.cpp
eXtremal-ik7/config4cpp
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
[ "MIT" ]
null
null
null
src/SchemaLex.cpp
eXtremal-ik7/config4cpp
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include "SchemaLex.h" namespace CONFIG4CPP_NAMESPACE { //-------- // This array must be kept sorted becaue we do a binary search on it. //-------- static LexBase::KeywordInfo keywordInfoArray[] = { //---------------------------------------------------------------------- // spelling symbol //---------------------------------------------------------------------- {"@ignoreEverythingIn", SchemaLex::LEX_IGNORE_EVERYTHING_IN_SYM}, {"@ignoreScopesIn", SchemaLex::LEX_IGNORE_SCOPES_IN_SYM}, {"@ignoreVariablesIn", SchemaLex::LEX_IGNORE_VARIABLES_IN_SYM}, {"@optional", SchemaLex::LEX_OPTIONAL_SYM}, {"@required", SchemaLex::LEX_REQUIRED_SYM}, {"@typedef", SchemaLex::LEX_TYPEDEF_SYM}, }; const static int keywordInfoArraySize = sizeof(keywordInfoArray) / sizeof(keywordInfoArray[0]); SchemaLex::SchemaLex(const char * str) : LexBase(str) { m_keywordInfoArray = keywordInfoArray; m_keywordInfoArraySize = keywordInfoArraySize; } SchemaLex::~SchemaLex() { } }; // namespace CONFIG4CPP_NAMESPACE
33.928571
73
0.633684
eXtremal-ik7
922a63aeb275ce1f99a7af8012a001ed473ee879
1,582
cpp
C++
graphs/dijkstraPqueue.cpp
tkjenll/algorhythm
00c20a1676520a8f34a1be74773faa9903049ce5
[ "MIT" ]
3
2017-10-13T04:08:01.000Z
2021-03-02T10:04:32.000Z
graphs/dijkstraPqueue.cpp
METHLAB-LTD/algorhythm
00c20a1676520a8f34a1be74773faa9903049ce5
[ "MIT" ]
null
null
null
graphs/dijkstraPqueue.cpp
METHLAB-LTD/algorhythm
00c20a1676520a8f34a1be74773faa9903049ce5
[ "MIT" ]
4
2019-02-06T01:22:51.000Z
2020-09-12T16:26:43.000Z
/* Time Complexity : 1. Shortest path by Dijkstra, using a Binary Min-heap as priority queue O(|V| + |E|)*log|V| = O(|E|log|V|) 2. Shortest path by Dijkstra, using a Fibonacci Min-heap as priority queue O(|E| + |V|log|V|) 3. Shortest path by Dijkstra, using an unsorted array as priority queue O(|V|^2) */ #include<cstdio> #include<vector> #include<queue> using namespace std; enum{NIL = -1, MAX = 50, INF = 9999}; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<vii> vvii; vvii G(MAX); vi dist(MAX); vi parent(MAX); int n; void dijkstra(int s) { for(int u = 0; u < n; u++) { dist[u] = INF; parent[u] = NIL; } dist[s] = 0; priority_queue<ii, vector<ii>, greater<ii> > Q; Q.push(ii(dist[s],s)); while(!Q.empty()) { ii top = Q.top(); Q.pop(); int u = top.second; int d = top.first; if(d <= dist[u]) { for(vii::iterator it = G[u].begin(); it != G[u].end(); ++it) { int v = it->first; int w = it->second; if(dist[v] > dist[u] + w) { dist[v] = dist[u] + w; parent[v] = u; Q.push(ii(dist[v],v)); } } } } } void printPath(int s, int t) { if(t == s) printf("%d ",s); else { printPath(s, parent[t]); printf("%d ",t); } } int main() { int m; scanf("%d %d",&n,&m); int u,v,w; for(int i = 0; i < m; i++) { scanf("%d %d %d",&u,&v,&w); G[u].push_back(ii(v,w)); G[v].push_back(ii(u,w)); } int s, t; scanf("%d %d",&s,&t); dijkstra(s); printPath(s,t); printf("\n"); return 0; }
16.652632
63
0.540455
tkjenll
923092eda6175b36a232014efadd28ee45a85db4
1,651
cpp
C++
miscellaneous/MaximalRectangleInGrid_leetcode.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
6
2019-10-06T17:39:42.000Z
2022-03-03T10:57:52.000Z
miscellaneous/MaximalRectangleInGrid_leetcode.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
null
null
null
miscellaneous/MaximalRectangleInGrid_leetcode.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
2
2019-10-06T11:09:01.000Z
2019-10-06T17:40:46.000Z
class Solution { public: int hist(vector<int> &h){ int ans=0; stack<int> s; int i=0; for(i=0;i<h.size();i++){ if(s.empty() || h[i]>=h[s.top()]){ s.push(i); } else{ while(!s.empty() && h[i]<h[s.top()]){ int top=s.top(); s.pop(); if(s.empty()){ ans = max(ans, h[top]*i); } else{ ans = max(ans, h[top]*(i-1-s.top())); } } s.push(i); } } while(!s.empty()){ int top=s.top(); s.pop(); if(s.empty()){ ans = max(ans, h[top]*i); } else{ ans = max(ans, h[top]*(i-1-s.top())); } } return ans; } int maximalRectangle(vector<vector<char>>& m) { if(m.size()==0 || m[0].size()==0) return 0; vector<vector<int>> v(m.size(), vector<int> (m[0].size())); for(int i=0;i<m.size();i++){ for(int j=0;j<m[0].size();j++){ v[i][j] = m[i][j]-'0'; } } for(int j=0;j<m[0].size();j++){ for(int i=1;i<m.size();i++){ if(v[i][j]!=0){ v[i][j]+=v[i-1][j]; } } } int ans=0; for(int i=0;i<m.size();i++){ ans = max(ans, hist(v[i])); } return ans; } };
26.629032
67
0.289522
Cobnagi
9233fff7d85eb23b2f0b88dbe412a8a3c93d22e5
163
cpp
C++
src/Scripting/Natives/ScriptGameInstance.cpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
src/Scripting/Natives/ScriptGameInstance.cpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
src/Scripting/Natives/ScriptGameInstance.cpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#ifndef RED4EXT_STATIC_LIB #error Please define 'RED4EXT_STATIC_LIB' to compile this file. #endif #include <RED4ext/Scripting/Natives/ScriptGameInstance-inl.hpp>
27.166667
63
0.828221
jackhumbert
9236c7b57f0a5339bc436fa306c201b662c77c32
861
cpp
C++
src/return-several-values-and-structured-bindings/main.cpp
tarodnet/cplusplus-snippets
2866102b53534163c2ebc1aaf6096467dfbdadaf
[ "Apache-2.0" ]
null
null
null
src/return-several-values-and-structured-bindings/main.cpp
tarodnet/cplusplus-snippets
2866102b53534163c2ebc1aaf6096467dfbdadaf
[ "Apache-2.0" ]
null
null
null
src/return-several-values-and-structured-bindings/main.cpp
tarodnet/cplusplus-snippets
2866102b53534163c2ebc1aaf6096467dfbdadaf
[ "Apache-2.0" ]
1
2015-06-06T02:23:20.000Z
2015-06-06T02:23:20.000Z
#include <iostream> class Foo { public: int foo; }; class Bar { public: char bar; }; std::pair<Foo, Bar> f() { std::pair<Foo, Bar> result; auto& foo = result.first; auto& bar = result.second; // fill foo and bar... foo.foo = 0xFF; bar.bar = 'x'; return result; } int main(int argc, char** argv) { /* Structured bindings * A proposal for de-structuring initialization, that would allow writing auto [ x, y, z ] = expr; * where the type of expr was a tuple-like object, whose elements * would be bound to the variables x, y, and z (which this construct declares). * Tuple-like objects include std::tuple, std::pair, std::array, and aggregate structures. */ auto [foo, bar] = f(); std::cout << foo.foo << std::endl; std::cout << bar.bar << std::endl; return 0; }
19.568182
101
0.595819
tarodnet
923a66a623dc3654b9b018aaba9c5b2b6d597c56
1,135
cpp
C++
Copy List with Random Pointers.cpp
AMARTYA2020/DSA
54936ce7a63535704f81784ade9af743a68ba419
[ "MIT" ]
3
2021-02-03T10:39:17.000Z
2021-05-28T11:50:01.000Z
Copy List with Random Pointers.cpp
AMARTYA2020/DSA
54936ce7a63535704f81784ade9af743a68ba419
[ "MIT" ]
null
null
null
Copy List with Random Pointers.cpp
AMARTYA2020/DSA
54936ce7a63535704f81784ade9af743a68ba419
[ "MIT" ]
1
2021-02-07T07:19:25.000Z
2021-02-07T07:19:25.000Z
#include<bits/stdc++.h> using namespace std; // COPY LIST WITH RANDOM POINTER: class solution{ public: Node* copyRandomList(Node* head){ // CREATING NORMAL LINKED LIST THAT HAS A DATA FIELD AND ADDRESS FIELD: Node* curr=head; while(curr!=NULL){ Node* next=curr->next; curr->next=new Node(curr->val); curr->next->next=next; curr=next; } // CREATING LINKED LIST THAT HAS A RANDOM ADDRESS FIELD: curr=head; while(curr!=NULL){ if(curr->random!=NULL){ curr->next->random=curr->random->next; }else{ curr->next->random=NULL; } curr=curr->next->next; } // CREATING ANOTHER LINKED LIST: Node* newhead=new Node(0); Node* copycurr=newhead; curr=head; while(curr!=NULL){ copycurr->next=curr->next; curr->next=copycurr->next->next; curr=curr->next; copycurr=copycurr->next; } return newnode->next; } };
28.375
80
0.502203
AMARTYA2020
923c947f3f73180e470c109103abeb14f7b60a45
527
hpp
C++
include/util/any.hpp
BaroboRobotics/cxx-util
624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd
[ "BSL-1.0" ]
null
null
null
include/util/any.hpp
BaroboRobotics/cxx-util
624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd
[ "BSL-1.0" ]
null
null
null
include/util/any.hpp
BaroboRobotics/cxx-util
624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd
[ "BSL-1.0" ]
1
2018-11-13T15:02:23.000Z
2018-11-13T15:02:23.000Z
// Copyright (c) 2014-2016 Barobo, Inc. // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef UTIL_ANY_HPP #define UTIL_ANY_HPP #include <utility> namespace util { template <class T> constexpr bool any (T&& x) { return std::forward<T>(x); } template <class T, class... Ts> constexpr bool any (T&& x, Ts&&... xs) { return std::forward<T>(x) || any(std::forward<Ts>(xs)...); } } // namespace util #endif
20.269231
79
0.671727
BaroboRobotics
923dce66fe2a31a0efe4eb5249b0ae605820ffa0
5,904
hpp
C++
code/jsbind/v8/convert.hpp
Chobolabs/jsbind
874b41df6bbc9a3b756e828c64e43e1b6cbd4386
[ "MIT" ]
57
2019-03-30T21:26:08.000Z
2022-03-11T02:22:09.000Z
code/jsbind/v8/convert.hpp
Chobolabs/jsbind
874b41df6bbc9a3b756e828c64e43e1b6cbd4386
[ "MIT" ]
null
null
null
code/jsbind/v8/convert.hpp
Chobolabs/jsbind
874b41df6bbc9a3b756e828c64e43e1b6cbd4386
[ "MIT" ]
3
2020-04-11T09:19:44.000Z
2021-09-30T07:30:45.000Z
// jsbind // Copyright (c) 2019 Chobolabs Inc. // http://www.chobolabs.com/ // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // http://opensource.org/licenses/MIT // #pragma once #include "global.hpp" #include "jsbind/common/wrapped_class.hpp" #include <string> #include <type_traits> #include <climits> namespace jsbind { class local; namespace internal { template <typename T, typename Enable = void> // enable used by enable_if specializations struct convert; template <> struct convert<std::string> { using from_type = std::string; using to_type = v8::Local<v8::String>; static from_type from_v8(v8::Local<v8::Value> val) { const v8::String::Utf8Value str(isolate, val); return from_type(*str, str.length()); } static to_type to_v8(const from_type& val) { return v8::String::NewFromUtf8(isolate, val.c_str(), v8::String::kNormalString, int(val.length())); } }; template <> struct convert<const char*> { using from_type = const char*; using to_type = v8::Local<v8::String>; // raw pointer converion not supported // it could be supported but emscripten doesn't do it, so we'll follow static from_type from_v8(v8::Local<v8::Value> val) = delete; static to_type to_v8(const char* val) { return v8::String::NewFromUtf8(isolate, val); } }; template<> struct convert<bool> { using from_type = bool; using to_type = v8::Local<v8::Boolean>; static from_type from_v8(v8::Local<v8::Value> value) { return value->ToBoolean(isolate)->Value(); } static to_type to_v8(bool value) { return v8::Boolean::New(isolate, value); } }; template<typename T> struct convert<T, typename std::enable_if<std::is_integral<T>::value>::type> { using from_type = T; using to_type = v8::Local<v8::Number>; enum { bits = sizeof(T) * CHAR_BIT, is_signed = std::is_signed<T>::value }; static from_type from_v8(v8::Local<v8::Value> value) { auto& v8ctx = *reinterpret_cast<v8::Local<v8::Context>*>(&internal::ctx.v8ctx); if (bits <= 32) { if (is_signed) { return static_cast<T>(value->Int32Value(v8ctx).FromMaybe(0)); } else { return static_cast<T>(value->Uint32Value(v8ctx).FromMaybe(0)); } } else { return static_cast<T>(value->IntegerValue(v8ctx).FromMaybe(0)); } } static to_type to_v8(from_type value) { if (bits <= 32) { if (is_signed) { return v8::Integer::New(isolate, static_cast<int32_t>(value)); } else { return v8::Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(value)); } } else { // check value < (1<<57) to fit in double? return v8::Number::New(isolate, static_cast<double>(value)); } } }; template<typename T> struct convert<T, typename std::enable_if<std::is_floating_point<T>::value>::type> { using from_type = T; using to_type = v8::Local<v8::Number>; static from_type from_v8(v8::Local<v8::Value> value) { auto& v8ctx = *reinterpret_cast<v8::Local<v8::Context>*>(&internal::ctx.v8ctx); return static_cast<T>(value->NumberValue(v8ctx).FromMaybe(0)); } static to_type to_v8(T value) { return v8::Number::New(isolate, value); } }; template <> struct convert<void> { using from_type = void; using to_type = v8::Local<v8::Primitive>; static from_type from_v8(v8::Local<v8::Value>) {} static to_type to_v8() { return v8::Undefined(isolate); } }; template <> struct convert<local> { using from_type = local; using to_type = v8::Local<v8::Value>; static from_type from_v8(v8::Local<v8::Value>); static to_type to_v8(const from_type&); }; template<typename T> struct convert<T&> : convert<T>{}; template<typename T> struct convert<const T&> : convert<T>{}; /////////////////////////////////////////////////////////////////////////// template <typename T> T convert_wrapped_class_from_v8(v8::Local<v8::Value> value); template <typename T> v8::Local<v8::Object> convert_wrapped_class_to_v8(const T& t); template <typename T> struct convert<T, typename std::enable_if<is_wrapped_class<T>::value>::type> { using from_type = T; using to_type = v8::Local<v8::Object>; static from_type from_v8(v8::Local<v8::Value> value) { return convert_wrapped_class_from_v8<from_type>(value); } static to_type to_v8(const from_type& value) { return convert_wrapped_class_to_v8(value); } }; /////////////////////////////////////////////////////////////////////////// template<typename T> typename convert<T>::from_type from_v8(v8::Local<v8::Value> value) { return convert<T>::from_v8(value); } template<size_t N> v8::Local<v8::String> to_v8(const char (&str)[N]) { return convert<const char*>::to_v8(str); } template<typename T> typename convert<T>::to_type to_v8(const T& value) { return convert<T>::to_v8(value); } } }
26.594595
95
0.54065
Chobolabs
92404c1d3c0ab2222f506e2b240dd972433768a4
657
cpp
C++
OrionUO/GUI/GUIHTMLButton.cpp
SirGlorg/OrionUO
42209bd144392fddff9e910562ccec1bf5704049
[ "MIT" ]
1
2019-04-27T22:20:34.000Z
2019-04-27T22:20:34.000Z
OrionUO/GUI/GUIHTMLButton.cpp
SirGlorg/OrionUO
42209bd144392fddff9e910562ccec1bf5704049
[ "MIT" ]
1
2018-12-28T13:45:08.000Z
2018-12-28T13:45:08.000Z
OrionUO/GUI/GUIHTMLButton.cpp
heppcatt/Siebenwind-Beta-Client
ba25683f37f9bb7496d12aa2b2117cba397370e2
[ "MIT" ]
null
null
null
// MIT License // Copyright (C) August 2016 Hotride CGUIHTMLButton::CGUIHTMLButton( CGUIHTMLGump *htmlGump, int serial, uint16_t graphic, uint16_t graphicSelected, uint16_t graphicPressed, int x, int y) : CGUIButton(serial, graphic, graphicSelected, graphicPressed, x, y) , m_HTMLGump(htmlGump) { } CGUIHTMLButton::~CGUIHTMLButton() { } void CGUIHTMLButton::SetShaderMode() { DEBUG_TRACE_FUNCTION; glUniform1iARB(g_ShaderDrawMode, SDM_NO_COLOR); } void CGUIHTMLButton::Scroll(bool up, int delay) { DEBUG_TRACE_FUNCTION; if (m_HTMLGump != nullptr) { m_HTMLGump->Scroll(up, delay); } }
18.771429
72
0.692542
SirGlorg
924c0db79b8f383d8dc3d30eed312be6cd6580ba
777
hpp
C++
Runtime/World/CScriptBeam.hpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
null
null
null
Runtime/World/CScriptBeam.hpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
null
null
null
Runtime/World/CScriptBeam.hpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
null
null
null
#pragma once #include <string_view> #include "Runtime/Weapon/CBeamInfo.hpp" #include "Runtime/World/CActor.hpp" #include "Runtime/World/CDamageInfo.hpp" namespace metaforce { class CWeaponDescription; class CScriptBeam : public CActor { TCachedToken<CWeaponDescription> xe8_weaponDescription; CBeamInfo xf4_beamInfo; CDamageInfo x138_damageInfo; TUniqueId x154_projectileId; public: CScriptBeam(TUniqueId, std::string_view, const CEntityInfo&, const zeus::CTransform&, bool, const TToken<CWeaponDescription>&, const CBeamInfo&, const CDamageInfo&); void Accept(IVisitor& visitor) override; void Think(float, CStateManager&) override; void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override; }; } // namespace metaforce
29.884615
93
0.78121
Jcw87
924d63d5f43ad2567313e7584a5941997b3a6580
3,321
cpp
C++
test/unit-modcc/test_kinetic_rewriter.cpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
53
2018-10-18T12:08:21.000Z
2022-03-26T22:03:51.000Z
test/unit-modcc/test_kinetic_rewriter.cpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
864
2018-10-01T08:06:00.000Z
2022-03-31T08:06:48.000Z
test/unit-modcc/test_kinetic_rewriter.cpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
37
2019-03-03T16:18:49.000Z
2022-03-24T10:39:51.000Z
#include <iostream> #include <string> #include "expression.hpp" #include "kineticrewriter.hpp" #include "parser.hpp" #include "alg_collect.hpp" #include "common.hpp" #include "expr_expand.hpp" expr_list_type& statements(Expression *e) { if (e) { if (auto block = e->is_block()) { return block->statements(); } if (auto sym = e->is_symbol()) { if (auto proc = sym->is_procedure()) { return proc->body()->statements(); } if (auto proc = sym->is_procedure()) { return proc->body()->statements(); } } } throw std::runtime_error("not a block, function or procedure"); } inline symbol_ptr state_var(const char* name) { auto v = make_symbol<VariableExpression>(Location(), name); v->is_variable()->state(true); return v; } inline symbol_ptr assigned_var(const char* name) { return make_symbol<VariableExpression>(Location(), name); } static const char* kinetic_abc = "KINETIC kin { \n" " u = 3 \n" " ~ a <-> b (u, v) \n" " u = 4 \n" " v = sin(u) \n" " ~ b <-> 3b + c (u, v) \n" "} \n"; static const char* derivative_abc = "DERIVATIVE deriv { \n" " a' = -3*a + b*v \n" " LOCAL rev2 \n" " rev2 = c*b^3*sin(4) \n" " b' = 3*a - v*b + 8*b - 2*rev2\n" " c' = 4*b - rev2 \n" "} \n"; TEST(KineticRewriter, equiv) { auto kin = Parser(kinetic_abc).parse_procedure(); auto deriv = Parser(derivative_abc).parse_procedure(); auto kin_ptr = kin.get(); auto deriv_ptr = deriv.get(); ASSERT_NE(nullptr, kin); ASSERT_NE(nullptr, deriv); ASSERT_TRUE(kin->is_symbol() && kin->is_symbol()->is_procedure()); ASSERT_TRUE(deriv->is_symbol() && deriv->is_symbol()->is_procedure()); scope_type::symbol_map globals; globals["kin"] = std::move(kin); globals["deriv"] = std::move(deriv); globals["a"] = state_var("a"); globals["b"] = state_var("b"); globals["c"] = state_var("c"); globals["u"] = assigned_var("u"); globals["v"] = assigned_var("v"); deriv_ptr->semantic(globals); auto kin_body = kin_ptr->is_procedure()->body(); scope_ptr scope = std::make_shared<scope_type>(globals); kin_body->semantic(scope); auto kin_deriv = kinetic_rewrite(kin_body); verbose_print("derivative procedure:\n", deriv_ptr); verbose_print("kin procedure:\n", kin_ptr); verbose_print("rewritten kin body:\n", kin_deriv); auto deriv_map = expand_assignments(statements(deriv_ptr)); auto kin_map = expand_assignments(statements(kin_deriv.get())); if (g_verbose_flag) { std::cout << "derivative assignments (canonical):\n"; for (const auto&p: deriv_map) { std::cout << p.first << ": " << p.second << "\n"; } std::cout << "rewritten kin assignments (canonical):\n"; for (const auto&p: kin_map) { std::cout << p.first << ": " << p.second << "\n"; } } EXPECT_EQ(deriv_map["a'"], kin_map["a'"]); EXPECT_EQ(deriv_map["b'"], kin_map["b'"]); EXPECT_EQ(deriv_map["c'"], kin_map["c'"]); }
29.651786
74
0.552243
kanzl
924eb6611f6d5a383f9a0e27dada734eb9ee7b17
713
cpp
C++
sauce/core/collections/abstractions/strange__queue_a.cpp
oneish/strange
e6c47eca5738dd98f4e09ee5c0bb820146e8b48f
[ "Apache-2.0" ]
null
null
null
sauce/core/collections/abstractions/strange__queue_a.cpp
oneish/strange
e6c47eca5738dd98f4e09ee5c0bb820146e8b48f
[ "Apache-2.0" ]
null
null
null
sauce/core/collections/abstractions/strange__queue_a.cpp
oneish/strange
e6c47eca5738dd98f4e09ee5c0bb820146e8b48f
[ "Apache-2.0" ]
null
null
null
#include "../../strange__core.h" namespace strange { template <typename element_d> var<symbol_a> queue_a<element_d>::cat(con<> const& me) { static auto r = sym("<strange::queue>"); //TODO cat return r; } template <typename element_d> typename queue_a<element_d>::creator_fp queue_a<element_d>::creator(con<symbol_a> const& scope, con<symbol_a> const& thing, con<symbol_a> const& function) { if (scope == "strange") { if (thing == "queue") { if (function == "create_from_range") { // return thing_t::create_from_range; } } } return nullptr; } // instantiation template struct queue_a<>; template struct queue_a<int64_t>; template struct queue_a<uint8_t>; }
20.371429
96
0.667602
oneish
924f78caafafaacfd4d8d9a754dfce0594908a0a
596
hpp
C++
test/src/Algorithm/NoneOf.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
48
2019-05-14T10:07:08.000Z
2021-04-08T08:26:20.000Z
test/src/Algorithm/NoneOf.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
null
null
null
test/src/Algorithm/NoneOf.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
4
2019-11-18T15:35:32.000Z
2021-12-02T05:23:04.000Z
#include "CppML/CppML.hpp" namespace NoneOfTest { template <typename T> using Predicate = std::is_class<T>; template <typename T> struct R {}; struct Type0 {}; struct Type1 {}; void run() { { using T = ml::f<ml::NoneOf<ml::F<Predicate>, ml::F<R>>, int, char, Type0>; static_assert(std::is_same<T, R<ml::Bool<false>>>::value, "NoneOf with a non-empty pack 1"); } { using T = ml::f<ml::NoneOf<ml::F<Predicate>, ml::F<R>>>; static_assert(std::is_same<T, R<ml::Bool<true>>>::value, "NoneOf with empty pack"); } } } // namespace NoneOfTest
28.380952
78
0.597315
changjurhee
9254c035c212013bc6916d0a329190d8981cec1a
1,287
cpp
C++
Flims 2019/Flims Contest Friday/Icebreaker/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
Flims 2019/Flims Contest Friday/Icebreaker/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
Flims 2019/Flims Contest Friday/Icebreaker/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n, groups; cin >> n >> groups; vector<vector<bool>>con(n, vector<bool>(n)); vector<vector<int>>E(n); for (int i = 0; i < n; ++i) { int k; cin >> k; for (int j = 0; j < k; ++j) { int x; cin >> x; con[i][x]=true; con[x][i]=true; E[x].push_back(i); } } vector<int>first, second; vector<int>cols(n,-1); vector<vector<int>>g(groups); for (int i = 0; i < n; ++i) { vector<bool>used(groups); for (int w : E[i]) { if(cols[w]==-1){ continue;} used[cols[w]]=true; } for (int j = 0; j < groups; ++j) { if(used[j]){ continue;} cols[i]=j; g[j].push_back(i); break; } } for (int i = 0; i < groups; ++i) { cout << g[i].size() << " "; for (int j = 0; j < g[i].size(); ++j) { cout << g[i][j] << " "; } cout << "\n"; } }
25.235294
72
0.440559
wdjpng
92553a8f958ed44a6481a91f1184e2bc0f73d132
3,014
cpp
C++
lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp
jessicadavies-intel/llvm
4236bbba4c562a1355e75fa6d237b7c6b15a3193
[ "Apache-2.0" ]
1
2022-01-06T15:44:48.000Z
2022-01-06T15:44:48.000Z
lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp
jessicadavies-intel/llvm
4236bbba4c562a1355e75fa6d237b7c6b15a3193
[ "Apache-2.0" ]
2
2019-06-27T00:36:28.000Z
2021-06-29T20:05:03.000Z
lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp
kbobrovs/llvm
b57c6bf3b16e6d3f6c052ba9ba3616a24e0beae5
[ "Apache-2.0" ]
null
null
null
//===-- RegisterContextPOSIX_arm.cpp --------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <cerrno> #include <cstdint> #include <cstring> #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/RegisterValue.h" #include "lldb/Utility/Scalar.h" #include "llvm/Support/Compiler.h" #include "RegisterContextPOSIX_arm.h" using namespace lldb; using namespace lldb_private; bool RegisterContextPOSIX_arm::IsGPR(unsigned reg) { if (m_register_info_up->GetRegisterSetFromRegisterIndex(reg) == RegisterInfoPOSIX_arm::GPRegSet) return true; return false; } bool RegisterContextPOSIX_arm::IsFPR(unsigned reg) { if (m_register_info_up->GetRegisterSetFromRegisterIndex(reg) == RegisterInfoPOSIX_arm::FPRegSet) return true; return false; } RegisterContextPOSIX_arm::RegisterContextPOSIX_arm( lldb_private::Thread &thread, std::unique_ptr<RegisterInfoPOSIX_arm> register_info) : lldb_private::RegisterContext(thread, 0), m_register_info_up(std::move(register_info)) {} RegisterContextPOSIX_arm::~RegisterContextPOSIX_arm() {} void RegisterContextPOSIX_arm::Invalidate() {} void RegisterContextPOSIX_arm::InvalidateAllRegisters() {} unsigned RegisterContextPOSIX_arm::GetRegisterOffset(unsigned reg) { return m_register_info_up->GetRegisterInfo()[reg].byte_offset; } unsigned RegisterContextPOSIX_arm::GetRegisterSize(unsigned reg) { return m_register_info_up->GetRegisterInfo()[reg].byte_size; } size_t RegisterContextPOSIX_arm::GetRegisterCount() { return m_register_info_up->GetRegisterCount(); } size_t RegisterContextPOSIX_arm::GetGPRSize() { return m_register_info_up->GetGPRSize(); } const lldb_private::RegisterInfo *RegisterContextPOSIX_arm::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. return m_register_info_up->GetRegisterInfo(); } const lldb_private::RegisterInfo * RegisterContextPOSIX_arm::GetRegisterInfoAtIndex(size_t reg) { if (reg < GetRegisterCount()) return &GetRegisterInfo()[reg]; return nullptr; } size_t RegisterContextPOSIX_arm::GetRegisterSetCount() { return m_register_info_up->GetRegisterSetCount(); } const lldb_private::RegisterSet * RegisterContextPOSIX_arm::GetRegisterSet(size_t set) { return m_register_info_up->GetRegisterSet(set); } const char *RegisterContextPOSIX_arm::GetRegisterName(unsigned reg) { if (reg < GetRegisterCount()) return GetRegisterInfo()[reg].name; return nullptr; }
30.444444
80
0.748507
jessicadavies-intel
9256d552a8fc7886c210b2b48a985722d598b601
666
hpp
C++
z/util/regex/rgx.hpp
ZacharyWesterman/zLibraries
cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d
[ "MIT" ]
null
null
null
z/util/regex/rgx.hpp
ZacharyWesterman/zLibraries
cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d
[ "MIT" ]
12
2022-01-09T04:05:56.000Z
2022-01-16T04:50:52.000Z
z/util/regex/rgx.hpp
ZacharyWesterman/zLibraries
cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d
[ "MIT" ]
1
2021-01-30T01:19:02.000Z
2021-01-30T01:19:02.000Z
#pragma once /** * \file z/util/regex/rgx.hpp * \namespace z::util::rgx * \brief Namespace containing all regex rules for the sake of organization. **/ #include "rules/alpha.hpp" #include "rules/alnum.hpp" #include "rules/andlist.hpp" #include "rules/anything.hpp" #include "rules/begin.hpp" #include "rules/boundary.hpp" #include "rules/character.hpp" #include "rules/compound.hpp" #include "rules/digit.hpp" #include "rules/end.hpp" #include "rules/lookahead.hpp" #include "rules/lookbehind.hpp" #include "rules/newline.hpp" #include "rules/orlist.hpp" #include "rules/punct.hpp" #include "rules/range.hpp" #include "rules/space.hpp" #include "rules/word.hpp"
25.615385
76
0.738739
ZacharyWesterman
925be2325232508739c27e2f3f2acdb423c2d297
517
cpp
C++
perm/remoteExec.cpp
cationstudio/arma-3-life-management
e74aa843222e612d7b2435cc9a37d0c515d82b47
[ "MIT" ]
null
null
null
perm/remoteExec.cpp
cationstudio/arma-3-life-management
e74aa843222e612d7b2435cc9a37d0c515d82b47
[ "MIT" ]
null
null
null
perm/remoteExec.cpp
cationstudio/arma-3-life-management
e74aa843222e612d7b2435cc9a37d0c515d82b47
[ "MIT" ]
null
null
null
/* File: remoteExec.cpp Author: Julian Bauer ([email protected]) Description: Remote exec config file for management system. */ class cat_perm_fnc_getInfos { allowedTargets=2; }; class cat_perm_fnc_updateRank { allowedTargets=2; }; class cat_perm_fnc_getInfosHC { allowedTargets=HC_Life; }; class cat_perm_fnc_updateRankHC { allowedTargets=HC_Life; }; class cat_perm_fnc_updatePlayer { allowedTargets=1; } class cat_perm_fnc_updatePermDialog { allowedTargets=1; }
20.68
56
0.750484
cationstudio
925ca1c942da4971f72c6c38f301070e283e4934
614
hpp
C++
include/lsfml/resource_text.hpp
Oberon00/lsfml
c5440216c408234a856e59044addc7e6f6bd99b3
[ "BSD-2-Clause" ]
5
2015-02-21T23:28:39.000Z
2017-01-04T10:04:45.000Z
include/lsfml/resource_text.hpp
Oberon00/lsfml
c5440216c408234a856e59044addc7e6f6bd99b3
[ "BSD-2-Clause" ]
null
null
null
include/lsfml/resource_text.hpp
Oberon00/lsfml
c5440216c408234a856e59044addc7e6f6bd99b3
[ "BSD-2-Clause" ]
null
null
null
// Part of the LSFML library -- Copyright (c) Christian Neumüller 2015 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #ifndef LSFML_RESOURCE_TEXT_HPP_INCLUDED #define LSFML_RESOURCE_TEXT_HPP_INCLUDED #include <lsfml/resource_media.hpp> #include <SFML/Graphics/Text.hpp> namespace lsfml { using resource_text = resource_media<sf::Text, sf::Font>; inline void update_resource_media( sf::Text& s, resource_text::res_ptr const& fnt) { s.setFont(*fnt); } } // namespace lsfml #endif // LSFML_RESOURCE_TEXT_HPP_INCLUDED
25.583333
70
0.763844
Oberon00
1787ed14d3818441f867030aca7213c26cfd5fb6
2,634
hpp
C++
Transport-Guide-CPP/Guide/Route/RoutesMap.hpp
Cheshulko/Transport-Guide-CPP
84d8e447ecf45d1f6f7598ef773b70d6611413e8
[ "MIT" ]
null
null
null
Transport-Guide-CPP/Guide/Route/RoutesMap.hpp
Cheshulko/Transport-Guide-CPP
84d8e447ecf45d1f6f7598ef773b70d6611413e8
[ "MIT" ]
null
null
null
Transport-Guide-CPP/Guide/Route/RoutesMap.hpp
Cheshulko/Transport-Guide-CPP
84d8e447ecf45d1f6f7598ef773b70d6611413e8
[ "MIT" ]
null
null
null
// // RoutesMap.hpp // transportnyi-spravochnik // // Created by Mykyta Cheshulko on 02.07.2020. // Copyright © 2020 Mykyta Cheshulko. All rights reserved. // #ifndef RoutesMap_hpp #define RoutesMap_hpp #include "Route.hpp" #include "Stop.hpp" #include "DirectedWeightedGraph.hpp" #include "Router.hpp" #include <optional> #include <set> #include <unordered_map> #include <map> #include <tuple> namespace guide::route { class RoutesMap { public: class Settings final { public: Settings(size_t busWaitTime, size_t busVelocity); size_t GetBusWaitTime() const; size_t GetBusVelocity() const; private: size_t busWaitTime_; size_t busVelocity_; }; public: RoutesMap(); RoutesMap(std::vector<std::shared_ptr<Route>> routes, std::vector<std::shared_ptr<Stop>> stops); bool AddStop(std::shared_ptr<Stop> stop); bool AddRoute(std::shared_ptr<Route> route); std::optional<std::weak_ptr<Stop>> FindStop(const std::string& name) const; std::optional<std::weak_ptr<Stop>> FindStop(std::shared_ptr<Stop> stop) const; std::optional<std::weak_ptr<Route>> FindRoute(const std::string& name) const; void SetSettings(std::shared_ptr<Settings> settings_); size_t GetStopsCount() const; const Settings& GetSettings() const; std::optional<size_t> GetStopId(std::shared_ptr<Stop> stop) const; std::optional<std::weak_ptr<Stop>> GetStop(size_t stopId) const; std::optional<std::weak_ptr<Route>> GetRoute(size_t routeId) const; std::optional< std::vector<std::tuple< std::weak_ptr<Stop>, /* From stop */ std::weak_ptr<Stop>, /* To stop */ double, /* Time, minutes */ std::weak_ptr<Route>, /* Using route */ size_t /* Stops count */ >>> GetOptimalRoute(std::shared_ptr<Stop> fromStop, std::shared_ptr<Stop> toStop); void BuildGraph(); private: std::shared_ptr<Settings> settings_; private: std::set<std::shared_ptr<Route>, Route::SharedComparator> routes_; std::set<std::shared_ptr<Stop>, Stop::SharedComparator> stops_; private: /* These for graph */ std::map< std::weak_ptr<Stop>, size_t, Stop::WeakComparator > stopsId_; std::vector<std::weak_ptr<Stop>> idStops_; std::vector<std::weak_ptr<Route>> idRoutes_; private: std::unique_ptr<structure::graph::Router<double>> router_; std::unique_ptr<structure::graph::DirectedWeightedGraph<double>> graph_; }; } #endif /* RoutesMap_hpp */
27.4375
100
0.645406
Cheshulko
17971ac9b543b8d878817783d80d200a9d41c8f9
11,146
hpp
C++
CaWE/MapEditor/ObserverPattern.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/MapEditor/ObserverPattern.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/MapEditor/ObserverPattern.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_OBSERVER_PATTERN_HPP_INCLUDED #define CAFU_OBSERVER_PATTERN_HPP_INCLUDED /// \file /// This file provides the classes for the Observer pattern as described in the book by the GoF. /// Note that implementations of ObserverT normally maintain a pointer to the subject(s) that they observe, /// e.g. in order to be able to redraw themselves also outside of and independent from the NotifySubjectChanged() method. /// This however in turn creates problems when the life of the observer begins before or ends after the life of the observed subject(s). /// In fact, it seems that the observers have to maintain lists of valid, observed subjects as the subjects maintain lists of observers. /// Fortunately, these possibly tough problems can (and apparently must) be addressed by the concrete implementation classes of /// observers and subjects, not by the base classes that the Observer pattern describes and provided herein. #include "Math3D/BoundingBox.hpp" #include "Templates/Array.hpp" #include "Templates/Pointer.hpp" #include "wx/string.h" namespace cf { namespace GameSys { class EntityT; } } namespace cf { namespace TypeSys { class VarBaseT; } } namespace MapEditor { class CompMapEntityT; } class SubjectT; class MapElementT; class MapPrimitiveT; //##################################### //# New observer notifications hints. # //##################################### enum MapElemModDetailE { MEMD_GENERIC, ///< Generic change of map elements (useful if the subject doesn't know what exactly has been changed). MEMD_TRANSFORM, ///< A map element has been transformed. MEMD_PRIMITIVE_PROPS_CHANGED, ///< The properties of a map primitive have been modified. MEMD_SURFACE_INFO_CHANGED, ///< The surface info of a map element has changed. Note that surface info changes also include the selection of faces. MEMD_ASSIGN_PRIM_TO_ENTITY, ///< A map primitive has been assigned to another entity (the world or any custom entity). MEMD_VISIBILITY ///< The visibility of a map element has changed. }; enum EntityModDetailE { EMD_COMPONENTS, ///< The set of components has changed (e.g. added, deleted, order changed). EMD_HIERARCHY ///< The position of an entity in the entity hierarchy has changed. }; enum MapDocOtherDetailT { UPDATE_GRID, UPDATE_POINTFILE, UPDATE_GLOBALOPTIONS }; //############################################ //# End of new observer notifications hints. # //############################################ class ObserverT { public: //################################################################################################################################### //# New observer notifications methods. These methods differ from the basic observer pattern from the GoF and are CaWE specific! # //# Note that the new methods are NOT pure virtual since a concrete observer might not be interested in some of these notifications # //################################################################################################################################### /// Notifies the observer that some other detail than those specifically addressed below has changed. virtual void NotifySubjectChanged(SubjectT* Subject, MapDocOtherDetailT OtherDetail) { } /// Notifies the observer that the selection in the current subject has been changed. /// @param Subject The map document in which the selection has been changed. /// @param OldSelection Array of the previously selected objects. /// @param NewSelection Array of the new selected objects. virtual void NotifySubjectChanged_Selection(SubjectT* Subject, const ArrayT<MapElementT*>& OldSelection, const ArrayT<MapElementT*>& NewSelection) { } /// Notifies the observer that the groups in the current subject have been changed (new group added, group deleted, visibility changed, anything). /// @param Subject The map document in which the group inventory has been changed. virtual void NotifySubjectChanged_Groups(SubjectT* Subject) { } /// Notifies the observer that one or more entities have been created. /// @param Subject The map document in which the entities have been created. /// @param Entities List of created entities. virtual void NotifySubjectChanged_Created(SubjectT* Subject, const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities) { } /// Notifies the observer that one or more map primitives have been created. /// @param Subject The map document in which the primitives have been created. /// @param Primitives List of created map primitives. virtual void NotifySubjectChanged_Created(SubjectT* Subject, const ArrayT<MapPrimitiveT*>& Primitives) { } /// Notifies the observer that one or more entities have been deleted. /// @param Subject The map document in which the entities have been deleted. /// @param Entities List of deleted entities. virtual void NotifySubjectChanged_Deleted(SubjectT* Subject, const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities) { } /// Notifies the observer that one or more map primitives have been deleted. /// @param Subject The map document in which the primitives have been deleted. /// @param Primitives List of deleted map primitives. virtual void NotifySubjectChanged_Deleted(SubjectT* Subject, const ArrayT<MapPrimitiveT*>& Primitives) { } /// @name Modification notification method and overloads. /// These methods notify the observer that one or more map elements have been modified. /// The first 3 parameters are common to all of these methods since they are the basic information needed to communicate /// an object modification. //@{ /// @param Subject The map document in which the elements have been modified. /// @param MapElements List of modified map elements. /// @param Detail Information about what has been modified: /// Can be one of MEMD_PRIMITIVE_PROPS_CHANGED, MEMD_GENERIC, MEMD_ASSIGN_PRIM_TO_ENTITY and MEMD_MATERIAL_CHANGED. virtual void NotifySubjectChanged_Modified(SubjectT* Subject, const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail) { } /// @param Subject The map document in which the elements have been modified. /// @param MapElements List of modified map elements. /// @param Detail Information about what has been modified: /// Can be MEMD_TRANSFORM or MEMD_PRIMITIVE_PROPS_CHANGED. /// In the case of MEMD_PRIMITIVE_PROPS_CHANGED one can assume that /// only map primitives (no entities) are in the MapElements array. /// @param OldBounds Holds the bounds of each objects BEFORE the modification (has the same size as MapElements). virtual void NotifySubjectChanged_Modified(SubjectT* Subject, const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail, const ArrayT<BoundingBox3fT>& OldBounds) { } /// @param Subject The map document in which the entities have been modified. /// @param Entities List of modified map entities. /// @param Detail Information about what has been modified. virtual void Notify_EntChanged(SubjectT* Subject, const ArrayT< IntrusivePtrT<MapEditor::CompMapEntityT> >& Entities, EntityModDetailE Detail) { } /// Notifies the observer that a variable has changed. /// @param Subject The map document in which a variable has changed. /// @param Var The variable whose value has changed. virtual void Notify_VarChanged(SubjectT* Subject, const cf::TypeSys::VarBaseT& Var) { } //@} //############################################ //# End of new observer notification methods # //############################################ /// This method is called whenever a subject is about the be destroyed (and become unavailable). /// \param dyingSubject The subject that is being destroyed. virtual void NotifySubjectDies(SubjectT* dyingSubject)=0; /// The virtual destructor. virtual ~ObserverT(); protected: /// The constructor. It is protected so that only derived classes can create instances of this class. ObserverT(); }; class SubjectT { public: /// Registers the observer Obs for notification on updates of this class. /// \param Obs The observer that is to be registered. void RegisterObserver(ObserverT* Obs); /// Unregisters the observer Obs from further notification on updates of this class. /// \param Obs The observer that is to be unregistered. void UnregisterObserver(ObserverT* Obs); //################################################################################################################################### //# New observer notifications methods. These methods differ from the basic observer pattern from the GoF and are CaWE specific! # //# For detailed comments on the parameters, see the equivalent methods in ObserverT # //################################################################################################################################### void UpdateAllObservers(MapDocOtherDetailT OtherDetail); void UpdateAllObservers_SelectionChanged(const ArrayT<MapElementT*>& OldSelection, const ArrayT<MapElementT*>& NewSelection); void UpdateAllObservers_GroupsChanged(); void UpdateAllObservers_Created(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities); void UpdateAllObservers_Created(const ArrayT<MapPrimitiveT*>& Primitives); void UpdateAllObservers_Deleted(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entites); void UpdateAllObservers_Deleted(const ArrayT<MapPrimitiveT*>& Primitives); void UpdateAllObservers_Modified(const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail); void UpdateAllObservers_Modified(const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail, const ArrayT<BoundingBox3fT>& OldBounds); void UpdateAllObservers_EntChanged(const ArrayT< IntrusivePtrT<MapEditor::CompMapEntityT> >& Entities, EntityModDetailE Detail); void UpdateAllObservers_EntChanged(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities, EntityModDetailE Detail); void UpdateAllObservers_EntChanged(IntrusivePtrT<cf::GameSys::EntityT> Entity, EntityModDetailE Detail); void UpdateAllObservers_VarChanged(const cf::TypeSys::VarBaseT& Var); void UpdateAllObservers_SubjectDies(); /// The virtual destructor. virtual ~SubjectT(); protected: /// The constructor. It is protected so that only derived classes can create instances of this class. SubjectT(); private: /// The list of the observers that have registered for notification on updates of this class. ArrayT<ObserverT*> m_Observers; }; #endif
53.845411
177
0.679795
dns
179a3912a5ee10485fb2b720edeb71cc6cbdce99
5,354
cpp
C++
src/rfx/application/Window.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
src/rfx/application/Window.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
src/rfx/application/Window.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
#include "rfx/pch.h" #include "rfx/application/Window.h" #include <rfx/common/Algorithm.h> #ifdef _WINDOWS #define GLFW_EXPOSE_NATIVE_WIN32 #include <GLFW/glfw3native.h> #endif // _WINDOWS using namespace rfx; using namespace std; // --------------------------------------------------------------------------------------------------------------------- void Window::create(const string& title, int width, int height) { glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); if (!window) { RFX_THROW("Failed to create window"); } glfwGetFramebufferSize(window, &width_, &height_); glfwSetWindowUserPointer(window, this); glfwSetKeyCallback(window, onKeyEvent); glfwSetFramebufferSizeCallback(window, onResize); glfwSetCursorEnterCallback(window, onCursorEntered); glfwSetCursorPosCallback(window, onCursorPos); } // --------------------------------------------------------------------------------------------------------------------- void Window::show() { glfwShowWindow(window); } // --------------------------------------------------------------------------------------------------------------------- void Window::onResize(GLFWwindow* window, int width, int height) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onResize(width, height); } // --------------------------------------------------------------------------------------------------------------------- void Window::onResize(int width, int height) { width_ = width; height_ = height; ranges::for_each(listeners, [this, width, height](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onResized(*this, width, height); } }); } // --------------------------------------------------------------------------------------------------------------------- GLFWwindow* Window::getGlfwWindow() const { return window; } // --------------------------------------------------------------------------------------------------------------------- void* Window::getHandle() const { return glfwGetWin32Window(window); } // --------------------------------------------------------------------------------------------------------------------- uint32_t Window::getClientWidth() const { return width_; } // --------------------------------------------------------------------------------------------------------------------- uint32_t Window::getClientHeight() const { return height_; } // --------------------------------------------------------------------------------------------------------------------- void Window::addListener(const shared_ptr<WindowListener>& listener) { if (!contains(listeners, listener)) { listeners.push_back(listener); } } // --------------------------------------------------------------------------------------------------------------------- void Window::onKeyEvent(GLFWwindow* window, int key, int scancode, int action, int mods) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onKeyEvent(key, scancode, action, mods); } // --------------------------------------------------------------------------------------------------------------------- void Window::onKeyEvent(int key, int scancode, int action, int mods) { ranges::for_each(listeners, [this, key, scancode, action, mods](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onKeyEvent(*this, key, scancode, action, mods); } }); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorPos(GLFWwindow* window, double x, double y) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onCursorPos(static_cast<float>(x), static_cast<float>(y)); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorPos(float x, float y) { ranges::for_each(listeners, [this, x, y](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onCursorPos(*this, x, y); } }); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorEntered(GLFWwindow* window, int entered) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onCursorEntered(entered); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorEntered(bool entered) { ranges::for_each(listeners, [this, entered](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onCursorEntered(*this, entered); } }); } // ---------------------------------------------------------------------------------------------------------------------
33.254658
120
0.432013
rfruesmer
179d24ecf183dab489c1eb0f50bda30091244204
54,032
cpp
C++
src/imaging/ossimImageChain.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
src/imaging/ossimImageChain.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
src/imaging/ossimImageChain.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageChain.cpp 21850 2012-10-21 20:09:55Z dburken $ #include <ossim/imaging/ossimImageChain.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimConnectableContainer.h> #include <ossim/base/ossimDrect.h> #include <ossim/base/ossimNotifyContext.h> #include <ossim/base/ossimObjectFactoryRegistry.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimEventIds.h> #include <ossim/base/ossimObjectEvents.h> #include <ossim/base/ossimIdManager.h> #include <ossim/base/ossimVisitor.h> #include <ossim/imaging/ossimImageData.h> #include <ossim/imaging/ossimImageGeometry.h> #include <algorithm> #include <iostream> #include <iterator> using namespace std; static ossimTrace traceDebug("ossimImageChain"); RTTI_DEF3(ossimImageChain, "ossimImageChain", ossimImageSource, ossimConnectableObjectListener, ossimConnectableContainerInterface); void ossimImageChain::processEvent(ossimEvent& event) { ossimConnectableObjectListener::processEvent(event); ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, event.getCurrentObject()); if((ossimConnectableObject*)getFirstSource() == obj) { if(event.isPropagatingToOutputs()) { ossimConnectableObject::ConnectableObjectList& outputList = getOutputList(); ossim_uint32 idx = 0; for(idx = 0; idx < outputList.size();++idx) { if(outputList[idx].valid()) { outputList[idx]->fireEvent(event); outputList[idx]->propagateEventToOutputs(event); } } } } } ossimImageChain::ossimImageChain() :ossimImageSource(0, 0, // number of inputs 0, // number of outputs false, // input's fixed false), // outputs are not fixed ossimConnectableContainerInterface((ossimObject*)NULL), theBlankTile(NULL), theLoadStateFlag(false) { ossimConnectableContainerInterface::theBaseObject = this; //thePropagateEventFlag = false; addListener((ossimConnectableObjectListener*)this); } ossimImageChain::~ossimImageChain() { removeListener((ossimConnectableObjectListener*)this); deleteList(); } bool ossimImageChain::addFirst(ossimConnectableObject* obj) { ossimConnectableObject* rightOfThisObj = (ossimConnectableObject*)getFirstObject(); return insertRight(obj, rightOfThisObj); } bool ossimImageChain::addLast(ossimConnectableObject* obj) { if(imageChainList().size() > 0) { ossimConnectableObject* lastSource = imageChainList()[ imageChainList().size() -1].get(); // if(dynamic_cast<ossimImageSource*>(obj)&&lastSource) if(lastSource) { // obj->disconnect(); ossimConnectableObject::ConnectableObjectList tempIn = getInputList(); lastSource->disconnectAllInputs(); lastSource->connectMyInputTo(obj); obj->changeOwner(this); obj->connectInputList(tempIn); tempIn = obj->getInputList(); theInputListIsFixedFlag = obj->getInputListIsFixedFlag(); setNumberOfInputs(obj->getNumberOfInputs()); imageChainList().push_back(obj); obj->addListener((ossimConnectableObjectListener*)this); // Send an event to any listeners. ossimContainerEvent event((ossimObject*)this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(obj); fireEvent(event); return true; } } else { return add(obj); } return false;; } ossimImageSource* ossimImageChain::getFirstSource() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>(imageChainList()[0].get()); } return 0; } const ossimImageSource* ossimImageChain::getFirstSource() const { if(imageChainList().size()>0) return dynamic_cast<const ossimImageSource*>(imageChainList()[0].get()); return 0; } ossimObject* ossimImageChain::getFirstObject() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>(imageChainList()[0].get()); } return 0; } ossimImageSource* ossimImageChain::getLastSource() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>((*(imageChainList().end()-1)).get()); } return NULL; } const ossimImageSource* ossimImageChain::getLastSource() const { if(imageChainList().size()>0) return dynamic_cast<const ossimImageSource*>((*(imageChainList().end()-1)).get()); return NULL; } ossimObject* ossimImageChain::getLastObject() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>((*(imageChainList().end()-1)).get()); } return 0; } ossimConnectableObject* ossimImageChain::findObject(const ossimId& id, bool /* recurse */) { std::vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).get()) { if(id == (*current)->getId()) { return (*current).get(); } } ++current; } current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* object = child->findObject(id, true); if(object) return object; } ++current; } return NULL; } ossimConnectableObject* ossimImageChain::findObject(const ossimConnectableObject* obj, bool /* recurse */) { std::vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()) { if(obj == (*current).get()) { return (*current).get(); } } ++current; } current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* object = child->findObject(obj, true); if(object) return object; } ++current; } return 0; } ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const RTTItypeid& typeInfo, bool recurse) { vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(typeInfo)) { return (*current).get(); } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* temp = child->findFirstObjectOfType(typeInfo, recurse); if(temp) { return temp; } } ++current; } } return (ossimConnectableObject*)NULL; } ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const ossimString& className, bool recurse) { vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(className) ) { return (*current).get(); } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* temp = child->findFirstObjectOfType(className, recurse); if(temp) { return temp; } } ++current; } } return (ossimConnectableObject*)0; } ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const RTTItypeid& typeInfo, bool recurse) { ossimConnectableObject::ConnectableObjectList result; ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(typeInfo)) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), (*current).get()); if(iter == result.end()) { result.push_back((*current).get()); } } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject::ConnectableObjectList temp; temp = child->findAllObjectsOfType(typeInfo, recurse); for(long index=0; index < (long)temp.size();++index) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]); if(iter == result.end()) { result.push_back(temp[index]); } } } ++current; } } return result; } ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const ossimString& className, bool recurse) { ossimConnectableObject::ConnectableObjectList result; ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(className)) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), (*current).get()); if(iter == result.end()) { result.push_back((*current).get()); } } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject::ConnectableObjectList temp; temp = child->findAllObjectsOfType(className, recurse); for(long index=0; index < (long)temp.size();++index) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]); if(iter == result.end()) { result.push_back(temp[index]); } } } ++current; } } return result; } void ossimImageChain::makeUniqueIds() { setId(ossimIdManager::instance()->generateId()); for(long index = 0; index < (long)imageChainList().size(); ++index) { ossimConnectableContainerInterface* container = PTR_CAST(ossimConnectableContainerInterface, imageChainList()[index].get()); if(container) { container->makeUniqueIds(); } else { if(imageChainList()[index].valid()) { imageChainList()[index]->setId(ossimIdManager::instance()->generateId()); } } } } ossim_uint32 ossimImageChain::getNumberOfObjects(bool recurse)const { ossim_uint32 result = (ossim_uint32)imageChainList().size(); if(recurse) { for(ossim_uint32 i = 0; i < imageChainList().size(); ++i) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, imageChainList()[i].get()); if(child) { result += child->getNumberOfObjects(true); } } } return result; } ossim_uint32 ossimImageChain::getNumberOfSources() const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimImageChain::getNumberOfSources is deprecated!" << "\nUse: ossimImageChain::getNumberOfObjects(false)" << std::endl; return getNumberOfObjects(false); } bool ossimImageChain::addChild(ossimConnectableObject* object) { return add(object); } bool ossimImageChain::removeChild(ossimConnectableObject* object) { bool result = false; vector<ossimRefPtr<ossimConnectableObject> >::iterator current = std::find(imageChainList().begin(), imageChainList().end(), object); if(current!=imageChainList().end()) { result = true; object->removeListener((ossimConnectableObjectListener*)this); if(current == imageChainList().begin()) { object->removeListener((ossimConnectableObjectListener*)this); } if(imageChainList().size() == 1) { object->changeOwner(0); current = imageChainList().erase(current); } else { ossimConnectableObject::ConnectableObjectList input = object->getInputList(); ossimConnectableObject::ConnectableObjectList output = object->getOutputList(); object->changeOwner(0);// set the owner to 0 bool erasingBeginning = (current == imageChainList().begin()); // bool erasingEnd = (current+1) == imageChainList().end(); current = imageChainList().erase(current); object->disconnect(); if(!imageChainList().empty()) { if(erasingBeginning) // the one that receives the first getTile { (*imageChainList().begin())->addListener(this); } else if(current==imageChainList().end()) // one that receives the last getTIle { current = imageChainList().begin()+(imageChainList().size()-1); (*current)->connectInputList(input); theInputObjectList = (*current)->getInputList(); theInputListIsFixedFlag = (*current)->getInputListIsFixedFlag(); } else { // prepare interior setup and removal and connect surrounding nodes // take the outputs of the node we are removing and connect them to the old inputs ossim_uint32 outIndex = 0; for(outIndex = 0; outIndex < output.size();++outIndex) { output[outIndex]->connectInputList(input); } } } } // Send an event to any listeners. ossimContainerEvent event((ossimObject*)this, OSSIM_EVENT_REMOVE_OBJECT_ID); event.setObjectList(object); fireEvent(event); } return result; } ossimConnectableObject* ossimImageChain::removeChild(const ossimId& id) { ossimIdVisitor visitor( id, (ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS ) ); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { removeChild(obj); } return obj; } void ossimImageChain::getChildren(vector<ossimConnectableObject*>& children, bool immediateChildrenOnlyFlag) { ossim_uint32 i = 0; vector<ossimConnectableObject*> temp; for(i = 0; i < imageChainList().size();++i) { temp.push_back(imageChainList()[i].get()); } for(i = 0; i < temp.size();++i) { ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface, temp[i]); if(immediateChildrenOnlyFlag) { children.push_back(temp[i]); } else if(!interface) { children.push_back(temp[i]); } } if(!immediateChildrenOnlyFlag) { for(i = 0; i < temp.size();++i) { ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface, temp[i]); if(interface) { interface->getChildren(children, false); } } } } bool ossimImageChain::add(ossimConnectableObject* source) { bool result = false; // if(PTR_CAST(ossimImageSource, source)) { source->changeOwner(this); if(imageChainList().size() > 0) { source->disconnectAllOutputs(); theOutputListIsFixedFlag = source->getOutputListIsFixedFlag(); imageChainList()[0]->removeListener(this); imageChainList().insert(imageChainList().begin(), source); imageChainList()[0]->addListener(this); source->addListener((ossimConnectableObjectListener*)this); imageChainList()[0]->connectMyInputTo(imageChainList()[1].get()); result = true; } else { theInputListIsFixedFlag = false; theOutputListIsFixedFlag = false; if(!theInputObjectList.empty()) { source->connectInputList(getInputList()); } theInputObjectList = source->getInputList(); theInputListIsFixedFlag = source->getInputListIsFixedFlag(); // theOutputObjectList = source->getOutputList(); // theOutputListIsFixedFlag= source->getOutputListIsFixedFlag(); imageChainList().push_back(source); source->addListener((ossimConnectableObjectListener*)this); source->addListener(this); result = true; } } if (result && source) { ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(source); fireEvent(event); } return result; } bool ossimImageChain::insertRight(ossimConnectableObject* newObj, ossimConnectableObject* rightOfThisObj) { if(!newObj&&!rightOfThisObj) return false; if(!imageChainList().size()) { return add(newObj); } std::vector<ossimRefPtr<ossimConnectableObject> >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), rightOfThisObj); if(iter!=imageChainList().end()) { if(iter == imageChainList().begin()) { return add(newObj); } else //if(PTR_CAST(ossimImageSource, newObj)) { ossimConnectableObject::ConnectableObjectList outputList = rightOfThisObj->getOutputList(); rightOfThisObj->disconnectAllOutputs(); // Core dump fix. Connect input prior to outputs. (drb) newObj->connectMyInputTo(rightOfThisObj); newObj->connectOutputList(outputList); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); imageChainList().insert(iter, newObj); // Send event to any listeners. ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(newObj); fireEvent(event); return true; } } return false; } bool ossimImageChain::insertRight(ossimConnectableObject* newObj, const ossimId& id) { #if 1 ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN ); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { return insertRight(newObj, obj); } return false; #else ossimConnectableObject* obj = findObject(id, false); if(obj) { return insertRight(newObj, obj); } return false; #endif } bool ossimImageChain::insertLeft(ossimConnectableObject* newObj, ossimConnectableObject* leftOfThisObj) { if(!newObj&&!leftOfThisObj) return false; if(!imageChainList().size()) { return add(newObj); } std::vector<ossimRefPtr<ossimConnectableObject> >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), leftOfThisObj); if(iter!=imageChainList().end()) { if((iter+1)==imageChainList().end()) { return addLast(newObj); } else { ossimConnectableObject::ConnectableObjectList inputList = leftOfThisObj->getInputList(); newObj->connectInputList(inputList); leftOfThisObj->disconnectAllInputs(); leftOfThisObj->connectMyInputTo(newObj); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); imageChainList().insert(iter+1, newObj); // Send an event to any listeners. ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(newObj); fireEvent(event); return true; } } return false; } bool ossimImageChain::insertLeft(ossimConnectableObject* newObj, const ossimId& id) { #if 1 ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { return insertLeft(newObj, obj); } return false; #else ossimConnectableObject* obj = findObject(id, false); if(obj) { return insertLeft(newObj, obj); } return false; #endif } bool ossimImageChain::replace(ossimConnectableObject* newObj, ossimConnectableObject* oldObj) { ossim_int32 idx = indexOf(oldObj); if(idx >= 0) { ossimConnectableObject::ConnectableObjectList& inputList = oldObj->getInputList(); ossimConnectableObject::ConnectableObjectList& outputList = oldObj->getOutputList(); oldObj->removeListener((ossimConnectableObjectListener*)this); oldObj->removeListener(this); oldObj->changeOwner(0); imageChainList()[idx] = newObj; newObj->connectInputList(inputList); newObj->connectOutputList(outputList); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); if(idx == 0) { newObj->addListener(this); } } return (idx >= 0); } ossimRefPtr<ossimImageData> ossimImageChain::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* inputSource = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(inputSource) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs return inputSource->getTile(tileRect, resLevel); } } else { if(getInput(0)) { ossimImageSource* inputSource = PTR_CAST(ossimImageSource, getInput(0)); if(inputSource) { ossimRefPtr<ossimImageData> inputTile = inputSource->getTile(tileRect, resLevel); // if(inputTile.valid()) // { // std::cout << *(inputTile.get()) << std::endl; // } return inputTile.get(); } } } // std::cout << "RETURNING A BLANK TILE!!!!" << std::endl; /* if(theBlankTile.get()) { theBlankTile->setImageRectangle(tileRect); } return theBlankTile; */ return 0; } ossim_uint32 ossimImageChain::getNumberOfInputBands() const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNumberOfOutputBands(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNumberOfOutputBands(); } } } return 0; } double ossimImageChain::getNullPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNullPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNullPixelValue(band); } } } return ossim::defaultNull(getOutputScalarType()); } double ossimImageChain::getMinPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getMinPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getMinPixelValue(band); } } } return ossim::defaultMin(getOutputScalarType()); } double ossimImageChain::getMaxPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* inter = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(inter) { return inter->getMaxPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getMaxPixelValue(band); } } } return ossim::defaultMax(getOutputScalarType()); } void ossimImageChain::getOutputBandList(std::vector<ossim_uint32>& bandList) const { if( (imageChainList().size() > 0) && isSourceEnabled() ) { ossimRefPtr<const ossimImageSource> inter = dynamic_cast<const ossimImageSource*>( imageChainList()[0].get() ); if( inter.valid() ) { // cout << "cn: " << inter->getClassName() << endl; inter->getOutputBandList(bandList); } } } ossimScalarType ossimImageChain::getOutputScalarType() const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getOutputScalarType(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getOutputScalarType(); } } } return OSSIM_SCALAR_UNKNOWN; } ossim_uint32 ossimImageChain::getTileWidth()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getTileWidth();; } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getTileWidth(); } } } return 0; } ossim_uint32 ossimImageChain::getTileHeight()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getTileHeight(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getTileHeight(); } } } return 0; } ossimIrect ossimImageChain::getBoundingRect(ossim_uint32 resLevel)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getBoundingRect(resLevel); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getBoundingRect(); } } } ossimDrect rect; rect.makeNan(); return rect; } void ossimImageChain::getValidImageVertices(vector<ossimIpt>& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface =PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getValidImageVertices(validVertices, ordering, resLevel); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getValidImageVertices(validVertices, ordering, resLevel); } } } } ossimRefPtr<ossimImageGeometry> ossimImageChain::getImageGeometry() { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if( interface ) { return interface->getImageGeometry(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getImageGeometry(); } } } return ossimRefPtr<ossimImageGeometry>(); } void ossimImageChain::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getDecimationFactor(resLevel, result); return; } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactor(resLevel, result); return; } } } result.makeNan(); } void ossimImageChain::getDecimationFactors(vector<ossimDpt>& decimations) const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getDecimationFactors(decimations); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactors(decimations); return; } } } } ossim_uint32 ossimImageChain::getNumberOfDecimationLevels()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNumberOfDecimationLevels(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNumberOfDecimationLevels(); } } } return 1; } bool ossimImageChain::addAllSources(map<ossimId, vector<ossimId> >& idMapping, const ossimKeywordlist& kwl, const char* prefix) { static const char* MODULE = "ossimImageChain::addAllSources"; ossimString copyPrefix = prefix; bool result = ossimImageSource::loadState(kwl, copyPrefix.c_str()); if(!result) { return result; } long index = 0; // ossimSource* source = NULL; vector<ossimId> inputConnectionIds; ossimString regExpression = ossimString("^(") + copyPrefix + "object[0-9]+.)"; vector<ossimString> keys = kwl.getSubstringKeyList( regExpression ); long numberOfSources = (long)keys.size();//kwl.getNumberOfSubstringKeys(regExpression); int offset = (int)(copyPrefix+"object").size(); int idx = 0; std::vector<int> theNumberList(numberOfSources); for(idx = 0; idx < (int)theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); for(idx=0;idx < (int)theNumberList.size();++idx) { ossimString newPrefix = copyPrefix; newPrefix += ossimString("object"); newPrefix += ossimString::toString(theNumberList[idx]); newPrefix += ossimString("."); if(traceDebug()) { CLOG << "trying to create source with prefix: " << newPrefix << std::endl; } ossimRefPtr<ossimObject> object = ossimObjectFactoryRegistry::instance()->createObject(kwl, newPrefix.c_str()); ossimConnectableObject* source = PTR_CAST(ossimConnectableObject, object.get()); if(source) { // we did find a source so include it in the count if(traceDebug()) { CLOG << "Created source with prefix: " << newPrefix << std::endl; } //if(PTR_CAST(ossimImageSource, source)) { ossimId id = source->getId(); inputConnectionIds.clear(); findInputConnectionIds(inputConnectionIds, kwl, newPrefix); if(inputConnectionIds.size() == 0) { // we will try to do a default connection // if(imageChainList().size()) { if(traceDebug()) { CLOG << "connecting " << source->getClassName() << " to " << imageChainList()[0]->getClassName() << std::endl; } source->connectMyInputTo(0, imageChainList()[0].get()); } } else { // we remember the connection id's so we can connect this later. // this way we make sure all sources were actually // allocated. // idMapping.insert(std::make_pair(id, inputConnectionIds)); } add(source); } // else // { source = 0; // } } else { object = 0; source = 0; } ++index; } if(imageChainList().size()) { ossimConnectableObject* obj = imageChainList()[(ossim_int32)imageChainList().size()-1].get(); if(obj) { setNumberOfInputs(obj->getNumberOfInputs()); } } return result; } void ossimImageChain::findInputConnectionIds(vector<ossimId>& result, const ossimKeywordlist& kwl, const char* prefix) { ossimString copyPrefix = prefix; ossim_uint32 idx = 0; ossimString regExpression = ossimString("^") + ossimString(prefix) + "input_connection[0-9]+"; vector<ossimString> keys = kwl.getSubstringKeyList( regExpression ); ossim_int32 offset = (ossim_int32)(copyPrefix+"input_connection").size(); ossim_uint32 numberOfKeys = (ossim_uint32)keys.size(); std::vector<int> theNumberList(numberOfKeys); for(idx = 0; idx < theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); copyPrefix += ossimString("input_connection"); for(idx=0;idx < theNumberList.size();++idx) { const char* lookup = kwl.find(copyPrefix,ossimString::toString(theNumberList[idx])); if(lookup) { long id = ossimString(lookup).toLong(); result.push_back(ossimId(id)); } } } bool ossimImageChain::connectAllSources(const map<ossimId, vector<ossimId> >& idMapping) { // cout << "this->getId(): " << this->getId() << endl; if(idMapping.size()) { map<ossimId, vector<ossimId> >::const_iterator iter = idMapping.begin(); while(iter != idMapping.end()) { // cout << "(*iter).first): " << (*iter).first << endl; #if 0 ossimConnectableObject* currentSource = findObject((*iter).first); #else ossimIdVisitor visitor( (*iter).first, (ossimVisitor::VISIT_CHILDREN ) ); // ossimVisitor::VISIT_INPUTS ) ); accept( visitor ); ossimConnectableObject* currentSource = visitor.getObject(); #endif if(currentSource) { // cout << "currentSource->getClassName: " << currentSource->getClassName() << endl; long upperBound = (long)(*iter).second.size(); for(long index = 0; index < upperBound; ++index) { //cout << "(*iter).second[index]: " << (*iter).second[index] << endl; if((*iter).second[index].getId() > -1) { #if 0 ossimConnectableObject* inputSource = PTR_CAST(ossimConnectableObject, findObject((*iter).second[index])); #else visitor.reset(); visitor.setId( (*iter).second[index] ); accept( visitor ); ossimConnectableObject* inputSource = visitor.getObject(); #endif // cout << "inputSource is " << (inputSource?"good...":"null...") << endl; if ( inputSource ) { // cout << "inputSource->getClassName(): " << inputSource->getClassName() << endl; // Check for connection to self. if ( this != inputSource ) { currentSource->connectMyInputTo(index, inputSource); } // else warning??? } } else // -1 id { currentSource->disconnectMyInput((ossim_int32)index); } } } else { cerr << "Could not find " << (*iter).first << " for source: "; return false; } ++iter; } } // abort(); return true; } bool ossimImageChain::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = true; result = ossimImageSource::saveState(kwl, prefix); if(!result) { return result; } ossim_uint32 upper = (ossim_uint32)imageChainList().size(); ossim_uint32 counter = 1; if (upper) { ossim_int32 idx = upper-1; // start with the tail and go to the head fo the list. for(;((idx >= 0)&&result);--idx, ++counter) { ossimString newPrefix = prefix; newPrefix += (ossimString("object") + ossimString::toString(counter) + ossimString(".")); result = imageChainList()[idx]->saveState(kwl, newPrefix.c_str()); } } return result; } bool ossimImageChain::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char* MODULE = "ossimImageChain::loadState(kwl, prefix)"; deleteList(); ossimImageSource::loadState(kwl, prefix); theLoadStateFlag = true; bool result = true; map<ossimId, vector<ossimId> > idMapping; result = addAllSources(idMapping, kwl, prefix); if(!result) { CLOG << "problems adding sources" << std::endl; } result = connectAllSources(idMapping); if(!result) { CLOG << "problems connecting sources" << std::endl; } theLoadStateFlag = false; return result; } void ossimImageChain::initialize() { static const char* MODULE = "ossimImageChain::initialize()"; if (traceDebug()) CLOG << " Entered..." << std::endl; long upper = (ossim_uint32)imageChainList().size(); for(long index = upper - 1; index >= 0; --index) { if(traceDebug()) { CLOG << "initializing source: " << imageChainList()[index]->getClassName() << std::endl; } if(imageChainList()[index].valid()) { ossimSource* interface = PTR_CAST(ossimSource, imageChainList()[index].get()); if(interface) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs interface->initialize(); } } } if (traceDebug()) CLOG << " Exited..." << std::endl; } void ossimImageChain::enableSource() { ossim_int32 upper = static_cast<ossim_int32>(imageChainList().size()); ossim_int32 index = 0; for(index = upper - 1; index >= 0; --index) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get()); if(source) { source->enableSource(); } } theEnableFlag = true; } void ossimImageChain::disableSource() { long upper = (ossim_uint32)imageChainList().size(); for(long index = upper - 1; index >= 0; --index) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get()); if(source) { source->disableSource(); } } theEnableFlag = false; } void ossimImageChain::prepareForRemoval(ossimConnectableObject* connectableObject) { if(connectableObject) { connectableObject->removeListener((ossimConnectableObjectListener*)this); connectableObject->changeOwner(0); connectableObject->disconnect(); } } bool ossimImageChain::deleteFirst() { if (imageChainList().size() == 0) return false; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); prepareForRemoval(imageChainList()[0].get()); // Clear any listeners, memory. event.setObjectList(imageChainList()[0].get()); imageChainList()[0] = 0; // Remove from the vector. std::vector<ossimRefPtr<ossimConnectableObject> >::iterator i = imageChainList().begin(); imageChainList().erase(i); fireEvent(event); return true; } bool ossimImageChain::deleteLast() { if (imageChainList().size() == 0) return false; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); // Clear any listeners, memory. ossim_uint32 idx = (ossim_uint32)imageChainList().size() - 1; prepareForRemoval(imageChainList()[idx].get()); event.setObjectList(imageChainList()[idx].get()); imageChainList()[idx] = 0; // Remove from the vector. imageChainList().pop_back(); fireEvent(event); return true; } void ossimImageChain::deleteList() { ossim_uint32 upper = (ossim_uint32) imageChainList().size(); ossim_uint32 idx = 0; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); for(; idx < upper; ++idx) { if(imageChainList()[idx].valid()) { event.getObjectList().push_back(imageChainList()[idx].get()); prepareForRemoval(imageChainList()[idx].get()); imageChainList()[idx] = 0; } } imageChainList().clear(); fireEvent(event); } void ossimImageChain::disconnectInputEvent(ossimConnectionEvent& event) { if(imageChainList().size()) { if(event.getObject()==this) { if(imageChainList()[imageChainList().size()-1].valid()) { for(ossim_uint32 i = 0; i < event.getNumberOfOldObjects(); ++i) { imageChainList()[imageChainList().size()-1]->disconnectMyInput(event.getOldObject(i)); } } } } } void ossimImageChain::disconnectOutputEvent(ossimConnectionEvent& /* event */) { } void ossimImageChain::connectInputEvent(ossimConnectionEvent& event) { if(imageChainList().size()) { if(event.getObject()==this) { if(imageChainList()[imageChainList().size()-1].valid()) { for(ossim_uint32 i = 0; i < event.getNumberOfNewObjects(); ++i) { ossimConnectableObject* obj = event.getNewObject(i); imageChainList()[imageChainList().size()-1]->connectMyInputTo(findInputIndex(obj), obj, false); } } } else if(event.getObject() == imageChainList()[0].get()) { if(!theLoadStateFlag) { // theInputObjectList = imageChainList()[0]->getInputList(); } } initialize(); } } void ossimImageChain::connectOutputEvent(ossimConnectionEvent& /* event */) { } // void ossimImageChain::propertyEvent(ossimPropertyEvent& event) // { // if(imageChainList().size()) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, // event.getObject()); // if(obj) // { // ossimImageSource* interface = findSource(obj->getId()); // if(interface) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, // interface.getObject()); // if(obj) // { // } // } // } // } // } void ossimImageChain::objectDestructingEvent(ossimObjectDestructingEvent& event) { if(!event.getObject()) return; if(imageChainList().size()&&(event.getObject()!=this)) { removeChild(PTR_CAST(ossimConnectableObject, event.getObject())); } } void ossimImageChain::propagateEventToOutputs(ossimEvent& event) { //if(thePropagateEventFlag) return; //thePropagateEventFlag = true; if(imageChainList().size()) { if(imageChainList()[imageChainList().size()-1].valid()) { imageChainList()[imageChainList().size()-1]->fireEvent(event); imageChainList()[imageChainList().size()-1]->propagateEventToOutputs(event); } } //ossimConnectableObject::propagateEventToOutputs(event); // thePropagateEventFlag = false; } void ossimImageChain::propagateEventToInputs(ossimEvent& event) { // if(thePropagateEventFlag) return; // thePropagateEventFlag = true; if(imageChainList().size()) { if(imageChainList()[0].valid()) { imageChainList()[0]->fireEvent(event); imageChainList()[0]->propagateEventToInputs(event); } } // thePropagateEventFlag = false; } ossimConnectableObject* ossimImageChain::operator[](ossim_uint32 index) { return getConnectableObject(index); } ossimConnectableObject* ossimImageChain::getConnectableObject( ossim_uint32 index) { if(imageChainList().size() && (index < imageChainList().size())) { return imageChainList()[index].get(); } return 0; } ossim_int32 ossimImageChain::indexOf(ossimConnectableObject* obj)const { ossim_uint32 idx = 0; for(idx = 0; idx < imageChainList().size();++idx) { if(imageChainList()[idx] == obj) { return (ossim_int32)idx; } } return -1; } void ossimImageChain::accept(ossimVisitor& visitor) { if(!visitor.hasVisited(this)) { visitor.visit(this); ossimVisitor::VisitorType currentType = visitor.getVisitorType(); //--- // Lets make sure inputs and outputs are turned off for we are traversing all children // and we should not have to have that enabled. //--- visitor.turnOffVisitorType(ossimVisitor::VISIT_INPUTS|ossimVisitor::VISIT_OUTPUTS); if(visitor.getVisitorType() & ossimVisitor::VISIT_CHILDREN) { ConnectableObjectList::reverse_iterator current = imageChainList().rbegin(); while((current != imageChainList().rend())&&!visitor.stopTraversal()) { ossimRefPtr<ossimConnectableObject> currentObject = (*current); if(currentObject.get() && !visitor.hasVisited(currentObject.get())) currentObject->accept(visitor); ++current; } } visitor.setVisitorType(currentType); ossimConnectableObject::accept(visitor); } } //************************************************************************************************** // Inserts all of its children and inputs into the container provided. Since ossimImageChain is // itself a form of container, this method will consolidate this chain with the argument // container. Therefore this chain object will not be represented in the container (but its // children will be, with correct input and output connections to external objects). // Returns TRUE if successful. //************************************************************************************************** #if 0 bool ossimImageChain::fillContainer(ossimConnectableContainer& container) { // Grab the first source in the chain and let it fill the container with itself and inputs. This // will traverse down the chain and will even pick up external sources that feed this chain: ossimRefPtr<ossimConnectableObject> first_source = getFirstSource(); if (!first_source.valid()) return false; first_source->fillContainer(container); // Instead of adding ourselves, make sure my first source is properly connected to my output, // thus obviating the need for this image chain (my chain items become part of 'container': ConnectableObjectList& obj_list = getOutputList(); ossimRefPtr<ossimConnectableObject> output_connection = 0; while (!obj_list.empty()) { // Always pick off the beginning of the list since it is shrinking with each disconnect: output_connection = obj_list[0]; disconnectMyOutput(output_connection.get(), true, false); first_source->connectMyOutputTo(output_connection.get()); } return true; } #endif
29.397171
146
0.56548
vladislav-horbatiuk
17a3497f4476a51f14d68b4a6844f65d212f964d
10,281
cpp
C++
test/image_threshold_to_zero_cts.cpp
daemyung/vps
b031151e42fb355446bb4e207b74e65eb0e4b9ac
[ "MIT" ]
null
null
null
test/image_threshold_to_zero_cts.cpp
daemyung/vps
b031151e42fb355446bb4e207b74e65eb0e4b9ac
[ "MIT" ]
null
null
null
test/image_threshold_to_zero_cts.cpp
daemyung/vps
b031151e42fb355446bb4e207b74e65eb0e4b9ac
[ "MIT" ]
null
null
null
// // This file is part of the "vps" project // See "LICENSE" for license information. // #include <doctest.h> #include <vps.h> #define VMA_IMPLEMENTATION #include <vk_mem_alloc.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> #include <iostream> using namespace std; using namespace doctest; TEST_SUITE_BEGIN("image threshold to zero test suite"); //---------------------------------------------------------------------------------------------------------------------- TEST_CASE("test image threshold to zero") { /*Window_desc desc; desc.title = default_title; desc.extent = default_extent; auto window = make_unique<Window>(desc); CHECK(window); REQUIRE(window->title() == default_title); REQUIRE(window->extent() == default_extent);*/ VkResult result; VkInstance instance; { const char* layerNames = "VK_LAYER_KHRONOS_validation"; VkInstanceCreateInfo create_info {}; create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = &layerNames; result = vkCreateInstance(&create_info, nullptr, &instance); } VkPhysicalDevice physical_device; { uint32_t cnt = 1; result = vkEnumeratePhysicalDevices(instance, &cnt, &physical_device); } VkDevice device; { float priority = 1.0f; VkDeviceQueueCreateInfo queue_info {}; queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_info.queueFamilyIndex = 0; queue_info.queueCount = 1; queue_info.pQueuePriorities = &priority; VkDeviceCreateInfo info {}; info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; info.queueCreateInfoCount = 1; info.pQueueCreateInfos = &queue_info; result = vkCreateDevice(physical_device, &info, nullptr, &device); } VmaAllocator allocator; { VmaAllocatorCreateInfo create_info {}; create_info.physicalDevice = physical_device; create_info.device = device; create_info.instance = instance; vmaCreateAllocator(&create_info, &allocator); } int x, y, n; unsigned char* contents; { contents = stbi_load(VPS_ASSET_PATH"/image/lena.bmp", &x, &y, &n, STBI_rgb_alpha); // contents = stbi_load("C:/Users/djang/repos/vps/build/vps/src.png", &x, &y, &n, STBI_rgb_alpha); } VkImage src_image; VmaAllocation src_allocation; VkImageView src_image_view; { VkImageCreateInfo image_info {}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = VK_FORMAT_R8G8B8A8_UNORM; image_info.extent.width = x; image_info.extent.height = y; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.tiling = VK_IMAGE_TILING_LINEAR; // image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.usage = VK_IMAGE_USAGE_STORAGE_BIT; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VmaAllocationCreateInfo allocation_info {}; allocation_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; vmaCreateImage(allocator, &image_info, &allocation_info, &src_image, &src_allocation, nullptr); VkImageViewCreateInfo view_info {}; view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_info.image = src_image; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.format = VK_FORMAT_R8G8B8A8_UNORM; view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.layerCount = 1; view_info.subresourceRange.levelCount = 1; vkCreateImageView(device, &view_info, nullptr, &src_image_view); } { void* ptr; vmaMapMemory(allocator, src_allocation, &ptr); memcpy(ptr, contents, x * y * 4); stbi_image_free(contents); } VkImage dst_image; VmaAllocation dst_allocation; VkImageView dst_image_view; VmaAllocationInfo i {}; { VkImageCreateInfo image_info {}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = VK_FORMAT_R8G8B8A8_UNORM; image_info.extent.width = x; image_info.extent.height = y; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.tiling = VK_IMAGE_TILING_LINEAR; image_info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VmaAllocationCreateInfo allocation_info {}; allocation_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; vmaCreateImage(allocator, &image_info, &allocation_info, &dst_image, &dst_allocation, &i); VkImageViewCreateInfo view_info {}; view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_info.image = dst_image; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.format = VK_FORMAT_R8G8B8A8_UNORM; view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.layerCount = 1; view_info.subresourceRange.levelCount = 1; vkCreateImageView(device, &view_info, nullptr, &dst_image_view); } VkBuffer dump; VmaAllocation dump_alloc; { VkBufferCreateInfo buffer_create_info {}; buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_create_info.size = x * y * 4; buffer_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocation_create_info {}; allocation_create_info.usage = VMA_MEMORY_USAGE_CPU_COPY; result = vmaCreateBuffer(allocator, &buffer_create_info, &allocation_create_info, &dump, &dump_alloc, nullptr); } VkCommandPool command_pool; { VkCommandPoolCreateInfo create_info {}; create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; create_info.queueFamilyIndex = 0; vkCreateCommandPool(device, &create_info, nullptr, &command_pool); } VkCommandBuffer cmd_buf; { VkCommandBufferAllocateInfo allocate_info {}; allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocate_info.commandPool = command_pool; allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocate_info.commandBufferCount = 1; vkAllocateCommandBuffers(device, &allocate_info, &cmd_buf); } VkQueue queue; vkGetDeviceQueue(device, 0, 0, &queue); VpsContextCreateInfo createInfo {}; createInfo.instance = instance; createInfo.physicalDevice = physical_device; createInfo.device = device; VpsContext context = VK_NULL_HANDLE; vpsCreateContext(&createInfo, &context); VkCommandBufferBeginInfo bi {}; bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; vkBeginCommandBuffer(cmd_buf, &bi); { VkImageMemoryBarrier barriers[2]; barriers[0] = {}; barriers[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barriers[0].srcAccessMask = 0; barriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; barriers[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barriers[0].newLayout = VK_IMAGE_LAYOUT_GENERAL; barriers[0].image = src_image; barriers[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barriers[0].subresourceRange.baseArrayLayer = 0; barriers[0].subresourceRange.baseMipLevel = 0; barriers[0].subresourceRange.layerCount = 1; barriers[0].subresourceRange.levelCount = 1; barriers[1] = {}; barriers[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barriers[1].srcAccessMask = 0; barriers[1].dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; barriers[1].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barriers[1].newLayout = VK_IMAGE_LAYOUT_GENERAL; barriers[1].image = dst_image; barriers[1].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barriers[1].subresourceRange.baseArrayLayer = 0; barriers[1].subresourceRange.baseMipLevel = 0; barriers[1].subresourceRange.layerCount = 1; barriers[1].subresourceRange.levelCount = 1; vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 2, barriers); } vpsCmdImageThresholdToZero(context, cmd_buf, src_image_view, dst_image_view, 0.2, nullptr); { VkImageMemoryBarrier barrier; barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.image = dst_image; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.layerCount = 1; barrier.subresourceRange.levelCount = 1; vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); } { VkBufferImageCopy region {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageSubresource.mipLevel = 0; region.imageExtent.width = x; region.imageExtent.height = y; region.imageExtent.depth = 1; vkCmdCopyImageToBuffer(cmd_buf, dst_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dump, 1, &region); } vkEndCommandBuffer(cmd_buf); VkSubmitInfo si {}; si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; si.commandBufferCount = 1; si.pCommandBuffers = &cmd_buf; vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE); vkDeviceWaitIdle(device); void* p; vmaMapMemory(allocator, dump_alloc, &p); stbi_write_png("result.png", x, y, STBI_rgb_alpha, p, 0); // vpsDestoryContext(context); } //---------------------------------------------------------------------------------------------------------------------- TEST_SUITE_END();
29.458453
146
0.744383
daemyung
17a387e83243244c68727d5b43f0490e257a98f1
5,425
cpp
C++
TileServer und Tiles/threadfilereaders.cpp
andr1312e/Russia-Tiles-Server
c1d596b84e22c170ba0f795ed6e2bfb80167eeb6
[ "Unlicense" ]
null
null
null
TileServer und Tiles/threadfilereaders.cpp
andr1312e/Russia-Tiles-Server
c1d596b84e22c170ba0f795ed6e2bfb80167eeb6
[ "Unlicense" ]
null
null
null
TileServer und Tiles/threadfilereaders.cpp
andr1312e/Russia-Tiles-Server
c1d596b84e22c170ba0f795ed6e2bfb80167eeb6
[ "Unlicense" ]
null
null
null
#include "threadfilereaders.h" ThreadImageRotator::ThreadImageRotator(const QString *pathToSourceSvg,const QString *pathToRendedImage,const QString *fileType, const QString *slash, QObject *parent) : QObject(parent) , m_timer(new QTimer(this)) , m_imageRotatorHash(new QHash<QThread*, ImageRotator*>()) , m_freeThreadsQueue(new std::queue<QThread*>()) , m_tilesQueue(new std::queue<TileData>()) , m_svgType(new QString(QStringLiteral(".svg"))) { qInfo()<<"ThreadFileReader constructor"; initTimer(); createDataStructs(pathToSourceSvg, pathToRendedImage, fileType, slash); createConnections(); } ThreadImageRotator::~ThreadImageRotator() { QHashIterator<QThread*, ImageRotator*> iterator(*m_imageRotatorHash); while (iterator.hasNext()) { iterator.next(); delete iterator.value(); delete iterator.key(); } delete m_tilesQueue; delete m_imageRotatorHash; delete m_freeThreadsQueue; delete m_timer; } void ThreadImageRotator::gettingTilesToConvert(QStringList &tiles, int &numOfImages, QString &azm, QString &layer) { char firstParam=azm.at(0).toLatin1(); char secondParam=azm.at(1).toLatin1(); char thirdParam=azm.at(2).toLatin1(); QStringList::iterator it=tiles.begin(); if(m_freeThreadsQueue->size()>=numOfImages) { for (; it!=tiles.end(); ++it) { QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->value(thread)->setParams(*it, azm, layer, firstParam, secondParam, thirdParam); thread->start(); } } else { int numImagesToQueue=numOfImages; for (int i=0; i<m_freeThreadsQueue->size(); i++, ++it) { QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->value(thread)->setParams(*it, azm, layer, firstParam, secondParam, thirdParam); thread->start(); numImagesToQueue--; } for (int i=numOfImages-1; i>numOfImages-numImagesToQueue; i--) { m_tilesQueue->push(TileData(tiles[i], azm , layer)); } m_timer->start(m_timerInterval); } } void ThreadImageRotator::seekAvailableThreads() { if (!m_tilesQueue->empty()) { readFilesFromQueue(); } } void ThreadImageRotator::addThreadToQueue() { m_freeThreadsQueue->push(qobject_cast<QThread *>(sender())); } void ThreadImageRotator::readFilesFromQueue() { if (!m_tilesQueue->empty()&&!m_freeThreadsQueue->empty()) { if(m_tilesQueue->size()<=m_freeThreadsQueue->size()) { for (int i=0; i<m_tilesQueue->size(); i++) { TileData tile= m_tilesQueue->front(); m_tilesQueue->pop(); char firstParam=tile.azm.at(0).toLatin1(); char secondParam=tile.azm.at(1).toLatin1(); char thirdParam=tile.azm.at(2).toLatin1(); QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->operator [](thread)->setParams(tile.tile, tile.azm, tile.layer, firstParam, secondParam, thirdParam); thread->start(QThread::TimeCriticalPriority); } } else { for (int i=0; i<m_freeThreadsQueue->size(); i++) { TileData tile= m_tilesQueue->front(); m_tilesQueue->pop(); char firstParam=tile.azm.at(0).toLatin1(); char secondParam=tile.azm.at(1).toLatin1(); char thirdParam=tile.azm.at(2).toLatin1(); QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->operator [](thread)->setParams(tile.tile, tile.azm, tile.layer, firstParam, secondParam, thirdParam); thread->start(QThread::TimeCriticalPriority); } m_timer->start(m_timerInterval); } } } void ThreadImageRotator::initTimer() { m_timer->setInterval(m_timerInterval); m_timer->setTimerType(Qt::CoarseTimer); m_timer->setSingleShot(true); } void ThreadImageRotator::createDataStructs(const QString *pathToSourceSvg,const QString *pathToRendedImage,const QString *fileType, const QString *slash) { for (int i=0; i<m_numOfThreads; i++) { m_imageRotatorHash->insert(new QThread(), new ImageRotator(pathToSourceSvg, pathToRendedImage, fileType, slash, m_svgType, nullptr)); } QList<QThread*>keys=m_imageRotatorHash->keys(); for (QList<QThread*>::const_iterator it=keys.cbegin(), total = keys.cend(); it!=total; ++it) { m_freeThreadsQueue->push(*it); } } void ThreadImageRotator::createConnections() { QHashIterator<QThread*, ImageRotator*> iterator(*m_imageRotatorHash); while (iterator.hasNext()) { iterator.next(); connect(iterator.key(), &QThread::started, iterator.value(), &ImageRotator::doing); connect(iterator.value(), &ImageRotator::finished, iterator.key(), &QThread::quit); connect(iterator.key(), &QThread::finished, this, &ThreadImageRotator::addThreadToQueue); iterator.value()->moveToThread(iterator.key()); } connect(m_timer, &QTimer::timeout, this, &ThreadImageRotator::seekAvailableThreads); }
36.409396
166
0.634101
andr1312e
17ab7dcda5ad069ac93417ade4b86295cf14ff6c
3,055
cpp
C++
code/opengl.cpp
elvismd/tanksgame
8c2c9daa9963b9d5a5e16a8515bd4c3e7d231799
[ "MIT" ]
null
null
null
code/opengl.cpp
elvismd/tanksgame
8c2c9daa9963b9d5a5e16a8515bd4c3e7d231799
[ "MIT" ]
null
null
null
code/opengl.cpp
elvismd/tanksgame
8c2c9daa9963b9d5a5e16a8515bd4c3e7d231799
[ "MIT" ]
null
null
null
#include "opengl.h" #include "logger.h" #define CHECK_GL(...) check_gl_error(__FILE__, __LINE__); int check_gl_error(char * file, int line) { GLuint err = glGetError(); if (err > 0) { log_warning("GL Error - file:%s line: %d error: %d", file, line, err); switch(err) { case GL_INVALID_ENUM: log_warning("GL_INVALID_ENUM: Given when an enumeration parameter is not a legal enumeration for that function. This is given only for local problems; if the spec allows the enumeration in certain circumstances, where other parameters or state dictate those circumstances, then GL_INVALID_OPERATION is the result instead."); break; case GL_INVALID_VALUE: log_warning("GL_INVALID_VALUE: Given when a value parameter is not a legal value for that function. This is only given for local problems; if the spec allows the value in certain circumstances, where other parameters or state dictate those circumstances, then GL_INVALID_OPERATION is the result instead."); break; case GL_INVALID_OPERATION: log_warning("GL_INVALID_OPERATION: Given when the set of state for a command is not legal for the parameters given to that command. It is also given for commands where combinations of parameters define what the legal parameters are."); break; case GL_STACK_OVERFLOW: log_warning("GL_STACK_OVERFLOW: Given when a stack pushing operation cannot be done because it would overflow the limit of that stack's size."); break; case GL_STACK_UNDERFLOW: log_warning("GL_STACK_UNDERFLOW: Given when a stack popping operation cannot be done because the stack is already at its lowest point."); break; case GL_OUT_OF_MEMORY: log_warning("GL_OUT_OF_MEMORY: Given when performing an operation that can allocate memory, and the memory cannot be allocated. The results of OpenGL functions that return this error are undefined; it is allowable for partial operations to happen."); break; case GL_INVALID_FRAMEBUFFER_OPERATION: log_warning("GL_INVALID_FRAMEBUFFER_OPERATION: Given when doing anything that would attempt to read from or write/render to a framebuffer that is not complete."); break; case GL_CONTEXT_LOST: log_warning("GL_CONTEXT_LOST: Given if the OpenGL context has been lost, due to a graphics card reset."); break; } } return err; } void init_renderer(void* data) { if (!gladLoadGLLoader((GLADloadproc)data)) { printf("Failed to init GLAD. \n"); Assert(false); } // TODO : Print those char* opengl_vendor = (char*)glGetString(GL_VENDOR); char* opengl_renderer = (char*)glGetString(GL_RENDERER); char* opengl_version = (char*)glGetString(GL_VERSION); char* shading_language_version = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION); log_info("GL Vendor %s", opengl_vendor); log_info("GL Renderer %s", opengl_renderer); log_info("GL Version %s", opengl_version); log_info("GL Shading Language Version %s", shading_language_version); // GLint n, i; // glGetIntegerv(GL_NUM_EXTENSIONS, &n); // for (i = 0; i < n; i++) // { // char* extension = (char*)glGetStringi(GL_EXTENSIONS, i); // } }
56.574074
356
0.762029
elvismd
17ada2e487cfb137c6cf76c9121d18e063a40fb9
29,878
hpp
C++
include/dca/phys/dca_step/cluster_solver/ctaux/accumulator/tp/accumulator_nonlocal_chi.hpp
yingwaili/DCA
31c298a1831f90daf62ea8bb6b683229513d7c08
[ "BSD-3-Clause" ]
null
null
null
include/dca/phys/dca_step/cluster_solver/ctaux/accumulator/tp/accumulator_nonlocal_chi.hpp
yingwaili/DCA
31c298a1831f90daf62ea8bb6b683229513d7c08
[ "BSD-3-Clause" ]
null
null
null
include/dca/phys/dca_step/cluster_solver/ctaux/accumulator/tp/accumulator_nonlocal_chi.hpp
yingwaili/DCA
31c298a1831f90daf62ea8bb6b683229513d7c08
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Peter Staar ([email protected]) // // This class computes the nonlocal \f$\chi(k_1,k_2,q)\f$. /* * Definition of two-particle functions: * * \section ph particle-hole channel: * * The magnetic channel, * * \f{eqnarray*}{ * G^{II}_{ph} &=& \frac{1}{4} \sum_{\sigma_1,\sigma_2 = \pm1} (\sigma_1 \: \sigma_2) \langle * T_\tau\{c^\dagger_{k_1+q,\sigma_1} c_{k_1,\sigma_1} c^\dagger_{k_2,\sigma_2} * c_{k_2+q,\sigma_2} \}\rangle * \f} * * The charge channel, * * \f{eqnarray*}{ * G^{II}_{ph} &=& \frac{1}{4} \sum_{\sigma_1,\sigma_2 = \pm1} \langle * T_\tau\{c^\dagger_{k_1+q,\sigma_1} c_{k_1,\sigma_1} c^\dagger_{k_2,\sigma_2} * c_{k_2+q,\sigma_2} \}\rangle * \f} * * The transverse channel, * * \f{eqnarray*}{ * G^{II}_{ph} &=& \frac{1}{2} \sum_{\sigma = \pm1} \langle T_\tau\{c^\dagger_{k_1+q,\sigma} * c_{k_1,-\sigma} c^\dagger_{k_2,-\sigma} c_{k_2+q,\sigma} \}\rangle * \f} * * \section pp particle-hole channel: * * The transverse (or superconducting) channel, * * \f{eqnarray*}{ * G^{II}_{pp} &=& \frac{1}{2} \sum_{\sigma= \pm1} \langle T_\tau\{ c^\dagger_{q-k_1,\sigma} * c^\dagger_{k_1,-\sigma} c_{k_2,-\sigma} c_{q-k_2,\sigma} \} * \f} */ #ifndef DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP #define DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP #include <cassert> #include <cmath> #include <complex> #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/phys/domains/cluster/cluster_domain.hpp" #include "dca/phys/domains/quantum/electron_band_domain.hpp" #include "dca/phys/domains/time_and_frequency/vertex_frequency_domain.hpp" #include "dca/phys/four_point_type.hpp" #include "dca/phys/domains/cluster/cluster_domain_aliases.hpp" namespace dca { namespace phys { namespace solver { namespace ctaux { // dca::phys::solver::ctaux:: template <class parameters_type, class MOMS_type> class accumulator_nonlocal_chi { public: using w_VERTEX = func::dmn_0<domains::vertex_frequency_domain<domains::COMPACT>>; using w_VERTEX_EXTENDED = func::dmn_0<domains::vertex_frequency_domain<domains::EXTENDED>>; using w_VERTEX_EXTENDED_POS = func::dmn_0<domains::vertex_frequency_domain<domains::EXTENDED_POSITIVE>>; using b = func::dmn_0<domains::electron_band_domain>; using CDA = ClusterDomainAliases<parameters_type::lattice_type::DIMENSION>; using RClusterDmn = typename CDA::RClusterDmn; using KClusterDmn = typename CDA::KClusterDmn; // This needs shifted to new aliases typedef RClusterDmn r_dmn_t; typedef KClusterDmn k_dmn_t; typedef typename r_dmn_t::parameter_type r_cluster_type; typedef typename k_dmn_t::parameter_type k_cluster_type; typedef typename parameters_type::profiler_type profiler_t; typedef typename parameters_type::concurrency_type concurrency_type; typedef typename parameters_type::MC_measurement_scalar_type scalar_type; typedef typename parameters_type::G4_w1_dmn_t w1_dmn_t; typedef typename parameters_type::G4_w2_dmn_t w2_dmn_t; typedef func::dmn_variadic<b, b, r_dmn_t, r_dmn_t, w1_dmn_t, w2_dmn_t> b_b_r_r_w_w_dmn_t; typedef func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w1_dmn_t, w2_dmn_t> b_b_k_k_w_w_dmn_t; public: accumulator_nonlocal_chi( parameters_type& parameters_ref, MOMS_type& MOMS_ref, int id, func::function<std::complex<double>, func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4_ref); void initialize(); void finalize(); template <class nonlocal_G_t> void execute(scalar_type current_sign, nonlocal_G_t& nonlocal_G_obj); private: void F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result); void F(int n1, int m1, int k1, int k2, int w1, int w2, func::function< std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result); void F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result); void F(int n1, int m1, int k1, int k2, int w1, int w2, func::function< std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function< std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result); void accumulate_particle_hole_transverse( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); void accumulate_particle_hole_magnetic( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); void accumulate_particle_hole_charge( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); void accumulate_particle_particle_superconducting( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); private: parameters_type& parameters; MOMS_type& MOMS; concurrency_type& concurrency; int thread_id; func::function<std::complex<double>, func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4; int w_VERTEX_EXTENDED_POS_dmn_size; func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED> b_b_k_k_w_full_w_full_dmn; func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED> b_b_k_k_w_pos_w_full_dmn; func::function<int, k_dmn_t> min_k_dmn_t; func::function<int, k_dmn_t> q_plus_; func::function<int, k_dmn_t> q_min_; func::function<int, w_VERTEX> min_w_vertex; func::function<int, w_VERTEX_EXTENDED> min_w_vertex_ext; func::function<int, w_VERTEX> w_vertex_2_w_vertex_ext; func::function<int, w_VERTEX_EXTENDED> w_vertex_ext_2_w_vertex_ext_pos; }; template <class parameters_type, class MOMS_type> accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulator_nonlocal_chi( parameters_type& parameters_ref, MOMS_type& MOMS_ref, int id, func::function<std::complex<double>, func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4_ref) : parameters(parameters_ref), MOMS(MOMS_ref), concurrency(parameters.get_concurrency()), thread_id(id), G4(G4_ref), w_VERTEX_EXTENDED_POS_dmn_size(w_VERTEX_EXTENDED_POS::dmn_size()), b_b_k_k_w_full_w_full_dmn(), b_b_k_k_w_pos_w_full_dmn(), min_k_dmn_t("min_k_dmn_t"), q_plus_("q_plus_"), q_min_("q_min_"), min_w_vertex(" min_w_vertex"), min_w_vertex_ext("min_w_vertex_ext"), w_vertex_2_w_vertex_ext("w_vertex_2_w_vertex_ext"), w_vertex_ext_2_w_vertex_ext_pos("w_vertex_ext_2_w_vertex_ext_pos") { int q_channel = parameters.get_four_point_momentum_transfer_index(); // int k0_index = k_cluster_type::get_k_0_index(); int k0_index = k_cluster_type::origin_index(); for (int l = 0; l < k_cluster_type::get_size(); l++) { min_k_dmn_t(l) = k_cluster_type::subtract(l, k0_index); q_plus_(l) = k_cluster_type::add(l, q_channel); q_min_(l) = k_cluster_type::subtract(l, q_channel); } { for (int l = 0; l < w_VERTEX::dmn_size(); l++) min_w_vertex(l) = w_VERTEX::dmn_size() - 1 - l; for (int l = 0; l < w_VERTEX_EXTENDED::dmn_size(); l++) min_w_vertex_ext(l) = w_VERTEX_EXTENDED::dmn_size() - 1 - l; } { for (int i = 0; i < w_VERTEX::dmn_size(); i++) for (int j = 0; j < w_VERTEX_EXTENDED::dmn_size(); j++) if (std::fabs(w_VERTEX::get_elements()[i] - w_VERTEX_EXTENDED::get_elements()[j]) < 1.e-6) w_vertex_2_w_vertex_ext(i) = j; } { for (int l = 0; l < w_VERTEX_EXTENDED::dmn_size(); l++) { if (l < w_VERTEX_EXTENDED_POS::dmn_size()) w_vertex_ext_2_w_vertex_ext_pos(l) = w_VERTEX_EXTENDED_POS::dmn_size() - 1 - l; else w_vertex_ext_2_w_vertex_ext_pos(l) = l - w_VERTEX_EXTENDED_POS::dmn_size(); // cout << l << "\t" << w_vertex_ext_2_w_vertex_ext_pos(l) << "\n"; } } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::initialize() { MOMS.get_G4_k_k_w_w() = 0.; } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::finalize() { // for(int i=0; i<G4.size(); i++) // MOMS.G4_k_k_w_w(i) = G4(i); } template <class parameters_type, class MOMS_type> template <class nonlocal_G_t> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::execute(scalar_type current_sign, nonlocal_G_t& nonlocal_G_obj) { profiler_t profiler("compute nonlocal-chi", "CT-AUX accumulator", __LINE__, thread_id); switch (parameters.get_four_point_type()) { case PARTICLE_HOLE_TRANSVERSE: accumulate_particle_hole_transverse(nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; case PARTICLE_HOLE_MAGNETIC: accumulate_particle_hole_magnetic(nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; case PARTICLE_HOLE_CHARGE: accumulate_particle_hole_charge(nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; case PARTICLE_PARTICLE_UP_DOWN: accumulate_particle_particle_superconducting( nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; default: throw std::logic_error(__FUNCTION__); } } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result) { G2_result = G2(n1, m1, k1, k2, w1, w2); } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result) { if (w1 < w_VERTEX_EXTENDED_POS_dmn_size) { G2_result = conj(G2(n1, m1, min_k_dmn_t(k1), min_k_dmn_t(k2), w_vertex_ext_2_w_vertex_ext_pos(w1), min_w_vertex_ext(w2))); } else { G2_result = G2(n1, m1, k1, k2, w_vertex_ext_2_w_vertex_ext_pos(w1), w2); } } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result) { int lin_ind = b_b_k_k_w_full_w_full_dmn(n1, m1, k1, k2, w1, w2); G2_dn_result = G2_dn(lin_ind); G2_up_result = G2_up(lin_ind); } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result) { if (w1 < w_VERTEX_EXTENDED_POS_dmn_size) { int lin_ind = b_b_k_k_w_pos_w_full_dmn(n1, m1, min_k_dmn_t(k1), min_k_dmn_t(k2), w_vertex_ext_2_w_vertex_ext_pos(w1), min_w_vertex_ext(w2)); G2_dn_result = conj(G2_dn(lin_ind)); G2_up_result = conj(G2_up(lin_ind)); } else { int lin_ind = b_b_k_k_w_pos_w_full_dmn(n1, m1, k1, k2, w_vertex_ext_2_w_vertex_ext_pos(w1), w2); G2_dn_result = G2_dn(lin_ind); G2_up_result = G2_up(lin_ind); } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_magnetic( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { // n1 ------------------------ m1 // | | // | | // | | // n2 ------------------------ m2 std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_UP_n1_m1_k1_k1_plus_q_w1_w1, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4_val; int k2_plus_q, k1_plus_q; scalar_type sign_div_2 = scalar_type(sign) / 2.; int w_nu = parameters.get_four_point_frequency_transfer(); for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w2_ext_plus_w_nu = w2_ext + w_nu; assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) < 1.e-6); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w1_ext_plus_w_nu = w1_ext + w_nu; for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { // int k2_plus_q = k_cluster_type::add(k2,q_channel); k2_plus_q = q_plus_(k2); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { // int k1_plus_q = k_cluster_type::add(k1,q_channel); k1_plus_q = q_plus_(k1); for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); F(n1, m1, k1, k1_plus_q, w1_ext, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k1_plus_q_w1_w1); F(n2, m2, k2_plus_q, k2, w2_ext_plus_w_nu, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_k2_plus_q_k2_w2_w2); G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 + G2_UP_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1) + (G2_UP_n1_m1_k1_k1_plus_q_w1_w1 - G2_DN_n1_m1_k1_k1_plus_q_w1_w1) * (G2_UP_n2_m2_k2_plus_q_k2_w2_w2 - G2_DN_n2_m2_k2_plus_q_k2_w2_w2); /* G4 = - (G2_k_k_w_w_e_DN(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_DN(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel) + G2_k_k_w_w_e_UP(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_UP(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel)) + (G2_k_k_w_w_e_UP(n1, m1, k1, k1_plus_q, w1, w1+w_channel) - G2_k_k_w_w_e_DN(n1, m1, k1, k1_plus_q, w1, w1+w_channel)) * (G2_k_k_w_w_e_UP(n2, m2, k2_plus_q, k2, w2+w_channel, w2) - G2_k_k_w_w_e_DN(n2, m2, k2_plus_q, k2, w2+w_channel, w2)); */ G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); // MOMS.G4_k_k_w_w(n1, n2, m1, m2, k1, k2, w1, w2) += // std::complex<double>(sign_div_2 * G4); } } } } } } } } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_transverse( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { // n1 ------------------------ m1 // | | // | | // | | // n2 ------------------------ m2 std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G4_val; int k2_plus_q, k1_plus_q; scalar_type sign_div_2 = scalar_type(sign) / 2.; int w_nu = parameters.get_four_point_frequency_transfer(); for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w2_ext_plus_w_nu = w2_ext + w_nu; assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) < 1.e-6); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w1_ext_plus_w_nu = w1_ext + w_nu; for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { k2_plus_q = q_plus_(k2); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { k1_plus_q = q_plus_(k1); for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { // F(n1, m2, k1, k2, w1, w2, // G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, // G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); // F(n2, m1, k2_plus_q, k1_plus_q, w2+w_nu, w1+w_nu, // G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, // G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1 + G2_UP_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1); G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); } } } } } } } } } /* template<class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_magnetic_fast(func::function<std::complex<scalar_type>, func::dmn_variadic<b,b,k_dmn_t,k_dmn_t,w_VERTEX,w_VERTEX> >& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, func::dmn_variadic<b,b,k_dmn_t,k_dmn_t,w_VERTEX,w_VERTEX> >& G2_k_k_w_w_e_UP, scalar_type sign) { std::complex<scalar_type> *G2_DN_n1_m2_k1_k2_w1_w2, *G2_UP_n1_m2_k1_k2_w1_w2, *G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, *G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, *G2_DN_n1_m1_k1_k1_plus_q_w1_w1, *G2_UP_n1_m1_k1_k1_plus_q_w1_w1, *G2_DN_n2_m2_k2_plus_q_k2_w2_w2, *G2_UP_n2_m2_k2_plus_q_k2_w2_w2; std::complex<double>* G4; int k2_plus_q, k1_plus_q; scalar_type sign_div_2 =scalar_type(sign)/2.; for(int w2=0; w2<w_VERTEX::dmn_size(); w2++){ for(int w1=0; w1<w_VERTEX::dmn_size(); w1++){ for(int k2=0; k2<k_dmn_t::dmn_size(); k2++){ // int k2_plus_q = k_cluster_type::add(k2,q_channel); k2_plus_q = q_plus_(k2); for(int k1=0; k1<k_dmn_t::dmn_size(); k1++){ // int k1_plus_q = k_cluster_type::add(k1,q_channel); k1_plus_q = q_plus_(k1); G2_DN_n1_m2_k1_k2_w1_w2 = &G2_k_k_w_w_e_DN(0, 0, k1, k2, w1, w2); G2_UP_n1_m2_k1_k2_w1_w2 = &G2_k_k_w_w_e_UP(0, 0, k1, k2, w1, w2); G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 = &G2_k_k_w_w_e_DN(0, 0, k2_plus_q, k1_plus_q, w2, w1); G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1 = &G2_k_k_w_w_e_UP(0, 0, k2_plus_q, k1_plus_q, w2, w1); G2_DN_n1_m1_k1_k1_plus_q_w1_w1 = &G2_k_k_w_w_e_DN(0, 0, k1, k1_plus_q, w1, w1); G2_UP_n1_m1_k1_k1_plus_q_w1_w1 = &G2_k_k_w_w_e_UP(0, 0, k1, k1_plus_q, w1, w1); G2_DN_n2_m2_k2_plus_q_k2_w2_w2 = &G2_k_k_w_w_e_DN(0, 0, k2_plus_q, k2, w2, w2); G2_UP_n2_m2_k2_plus_q_k2_w2_w2 = &G2_k_k_w_w_e_UP(0, 0, k2_plus_q, k2, w2, w2); G4 = &MOMS.G4_k_k_w_w(0,0,0,0, k1, k2, w1, w2); accumulator_nonlocal_chi_atomic<model, PARTICLE_HOLE_MAGNETIC>::execute(G2_DN_n1_m2_k1_k2_w1_w2 , G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n1_m1_k1_k1_plus_q_w1_w1 , G2_UP_n1_m1_k1_k1_plus_q_w1_w1, G2_DN_n2_m2_k2_plus_q_k2_w2_w2 , G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4, sign_div_2); } } } } } */ template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_charge( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { // n1 ------------------------ m1 // | | // | | // | | // n2 ------------------------ m2 // int q_channel = parameters.get_q_channel(); std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_UP_n1_m1_k1_k1_plus_q_w1_w1, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4_val; int w_nu = parameters.get_four_point_frequency_transfer(); scalar_type sign_div_2 = scalar_type(sign) / 2.; for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w2_ext_plus_w_nu = w2_ext + w_nu; assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) < 1.e-6); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w1_ext_plus_w_nu = w1_ext + w_nu; for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { // int k2_plus_q = k_cluster_type::add(k2,q_channel); int k2_plus_q = q_plus_(k2); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { // int k1_plus_q = k_cluster_type::add(k1,q_channel); int k1_plus_q = q_plus_(k1); for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); F(n1, m1, k1, k1_plus_q, w1_ext, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k1_plus_q_w1_w1); F(n2, m2, k2_plus_q, k2, w2_ext_plus_w_nu, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_k2_plus_q_k2_w2_w2); G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 + G2_UP_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1) + (G2_UP_n1_m1_k1_k1_plus_q_w1_w1 + G2_DN_n1_m1_k1_k1_plus_q_w1_w1) * (G2_UP_n2_m2_k2_plus_q_k2_w2_w2 + G2_DN_n2_m2_k2_plus_q_k2_w2_w2); /* G4 = - (G2_k_k_w_w_e_DN(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_DN(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel) + G2_k_k_w_w_e_UP(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_UP(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel)) + (G2_k_k_w_w_e_UP(n1, m1, k1, k1_plus_q, w1, w1+w_channel) + G2_k_k_w_w_e_DN(n1, m1, k1, k1_plus_q, w1, w1+w_channel)) * (G2_k_k_w_w_e_UP(n2, m2, k2_plus_q, k2, w2+w_channel, w2) + G2_k_k_w_w_e_DN(n2, m2, k2_plus_q, k2, w2+w_channel, w2)); */ G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); // MOMS.G4_k_k_w_w(n1, n2, m1, m2, k1, k2, w1, w2) += // std::complex<double>(sign_div_2 * G4); } } } } } } } } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_particle_superconducting( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { std::complex<scalar_type> G2_UP_n1_m1_k1_k2_w1_w2, G2_DN_n1_m1_k1_k2_w1_w2, G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G4_val; int w_nu = parameters.get_four_point_frequency_transfer(); scalar_type sign_div_2 = sign / 2.; for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w_nu_min_w2 = w_nu + w_vertex_2_w_vertex_ext(min_w_vertex(w2)); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w_nu_min_w1 = w_nu + w_vertex_2_w_vertex_ext(min_w_vertex(w1)); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { int q_minus_k1 = q_min_(k1); for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { int q_minus_k2 = q_min_(k2); for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { F(n1, m1, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k2_w1_w2); F(n2, m2, q_minus_k1, q_minus_k2, w_nu_min_w1, w_nu_min_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G2_k_k_w_w_e_DN, G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2); G4_val = (G2_UP_n1_m1_k1_k2_w1_w2 * G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2 + G2_DN_n1_m1_k1_k2_w1_w2 * G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2); G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); } } } } } } } } } } // ctaux } // solver } // phys } // dca #endif // DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP
41.041209
112
0.651483
yingwaili
17af2153521afd985ec8b8a9d34f7ba5fcd12d90
1,240
hpp
C++
include/tracker/MarkerFilter.hpp
anqixu/ftag2
f77c0c0960a1ed44cc8723fd6c5320b7bb256a68
[ "BSD-2-Clause" ]
5
2019-08-16T07:04:32.000Z
2022-03-31T11:02:09.000Z
include/tracker/MarkerFilter.hpp
anqixu/ftag2
f77c0c0960a1ed44cc8723fd6c5320b7bb256a68
[ "BSD-2-Clause" ]
null
null
null
include/tracker/MarkerFilter.hpp
anqixu/ftag2
f77c0c0960a1ed44cc8723fd6c5320b7bb256a68
[ "BSD-2-Clause" ]
1
2021-12-09T21:05:56.000Z
2021-12-09T21:05:56.000Z
/* * MarkerFilter.hpp * * Created on: Mar 4, 2014 * Author: dacocp */ #ifndef MARKERFILTER_HPP_ #define MARKERFILTER_HPP_ #include "common/FTag2.hpp" #include "tracker/PayloadFilter.hpp" #include "detector/FTag2Detector.hpp" #include "tracker/Kalman.hpp" using namespace std; class MarkerFilter { private: FTag2Marker detectedTag; int frames_without_detection; PayloadFilter IF; Kalman KF; static int num_Markers; int marker_id; public: bool active; bool got_detection_in_current_frame; FTag2Marker hypothesis; MarkerFilter(int tagType) : detectedTag(tagType), IF(tagType), hypothesis(tagType) { frames_without_detection = 0; active = false; got_detection_in_current_frame = false; }; MarkerFilter(FTag2Marker detection, double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion ); virtual ~MarkerFilter() {}; FTag2Marker getHypothesis() { return hypothesis; } int get_frames_without_detection() { return frames_without_detection; } void step( FTag2Marker detection, double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion ); void step( double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion ); void updateParameters(); }; #endif /* MARKERFILTER_HPP_ */
26.956522
115
0.762903
anqixu
17b1fb67d0a3acfb9257e63bafdd5fb33d5d3dca
728
cpp
C++
GEARBOX/res/scripts/TestScript.cpp
AndrewRichards-Code/GEAR_CORE
4d4e77bf643dc9b98de9f38445eae690290e1895
[ "MIT" ]
null
null
null
GEARBOX/res/scripts/TestScript.cpp
AndrewRichards-Code/GEAR_CORE
4d4e77bf643dc9b98de9f38445eae690290e1895
[ "MIT" ]
null
null
null
GEARBOX/res/scripts/TestScript.cpp
AndrewRichards-Code/GEAR_CORE
4d4e77bf643dc9b98de9f38445eae690290e1895
[ "MIT" ]
null
null
null
#include "Scene/INativeScript.h" using namespace gear; using namespace scene; class TestScript : public INativeScript { public: TestScript() = default; ~TestScript() = default; bool first = true; mars::float3 initPos; void OnCreate() { } void OnDestroy() { objects::Transform& transform = GetEntity().GetComponent<TransformComponent>().transform; transform.translation = initPos; } void OnUpdate(float deltaTime) { objects::Transform& transform = GetEntity().GetComponent<TransformComponent>().transform; mars::float3& pos = transform.translation; if (first) { initPos = pos; first = false; } pos.z += 0.5f * deltaTime; } }; GEAR_LOAD_SCRIPT(TestScript); GEAR_UNLOAD_SCRIPT(TestScript);
18.666667
91
0.715659
AndrewRichards-Code
17b468aaa75a8a0bc536f24c3af4f66cfe0edc63
2,860
cpp
C++
src/vgui2/src/MessageListener.cpp
DeadZoneLuna/csso-src
6c978ea304ee2df3796bc9c0d2916bac550050d5
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/vgui2/src/MessageListener.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/vgui2/src/MessageListener.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "IMessageListener.h" #include "VPanel.h" #include "vgui_internal.h" #include <KeyValues.h> #include "vgui/IClientPanel.h" #include "vgui/IVGui.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" namespace vgui { //----------------------------------------------------------------------------- // Implementation of the message listener //----------------------------------------------------------------------------- class CMessageListener : public IMessageListener { public: virtual void Message( VPanel* pSender, VPanel* pReceiver, KeyValues* pKeyValues, MessageSendType_t type ); }; void CMessageListener::Message( VPanel* pSender, VPanel* pReceiver, KeyValues* pKeyValues, MessageSendType_t type ) { char const *pSenderName = "NULL"; if (pSender) pSenderName = pSender->Client()->GetName(); char const *pSenderClass = "NULL"; if (pSender) pSenderClass = pSender->Client()->GetClassName(); char const *pReceiverName = "unknown name"; if (pReceiver) pReceiverName = pReceiver->Client()->GetName(); char const *pReceiverClass = "unknown class"; if (pReceiver) pReceiverClass = pReceiver->Client()->GetClassName(); // FIXME: Make a bunch of filters here // filter out key focus messages if (!strcmp (pKeyValues->GetName(), "KeyFocusTicked")) { return; } // filter out mousefocus messages else if (!strcmp (pKeyValues->GetName(), "MouseFocusTicked")) { return; } // filter out cursor movement messages else if (!strcmp (pKeyValues->GetName(), "CursorMoved")) { return; } // filter out cursor entered messages else if (!strcmp (pKeyValues->GetName(), "CursorEntered")) { return; } // filter out cursor exited messages else if (!strcmp (pKeyValues->GetName(), "CursorExited")) { return; } // filter out MouseCaptureLost messages else if (!strcmp (pKeyValues->GetName(), "MouseCaptureLost")) { return; } // filter out MousePressed messages else if (!strcmp (pKeyValues->GetName(), "MousePressed")) { return; } // filter out MouseReleased messages else if (!strcmp (pKeyValues->GetName(), "MouseReleased")) { return; } // filter out Tick messages else if (!strcmp (pKeyValues->GetName(), "Tick")) { return; } Msg( "%s : (%s (%s) - > %s (%s)) )\n", pKeyValues->GetName(), pSenderClass, pSenderName, pReceiverClass, pReceiverName ); } //----------------------------------------------------------------------------- // Singleton instance //----------------------------------------------------------------------------- static CMessageListener s_MessageListener; IMessageListener *MessageListener() { return &s_MessageListener; } }
25.535714
115
0.597203
DeadZoneLuna
17b5f7ec7dd976b40e6f84cbfc8bff2cfbe49bfb
21,324
cpp
C++
Utils/spawn-wthttpd.cpp
NuLL3rr0r/blog-subscription-service
4458c0679229ad20ee446e1d1f7c58d1aa04b64d
[ "MIT" ]
6
2016-01-30T03:25:00.000Z
2022-01-23T23:29:22.000Z
Utils/spawn-wthttpd.cpp
NuLL3rr0r/blog-subscription-service
4458c0679229ad20ee446e1d1f7c58d1aa04b64d
[ "MIT" ]
1
2018-09-01T09:46:34.000Z
2019-01-12T15:05:50.000Z
Utils/spawn-wthttpd.cpp
NuLL3rr0r/blog-subscription-service
4458c0679229ad20ee446e1d1f7c58d1aa04b64d
[ "MIT" ]
6
2017-01-05T14:55:02.000Z
2021-03-30T14:05:10.000Z
/** * @file * @author Mamadou Babaei <[email protected]> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2016 - 2021 Mamadou Babaei * * 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. * * @section DESCRIPTION * * A tiny utility program to spawn a collection of wthttpd applications if they * won't exists in memory already. In addition to that, it monitors the * application and does re-spawn it in case of a crash. * You might want to run this as a cron job. */ #include <fstream> #include <iostream> #include <map> #include <stdexcept> #include <streambuf> #include <string> #include <vector> #include <csignal> #include <cstdlib> #include <boost/algorithm/string.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <CoreLib/CoreLib.hpp> #include <CoreLib/Exception.hpp> #include <CoreLib/FileSystem.hpp> #include <CoreLib/Log.hpp> #include <CoreLib/System.hpp> #define UNKNOWN_ERROR "Unknown error!" const std::string DATABASE_FILE_NAME = "spawn-wthttpd.db"; static boost::property_tree::ptree appsTree; [[ noreturn ]] void Terminate(int signo); bool ReadApps(); void ReSpawn(); int main(int argc, char **argv) { try { /// Gracefully handling SIGTERM void (*prev_fn)(int); prev_fn = signal(SIGTERM, Terminate); if (prev_fn == SIG_IGN) signal(SIGTERM, SIG_IGN); /// Extract the executable path and name boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>()); if (argc > 0 && argv[0] != NULL) path = boost::filesystem::system_complete(boost::filesystem::path(argv[0])); std::string appId(path.filename().string()); std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, "")); /// Force changing the current path to executable path boost::filesystem::current_path(appPath); /// Initializing CoreLib CoreLib::CoreLibInitialize(argc, argv); #if GDPR_COMPLIANCE CoreLib::Log::Initialize(std::cout); #else // GDPR_COMPLIANCE CoreLib::Log::Initialize(std::cout, (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("log")).string(), "SpawnWtHttpd"); #endif // GDPR_COMPLIANCE /// Acquiring process lock std::string lockId; #if defined ( __unix__ ) int lock; lockId = (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("tmp") / (appId + ".lock")).string(); #elif defined ( _WIN32 ) HANDLE lock; lockId = appId; #endif // defined ( __unix__ ) if(!CoreLib::System::GetLock(lockId, lock)) { std::cerr << "Could not get lock!" << std::endl; std::cerr << "Probably process is already running!" << std::endl; return EXIT_FAILURE; } else { LOG_INFO("Got the process lock!"); } if(!ReadApps()) { return EXIT_FAILURE; } if (appsTree.empty() || appsTree.count("apps") == 0 || appsTree.get_child("apps").count("") == 0) { std::cerr << "There is no WtHttpd app to spawn!" << std::endl; return EXIT_FAILURE; } while (true) { ReSpawn(); sleep(1); } } catch (CoreLib::Exception<std::string> &ex) { LOG_ERROR(ex.What()); } catch (boost::exception &ex) { LOG_ERROR(boost::diagnostic_information(ex)); } catch (std::exception &ex) { LOG_ERROR(ex.what()); } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } return EXIT_SUCCESS; } void Terminate(int signo) { std::clog << "Terminating...." << std::endl; exit(signo); } bool ReadApps() { std::ifstream dbFile( (boost::filesystem::path("..") / boost::filesystem::path("db") / DATABASE_FILE_NAME).string() ); if (!dbFile.is_open()) { std::cerr << "Unable to open the database file!" << std::endl; return false; } try { boost::property_tree::read_json(dbFile, appsTree); } catch (std::exception const &ex) { LOG_ERROR(ex.what()); return false; } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } return true; } void ReSpawn() { try { BOOST_FOREACH(boost::property_tree::ptree::value_type &appNode, appsTree.get_child("apps")) { if (appNode.first.empty()) { bool running = false; std::vector<int> pids; if (appNode.second.get_child_optional("pid-file")) { if (CoreLib::FileSystem::FileExists(appNode.second.get<std::string>("pid-file"))) { std::ifstream pidFile(appNode.second.get<std::string>("pid-file")); if (pidFile.is_open()) { std::string firstLine; getline(pidFile, firstLine); pidFile.close(); boost::algorithm::trim(firstLine); try { int pid = boost::lexical_cast<int>(firstLine); // The shell way: // To check if ${PID} exists // kill -0 ${PID} // Other possible ways to get process name or full-path // ps -p ${PID} -o comm= // or // FreeBSD // ps axwww -o pid,command | grep ${PID} // GNU/Linux // ps ax -o pid,cmd | grep ${PID} if (CoreLib::System::GetPidsOfProcess( CoreLib::System::GetProcessNameFromPath(appNode.second.get<std::string>("app")), pids)) { if (pids.size() > 0 && std::find(pids.begin(), pids.end(), pid) != pids.end()) { running = true; } } } catch (...) { } } else { } } else { } } else { throw "No socket or port specified!"; } if (!running) { for (std::vector<int>::const_iterator it = pids.begin(); it != pids.end(); ++it) { std::string output; std::string cmd = (boost::format("/bin/ps -p %1% | grep '%2%'") % *it % appNode.second.get<std::string>("app")).str(); CoreLib::System::Exec(cmd, output); if (output.find(appNode.second.get<std::string>("app")) != std::string::npos) { std::clog << std::endl << (boost::format(" * KILLING ==> %1%" "\n\t%2%") % *it % appNode.second.get<std::string>("app")).str() << std::endl; cmd = (boost::format("/bin/kill -SIGKILL %1%") % *it).str(); CoreLib::System::Exec(cmd); } } std::clog << std::endl << (boost::format(" * RESPAWNING WTHTTPD APP ==> %1%" "\n\tWorking Directory : %2%" "\n\tThreads : %3%" "\n\tServer Name : %4%" "\n\tDocument Root : %5%" "\n\tApplication Root : %6%" "\n\tError Root : %7%" "\n\tAccess Log : %8%" "\n\tCompression : %9%" "\n\tDeploy Path : %10%" "\n\tSession ID Prefix : %11%" "\n\tPid File : %12%" "\n\tConfig File : %13%" "\n\tMax Memory Request Size : %14%" "\n\tGDB : %15%" "\n\tHttp Address : %16%" "\n\tHttp Port : %17%" "\n\tHttps Address : %18%" "\n\tHttps Port : %19%" "\n\tSSL Certificate : %20%" "\n\tSSL Private Key : %21%" "\n\tSSL Temp Diffie Hellman : %22%" "\n\tSSL Enable v3 : %23%" "\n\tSSL Client Verification : %24%" "\n\tSSL Verify Depth : %25%" "\n\tSSL CA Certificates : %26%" "\n\tSSL Cipherlist : %27%") % appNode.second.get<std::string>("app") % appNode.second.get<std::string>("workdir") % appNode.second.get<std::string>("threads") % appNode.second.get<std::string>("servername") % appNode.second.get<std::string>("docroot") % appNode.second.get<std::string>("approot") % appNode.second.get<std::string>("errroot") % appNode.second.get<std::string>("accesslog") % appNode.second.get<std::string>("compression") % appNode.second.get<std::string>("deploy-path") % appNode.second.get<std::string>("session-id-prefix") % appNode.second.get<std::string>("pid-file") % appNode.second.get<std::string>("config") % appNode.second.get<std::string>("max-memory-request-size") % appNode.second.get<std::string>("gdb") % appNode.second.get<std::string>("http-address") % appNode.second.get<std::string>("http-port") % appNode.second.get<std::string>("https-address") % appNode.second.get<std::string>("https-port") % appNode.second.get<std::string>("ssl-certificate") % appNode.second.get<std::string>("ssl-private-key") % appNode.second.get<std::string>("ssl-tmp-dh") % appNode.second.get<std::string>("ssl-enable-v3") % appNode.second.get<std::string>("ssl-client-verification") % appNode.second.get<std::string>("ssl-verify-depth") % appNode.second.get<std::string>("ssl-ca-certificates") % appNode.second.get<std::string>("ssl-cipherlist") ).str() << std::endl << std::endl; std::string cmd((boost::format("cd %2% && %1%") % appNode.second.get<std::string>("app") % appNode.second.get<std::string>("workdir") ).str()); if (!appNode.second.get<std::string>("threads").empty() && appNode.second.get<std::string>("threads") != "-1") { cmd += (boost::format(" --threads %1%") % appNode.second.get<std::string>("threads")).str(); } if (!appNode.second.get<std::string>("servername").empty()) { cmd += (boost::format(" --servername %1%") % appNode.second.get<std::string>("servername")).str(); } if (!appNode.second.get<std::string>("docroot").empty()) { cmd += (boost::format(" --docroot \"%1%\"") % appNode.second.get<std::string>("docroot")).str(); } if (!appNode.second.get<std::string>("approot").empty()) { cmd += (boost::format(" --approot \"%1%\"") % appNode.second.get<std::string>("approot")).str(); } if (!appNode.second.get<std::string>("errroot").empty()) { cmd += (boost::format(" --errroot \"%1%\"") % appNode.second.get<std::string>("errroot")).str(); } if (!appNode.second.get<std::string>("accesslog").empty()) { cmd += (boost::format(" --accesslog \"%1%\"") % appNode.second.get<std::string>("accesslog")).str(); } if (!appNode.second.get<std::string>("compression").empty() && appNode.second.get<std::string>("compression") != "yes") { cmd += " --no-compression"; } if (!appNode.second.get<std::string>("deploy-path").empty()) { cmd += (boost::format(" --deploy-path %1%") % appNode.second.get<std::string>("deploy-path")).str(); } if (!appNode.second.get<std::string>("session-id-prefix").empty()) { cmd += (boost::format(" --session-id-prefix %1%") % appNode.second.get<std::string>("session-id-prefix")).str(); } if (!appNode.second.get<std::string>("pid-file").empty()) { cmd += (boost::format(" --pid-file \"%1%\"") % appNode.second.get<std::string>("pid-file")).str(); } if (!appNode.second.get<std::string>("config").empty()) { cmd += (boost::format(" --config \"%1%\"") % appNode.second.get<std::string>("config")).str(); } if (!appNode.second.get<std::string>("max-memory-request-size").empty()) { cmd += (boost::format(" --max-memory-request-size %1%") % appNode.second.get<std::string>("max-memory-request-size")).str(); } if (!appNode.second.get<std::string>("gdb").empty() && appNode.second.get<std::string>("gdb") != "yes") { cmd += " --gdb"; } if (!appNode.second.get<std::string>("http-address").empty()) { cmd += (boost::format(" --http-address %1%") % appNode.second.get<std::string>("http-address")).str(); } if (!appNode.second.get<std::string>("http-port").empty()) { cmd += (boost::format(" --http-port %1%") % appNode.second.get<std::string>("http-port")).str(); } if (!appNode.second.get<std::string>("https-address").empty()) { cmd += (boost::format(" --https-address %1%") % appNode.second.get<std::string>("https-address")).str(); } if (!appNode.second.get<std::string>("https-port").empty()) { cmd += (boost::format(" --https-port %1%") % appNode.second.get<std::string>("https-port")).str(); } if (!appNode.second.get<std::string>("ssl-certificate").empty()) { cmd += (boost::format(" --ssl-certificate \"%1%\"") % appNode.second.get<std::string>("ssl-certificate")).str(); } if (!appNode.second.get<std::string>("ssl-private-key").empty()) { cmd += (boost::format(" --ssl-private-key \"%1%\"") % appNode.second.get<std::string>("ssl-private-key")).str(); } if (!appNode.second.get<std::string>("ssl-tmp-dh").empty()) { cmd += (boost::format(" --ssl-tmp-dh \"%1%\"") % appNode.second.get<std::string>("ssl-tmp-dh")).str(); } if (!appNode.second.get<std::string>("ssl-enable-v3").empty() && appNode.second.get<std::string>("ssl-enable-v3") != "yes") { cmd += " --ssl-enable-v3"; } if (!appNode.second.get<std::string>("ssl-client-verification").empty()) { cmd += (boost::format(" --ssl-client-verification %1%") % appNode.second.get<std::string>("ssl-client-verification")).str(); } if (!appNode.second.get<std::string>("ssl-verify-depth").empty()) { cmd += (boost::format(" --ssl-verify-depth %1%") % appNode.second.get<std::string>("ssl-verify-depth")).str(); } if (!appNode.second.get<std::string>("ssl-ca-certificates").empty()) { cmd += (boost::format(" --ssl-ca-certificates \"%1%\"") % appNode.second.get<std::string>("ssl-ca-certificates")).str(); } if (!appNode.second.get<std::string>("ssl-cipherlist").empty()) { cmd += (boost::format(" --ssl-cipherlist %1%") % appNode.second.get<std::string>("ssl-cipherlist")).str(); } cmd += " &"; CoreLib::System::Exec(cmd); } } } } catch (const char * const &ex) { LOG_ERROR(ex); } catch (std::exception const &ex) { LOG_ERROR(ex.what()); } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } }
46.356522
124
0.422998
NuLL3rr0r
17b9a3a619dc2f0ce902205a7086ac9fd2a5d60d
5,969
cpp
C++
src/mongo/db/fts/fts_search.cpp
nleite/mongo
1a1b6b0aaeefbae06942867e4dcf55d00d42afe0
[ "Apache-2.0" ]
24
2015-10-15T00:03:57.000Z
2021-04-25T18:21:31.000Z
src/mongo/db/fts/fts_search.cpp
nleite/mongo
1a1b6b0aaeefbae06942867e4dcf55d00d42afe0
[ "Apache-2.0" ]
1
2015-06-02T12:19:19.000Z
2015-06-02T12:19:19.000Z
src/mongo/db/fts/fts_search.cpp
nleite/mongo
1a1b6b0aaeefbae06942867e4dcf55d00d42afe0
[ "Apache-2.0" ]
3
2017-07-26T11:17:11.000Z
2021-11-30T00:11:32.000Z
// fts_search.cpp /** * Copyright (C) 2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mongo/pch.h" #include "mongo/db/btreecursor.h" #include "mongo/db/fts/fts_index_format.h" #include "mongo/db/fts/fts_search.h" #include "mongo/db/kill_current_op.h" #include "mongo/db/pdfile.h" namespace mongo { namespace fts { /* * Constructor generates query and term dictionaries * @param ns, namespace * @param idxNum, index number * @param search, query string * @param language, language of the query * @param filter, filter object */ FTSSearch::FTSSearch( IndexDescriptor* descriptor, const FTSSpec& ftsSpec, const BSONObj& indexPrefix, const FTSQuery& query, const BSONObj& filter ) : _descriptor(descriptor), _ftsSpec(ftsSpec), _indexPrefix( indexPrefix ), _query( query ), _ftsMatcher(query, ftsSpec) { if ( !filter.isEmpty() ) _matcher.reset( new CoveredIndexMatcher( filter, _descriptor->keyPattern() ) ); _keysLookedAt = 0; _objectsLookedAt = 0; } bool FTSSearch::_ok( Record* record ) const { if ( !_query.hasNonTermPieces() ) return true; return _ftsMatcher.matchesNonTerm( BSONObj::make( record ) ); } /* * GO: sets the tree cursors on each term in terms, processes the terms by advancing * the terms cursors and storing the partial * results and lastly calculates the top results * @param results, the priority queue containing the top results * @param limit, number of results in the priority queue */ void FTSSearch::go(Results* results, unsigned limit ) { vector< shared_ptr<BtreeCursor> > cursors; for ( unsigned i = 0; i < _query.getTerms().size(); i++ ) { const string& term = _query.getTerms()[i]; BSONObj min = FTSIndexFormat::getIndexKey( MAX_WEIGHT, term, _indexPrefix ); BSONObj max = FTSIndexFormat::getIndexKey( 0, term, _indexPrefix ); shared_ptr<BtreeCursor> c( BtreeCursor::make( nsdetails(_descriptor->parentNS().c_str()), _descriptor->getOnDisk(), min, max, true, -1 ) ); cursors.push_back( c ); } while ( !inShutdown() ) { bool gotAny = false; for ( unsigned i = 0; i < cursors.size(); i++ ) { if ( cursors[i]->eof() ) continue; gotAny = true; _process( cursors[i].get() ); cursors[i]->advance(); } if ( !gotAny ) break; RARELY killCurrentOp.checkForInterrupt(); } // priority queue using a compare that grabs the lowest of two ScoredLocations by score. for ( Scores::iterator i = _scores.begin(); i != _scores.end(); ++i ) { if ( i->second < 0 ) continue; // priority queue if ( results->size() < limit ) { // case a: queue unfilled if ( !_ok( i->first ) ) continue; results->push( ScoredLocation( i->first, i->second ) ); } else if ( i->second > results->top().score ) { // case b: queue filled if ( !_ok( i->first ) ) continue; results->pop(); results->push( ScoredLocation( i->first, i->second ) ); } else { // else do nothing (case c) } } } /* * Takes a cursor and updates the partial score for said cursor in _scores map * @param cursor, btree cursor pointing to the current document to be scored */ void FTSSearch::_process( BtreeCursor* cursor ) { _keysLookedAt++; BSONObj key = cursor->currKey(); BSONObjIterator i( key ); for ( unsigned j = 0; j < _ftsSpec.numExtraBefore(); j++) i.next(); i.next(); // move past indexToken BSONElement scoreElement = i.next(); double score = scoreElement.number(); double& cur = _scores[(cursor->currLoc()).rec()]; if ( cur < 0 ) { // already been rejected return; } if ( cur == 0 && _matcher.get() ) { // we haven't seen this before and we have a matcher MatchDetails d; if ( !_matcher->matchesCurrent( cursor, &d ) ) { cur = -1; } if ( d.hasLoadedRecord() ) _objectsLookedAt++; if ( cur == -1 ) return; } if ( cur ) cur += score * (1 + 1 / score); else cur += score; } } }
32.796703
100
0.501424
nleite
17bd5ed31ba7debeab07f15da466c585475700eb
4,364
cpp
C++
CalFp02-/src/Sudoku.cpp
GuilhermeJSilva/CAL-TP
5e9dac1c56370a82d16f1633f03ec6302d81652d
[ "MIT" ]
null
null
null
CalFp02-/src/Sudoku.cpp
GuilhermeJSilva/CAL-TP
5e9dac1c56370a82d16f1633f03ec6302d81652d
[ "MIT" ]
null
null
null
CalFp02-/src/Sudoku.cpp
GuilhermeJSilva/CAL-TP
5e9dac1c56370a82d16f1633f03ec6302d81652d
[ "MIT" ]
null
null
null
/* * Sudoku.cpp * */ #include "Sudoku.h" #include <vector> #include <string.h> #include <climits> /** Inicia um Sudoku vazio. */ Sudoku::Sudoku() { this->initialize(); this->n_solucoes = 0; this->countFilled = 0; } /** * Inicia um Sudoku com um conte�do inicial. * Lan�a excep��o IllegalArgumentException se os valores * estiverem fora da gama de 1 a 9 ou se existirem n�meros repetidos * por linha, coluna ou bloc 3x3. * * @param nums matriz com os valores iniciais (0 significa por preencher) */ Sudoku::Sudoku(int nums[9][9]) { this->initialize(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (nums[i][j] != 0) { int n = nums[i][j]; numbers[i][j] = n; lineHasNumber[i][n] = true; columnHasNumber[j][n] = true; block3x3HasNumber[i / 3][j / 3][n] = true; countFilled++; } } } this->n_solucoes = 0; } void Sudoku::initialize() { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { for (int n = 0; n < 10; n++) { numbers[i][j] = 0; lineHasNumber[i][n] = false; columnHasNumber[j][n] = false; block3x3HasNumber[i / 3][j / 3][n] = false; } } } this->countFilled = 0; } /** * Obtem o conte�do actual (s� para leitura!). */ int** Sudoku::getNumbers() { int** ret = new int*[9]; for (int i = 0; i < 9; i++) { ret[i] = new int[9]; for (int a = 0; a < 9; a++) ret[i][a] = numbers[i][a]; } return ret; } /** * Verifica se o Sudoku j� est� completamente resolvido */ bool Sudoku::isComplete() { return countFilled == 9 * 9; } /** * Resolve o Sudoku. * Retorna indica��o de sucesso ou insucesso (sudoku imposs�vel). */ bool Sudoku::solve() { //this->print(); //cout << endl; if(countFilled == 81) { this->print(); cout << endl; n_solucoes++; return true; } int x ,y; int n_accepted = INT_MAX; vector<bool> num_accepted; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int tmp_n_accepted = 9; vector<bool> acceptable_num(10,true); if(this->numbers[i][j] != 0) continue; for(int k = 0; k < 10; k++) { acceptable_num[k] = acceptable_num[k] & !this->columnHasNumber[j][k]; acceptable_num[k] = acceptable_num[k] & !this->lineHasNumber[i][k]; acceptable_num[k] = acceptable_num[k] & !this->block3x3HasNumber[i/3][j/3][k]; if(!acceptable_num[k]) tmp_n_accepted--; } //cout << "x: " << i << " y: " << j << endl; //cout << tmp_n_accepted << ' ' << n_accepted << endl; if(tmp_n_accepted == 0) return false; if(tmp_n_accepted <= n_accepted) { n_accepted = tmp_n_accepted; num_accepted.clear(); num_accepted.insert(num_accepted.begin(),acceptable_num.begin(), acceptable_num.end()); x = i; y = j; } } } if(n_accepted == 1) { int a = 1; while(!num_accepted[a]) a++; //cout << "Added: " << a << " in x: " << x << " y: " << y << endl << endl; this->numbers[x][y] = a; this->countFilled++; lineHasNumber[x][a] = true; columnHasNumber[y][a] = true; block3x3HasNumber[x / 3][y / 3][a] = true; if(this->solve()) { return true; } else { this->numbers[x][y] = 0; this->countFilled--; lineHasNumber[x][a] = false; columnHasNumber[y][a] = false; block3x3HasNumber[x / 3][y / 3][a] = false; return false; } } else { //cout << x << "\t" << y << "\n"; std::vector<int> possible_sol; for(int i = 1; i < 10; i++) if(num_accepted[i]) { //cout << i << " acceptated\n"; possible_sol.push_back(i); } for(size_t j = 0; j < possible_sol.size(); j++) { //cout << "Added: " << possible_sol[j] << " in x: " << x << " y: " << y << endl << endl; this->numbers[x][y] = possible_sol[j]; this->countFilled++; lineHasNumber[x][possible_sol[j]] = true; columnHasNumber[y][possible_sol[j]] = true; block3x3HasNumber[x / 3][y / 3][possible_sol[j]] = true; if(this->solve()) { return true; } else { this->numbers[x][y] = 0; this->countFilled--; lineHasNumber[x][possible_sol[j]] = false; columnHasNumber[y][possible_sol[j]] = false; block3x3HasNumber[x / 3][y / 3][possible_sol[j]] = false; } } } return false; } /** * Imprime o Sudoku. */ void Sudoku::print() { for (int i = 0; i < 9; i++) { for (int a = 0; a < 9; a++) cout << this->numbers[i][a] << " "; cout << endl; } }
19.056769
91
0.555454
GuilhermeJSilva
17c0db6e2c3ccbf82be67c5a1f0f9e818cd28de9
1,001
hpp
C++
Type.hpp
Racinettee/Inked
231ba994772d0847b19df5b1da2abaed113d58d6
[ "MIT" ]
null
null
null
Type.hpp
Racinettee/Inked
231ba994772d0847b19df5b1da2abaed113d58d6
[ "MIT" ]
null
null
null
Type.hpp
Racinettee/Inked
231ba994772d0847b19df5b1da2abaed113d58d6
[ "MIT" ]
null
null
null
#ifndef _TYPE_HPP_ #define _TYPE_HPP_ #include "ICompilerEngine.hpp" class Type { std::string name; llvm::Type* type; public: const std::string& Name() { return name; } const llvm::Type* Type() { return type; } std::size_t SizeBytes() const { // figure out the type of type of type. if its primitive just return the size, if its a struct type // then it will have to be interated over unsigned std::size_t sizeof_type = 0; if(type->isFloatTy()) sizeof_type = 4; // 32 bits else if(type->isDoubleTy()) // 64 bits sizeof_type = 8; else if(type->isIntegerTy()) { // variable width that type can report sizeof_type = dynamic_cast<llvm::IntegerType>(type)->getBitWidth(); } else if(type->isStructTy()) { // iterate over all elements and sum them } } }; #endif // _TYPE_HPP_
25.025
107
0.551449
Racinettee
17c2f4f24fc2ccf0616b763a9acf0ff599e21539
1,996
cpp
C++
c03/ex3_16.cpp
qzhang0/CppPrimer
315ef879bd4d3b51d594e33b049adee0d47e4c11
[ "MIT" ]
null
null
null
c03/ex3_16.cpp
qzhang0/CppPrimer
315ef879bd4d3b51d594e33b049adee0d47e4c11
[ "MIT" ]
null
null
null
c03/ex3_16.cpp
qzhang0/CppPrimer
315ef879bd4d3b51d594e33b049adee0d47e4c11
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using std::cout; using std::cin; using std::endl; using std::string; using std::vector; int main() { vector<int> v1; // size:0, no values. vector<int> v2(10); // size:10, value:0 vector<int> v3(10, 42); // size:10, value:42 vector<int> v4{ 10 }; // size:1, value:10 vector<int> v5{ 10, 42 }; // size:2, value:10, 42 vector<string> v6{ 10 }; // size:10, value:"" vector<string> v7{ 10, "hi" }; // size:10, value:"hi" cout << "v1 has " << v1.size() << " elements: " << endl; if (v1.size() > 0) { for (auto a : v1) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v2 has " << v2.size() << " elements: " << endl; if (v2.size() > 0) { for (auto a : v2) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v3 has " << v3.size() << " elements: " << endl; if (v3.size() > 0) { for (auto a : v3) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v4 has " << v4.size() << " elements: " << endl; if (v4.size() > 0) { for (auto a : v4) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v5 has " << v5.size() << " elements: " << endl; if (v5.size() > 0) { for (auto a : v5) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v6 has " << v6.size() << " elements: " << endl; if (v6.size() > 0) { for (auto a : v6) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v7 has " << v7.size() << " elements: " << endl; if (v7.size() > 0) { for (auto a : v7) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } return 0; }
25.589744
60
0.40982
qzhang0
17c5e1257d39c35c1542de3d5e0f8dfb670382b5
1,346
hh
C++
src/cxx/lib/layout/cppunit/testBarcodeCollisionDetector.hh
sbooeshaghi/bcl2fastq
3f39a24cd743fa71fba9b7dcf62e5d33cea8272d
[ "BSD-3-Clause" ]
5
2021-06-07T12:36:11.000Z
2022-02-08T09:49:02.000Z
src/cxx/lib/layout/cppunit/testBarcodeCollisionDetector.hh
sbooeshaghi/bcl2fastq
3f39a24cd743fa71fba9b7dcf62e5d33cea8272d
[ "BSD-3-Clause" ]
1
2022-03-01T23:55:57.000Z
2022-03-01T23:57:15.000Z
src/cxx/lib/layout/cppunit/testBarcodeCollisionDetector.hh
sbooeshaghi/bcl2fastq
3f39a24cd743fa71fba9b7dcf62e5d33cea8272d
[ "BSD-3-Clause" ]
null
null
null
/** * BCL to FASTQ file converter * Copyright (c) 2007-2017 Illumina, Inc. * * This software is covered by the accompanying EULA * and certain third party copyright/licenses, and any user of this * source file is bound by the terms therein. * * \file barcodeCollisionDetector.hh * * \brief BarcodeCollisionDetector cppunit test declarations. * * \author Aaron Day */ #ifndef BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH #define BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH #include <cppunit/extensions/HelperMacros.h> #include <vector> /// \brief Test suite for BarcodeCollisionDetector. class TestBarcodeCollisionDetector : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestBarcodeCollisionDetector); CPPUNIT_TEST(testSuccess); CPPUNIT_TEST(testMismatchLength); CPPUNIT_TEST(testNumComponents); CPPUNIT_TEST(testCollisionSameSample); CPPUNIT_TEST(testCollision); CPPUNIT_TEST_SUITE_END(); private: std::vector<std::size_t> componentMaxMismatches_; public: TestBarcodeCollisionDetector() : componentMaxMismatches_() {} void setUp(); void tearDown(); void testSuccess(); void testMismatchLength(); void testNumComponents(); void testCollisionSameSample(); void testCollision(); }; #endif // BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH
25.884615
67
0.767459
sbooeshaghi
17c84e975dc7f786a073022412fcc6f6169550d7
35,778
cpp
C++
src/RenderSystem/Vulkan/Vulkan.cpp
przemyslaw-szymanski/vke
1d8fb139e0e995e330db6b8873dfc49463ec312c
[ "MIT" ]
1
2018-01-06T04:44:36.000Z
2018-01-06T04:44:36.000Z
src/RenderSystem/Vulkan/Vulkan.cpp
przemyslaw-szymanski/vke
1d8fb139e0e995e330db6b8873dfc49463ec312c
[ "MIT" ]
null
null
null
src/RenderSystem/Vulkan/Vulkan.cpp
przemyslaw-szymanski/vke
1d8fb139e0e995e330db6b8873dfc49463ec312c
[ "MIT" ]
null
null
null
#include "RenderSystem/Vulkan/Vulkan.h" #include "Core/Platform/CPlatform.h" #include "Core/Utils/CLogger.h" //#undef VKE_VK_FUNCTION //#define VKE_VK_FUNCTION(_name) PFN_##_name _name //#undef VK_EXPORTED_FUNCTION //#undef VKE_ICD_GLOBAL //#undef VKE_INSTANCE_ICD //#undef VKE_DEVICE_ICD //#define VK_EXPORTED_FUNCTION(name) PFN_##name name = 0 //#define VKE_ICD_GLOBAL(name) PFN_##name name = 0 //#define VKE_INSTANCE_ICD(name) PFN_##name name = 0 //#define VKE_DEVICE_ICD(name) PFN_##name name = 0 //#include "ThirdParty/vulkan/funclist.h" //#undef VKE_DEVICE_ICD //#undef VKE_INSTANCE_ICD //#undef VKE_ICD_GLOBAL //#undef VK_EXPORTED_FUNCTION //#undef VKE_VK_FUNCTION namespace VKE { namespace Vulkan { using ErrorMap = std::map< std::thread::id, VkResult >; ErrorMap g_mErrors; std::mutex g_ErrorMutex; void SetLastError( VkResult err ) { g_ErrorMutex.lock(); g_mErrors[ std::this_thread::get_id() ] = err; g_ErrorMutex.unlock(); } VkResult GetLastError() { g_ErrorMutex.lock(); auto ret = g_mErrors[ std::this_thread::get_id() ]; g_ErrorMutex.unlock(); return ret; } SQueue::SQueue() { this->m_objRefCount = 0; Vulkan::InitInfo( &m_PresentInfo, VK_STRUCTURE_TYPE_PRESENT_INFO_KHR ); m_PresentInfo.pResults = nullptr; } VkResult SQueue::Submit( const VkICD::Device& ICD, const VkSubmitInfo& Info, const VkFence& vkFence ) { Lock(); auto res = ICD.vkQueueSubmit( vkQueue, 1, &Info, vkFence ); Unlock(); return res; } bool SQueue::IsPresentDone() { return m_isPresentDone; } void SQueue::ReleasePresentNotify() { Lock(); if( m_presentCount-- < 0 ) m_presentCount = 0; m_isPresentDone = m_presentCount == 0; Unlock(); } void SQueue::Wait( const VkICD::Device& ICD ) { ICD.vkQueueWaitIdle( vkQueue ); } Result SQueue::Present( const VkICD::Device& ICD, uint32_t imgIdx, VkSwapchainKHR vkSwpChain, VkSemaphore vkWaitSemaphore ) { Result res = VKE_ENOTREADY; Lock(); m_PresentData.vImageIndices.PushBack( imgIdx ); m_PresentData.vSwapChains.PushBack( vkSwpChain ); m_PresentData.vWaitSemaphores.PushBack( vkWaitSemaphore ); m_presentCount++; m_isPresentDone = false; if( this->GetRefCount() == m_PresentData.vSwapChains.GetCount() ) { m_PresentInfo.pImageIndices = &m_PresentData.vImageIndices[ 0 ]; m_PresentInfo.pSwapchains = &m_PresentData.vSwapChains[ 0 ]; m_PresentInfo.pWaitSemaphores = &m_PresentData.vWaitSemaphores[ 0 ]; m_PresentInfo.swapchainCount = m_PresentData.vSwapChains.GetCount(); m_PresentInfo.waitSemaphoreCount = m_PresentData.vWaitSemaphores.GetCount(); VK_ERR( ICD.vkQueuePresentKHR( vkQueue, &m_PresentInfo ) ); // $TID Present: q={vkQueue}, sc={m_PresentInfo.pSwapchains[0]}, imgIdx={m_PresentInfo.pImageIndices[0]}, ws={m_PresentInfo.pWaitSemaphores[0]} m_isPresentDone = true; m_PresentData.vImageIndices.Clear(); m_PresentData.vSwapChains.Clear(); m_PresentData.vWaitSemaphores.Clear(); res = VKE_OK; } Unlock(); return res; } bool IsColorImage( VkFormat format ) { switch( format ) { case VK_FORMAT_UNDEFINED: case VK_FORMAT_D16_UNORM: case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D24_UNORM_S8_UINT: case VK_FORMAT_D32_SFLOAT: case VK_FORMAT_D32_SFLOAT_S8_UINT: case VK_FORMAT_X8_D24_UNORM_PACK32: case VK_FORMAT_S8_UINT: return false; } return true; } bool IsDepthImage( VkFormat format ) { switch( format ) { case VK_FORMAT_D16_UNORM: case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D24_UNORM_S8_UINT: case VK_FORMAT_D32_SFLOAT: case VK_FORMAT_D32_SFLOAT_S8_UINT: case VK_FORMAT_X8_D24_UNORM_PACK32: case VK_FORMAT_S8_UINT: return true; } return false; } bool IsStencilImage( VkFormat format ) { switch( format ) { case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D24_UNORM_S8_UINT: case VK_FORMAT_D32_SFLOAT_S8_UINT: case VK_FORMAT_S8_UINT: return true; } return false; } namespace Map { VkImageType ImageType( RenderSystem::TEXTURE_TYPE type ) { static const VkImageType aVkImageTypes[] = { VK_IMAGE_TYPE_1D, VK_IMAGE_TYPE_2D, VK_IMAGE_TYPE_3D, VK_IMAGE_TYPE_2D, // cube }; return aVkImageTypes[ type ]; } VkImageViewType ImageViewType( RenderSystem::TEXTURE_VIEW_TYPE type ) { static const VkImageViewType aVkTypes[] = { VK_IMAGE_VIEW_TYPE_1D, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D_ARRAY, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_VIEW_TYPE_CUBE, VK_IMAGE_VIEW_TYPE_CUBE_ARRAY }; return aVkTypes[ type ]; } VkImageUsageFlags ImageUsage( RenderSystem::TEXTURE_USAGE usage ) { /*static const VkImageUsageFlags aVkUsages[] = { VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_USAGE_STORAGE_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT }; return aVkUsages[ usage ];*/ using namespace RenderSystem; VkImageUsageFlags flags = 0; if( usage & TextureUsages::SAMPLED ) { flags |= VK_IMAGE_USAGE_SAMPLED_BIT; } if( usage & TextureUsages::COLOR_RENDER_TARGET ) { flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; } else if( usage & TextureUsages::DEPTH_STENCIL_RENDER_TARGET ) { flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; } if( usage & TextureUsages::STORAGE ) { flags |= VK_IMAGE_USAGE_STORAGE_BIT; } if( usage & TextureUsages::TRANSFER_DST ) { flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; } if( usage & TextureUsages::TRANSFER_SRC ) { flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } return flags; } VkImageLayout ImageLayout( RenderSystem::TEXTURE_STATE layout ) { static const VkImageLayout aVkLayouts[] = { VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR }; return aVkLayouts[ layout ]; } VkImageAspectFlags ImageAspect( RenderSystem::TEXTURE_ASPECT aspect ) { static const VkImageAspectFlags aVkAspects[] = { // UNKNOWN 0, // COLOR VK_IMAGE_ASPECT_COLOR_BIT, // DEPTH VK_IMAGE_ASPECT_DEPTH_BIT, // STENCIL VK_IMAGE_ASPECT_STENCIL_BIT, // DEPTH_STENCIL VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT }; return aVkAspects[ aspect ]; } VkMemoryPropertyFlags MemoryPropertyFlags( RenderSystem::MEMORY_USAGE usages ) { using namespace RenderSystem; VkMemoryPropertyFlags flags = 0; if( usages & MemoryUsages::CPU_ACCESS ) { flags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; } if( usages & MemoryUsages::CPU_CACHED ) { flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; } if( usages & MemoryUsages::CPU_NO_FLUSH ) { flags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; } if( usages & MemoryUsages::GPU_ACCESS ) { flags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; } return flags; } VkBlendOp BlendOp( const RenderSystem::BLEND_OPERATION& op ) { static const VkBlendOp aVkOps[] = { VK_BLEND_OP_ADD, VK_BLEND_OP_SUBTRACT, VK_BLEND_OP_REVERSE_SUBTRACT, VK_BLEND_OP_MIN, VK_BLEND_OP_MAX }; return aVkOps[ op ]; } VkColorComponentFlags ColorComponent( const RenderSystem::ColorComponent& component ) { VkColorComponentFlags vkComponent = 0; if( component & RenderSystem::ColorComponents::ALL ) { vkComponent = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; } else { if( component & RenderSystem::ColorComponents::ALPHA ) { vkComponent |= VK_COLOR_COMPONENT_A_BIT; } if( component & RenderSystem::ColorComponents::BLUE ) { vkComponent |= VK_COLOR_COMPONENT_B_BIT; } if( component & RenderSystem::ColorComponents::GREEN ) { vkComponent |= VK_COLOR_COMPONENT_G_BIT; } if( component & RenderSystem::ColorComponents::RED ) { vkComponent |= VK_COLOR_COMPONENT_R_BIT; } } return vkComponent; } VkBlendFactor BlendFactor( const RenderSystem::BLEND_FACTOR& factor ) { static const VkBlendFactor aVkFactors[] = { VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA }; return aVkFactors[ factor ]; } VkLogicOp LogicOperation( const RenderSystem::LOGIC_OPERATION& op ) { static const VkLogicOp aVkOps[] = { VK_LOGIC_OP_CLEAR, VK_LOGIC_OP_AND, VK_LOGIC_OP_AND_REVERSE, VK_LOGIC_OP_COPY, VK_LOGIC_OP_AND_INVERTED, VK_LOGIC_OP_NO_OP, VK_LOGIC_OP_XOR, VK_LOGIC_OP_OR, VK_LOGIC_OP_NOR, VK_LOGIC_OP_EQUIVALENT, VK_LOGIC_OP_INVERT, VK_LOGIC_OP_OR_REVERSE, VK_LOGIC_OP_COPY_INVERTED, VK_LOGIC_OP_OR_INVERTED, VK_LOGIC_OP_NAND, VK_LOGIC_OP_SET }; return aVkOps[ op ]; } VkStencilOp StencilOperation( const RenderSystem::STENCIL_FUNCTION& op ) { static const VkStencilOp aVkOps[] = { VK_STENCIL_OP_KEEP, VK_STENCIL_OP_ZERO, VK_STENCIL_OP_REPLACE, VK_STENCIL_OP_INCREMENT_AND_CLAMP, VK_STENCIL_OP_DECREMENT_AND_CLAMP, VK_STENCIL_OP_INVERT, VK_STENCIL_OP_INCREMENT_AND_WRAP, VK_STENCIL_OP_DECREMENT_AND_WRAP }; return aVkOps[ op ]; } VkCompareOp CompareOperation( const RenderSystem::COMPARE_FUNCTION& op ) { static const VkCompareOp aVkOps[] = { VK_COMPARE_OP_NEVER, VK_COMPARE_OP_LESS, VK_COMPARE_OP_EQUAL, VK_COMPARE_OP_LESS_OR_EQUAL, VK_COMPARE_OP_GREATER, VK_COMPARE_OP_NOT_EQUAL, VK_COMPARE_OP_GREATER_OR_EQUAL, VK_COMPARE_OP_ALWAYS }; return aVkOps[ op ]; } VkPrimitiveTopology PrimitiveTopology(const RenderSystem::PRIMITIVE_TOPOLOGY& topology) { static const VkPrimitiveTopology aVkTopologies[] = { VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_PATCH_LIST }; return aVkTopologies[ topology ]; } VkSampleCountFlagBits SampleCount(const RenderSystem::SAMPLE_COUNT& count) { static const VkSampleCountFlagBits aVkSamples[] = { VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_8_BIT, VK_SAMPLE_COUNT_16_BIT, VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT }; return aVkSamples[ count ]; } VkCullModeFlags CullMode( const RenderSystem::CULL_MODE& mode ) { static const VkCullModeFlagBits aVkModes[] = { VK_CULL_MODE_NONE, VK_CULL_MODE_FRONT_BIT, VK_CULL_MODE_BACK_BIT, VK_CULL_MODE_FRONT_AND_BACK }; return aVkModes[ mode ]; } VkFrontFace FrontFace( const RenderSystem::FRONT_FACE& face ) { static const VkFrontFace aVkFaces[] = { VK_FRONT_FACE_COUNTER_CLOCKWISE, VK_FRONT_FACE_CLOCKWISE }; return aVkFaces[ face ]; } VkPolygonMode PolygonMode( const RenderSystem::POLYGON_MODE& mode ) { static const VkPolygonMode aVkModes[] = { VK_POLYGON_MODE_FILL, VK_POLYGON_MODE_LINE, VK_POLYGON_MODE_POINT }; return aVkModes[ mode ]; } VkShaderStageFlagBits ShaderStage( const RenderSystem::SHADER_TYPE& type ) { static const VkShaderStageFlagBits aVkBits[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, VK_SHADER_STAGE_COMPUTE_BIT }; return aVkBits[ type ]; } VkVertexInputRate InputRate( const RenderSystem::VERTEX_INPUT_RATE& rate ) { static const VkVertexInputRate aVkRates[] = { VK_VERTEX_INPUT_RATE_VERTEX, VK_VERTEX_INPUT_RATE_INSTANCE }; return aVkRates[ rate ]; } VkDescriptorType DescriptorType(const RenderSystem::DESCRIPTOR_SET_TYPE& type) { static const VkDescriptorType aVkDescriptorType[] = { VK_DESCRIPTOR_TYPE_SAMPLER, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT }; return aVkDescriptorType[ type ]; } } // Map namespace Convert { VkImageAspectFlags UsageToAspectMask( VkImageUsageFlags usage ) { if( usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) { return VK_IMAGE_ASPECT_COLOR_BIT; } if( usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT ) { return VK_IMAGE_ASPECT_DEPTH_BIT; } VKE_LOG_ERR( "Invalid image usage: " << usage << " to use for aspectMask" ); assert( 0 && "Invalid image usage" ); return VK_IMAGE_ASPECT_COLOR_BIT; } VkImageViewType ImageTypeToViewType( VkImageType type ) { static const VkImageViewType aTypes[] = { VK_IMAGE_VIEW_TYPE_1D, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_3D }; assert( type <= VK_IMAGE_TYPE_3D && "Invalid image type for image view type" ); return aTypes[ type ]; } VkAttachmentLoadOp UsageToLoadOp( RenderSystem::RENDER_PASS_ATTACHMENT_USAGE usage ) { static const VkAttachmentLoadOp aLoads[] = { VK_ATTACHMENT_LOAD_OP_DONT_CARE, // undefined VK_ATTACHMENT_LOAD_OP_LOAD, // color VK_ATTACHMENT_LOAD_OP_CLEAR, // color clear VK_ATTACHMENT_LOAD_OP_LOAD, // color store VK_ATTACHMENT_LOAD_OP_CLEAR, // color clear store VK_ATTACHMENT_LOAD_OP_LOAD, // depth VK_ATTACHMENT_LOAD_OP_CLEAR, // depth clear VK_ATTACHMENT_LOAD_OP_LOAD, // depth store VK_ATTACHMENT_LOAD_OP_CLEAR, // depth clear store }; return aLoads[ usage ]; } VkAttachmentStoreOp UsageToStoreOp( RenderSystem::RENDER_PASS_ATTACHMENT_USAGE usage ) { static const VkAttachmentStoreOp aStores[] = { VK_ATTACHMENT_STORE_OP_STORE, // undefined VK_ATTACHMENT_STORE_OP_STORE, // color VK_ATTACHMENT_STORE_OP_STORE, // color clear VK_ATTACHMENT_STORE_OP_STORE, // color store VK_ATTACHMENT_STORE_OP_STORE, // color clear store VK_ATTACHMENT_STORE_OP_STORE, // depth VK_ATTACHMENT_STORE_OP_STORE, // depth clear VK_ATTACHMENT_STORE_OP_STORE, // depth store VK_ATTACHMENT_STORE_OP_STORE, // depth clear store }; return aStores[ usage ]; } VkImageLayout ImageUsageToLayout( VkImageUsageFlags vkFlags ) { const auto imgSampled = vkFlags & VK_IMAGE_USAGE_SAMPLED_BIT; const auto inputAttachment = vkFlags & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; const auto isReadOnly = imgSampled || inputAttachment; if( vkFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) { return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } else if( vkFlags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT ) { if( isReadOnly ) return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } else if( vkFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT ) { return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; } else if( vkFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) { return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; } else if( isReadOnly ) { return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } assert( 0 && "Invalid image usage flags" ); VKE_LOG_ERR( "Usage flags: " << vkFlags << " are invalid." ); return VK_IMAGE_LAYOUT_UNDEFINED; } VkImageLayout ImageUsageToInitialLayout( VkImageUsageFlags vkFlags ) { if( vkFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) { return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } else if( vkFlags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT ) { return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } assert( 0 && "Invalid image usage flags" ); VKE_LOG_ERR( "Usage flags: " << vkFlags << " are invalid." ); return VK_IMAGE_LAYOUT_UNDEFINED; } VkImageLayout ImageUsageToFinalLayout( VkImageUsageFlags vkFlags ) { const auto imgSampled = vkFlags & VK_IMAGE_USAGE_SAMPLED_BIT; const auto inputAttachment = vkFlags & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; bool isReadOnly = imgSampled || inputAttachment; if( vkFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) { if( isReadOnly ) return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } else if( vkFlags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT ) { if( isReadOnly ) return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } assert( 0 && "Invalid image usage flags" ); VKE_LOG_ERR( "Usage flags: " << vkFlags << " are invalid." ); return VK_IMAGE_LAYOUT_UNDEFINED; } VkImageLayout NextAttachmentLayoutRread( VkImageLayout currLayout ) { if( currLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL ) { return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } if( currLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ) { return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; } assert( 0 && "Incorrect initial layout for attachment." ); return VK_IMAGE_LAYOUT_UNDEFINED; } VkImageLayout NextAttachmentLayoutOptimal( VkImageLayout currLayout ) { if( currLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL ) { return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } if( currLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ) { return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } assert( 0 && "Incorrect initial layout for attachment." ); return VK_IMAGE_LAYOUT_UNDEFINED; } RenderSystem::TEXTURE_FORMAT ImageFormat( VkFormat vkFormat ) { switch( vkFormat ) { case VK_FORMAT_B8G8R8A8_UNORM: return RenderSystem::Formats::B8G8R8A8_UNORM; }; assert( 0 && "Cannot convert VkFormat to RenderSystem format" ); return RenderSystem::Formats::UNDEFINED; } VkPipelineStageFlags PipelineStages(const RenderSystem::PIPELINE_STAGES& stages) { VkPipelineStageFlags vkFlags = 0; if( stages & RenderSystem::PipelineStages::COMPUTE ) { vkFlags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( stages & RenderSystem::PipelineStages::GEOMETRY ) { vkFlags |= VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT; } if( stages & RenderSystem::PipelineStages::PIXEL ) { vkFlags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } if( stages & RenderSystem::PipelineStages::TS_DOMAIN ) { vkFlags |= VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT; } if( stages & RenderSystem::PipelineStages::TS_HULL ) { vkFlags |= VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; } if( stages & RenderSystem::PipelineStages::VERTEX ) { vkFlags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; } return vkFlags; } VkBufferUsageFlags BufferUsage( const RenderSystem::BUFFER_USAGE& usage ) { VkBufferUsageFlags vkFlags = 0; if( usage & RenderSystem::BufferUsages::INDEX_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT; } if( usage & RenderSystem::BufferUsages::VERTEX_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; } if( usage & RenderSystem::BufferUsages::CONSTANT_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; } if( usage & RenderSystem::BufferUsages::TRANSFER_DST ) { vkFlags |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; } if( usage & RenderSystem::BufferUsages::TRANSFER_SRC ) { vkFlags |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT; } if( usage & RenderSystem::BufferUsages::INDIRECT_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; } if( usage & RenderSystem::BufferUsages::STORAGE_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; } if( usage & RenderSystem::BufferUsages::STORAGE_TEXEL_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT; } if( usage & RenderSystem::BufferUsages::UNIFORM_TEXEL_BUFFER ) { vkFlags |= VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT; } return vkFlags; } VkImageTiling ImageUsageToTiling( const RenderSystem::TEXTURE_USAGE& usage ) { VkImageTiling vkTiling = VK_IMAGE_TILING_OPTIMAL; if( usage & RenderSystem::TextureUsages::FILE_IO ) { vkTiling = VK_IMAGE_TILING_LINEAR; } return vkTiling; } static const VkMemoryPropertyFlags g_aRequiredMemoryFlags[] = { 0, // unknown VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // gpu VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, // cpu access VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT // cpu access optimal }; VkMemoryPropertyFlags MemoryUsagesToVkMemoryPropertyFlags( const RenderSystem::MEMORY_USAGE& usages ) { VkMemoryPropertyFlags flags = 0; if( usages & RenderSystem::MemoryUsages::GPU_ACCESS ) { flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; } else { if( usages & RenderSystem::MemoryUsages::CPU_ACCESS ) { flags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; } if( usages & RenderSystem::MemoryUsages::CPU_NO_FLUSH ) { flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; } if( usages & RenderSystem::MemoryUsages::CPU_CACHED ) { flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; } } return flags; } } // Convert #define VKE_EXPORT_FUNC(_name, _handle, _getProcAddr) \ pOut->_name = (PFN_##_name)(_getProcAddr((_handle), #_name)); \ if(!pOut->_name) \ { VKE_LOG_ERR("Unable to load function: " << #_name); err = VKE_ENOTFOUND; } #define VKE_EXPORT_EXT_FUNC(_name, _handle, _getProcAddr) \ pOut->_name = (PFN_##_name)(_getProcAddr((_handle), #_name)); \ if(!pOut->_name) \ { VKE_LOG_ERR("Unable to load function: " << #_name); } Result LoadGlobalFunctions( handle_t hLib, VkICD::Global* pOut ) { Result err = VKE_OK; #if VKE_AUTO_ICD #define VK_EXPORTED_FUNCTION(_name) VKE_EXPORT_FUNC(_name, hLib, Platform::DynamicLibrary::GetProcAddress) #include "ThirdParty/vulkan/VKEICD.h" #undef VK_EXPORTED_FUNCTION #define VKE_ICD_GLOBAL(_name) VKE_EXPORT_FUNC(_name, VK_NULL_HANDLE, pOut->vkGetInstanceProcAddr) #include "ThirdParty/vulkan/VKEICD.h" #undef VKE_ICD_GLOBAL #else // VKE_AUTO_ICD pOut->vkGetInstanceProcAddr = reinterpret_cast< PFN_vkGetInstanceProcAddr >( Platform::GetProcAddress( hLib, "vkGetInstanceProcAddr" ) ); pOut->vkCreateInstance = reinterpret_cast< PFN_vkCreateInstance >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkCreateInstance" ) ); //pOut->vkDestroyInstance = reinterpret_cast< PFN_vkDestroyInstance >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkDestroyInstance" ) ); pOut->vkEnumerateInstanceExtensionProperties = reinterpret_cast< PFN_vkEnumerateInstanceExtensionProperties >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties" ) ); pOut->vkEnumerateInstanceLayerProperties = reinterpret_cast< PFN_vkEnumerateInstanceLayerProperties >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties" ) ); #endif // VKE_AUTO_ICD return err; } Result LoadInstanceFunctions( VkInstance vkInstance, const VkICD::Global& Global, VkICD::Instance* pOut ) { Result err = VKE_OK; #if VKE_AUTO_ICD # undef VKE_INSTANCE_ICD # undef VKE_INSTANCE_EXT_ICD # define VKE_INSTANCE_ICD(_name) VKE_EXPORT_FUNC(_name, vkInstance, Global.vkGetInstanceProcAddr) # define VKE_INSTANCE_EXT_ICD(_name) VKE_EXPORT_EXT_FUNC(_name, vkInstance, Global.vkGetInstanceProcAddr) # include "ThirdParty/vulkan/VKEICD.h" # undef VKE_INSTANCE_ICD # undef VKE_INSTANCE_EXT_ICD #else // VKE_AUTO_ICD pOut->vkDestroySurfaceKHR = reinterpret_cast< PFN_vkDestroySurfaceKHR >( Global.vkGetInstanceProcAddr( vkInstance, "vkDestroySurfaceKHR" ) ); #endif // VKE_AUTO_ICD return err; } Result LoadDeviceFunctions( VkDevice vkDevice, const VkICD::Instance& Instance, VkICD::Device* pOut ) { Result err = VKE_OK; #if VKE_AUTO_ICD # undef VKE_DEVICE_ICD # undef VKE_DEVICE_EXT_ICD # define VKE_DEVICE_ICD(_name) VKE_EXPORT_FUNC(_name, vkDevice, Instance.vkGetDeviceProcAddr) # define VKE_DEVICE_EXT_ICD(_name) VKE_EXPORT_EXT_FUNC(_name, vkDevice, Instance.vkGetDeviceProcAddr); # include "ThirdParty/vulkan/VKEICD.h" # undef VKE_DEVICE_ICD # undef VKE_DEVICE_EXT_ICD #else // VKE_AUTO_ICD #endif // VKE_AUTO_ICD return err; } } }
40.656818
213
0.542764
przemyslaw-szymanski
17c8b1276609b9fd159b42401ccf7f84dada58ff
539
cpp
C++
Leetcode/Practice/N-Repeated Element in Size 2N Array.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
4
2019-06-04T11:03:38.000Z
2020-06-19T23:37:32.000Z
Leetcode/Practice/N-Repeated Element in Size 2N Array.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
Leetcode/Practice/N-Repeated Element in Size 2N Array.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
/*coderanant*/ #define ll long long #define f1(i,a,b) for(int i=a;i<b;i++) #define f2(i,a,b) for(int i=a;i>=b;i--) #define endl '\n' #define pb push_back #define gp " " #define ff first #define ss second #define mp make_pair const int mod=1000000007; ll temp; class Solution { public: int repeatedNTimes(vector<int>& A) { int n = A.size(); f1(i,0,n) { f1(j,max(i-3,0),i) { if(A[i]==A[j]) return A[i]; } } return 0; } };
18.586207
39
0.497217
coderanant
17c9c617f92aa763f28cf6945f5d1206b92c5b5a
14,580
cc
C++
tests/mpi_particle_test.cc
fuatfurkany/mpm
d840c91f1f6ed1d164dec30029717dcfe9d30f0c
[ "MIT" ]
null
null
null
tests/mpi_particle_test.cc
fuatfurkany/mpm
d840c91f1f6ed1d164dec30029717dcfe9d30f0c
[ "MIT" ]
null
null
null
tests/mpi_particle_test.cc
fuatfurkany/mpm
d840c91f1f6ed1d164dec30029717dcfe9d30f0c
[ "MIT" ]
null
null
null
#include <limits> #include "catch.hpp" #include "data_types.h" #include "hdf5_particle.h" #include "material/material.h" #include "mpi_datatypes.h" #include "particle.h" #ifdef USE_MPI //! \brief Check particle class for 1D case TEST_CASE("MPI HDF5 Particle is checked", "[particle][mpi][hdf5]") { // Dimension const unsigned Dim = 3; // Tolerance const double Tolerance = 1.E-7; // Check MPI transfer of HDF5 Particle SECTION("MPI HDF5 Particle") { mpm::Index id = 0; mpm::HDF5Particle h5_particle; h5_particle.id = 13; h5_particle.mass = 501.5; h5_particle.pressure = 125.75; Eigen::Vector3d coords; coords << 1., 2., 3.; h5_particle.coord_x = coords[0]; h5_particle.coord_y = coords[1]; h5_particle.coord_z = coords[2]; Eigen::Vector3d displacement; displacement << 0.01, 0.02, 0.03; h5_particle.displacement_x = displacement[0]; h5_particle.displacement_y = displacement[1]; h5_particle.displacement_z = displacement[2]; Eigen::Vector3d lsize; lsize << 0.25, 0.5, 0.75; h5_particle.nsize_x = lsize[0]; h5_particle.nsize_y = lsize[1]; h5_particle.nsize_z = lsize[2]; Eigen::Vector3d velocity; velocity << 1.5, 2.5, 3.5; h5_particle.velocity_x = velocity[0]; h5_particle.velocity_y = velocity[1]; h5_particle.velocity_z = velocity[2]; Eigen::Matrix<double, 6, 1> stress; stress << 11.5, -12.5, 13.5, 14.5, -15.5, 16.5; h5_particle.stress_xx = stress[0]; h5_particle.stress_yy = stress[1]; h5_particle.stress_zz = stress[2]; h5_particle.tau_xy = stress[3]; h5_particle.tau_yz = stress[4]; h5_particle.tau_xz = stress[5]; Eigen::Matrix<double, 6, 1> strain; strain << 0.115, -0.125, 0.135, 0.145, -0.155, 0.165; h5_particle.strain_xx = strain[0]; h5_particle.strain_yy = strain[1]; h5_particle.strain_zz = strain[2]; h5_particle.gamma_xy = strain[3]; h5_particle.gamma_yz = strain[4]; h5_particle.gamma_xz = strain[5]; h5_particle.epsilon_v = strain.head(Dim).sum(); h5_particle.status = true; h5_particle.cell_id = 1; h5_particle.volume = 2.; h5_particle.material_id = 1; h5_particle.nstate_vars = 0; for (unsigned i = 0; i < h5_particle.nstate_vars; ++i) h5_particle.svars[i] = 0.; // Check send and receive particle with HDF5 SECTION("Check send and receive particle with HDF5") { // Get number of MPI ranks int mpi_size; MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); // If on same rank int sender = 0; int receiver = 0; // Get rank and do the corresponding job for mpi size == 2 if (mpi_size == 2) receiver = 1; int mpi_rank; MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Send particle if (mpi_rank == sender) { // Initialize MPI datatypes MPI_Datatype particle_type = mpm::register_mpi_particle_type(h5_particle); MPI_Send(&h5_particle, 1, particle_type, receiver, 0, MPI_COMM_WORLD); mpm::deregister_mpi_particle_type(particle_type); } // Receive particle if (mpi_rank == receiver) { // Receive the messid struct mpm::HDF5Particle received; MPI_Datatype particle_type = mpm::register_mpi_particle_type(received); MPI_Recv(&received, 1, particle_type, sender, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); mpm::deregister_mpi_particle_type(particle_type); REQUIRE(h5_particle.id == received.id); REQUIRE(h5_particle.mass == received.mass); REQUIRE(h5_particle.pressure == Approx(received.pressure).epsilon(Tolerance)); REQUIRE(h5_particle.volume == Approx(received.volume).epsilon(Tolerance)); REQUIRE(h5_particle.coord_x == Approx(received.coord_x).epsilon(Tolerance)); REQUIRE(h5_particle.coord_y == Approx(received.coord_y).epsilon(Tolerance)); REQUIRE(h5_particle.coord_z == Approx(received.coord_z).epsilon(Tolerance)); REQUIRE(h5_particle.displacement_x == Approx(received.displacement_x).epsilon(Tolerance)); REQUIRE(h5_particle.displacement_y == Approx(received.displacement_y).epsilon(Tolerance)); REQUIRE(h5_particle.displacement_z == Approx(received.displacement_z).epsilon(Tolerance)); REQUIRE(h5_particle.nsize_x == received.nsize_x); REQUIRE(h5_particle.nsize_y == received.nsize_y); REQUIRE(h5_particle.nsize_z == received.nsize_z); REQUIRE(h5_particle.velocity_x == Approx(received.velocity_x).epsilon(Tolerance)); REQUIRE(h5_particle.velocity_y == Approx(received.velocity_y).epsilon(Tolerance)); REQUIRE(h5_particle.velocity_z == Approx(received.velocity_z).epsilon(Tolerance)); REQUIRE(h5_particle.stress_xx == Approx(received.stress_xx).epsilon(Tolerance)); REQUIRE(h5_particle.stress_yy == Approx(received.stress_yy).epsilon(Tolerance)); REQUIRE(h5_particle.stress_zz == Approx(received.stress_zz).epsilon(Tolerance)); REQUIRE(h5_particle.tau_xy == Approx(received.tau_xy).epsilon(Tolerance)); REQUIRE(h5_particle.tau_yz == Approx(received.tau_yz).epsilon(Tolerance)); REQUIRE(h5_particle.tau_xz == Approx(received.tau_xz).epsilon(Tolerance)); REQUIRE(h5_particle.strain_xx == Approx(received.strain_xx).epsilon(Tolerance)); REQUIRE(h5_particle.strain_yy == Approx(received.strain_yy).epsilon(Tolerance)); REQUIRE(h5_particle.strain_zz == Approx(received.strain_zz).epsilon(Tolerance)); REQUIRE(h5_particle.gamma_xy == Approx(received.gamma_xy).epsilon(Tolerance)); REQUIRE(h5_particle.gamma_yz == Approx(received.gamma_yz).epsilon(Tolerance)); REQUIRE(h5_particle.gamma_xz == Approx(received.gamma_xz).epsilon(Tolerance)); REQUIRE(h5_particle.epsilon_v == Approx(received.epsilon_v).epsilon(Tolerance)); REQUIRE(h5_particle.status == received.status); REQUIRE(h5_particle.cell_id == received.cell_id); REQUIRE(h5_particle.material_id == received.cell_id); REQUIRE(h5_particle.nstate_vars == received.nstate_vars); for (unsigned i = 0; i < h5_particle.nstate_vars; ++i) REQUIRE(h5_particle.svars[i] == Approx(h5_particle.svars[i]).epsilon(Tolerance)); } } // Check initialise particle from HDF5 file SECTION("Check initialise particle with HDF5 across MPI processes") { // Get number of MPI ranks int mpi_size; MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); int mpi_rank; MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // If on same rank int sender = 0; int receiver = 0; // Get rank and do the corresponding job for mpi size == 2 if (mpi_size == 2) receiver = 1; // Initial particle coordinates Eigen::Matrix<double, 3, 1> pcoordinates; pcoordinates.setZero(); if (mpi_rank == sender) { // Create and initialzie particle with HDF5 data std::shared_ptr<mpm::ParticleBase<Dim>> particle = std::make_shared<mpm::Particle<Dim>>(id, pcoordinates); // Assign material unsigned mid = 1; // Initialise material Json jmaterial; jmaterial["density"] = 1000.; jmaterial["youngs_modulus"] = 1.0E+7; jmaterial["poisson_ratio"] = 0.3; auto material = Factory<mpm::Material<Dim>, unsigned, const Json&>::instance() ->create("LinearElastic3D", std::move(mid), jmaterial); // Reinitialise particle from HDF5 data REQUIRE(particle->initialise_particle(h5_particle, material) == true); // Check particle id REQUIRE(particle->id() == h5_particle.id); // Check particle mass REQUIRE(particle->mass() == h5_particle.mass); // Check particle volume REQUIRE(particle->volume() == h5_particle.volume); // Check particle mass density REQUIRE(particle->mass_density() == h5_particle.mass / h5_particle.volume); // Check particle status REQUIRE(particle->status() == h5_particle.status); // Check for coordinates auto coordinates = particle->coordinates(); REQUIRE(coordinates.size() == Dim); for (unsigned i = 0; i < coordinates.size(); ++i) REQUIRE(coordinates(i) == Approx(coords(i)).epsilon(Tolerance)); REQUIRE(coordinates.size() == Dim); // Check for displacement auto pdisplacement = particle->displacement(); REQUIRE(pdisplacement.size() == Dim); for (unsigned i = 0; i < Dim; ++i) REQUIRE(pdisplacement(i) == Approx(displacement(i)).epsilon(Tolerance)); // Check for size auto size = particle->natural_size(); REQUIRE(size.size() == Dim); for (unsigned i = 0; i < size.size(); ++i) REQUIRE(size(i) == Approx(lsize(i)).epsilon(Tolerance)); // Check velocity auto pvelocity = particle->velocity(); REQUIRE(pvelocity.size() == Dim); for (unsigned i = 0; i < Dim; ++i) REQUIRE(pvelocity(i) == Approx(velocity(i)).epsilon(Tolerance)); // Check stress auto pstress = particle->stress(); REQUIRE(pstress.size() == stress.size()); for (unsigned i = 0; i < stress.size(); ++i) REQUIRE(pstress(i) == Approx(stress(i)).epsilon(Tolerance)); // Check strain auto pstrain = particle->strain(); REQUIRE(pstrain.size() == strain.size()); for (unsigned i = 0; i < strain.size(); ++i) REQUIRE(pstrain(i) == Approx(strain(i)).epsilon(Tolerance)); // Check particle volumetric strain centroid REQUIRE(particle->volumetric_strain_centroid() == h5_particle.epsilon_v); // Check cell id REQUIRE(particle->cell_id() == h5_particle.cell_id); // Check material id REQUIRE(particle->material_id() == h5_particle.material_id); // Write Particle HDF5 data const auto h5_send = particle->hdf5(); // Send MPI particle MPI_Datatype paritcle_type = mpm::register_mpi_particle_type(h5_send); MPI_Send(&h5_send, 1, paritcle_type, receiver, 0, MPI_COMM_WORLD); mpm::deregister_mpi_particle_type(paritcle_type); } if (mpi_rank == receiver) { // Receive the messid struct mpm::HDF5Particle received; MPI_Datatype paritcle_type = mpm::register_mpi_particle_type(received); MPI_Recv(&received, 1, paritcle_type, sender, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); mpm::deregister_mpi_particle_type(paritcle_type); // Received particle std::shared_ptr<mpm::ParticleBase<Dim>> rparticle = std::make_shared<mpm::Particle<Dim>>(id, pcoordinates); // Assign material unsigned mid = 1; // Initialise material Json jmaterial; jmaterial["density"] = 1000.; jmaterial["youngs_modulus"] = 1.0E+7; jmaterial["poisson_ratio"] = 0.3; auto material = Factory<mpm::Material<Dim>, unsigned, const Json&>::instance() ->create("LinearElastic3D", std::move(mid), jmaterial); // Reinitialise particle from HDF5 data REQUIRE(rparticle->initialise_particle(received, material) == true); // Check particle id REQUIRE(rparticle->id() == h5_particle.id); // Check particle mass REQUIRE(rparticle->mass() == h5_particle.mass); // Check particle volume REQUIRE(rparticle->volume() == h5_particle.volume); // Check particle mass density REQUIRE(rparticle->mass_density() == h5_particle.mass / h5_particle.volume); // Check particle status REQUIRE(rparticle->status() == h5_particle.status); // Check for coordinates auto coordinates = rparticle->coordinates(); REQUIRE(coordinates.size() == Dim); for (unsigned i = 0; i < coordinates.size(); ++i) REQUIRE(coordinates(i) == Approx(coords(i)).epsilon(Tolerance)); REQUIRE(coordinates.size() == Dim); // Check for displacement auto pdisplacement = rparticle->displacement(); REQUIRE(pdisplacement.size() == Dim); for (unsigned i = 0; i < Dim; ++i) REQUIRE(pdisplacement(i) == Approx(displacement(i)).epsilon(Tolerance)); // Check for size auto size = rparticle->natural_size(); REQUIRE(size.size() == Dim); for (unsigned i = 0; i < size.size(); ++i) REQUIRE(size(i) == Approx(lsize(i)).epsilon(Tolerance)); // Check velocity auto pvelocity = rparticle->velocity(); REQUIRE(pvelocity.size() == Dim); for (unsigned i = 0; i < Dim; ++i) REQUIRE(pvelocity(i) == Approx(velocity(i)).epsilon(Tolerance)); // Check stress auto pstress = rparticle->stress(); REQUIRE(pstress.size() == stress.size()); for (unsigned i = 0; i < stress.size(); ++i) REQUIRE(pstress(i) == Approx(stress(i)).epsilon(Tolerance)); // Check strain auto pstrain = rparticle->strain(); REQUIRE(pstrain.size() == strain.size()); for (unsigned i = 0; i < strain.size(); ++i) REQUIRE(pstrain(i) == Approx(strain(i)).epsilon(Tolerance)); // Check particle volumetric strain centroid REQUIRE(rparticle->volumetric_strain_centroid() == h5_particle.epsilon_v); // Check cell id REQUIRE(rparticle->cell_id() == h5_particle.cell_id); // Check material id REQUIRE(rparticle->material_id() == h5_particle.material_id); // Get Particle HDF5 data const auto h5_received = rparticle->hdf5(); // State variables REQUIRE(h5_received.nstate_vars == h5_particle.nstate_vars); // State variables for (unsigned i = 0; i < h5_particle.nstate_vars; ++i) REQUIRE(h5_received.svars[i] == Approx(h5_particle.svars[i]).epsilon(Tolerance)); } } } } #endif // MPI
36.541353
79
0.615844
fuatfurkany
17d34e71d4614171110adbde4c5970176be21c73
2,130
hpp
C++
embedded/src/fsw/FCCode/MissionManager_a.hpp
CornellDataScience/self-driving-car
449044840abdeed9f547a16cd192950e23ba189c
[ "MIT" ]
3
2021-09-29T21:15:25.000Z
2021-11-11T20:57:07.000Z
embedded/src/fsw/FCCode/MissionManager_a.hpp
CornellDataScience/self-driving-car
449044840abdeed9f547a16cd192950e23ba189c
[ "MIT" ]
44
2021-09-28T05:38:43.000Z
2022-03-31T21:29:48.000Z
embedded/src/fsw/FCCode/MissionManager_a.hpp
CornellDataScience/self-driving-car
449044840abdeed9f547a16cd192950e23ba189c
[ "MIT" ]
1
2020-12-23T03:32:11.000Z
2020-12-23T03:32:11.000Z
#ifndef MISSION_MANAGER_A_HPP_ #define MISSION_MANAGER_A_HPP_ #include "TimedControlTask.hpp" #include "mission_mode_t.enum" #include "adcs_mode_t.enum" class MissionManager_a : public TimedControlTask<void> { public: MissionManager_a(StateFieldRegistry& registry, unsigned int offset); void execute() override; protected: void set_mission_mode(mission_mode_t mode); void calibrate_data(); void dispatch_warmup(); void dispatch_initialization(); void pause(); void tvc(); void dispatch_landed(); // Fields that control overall mission state. /** * @brief Current mission mode (see mission_mode_t.enum) */ InternalStateField<unsigned char> mission_mode_f; InternalStateField<lin::Vector3f> acc_error_f; InternalStateField<lin::Vector4d> init_quat_d; InternalStateField<lin::Vector3d> euler_deg; InternalStateField<lin::Vector2f> init_lat_long_f; InternalStateField<float> ground_level_f; InternalStateField<bool> engine_on_f; InternalStateField<bool> servo_on_f; InternalStateField<float> agl_alt_f; InternalStateField<int> count; InternalStateField<double> init_global_roll; InternalStateField<float>* alt_fp; InternalStateField<lin::Vector3f>* acc_vec_fp; InternalStateField<lin::Vector4d>* quat_fp; InternalStateField<lin::Vector2f>* lat_long_fp; InternalStateField<lin::Vector3f>* lin_acc_vec_fp; InternalStateField<lin::Vector3f>* omega_vec_fp; InternalStateField<lin::Vector3f>* mag_vec_fp; InternalStateField<unsigned char>* sys_cal; InternalStateField<unsigned char>* gyro_cal; InternalStateField<unsigned char>* accel_cal; InternalStateField<unsigned char>* mag_cal; long enter_init_millis; int enter_init_ccno; long enter_flight_millis; int enter_freefall_cnno; int pause_ccno; //long enter_bellyflop_millis; // long enter_standby_millis; }; #endif
31.791045
76
0.686385
CornellDataScience
17d744b490831419ed1ed3326f534eb3cbe53938
4,712
cc
C++
src/automaton/examples/network/node_prototype.cc
liberatix/automaton-core
0e36bd5b616a308ea319a791b11f68df879f4571
[ "MIT" ]
null
null
null
src/automaton/examples/network/node_prototype.cc
liberatix/automaton-core
0e36bd5b616a308ea319a791b11f68df879f4571
[ "MIT" ]
null
null
null
src/automaton/examples/network/node_prototype.cc
liberatix/automaton-core
0e36bd5b616a308ea319a791b11f68df879f4571
[ "MIT" ]
null
null
null
#include "automaton/examples/network/node_prototype.h" #include "automaton/core/io/io.h" namespace acn = automaton::core::network; /// Node's connection handler node::handler::handler(node* n): node_(n) {} void node::handler::on_message_received(acn::connection* c, char* buffer, uint32_t bytes_read, uint32_t id) { std::string message = std::string(buffer, bytes_read); // logging("Message \"" + message + "\" received in <" + c->get_address() + ">"); if (std::stoul(message) > node_->height) { node_->height = std::stoul(message); node_->send_height(); } c -> async_read(buffer, 16, 0, 0); } void node::handler::on_message_sent(acn::connection* c, uint32_t id, acn::connection::error e) { if (e) { LOG(ERROR) << "Message with id " << std::to_string(id) << " was NOT sent to " << c->get_address() << "\nError " << std::to_string(e); } else { // logging("Message with id " + std::to_string(id) + " was successfully sent to " + // c->get_address()); } } void node::handler::on_connected(acn::connection* c) { c->async_read(node_->add_buffer(16), 16, 0, 0); } void node::handler::on_disconnected(acn::connection* c) { // logging("Disconnected with: " + c->get_address()); } void node::handler::on_error(acn::connection* c, acn::connection::error e) { if (e == acn::connection::no_error) { return; } LOG(ERROR) << "Error: " << std::to_string(e) << " (connection " << c->get_address() << ")"; } /// Node's acceptor handler node::lis_handler::lis_handler(node* n):node_(n) {} bool node::lis_handler::on_requested(acn::acceptor* a, const std::string& address) { // EXPECT_EQ(address, address_a); // logging("Connection request from: " + address + ". Accepting..."); return node_->accept_connection(/*address*/); } void node::lis_handler::on_connected(acn::acceptor* a, acn::connection* c, const std::string& address) { // logging("Accepted connection from: " + address); node_->peers[node_->get_next_peer_id()] = c; c->async_read(node_->add_buffer(16), 16, 0, 0); } void node::lis_handler::on_error(acn::acceptor* a, acn::connection::error e) { LOG(ERROR) << std::to_string(e); } /// Node node::node() { height = 0; peer_ids = 0; handler_ = new handler(this); lis_handler_ = new lis_handler(this); } node::~node() { for (int i = 0; i < buffers.size(); ++i) { delete [] buffers[i]; } // TODO(kari): delete all acceptors and connections } char* node::add_buffer(uint32_t size) { std::lock_guard<std::mutex> lock(buffer_mutex); buffers.push_back(new char[size]); return buffers[buffers.size() - 1]; } /// This function is created because the acceptor needs ids for the connections it accepts uint32_t node::get_next_peer_id() { return ++peer_ids; } bool node::accept_connection() { return true; } bool node::add_peer(uint32_t id, const std::string& connection_type, const std::string& address) { auto it = peers.find(id); if (it != peers.end()) { // delete it->second; /// Delete existing acceptor } acn::connection* new_connection; try { new_connection = acn::connection::create(connection_type, address, handler_); } catch (std::exception& e) { LOG(ERROR) << e.what(); peers[id] = nullptr; return false; } if (!new_connection) { LOG(ERROR) << "Connection was not created!"; // Possible reason: tcp_init was never called return false; } peers[id] = new_connection; new_connection->connect(); return true; } void node::remove_peer(uint32_t id) { auto it = peers.find(id); if (it != peers.end()) { peers.erase(it); } } bool node::add_acceptor(uint32_t id, const std::string& connection_type, const std::string& address) { auto it = acceptors.find(id); if (it != acceptors.end()) { // delete it->second; /// Delete existing acceptor } acn::acceptor* new_acceptor; try { new_acceptor = acn::acceptor::create(connection_type, address, lis_handler_, handler_); } catch (std::exception& e) { LOG(ERROR) << e.what(); acceptors[id] = nullptr; return false; } if (!new_acceptor) { LOG(ERROR) << "Acceptor was not created!"; return false; } acceptors[id] = new_acceptor; new_acceptor->start_accepting(); return true; } void node::remove_acceptor(uint32_t id) { auto it = acceptors.find(id); if (it != acceptors.end()) { acceptors.erase(it); } } void node::send_height(uint32_t connection_id) { if (!connection_id) { for (auto it = peers.begin(); it != peers.end(); ++it) { // TODO(kari): if connected it->second->async_send(std::to_string(height), 0); } } else { peers[connection_id]->async_send(std::to_string(height), 0); } }
30.597403
98
0.647071
liberatix
17d8c4394bf3d379ec772376c3523b82b649f910
739
cxx
C++
cgv/gui/gui_creator.cxx
IXDdev/IXD_engine
497c1fee90e486c19debc5347b740b56b1fef416
[ "BSD-3-Clause" ]
1
2020-07-26T10:54:41.000Z
2020-07-26T10:54:41.000Z
cgv/gui/gui_creator.cxx
IXDdev/IXD_engine
497c1fee90e486c19debc5347b740b56b1fef416
[ "BSD-3-Clause" ]
null
null
null
cgv/gui/gui_creator.cxx
IXDdev/IXD_engine
497c1fee90e486c19debc5347b740b56b1fef416
[ "BSD-3-Clause" ]
null
null
null
#include "gui_creator.h" #include <vector> namespace cgv { namespace gui { std::vector<gui_creator*>& ref_gui_creators() { static std::vector<gui_creator*> creators; return creators; } /// register a gui creator void register_gui_creator(gui_creator* gc, const char* creator_name) { ref_gui_creators().push_back(gc); } /// create the gui for a composed structure bool create_gui(provider* p, const std::string& label, void* value_ptr, const std::string& value_type, const std::string& gui_type, const std::string& options, bool* toggles) { for (unsigned i=0; i<ref_gui_creators().size(); ++i) if (ref_gui_creators()[i]->create(p,label,value_ptr,value_type,gui_type,options,toggles)) return true; return false; } } }
23.09375
91
0.728011
IXDdev
17db4def8352c85ce6e424972c4388b60871d83f
6,356
cpp
C++
src/LauncherSystem.cpp
OlivierAlgoet/angry-bricks-project
64b368bd623eadcd814b4f27bb19e02388f8799f
[ "MIT" ]
null
null
null
src/LauncherSystem.cpp
OlivierAlgoet/angry-bricks-project
64b368bd623eadcd814b4f27bb19e02388f8799f
[ "MIT" ]
null
null
null
src/LauncherSystem.cpp
OlivierAlgoet/angry-bricks-project
64b368bd623eadcd814b4f27bb19e02388f8799f
[ "MIT" ]
null
null
null
#include "LauncherSystem.h" void LauncherSystem::Update(){ std::set<Entity*> current_missile=engine_.GetEntityStream().WithTag(Component::Tag::CURRENTMISSILE); // ask for sprites, all entities containing a sprite have to use a scaled bitmap if (current_missile.empty()){ context_.changing=true; std::set<Entity*> missiles; PolygonComponent * pg; Point increment=Point((MISSILE_DST_WIDTH+MISSILE_SPACING),0); Point new_pos; for(int i=0;i<MISS_NR;i++){ missiles=engine_.GetEntityStream().WithTag(missile_list[i]); std::set<Entity*>::iterator it=missiles.begin(); for(;it!=missiles.end();it++){ pg=(PolygonComponent*)(*it)->GetComponent(Component::Tag::POLYGON); new_pos=pg->get_position()+increment; pg->set_position(new_pos); if(pg->get_position().x_>((MISS_NR-1)*(MISSILE_SPACING+MISSILE_DST_WIDTH))){ Point current=Point(MISSILEX,MISSILEY); CurrentMissileComponent * curr=new CurrentMissileComponent; (*it)->Add(curr); engine_.UpdateEntity((*it),(*it)->GetTags(),false); pg->set_position(current); CircleComponent * circle =(CircleComponent*)(*it)->GetComponent(Component::Tag::CIRCLE); if (circle!=NULL){ circle->set_pos(current); } } } } Entity * ent=new Entity; RandomMissile(0,Y_OFFSET,ent); engine_.AddEntity(ent); } // TODO click release check & zo ja positie van muis gelijkstellen aan x,y // als het gereleased is snelheid bepalen! else{ std::set<Entity*>::iterator it=current_missile.begin();// onlyone missile CurrentMissileComponent * Cm=(CurrentMissileComponent*)(*it)->GetComponent(Component::Tag::CURRENTMISSILE); if(!Cm->fired){ PolygonComponent * pg=(PolygonComponent*)(*it)->GetComponent(Component::Tag::POLYGON); if(!Cm->selected){ bool collision; CircleComponent * cr=(CircleComponent*)(*it)->GetComponent(Component::Tag::CIRCLE); // Check for collision if (cr!=NULL){ collision=CircleCollision_(context_.mouse,cr->get_center(),cr->radius); }else{ collision=PolyCollision_(context_.mouse,pg->get_polygon()); } // check if we clicked if (collision and context_.clicked){ Cm->selected=true; Cm->ClickCorrect=context_.mouse-pg->get_position(); } }else{ context_.changing=true; if (context_.mouse.x_<MISSILEX){ Point current_pos=context_.mouse-Cm->ClickCorrect; pg->set_position(current_pos); //Only set position of the polygon, the circle will only be used for the collision check so no sets are required here } //std::cout<<"selected!!"<<std::endl; if(context_.released){ //std::cout<<"changing the status to fired"<<std::endl; Cm->fired=true; Point speed_vector=Point(MISSILEX,MISSILEY)-(context_.mouse-Cm->ClickCorrect); Cm->speed.x_=KSPEED*speed_vector.x_; Cm->speed.y_=KSPEED*speed_vector.y_; //KSPEED is a proportional value to play with } } } } } bool LauncherSystem::CircleCollision_(Point& mouse,Point& center,double radius){ double length=mouse*center; //std::cout<<"the length is"<<length<<std::endl; bool collision=length<radius; //std::cout<<"collision"<<collision<<std::endl; return collision; } bool LauncherSystem::PolyCollision_(Point& mouse,std::vector<Point>& poly){ /* Some ugly copy and paste was done here, not using the functions directly from TargetSystems with the goal to keep the systems seperated for readability + future work*/ bool collision = true; std::vector<Point> edges_poly = GetEdges(poly); Point edge; std::vector<Point> mouse_point{mouse}; // made a vector such that the functions don't have to be changed // Loop through all the edges of both polygons for (std::size_t edge_id = 0; edge_id < edges_poly.size(); edge_id++) { edge = edges_poly[edge_id]; // Find perpendicular axis to current edge Point axis(-edge.y_, edge.x_); axis.Normalize(); // Find projection of polygon on current axis double min_dotp_poly = 0; double max_dotp_poly = 0; double dotp_mouse = 0; ProjectOnAxis(poly, axis, min_dotp_poly, max_dotp_poly); ProjectOnAxis(mouse_point, axis, dotp_mouse, dotp_mouse); // dotp_mouse in twice for function compatibility // Check if polygon projections overlap if (DistanceBetweenPolys(min_dotp_poly, max_dotp_poly, dotp_mouse) > 0) { collision = false; break; } } return collision; } std::vector<Point> LauncherSystem::GetEdges(std::vector<Point>& coordinates) { std::vector<Point> edges; Point prevPoint = coordinates[0]; for (std::size_t i = 1; i < coordinates.size(); i++) { edges.push_back(coordinates[i] - prevPoint); prevPoint = coordinates[i]; } edges.push_back(coordinates[0] - prevPoint); return edges; } void LauncherSystem::ProjectOnAxis(std::vector<Point>& coordinates, Point& axis, double& min, double& max) { double dotp = coordinates[0] >> axis; min = dotp; max = dotp; for (std::size_t i = 0; i < coordinates.size(); i++) { dotp = coordinates[i] >> axis; if (dotp < min) { min = dotp; } else if (dotp > max) { max = dotp; } } } double LauncherSystem::DistanceBetweenPolys(double min_dotp_poly, double max_dotp_poly, double dotp_mouse) { if (min_dotp_poly < dotp_mouse) { return dotp_mouse - max_dotp_poly; } else { return min_dotp_poly - dotp_mouse; } }
39.234568
185
0.584172
OlivierAlgoet
17db87f2a2c464be293923a5e29a43225df7691c
2,092
cc
C++
test/test_json/test_json.cc
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
test/test_json/test_json.cc
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
test/test_json/test_json.cc
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
#include "json.hpp" #include <iostream> #include <vector> #include <map> #include <string> #include <exception> using json = nlohmann::json; using namespace std; int main(){ // 序列化 // 普通数据序列化 json js; js["id"] = {1,2,3,4,5}; js["name"] = "zhang san"; js["msg"]["zhang san"] = "hello world"; js["msg"]["liu shuo"] = "hello from liu shuo"; cout << js <<endl; // 容器序列化 json js_; vector<int> vec{1,2,5}; js_["list"] = vec; map<int,string> m{{1,"一"},{2,"二"},{3,"三"}}; js_["num"] = m; cout << js_ <<endl; // 显式dump cout << js_.dump()<<endl; // 反序列化 cout << endl; string json_str = js.dump(); cout << "receive: " << json_str<<endl; json js2_parsed = json::parse(json_str); // 允许空格、回车等 json js3_parsed = json::parse("{\"msgid\":4,\"id\": 540000 } \n"); cout << "allow some noise like \\n and space" << js3_parsed.dump() <<endl; // 可以使用find检查键 cout << "json above has id "<<(js3_parsed.find("id")!=js3_parsed.end() )<< endl; cout << "json above has name "<<(js3_parsed.find("name")!=js3_parsed.end()) << endl; // 反序列化get为string json js_ex ; js_ex["msg"] = "message"; string js_ex_str = js_ex.dump(); json js_ex_r = json::parse( js_ex_str); cout <<"use [\"tag\"] directly : "<< js_ex_r["msg"] << endl; cout <<"use get<string> : "<< js_ex_r["msg"].get<string>()<< endl; // 单个变量 auto name = js2_parsed["name"]; cout << "name: " << name <<endl; // 容器 auto v = js2_parsed["id"]; cout << "id : "; for(const auto& x : v){ cout << x << " "; } cout << endl; // 容器 map<string,string> name_sentence = js2_parsed["msg"]; for(const auto& x : name_sentence){ cout << x.first << " : " <<x.second<<endl; } cout <<endl; // 多个json : 不行 try{ string two_js_str = js_ex.dump(); two_js_str += js_ex.dump(); cout << two_js_str <<endl; json two_js = json::parse(two_js_str); } catch (exception E){ cout << E.what()<<endl; } }
23.244444
88
0.526769
MUCZ
17e09d95d39bcd1b148b39c9853cafe1a89aa818
3,361
cpp
C++
Source/AllProjects/Drivers/LutronHW/Client/LutronHWC_Data.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/LutronHW/Client/LutronHWC_Data.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/LutronHW/Client/LutronHWC_Data.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// ---------------------------------------------------------------------------- // FILE: LutronHWC_Data.cpp // DATE: Fri, Feb 12 21:14:17 2021 -0500 // // This file was generated by the Charmed Quark CIDIDL compiler. Do not make // changes by hand, because they will be lost if the file is regenerated. // ---------------------------------------------------------------------------- #include "LutronHWC_.hpp" const TString kLutronHWC::strAttr_Addr(L"/Attr/Addr"); const TString kLutronHWC::strAttr_Name(L"/Attr/Name"); const TString kLutronHWC::strAttr_Number(L"/Attr/Number"); static TEnumMap::TEnumValItem aeitemValues_EListCols[4] = { { tCIDLib::TInt4(tLutronHWC::EListCols::Type), 0, 0, { L"", L"", L"", L"Type", L"EListCols::Type", L"" } } , { tCIDLib::TInt4(tLutronHWC::EListCols::Name), 0, 0, { L"", L"", L"", L"Name", L"EListCols::Name", L"" } } , { tCIDLib::TInt4(tLutronHWC::EListCols::Address), 0, 0, { L"", L"", L"", L"Address", L"EListCols::Address", L"" } } , { tCIDLib::TInt4(tLutronHWC::EListCols::Number), 0, 0, { L"", L"", L"", L"Number", L"EListCols::Number", L"" } } }; static TEnumMap emapEListCols ( L"EListCols" , 4 , kCIDLib::False , aeitemValues_EListCols , nullptr , tCIDLib::TCard4(tLutronHWC::EListCols::Count) ); const TString& tLutronHWC::strXlatEListCols(const tLutronHWC::EListCols eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEListCols.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tLutronHWC::EListCols tLutronHWC::eXlatEListCols(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tLutronHWC::EListCols(emapEListCols.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } tCIDLib::TBoolean tLutronHWC::bIsValidEnum(const tLutronHWC::EListCols eVal) { return emapEListCols.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EItemTypes[3] = { { tCIDLib::TInt4(tLutronHWC::EItemTypes::Button), 0, 0, { L"", L"", L"", L"Button", L"EItemTypes::Button", L"" } } , { tCIDLib::TInt4(tLutronHWC::EItemTypes::Dimmer), 0, 0, { L"", L"", L"", L"Dimmer", L"EItemTypes::Dimmer", L"" } } , { tCIDLib::TInt4(tLutronHWC::EItemTypes::LED), 0, 0, { L"", L"", L"", L"LED", L"EItemTypes::LED", L"" } } }; static TEnumMap emapEItemTypes ( L"EItemTypes" , 3 , kCIDLib::False , aeitemValues_EItemTypes , nullptr , tCIDLib::TCard4(tLutronHWC::EItemTypes::Count) ); const TString& tLutronHWC::strXlatEItemTypes(const tLutronHWC::EItemTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEItemTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tLutronHWC::EItemTypes tLutronHWC::eXlatEItemTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tLutronHWC::EItemTypes(emapEItemTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } TTextOutStream& tLutronHWC::operator<<(TTextOutStream& strmTar, const tLutronHWC::EItemTypes eVal) { strmTar << emapEItemTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, kCIDLib::False); return strmTar; } tCIDLib::TBoolean tLutronHWC::bIsValidEnum(const tLutronHWC::EItemTypes eVal) { return emapEItemTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); }
36.532609
121
0.670336
MarkStega
17e23fd60070009ef647e04a73074839c68147a6
534
cpp
C++
pool_and_pad/padding.cpp
navneel99/image_processing_library
c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76
[ "MIT" ]
null
null
null
pool_and_pad/padding.cpp
navneel99/image_processing_library
c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76
[ "MIT" ]
null
null
null
pool_and_pad/padding.cpp
navneel99/image_processing_library
c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76
[ "MIT" ]
null
null
null
#include "padding.hpp" vector<vector<float> > Padding(vector<vector<float> > mat, int pad){ for (int j = 0;j<mat.size();j++){ vector<float> row = mat.at(j); for (int i = 0; i<pad;i++){ row.push_back(0); row.emplace(row.begin(),0); } mat[j] = row; } int new_row_length = mat.size() + 2 * pad; vector<float> zero_row(new_row_length); for (int i = 0;i<pad;i++){ mat.push_back(zero_row); mat.emplace(mat.begin(),zero_row); } return mat; }
29.666667
68
0.533708
navneel99
17ebe2608250381839b77ac8344ca576667f996b
127
cpp
C++
Sources/Game/Application/main.cpp
vit3k/entity_system
5b00804bb772229cab90ea7de589faced98bc001
[ "MIT" ]
null
null
null
Sources/Game/Application/main.cpp
vit3k/entity_system
5b00804bb772229cab90ea7de589faced98bc001
[ "MIT" ]
null
null
null
Sources/Game/Application/main.cpp
vit3k/entity_system
5b00804bb772229cab90ea7de589faced98bc001
[ "MIT" ]
null
null
null
#include "Application.h" int main() { Application& app = Application::Instance(); app.Init(); app.Loop(); return 0; }
12.7
44
0.629921
vit3k
17f1536e10412892a011263ed09a218538630109
24,531
cpp
C++
tket/src/Circuit/macro_manipulation.cpp
CQCL/tket
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
[ "Apache-2.0" ]
104
2021-09-15T08:16:25.000Z
2022-03-28T21:19:00.000Z
tket/src/Circuit/macro_manipulation.cpp
CQCL/tket
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
[ "Apache-2.0" ]
109
2021-09-16T17:14:22.000Z
2022-03-29T06:48:40.000Z
tket/src/Circuit/macro_manipulation.cpp
CQCL/tket
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
[ "Apache-2.0" ]
8
2021-10-02T13:47:34.000Z
2022-03-17T15:36:56.000Z
// Copyright 2019-2022 Cambridge Quantum Computing // // 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. ///////////////////////////////////////////////////// // ALL METHODS TO PERFORM COMPLEX CIRCUIT MANIPULATION// ///////////////////////////////////////////////////// #include <memory> #include "Circuit.hpp" #include "Gate/Gate.hpp" #include "Ops/ClassicalOps.hpp" #include "Utils/TketLog.hpp" #include "Utils/UnitID.hpp" namespace tket { vertex_map_t Circuit::copy_graph( const Circuit& c2, BoundaryMerge boundary_merge, OpGroupTransfer opgroup_transfer) { switch (opgroup_transfer) { case OpGroupTransfer::Preserve: // Fail if any collisions. for (const auto& opgroupsig : c2.opgroupsigs) { if (opgroupsigs.find(opgroupsig.first) != opgroupsigs.end()) { throw CircuitInvalidity("Name collision in inserted circuit"); } } // Add inserted opgroups to circuit. opgroupsigs.insert(c2.opgroupsigs.begin(), c2.opgroupsigs.end()); break; case OpGroupTransfer::Disallow: // Fail if any opgroups. if (!c2.opgroupsigs.empty()) { throw CircuitInvalidity("Named op groups in inserted circuit"); } break; case OpGroupTransfer::Merge: // Fail if any mismatched signatures for (const auto& opgroupsig : c2.opgroupsigs) { if (opgroupsigs.find(opgroupsig.first) != opgroupsigs.end()) { if (opgroupsigs[opgroupsig.first] != opgroupsig.second) { throw CircuitInvalidity( "Name signature mismatch in inserted circuit"); } } } // Add inserted opgroups to circuit. opgroupsigs.insert(c2.opgroupsigs.begin(), c2.opgroupsigs.end()); break; default: TKET_ASSERT(opgroup_transfer == OpGroupTransfer::Remove); // Ignore inserted opgroups break; } vertex_map_t isomap; if (&c2 == this) { throw Unsupported( "Circuit Cannot currently copy itself using this method. Use * " "instead\n"); } BGL_FORALL_VERTICES(v, c2.dag, DAG) { Vertex v0 = boost::add_vertex(this->dag); this->dag[v0].op = c2.get_Op_ptr_from_Vertex(v); if (opgroup_transfer == OpGroupTransfer::Preserve || opgroup_transfer == OpGroupTransfer::Merge) { this->dag[v0].opgroup = c2.get_opgroup_from_Vertex(v); } isomap.insert({v, v0}); } BGL_FORALL_VERTICES(v, c2.dag, DAG) { EdgeVec edges = c2.get_in_edges(v); Vertex target_v = isomap.find(v)->second; for (EdgeVec::iterator e1 = edges.begin(); e1 != edges.end(); ++e1) { Vertex old_source_v = c2.source(*e1); Vertex source_v = isomap.find(old_source_v)->second; add_edge( {source_v, get_source_port(*e1)}, {target_v, get_target_port(*e1)}, c2.dag[*e1].type); } } if (boundary_merge == BoundaryMerge::Yes) { for (const BoundaryElement& el : c2.boundary.get<TagID>()) { std::string reg_name = el.id_.reg_name(); register_info_t reg_type = el.reg_info(); opt_reg_info_t reg_found = get_reg_info(reg_name); if (reg_found) { if (reg_found.value() != reg_type) { throw Unsupported( "Cannot merge circuits with different types for " "register with name: " + reg_name); } boundary_t::iterator unit_found = boundary.get<TagID>().find(el.id_); if (unit_found != boundary.get<TagID>().end()) { throw Unsupported( "Cannot merge circuits as both contain unit: " + el.id_.repr()); } } Vertex new_in = isomap[el.in_]; Vertex new_out = isomap[el.out_]; boundary.insert({el.id_, new_in, new_out}); } } return isomap; } // given two circuits, adds second circuit to first circuit object in parallel Circuit operator*(const Circuit& c1, const Circuit& c2) { // preliminary method to add circuit objects together Circuit new_circ; new_circ.copy_graph(c1); new_circ.copy_graph(c2); new_circ.add_phase(c1.get_phase() + c2.get_phase()); return new_circ; } void Circuit::append(const Circuit& c2) { append_with_map(c2, {}); } // qm is from the units on the second (appended) circuit to the units on the // first (this) circuit void Circuit::append_with_map(const Circuit& c2, const unit_map_t& qm) { Circuit copy = c2; copy.rename_units(qm); // Check what we need to do at the joins: // Output --- Input ==> ------------- // Output --- Create ==> --- Reset --- // Discard --- Input ==> [not allowed] // Discard --- Create ==> --- Reset --- qubit_vector_t qbs = copy.all_qubits(); std::set<Qubit> qbs_set(qbs.begin(), qbs.end()); std::set<Qubit> reset_qbs; for (auto qb : all_qubits()) { if (qbs_set.find(qb) != qbs_set.end()) { if (copy.is_created(qb)) { reset_qbs.insert(qb); } else if (is_discarded(qb)) { throw CircuitInvalidity("Cannot append input qubit to discarded qubit"); } } } // Copy c2 into c1 but do not merge boundaries vertex_map_t vm = copy_graph(copy, BoundaryMerge::No); const Op_ptr noop = get_op_ptr(OpType::noop); // Connect each matching qubit and bit, merging remainder for (const BoundaryElement& el : copy.boundary.get<TagID>()) { std::string reg_name = el.reg_name(); register_info_t reg_type = el.reg_info(); opt_reg_info_t reg_found = get_reg_info(reg_name); if (reg_found) { if (reg_found.value() != reg_type) { throw Unsupported( "Cannot append circuits with different types for " "register with name: " + reg_name); } boundary_t::iterator unit_found = boundary.get<TagID>().find(el.id_); if (unit_found != boundary.get<TagID>().end()) { Vertex out = unit_found->out_; Vertex in = vm[el.in_]; // Update map BoundaryElement new_elem = *unit_found; new_elem.out_ = vm[el.out_]; boundary.replace(unit_found, new_elem); // Tie together if (reg_type.first == UnitType::Qubit) add_edge({out, 0}, {in, 0}, EdgeType::Quantum); else add_edge({out, 0}, {in, 0}, EdgeType::Classical); dag[out].op = noop; dag[in].op = noop; remove_vertex(out, GraphRewiring::Yes, VertexDeletion::Yes); if (el.type() != UnitType::Qubit || reset_qbs.find(Qubit(el.id_)) == reset_qbs.end()) { remove_vertex(in, GraphRewiring::Yes, VertexDeletion::Yes); } else { dag[in].op = std::make_shared<const Gate>(OpType::Reset); } } else { Vertex new_in = vm[el.in_]; Vertex new_out = vm[el.out_]; boundary.insert({el.id_, new_in, new_out}); } } else { Vertex new_in = vm[el.in_]; Vertex new_out = vm[el.out_]; boundary.insert({el.id_, new_in, new_out}); } } add_phase(c2.get_phase()); } void Circuit::append_qubits( const Circuit& c2, const std::vector<unsigned>& qubits, const std::vector<unsigned>& bits) { unit_map_t qm; for (unsigned i = 0; i < qubits.size(); i++) { qm.insert({Qubit(i), Qubit(qubits[i])}); } for (unsigned i = 0; i < bits.size(); i++) { qm.insert({Bit(i), Bit(bits[i])}); } append_with_map(c2, qm); } // given two circuits, adds second circuit to first sequentially by tying qubits // together and returns a copy of this (to prevent destruction of initial // circuits) Circuit operator>>(const Circuit& ci1, const Circuit& ci2) { Circuit new_circ = ci1; new_circ.append(ci2); return new_circ; } // Important substitute method. Requires knowledge of the boundary to insert // into, and the vertices inside which are to be removed when substitution is // performed. Gives the option to isolate the removed vertices but not delete // them. void Circuit::substitute( const Circuit& to_insert, const Subcircuit& to_replace, VertexDeletion vertex_deletion, OpGroupTransfer opgroup_transfer) { if (!to_insert.is_simple()) throw SimpleOnly(); if (to_insert.n_qubits() != to_replace.q_in_hole.size() || to_insert.n_bits() != to_replace.c_in_hole.size()) throw CircuitInvalidity("Subcircuit boundary mismatch to hole"); vertex_map_t vm = copy_graph(to_insert, BoundaryMerge::No, opgroup_transfer); VertexList bin; EdgeSet ebin; // Needs to be a set since subcircuit to replace could be // trivial, essentially rewiring on a cut std::map<Edge, Vertex> c_out_map; const Op_ptr noop = get_op_ptr(OpType::noop); for (unsigned i = 0; i < to_replace.q_in_hole.size(); i++) { Edge edge = to_replace.q_in_hole[i]; Vertex pred_v = source(edge); port_t port1 = get_source_port(edge); ebin.insert(edge); Vertex inp = vm[to_insert.get_in(Qubit(i))]; add_edge({pred_v, port1}, {inp, 0}, EdgeType::Quantum); dag[inp].op = noop; bin.push_back(inp); } for (unsigned i = 0; i < to_replace.q_out_hole.size(); i++) { Edge edge = to_replace.q_out_hole[i]; Vertex succ_v = target(edge); port_t port2 = get_target_port(edge); ebin.insert(edge); Vertex outp = vm[to_insert.get_out(Qubit(i))]; add_edge({outp, 0}, {succ_v, port2}, EdgeType::Quantum); dag[outp].op = noop; bin.push_back(outp); } for (unsigned i = 0; i < to_replace.c_in_hole.size(); i++) { Edge edge = to_replace.c_in_hole[i]; Vertex pred_v = source(edge); port_t port1 = get_source_port(edge); ebin.insert(edge); Vertex inp = vm[to_insert.get_in(Bit(i))]; add_edge({pred_v, port1}, {inp, 0}, EdgeType::Classical); dag[inp].op = noop; bin.push_back(inp); } for (unsigned i = 0; i < to_replace.c_out_hole.size(); i++) { Edge edge = to_replace.c_out_hole[i]; Vertex succ_v = target(edge); port_t port2 = get_target_port(edge); ebin.insert(edge); Vertex outp = vm[to_insert.get_out(Bit(i))]; add_edge({outp, 0}, {succ_v, port2}, EdgeType::Classical); dag[outp].op = noop; bin.push_back(outp); c_out_map.insert({edge, outp}); } for (const Edge& e : to_replace.b_future) { Edge c_out = get_nth_out_edge(source(e), get_source_port(e)); Vertex outp = c_out_map[c_out]; add_edge({outp, 0}, {target(e), get_target_port(e)}, EdgeType::Boolean); ebin.insert(e); } for (const Edge& e : ebin) { remove_edge(e); } // automatically rewire these canned vertices remove_vertices(bin, GraphRewiring::Yes, VertexDeletion::Yes); remove_vertices(to_replace.verts, GraphRewiring::No, vertex_deletion); add_phase(to_insert.get_phase()); } void Circuit::substitute( const Circuit& to_insert, const Vertex& to_replace, VertexDeletion vertex_deletion, OpGroupTransfer opgroup_transfer) { Subcircuit sub = { get_in_edges_of_type(to_replace, EdgeType::Quantum), get_out_edges_of_type(to_replace, EdgeType::Quantum), get_in_edges_of_type(to_replace, EdgeType::Classical), get_out_edges_of_type(to_replace, EdgeType::Classical), get_out_edges_of_type(to_replace, EdgeType::Boolean), {to_replace}}; substitute(to_insert, sub, vertex_deletion, opgroup_transfer); } void Circuit::substitute_conditional( Circuit to_insert, const Vertex& to_replace, VertexDeletion vertex_deletion, OpGroupTransfer opgroup_transfer) { Op_ptr op = get_Op_ptr_from_Vertex(to_replace); if (op->get_type() != OpType::Conditional) throw CircuitInvalidity( "substitute_conditional called with an unconditional gate"); Subcircuit sub = { get_in_edges_of_type(to_replace, EdgeType::Quantum), get_out_edges_of_type(to_replace, EdgeType::Quantum), get_in_edges_of_type(to_replace, EdgeType::Classical), get_out_edges_of_type(to_replace, EdgeType::Classical), get_out_edges_of_type(to_replace, EdgeType::Boolean), {to_replace}}; const Conditional& cond = static_cast<const Conditional&>(*op); unsigned width = cond.get_width(); // Conditions are first few args, so increase index of all others bit_map_t rename_map; for (unsigned i = 0; i < to_insert.n_bits(); ++i) { rename_map[Bit(i)] = Bit(i + width); } to_insert.rename_units(rename_map); // Extend subcircuit hole with space for condition bits bit_vector_t cond_bits(width); EdgeVec cond_sources; for (unsigned i = 0; i < width; ++i) { cond_bits[i] = Bit(i); Edge read_in = get_nth_in_edge(to_replace, i); Edge source_write = get_nth_out_edge(source(read_in), get_source_port(read_in)); cond_sources.push_back(source_write); } sub.c_in_hole.insert( sub.c_in_hole.begin(), cond_sources.begin(), cond_sources.end()); sub.c_out_hole.insert( sub.c_out_hole.begin(), cond_sources.begin(), cond_sources.end()); to_insert = to_insert.conditional_circuit(cond_bits, cond.get_value()); substitute(to_insert, sub, vertex_deletion, opgroup_transfer); } // given the edges to be broken and new // circuit, implants circuit into old circuit void Circuit::cut_insert( const Circuit& incirc, const EdgeVec& q_preds, const EdgeVec& c_preds, const EdgeVec& b_future) { Subcircuit sub = {q_preds, q_preds, c_preds, c_preds, b_future}; substitute(incirc, sub, VertexDeletion::No); } void Circuit::replace_SWAPs() { VertexList bin; BGL_FORALL_VERTICES(v, dag, DAG) { if (get_Op_ptr_from_Vertex(v)->get_type() == OpType::SWAP) { Vertex swap = v; EdgeVec outs = get_all_out_edges(v); Edge out1 = outs[0]; dag[out1].ports.first = 1; Edge out2 = outs[1]; dag[out2].ports.first = 0; remove_vertex(swap, GraphRewiring::Yes, VertexDeletion::No); bin.push_back(swap); } } remove_vertices(bin, GraphRewiring::No, VertexDeletion::Yes); } void Circuit::replace_implicit_wire_swap( const Qubit first, const Qubit second) { add_op<UnitID>(OpType::CX, {first, second}); add_op<UnitID>(OpType::CX, {second, first}); Vertex cxvertex = add_op<UnitID>(OpType::CX, {first, second}); EdgeVec outs = get_all_out_edges(cxvertex); Edge out1 = outs[0]; dag[out1].ports.first = 1; Edge out2 = outs[1]; dag[out2].ports.first = 0; } // helper functions for the dagger and transpose void Circuit::_handle_boundaries(Circuit& circ, vertex_map_t& vmap) const { // Handle boundaries for (const BoundaryElement& el : this->boundary.get<TagID>()) { Vertex new_in; Vertex new_out; if (el.id_.type() == UnitType::Bit) { tket_log()->warn( "The circuit contains classical data for which the dagger/transpose " "might not be defined."); new_in = circ.add_vertex(OpType::ClInput); new_out = circ.add_vertex(OpType::ClOutput); } else { new_in = circ.add_vertex(OpType::Input); new_out = circ.add_vertex(OpType::Output); } Vertex old_in = el.in_; Vertex old_out = el.out_; vmap[old_in] = new_out; vmap[old_out] = new_in; circ.boundary.insert({el.id_, new_in, new_out}); } } void Circuit::_handle_interior( Circuit& circ, vertex_map_t& vmap, V_iterator& vi, V_iterator& vend, ReverseType reverse_op) const { // Handle interior for (std::tie(vi, vend) = boost::vertices(this->dag); vi != vend; vi++) { const Op_ptr op = get_Op_ptr_from_Vertex(*vi); OpDesc desc = op->get_desc(); if (is_boundary_q_type(desc.type())) { continue; } else if ((desc.is_gate() || desc.is_box()) && !desc.is_oneway()) { Op_ptr op_type_ptr; switch (reverse_op) { case ReverseType::dagger: { op_type_ptr = op->dagger(); break; } case ReverseType::transpose: { op_type_ptr = op->transpose(); break; } default: { throw std::logic_error( "Error in the definition of the dagger or transpose."); } } Vertex v = circ.add_vertex(op_type_ptr); vmap[*vi] = v; } else { throw CircuitInvalidity( "Cannot dagger or transpose op: " + op->get_name()); } } } void Circuit::_handle_edges( Circuit& circ, vertex_map_t& vmap, E_iterator& ei, E_iterator& eend) const { for (std::tie(ei, eend) = boost::edges(this->dag); ei != eend; ei++) { Vertex s = source(*ei); port_t sp = get_source_port(*ei); Vertex t = target(*ei); port_t tp = get_target_port(*ei); circ.add_edge({vmap[t], tp}, {vmap[s], sp}, get_edgetype(*ei)); } } // returns Hermitian conjugate of circuit, ie its inverse Circuit Circuit::dagger() const { Circuit c; vertex_map_t vmap; _handle_boundaries(c, vmap); V_iterator vi, vend; ReverseType dagger = ReverseType::dagger; _handle_interior(c, vmap, vi, vend, dagger); E_iterator ei, eend; _handle_edges(c, vmap, ei, eend); c.add_phase(-get_phase()); return c; } // returns transpose of circuit Circuit Circuit::transpose() const { Circuit c; vertex_map_t vmap; _handle_boundaries(c, vmap); V_iterator vi, vend; ReverseType transpose = ReverseType::transpose; _handle_interior(c, vmap, vi, vend, transpose); E_iterator ei, eend; _handle_edges(c, vmap, ei, eend); c.add_phase(get_phase()); return c; } bool Circuit::substitute_all(const Circuit& to_insert, const Op_ptr op) { if (!to_insert.is_simple()) throw SimpleOnly(); if (op->n_qubits() != to_insert.n_qubits()) throw CircuitInvalidity( "Cannot substitute all on mismatching arity between Vertex " "and inserted Circuit"); VertexVec to_replace; VertexVec conditional_to_replace; BGL_FORALL_VERTICES(v, dag, DAG) { Op_ptr v_op = get_Op_ptr_from_Vertex(v); if (*v_op == *op) to_replace.push_back(v); else if (v_op->get_type() == OpType::Conditional) { const Conditional& cond = static_cast<const Conditional&>(*v_op); if (*cond.get_op() == *op) conditional_to_replace.push_back(v); } } for (const Vertex& v : to_replace) { substitute(to_insert, v, VertexDeletion::Yes); } for (const Vertex& v : conditional_to_replace) { substitute_conditional(to_insert, v, VertexDeletion::Yes); } return !(to_replace.empty() && conditional_to_replace.empty()); } bool Circuit::substitute_named( const Circuit& to_insert, const std::string opname) { if (!to_insert.is_simple()) throw SimpleOnly(); // Check that no op group names are in common for (const auto& opgroupsig : to_insert.opgroupsigs) { if (opgroupsigs.find(opgroupsig.first) != opgroupsigs.end()) { throw CircuitInvalidity("Name collision in replacement circuit"); } } // Do nothing if opname not present if (opgroupsigs.find(opname) == opgroupsigs.end()) { return false; } // Check signatures match op_signature_t sig = opgroupsigs[opname]; unsigned sig_n_q = std::count(sig.begin(), sig.end(), EdgeType::Quantum); unsigned sig_n_c = std::count(sig.begin(), sig.end(), EdgeType::Classical); unsigned sig_n_b = std::count(sig.begin(), sig.end(), EdgeType::Boolean); if (to_insert.n_qubits() != sig_n_q || to_insert.n_bits() != sig_n_c || sig_n_b != 0) { throw CircuitInvalidity("Signature mismatch"); } VertexVec to_replace; BGL_FORALL_VERTICES(v, dag, DAG) { std::optional<std::string> v_opgroup = get_opgroup_from_Vertex(v); if (v_opgroup && v_opgroup.value() == opname) { to_replace.push_back(v); } } for (const Vertex& v : to_replace) { substitute(to_insert, v, VertexDeletion::Yes, OpGroupTransfer::Merge); } return !to_replace.empty(); } bool Circuit::substitute_named(Op_ptr to_insert, const std::string opname) { // Do nothing if opname not present if (opgroupsigs.find(opname) == opgroupsigs.end()) { return false; } // Check signatures match op_signature_t sig = opgroupsigs[opname]; if (to_insert->get_signature() != sig) { throw CircuitInvalidity("Signature mismatch"); } VertexVec to_replace; BGL_FORALL_VERTICES(v, dag, DAG) { std::optional<std::string> v_opgroup = get_opgroup_from_Vertex(v); if (v_opgroup && v_opgroup.value() == opname) { to_replace.push_back(v); } } unsigned sig_n_q = std::count(sig.begin(), sig.end(), EdgeType::Quantum); unsigned sig_n_c = std::count(sig.begin(), sig.end(), EdgeType::Classical); Circuit c(sig_n_q, sig_n_c); unit_vector_t args(sig_n_q + sig_n_c); for (unsigned i = 0; i < sig_n_q; i++) args[i] = Qubit(i); for (unsigned i = 0; i < sig_n_c; i++) args[sig_n_q + i] = Bit(i); c.add_op(to_insert, args, opname); for (const Vertex& v : to_replace) { substitute(c, v, VertexDeletion::Yes, OpGroupTransfer::Merge); } return !to_replace.empty(); } Circuit Circuit::conditional_circuit( const bit_vector_t& bits, unsigned value) const { if (has_implicit_wireswaps()) { throw CircuitInvalidity("Cannot add conditions to an implicit wireswap"); } Circuit cond_circ(all_qubits(), all_bits()); for (const Bit& b : bits) { if (contains_unit(b)) { Vertex in = get_in(b); Vertex out = get_out(b); if (get_successors_of_type(in, EdgeType::Classical).front() != out) { throw CircuitInvalidity( "Cannot add condition. Circuit has non-trivial " "actions on bit " + b.repr()); } } else { cond_circ.add_bit(b); } } unsigned width = bits.size(); for (const Command& com : *this) { const Op_ptr op = com.get_op_ptr(); Op_ptr cond_op = std::make_shared<Conditional>(op, width, value); unit_vector_t args = com.get_args(); args.insert(args.begin(), bits.begin(), bits.end()); cond_circ.add_op(cond_op, args); } cond_circ.add_phase(get_phase()); return cond_circ; } bool Circuit::substitute_box_vertex( Vertex& vert, VertexDeletion vertex_deletion) { Op_ptr op = get_Op_ptr_from_Vertex(vert); bool conditional = op->get_type() == OpType::Conditional; if (conditional) { const Conditional& cond = static_cast<const Conditional&>(*op); op = cond.get_op(); } if (!op->get_desc().is_box()) return false; const Box& b = static_cast<const Box&>(*op); Circuit replacement = *b.to_circuit(); if (conditional) { substitute_conditional( replacement, vert, vertex_deletion, OpGroupTransfer::Merge); } else { substitute(replacement, vert, vertex_deletion, OpGroupTransfer::Merge); } return true; } bool Circuit::decompose_boxes() { bool success = false; VertexList bin; BGL_FORALL_VERTICES(v, dag, DAG) { if (substitute_box_vertex(v, VertexDeletion::No)) { bin.push_back(v); success = true; } } remove_vertices(bin, GraphRewiring::No, VertexDeletion::Yes); return success; } void Circuit::decompose_boxes_recursively() { while (decompose_boxes()) { } } std::map<Bit, bool> Circuit::classical_eval( const std::map<Bit, bool>& values) const { std::map<Bit, bool> v(values); for (CommandIterator it = begin(); it != end(); ++it) { Op_ptr op = it->get_op_ptr(); OpType optype = op->get_type(); if (!is_classical_type(optype)) { throw CircuitInvalidity("Non-classical operation"); } std::shared_ptr<const ClassicalEvalOp> cop = std::dynamic_pointer_cast<const ClassicalEvalOp>(op); unit_vector_t args = it->get_args(); unsigned n_args = args.size(); switch (optype) { case OpType::ClassicalTransform: { std::vector<bool> input(n_args); for (unsigned i = 0; i < n_args; i++) { input[i] = v[Bit(args[i])]; } std::vector<bool> output = cop->eval(input); TKET_ASSERT(output.size() == n_args); for (unsigned i = 0; i < n_args; i++) { v[Bit(args[i])] = output[i]; } break; } case OpType::SetBits: { std::vector<bool> output = cop->eval({}); TKET_ASSERT(output.size() == n_args); for (unsigned i = 0; i < n_args; i++) { v[Bit(args[i])] = output[i]; } break; } default: throw CircuitInvalidity("Unexpected operation in circuit"); } } return v; } } // namespace tket
34.453652
80
0.65244
CQCL
17fd471e10483d78274657e2999449917ac836c3
4,653
cpp
C++
patterns/mytreeFragmentLinux.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
patterns/mytreeFragmentLinux.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
patterns/mytreeFragmentLinux.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////// // MYTREE Linuxvariante #include <sys/types.h> #include <dirent.h> #include <string> #include <list> #include <iostream> #include <algorithm> using namespace std; //////////////////////////////////////////// class Visitor { public: Visitor() {}; ~Visitor() {}; virtual void visit(class Verzeichnis& v) = 0; virtual void visit(class Datei& d) = 0; }; // Kompositstruktur class Datei // Komponente { public: Datei( const string &n ) : name( n ) {} virtual ~Datei(); const string & GibName() const { return name; } virtual void accept(Visitor& visitor) { } protected: string name; }; class Verzeichnis : public Datei // Komposite { public: Verzeichnis( const string &n ); ~Verzeichnis(); typedef std::list<Datei *> Dateiliste; Dateiliste liste; void accept(Visitor& visitor) override; }; /////////////////////// class RegulaereDatei : public Datei // Leaf { public: RegulaereDatei( const string &n ) : Datei( n ) {} }; class GeraeteDatei : public Datei // Leaf { public: GeraeteDatei( const string &n ) : Datei( n ) {} }; class KommunikationsDatei : public Datei // Leaf { public: KommunikationsDatei( const string &n ) : Datei( n ) {} }; class SonstigeDatei : public Datei // Leaf { public: SonstigeDatei( const string &n ) : Datei( n ) {} }; //////////////////////////////////////////////////////////////////////////////// Datei::~Datei() {} Verzeichnis::Verzeichnis( const string &n ) : Datei( n ) { struct dirent *pde; DIR *dirp = opendir( n.c_str() ); if( dirp != NULL ) { while( (pde = readdir( dirp )) != NULL ) { std::string dname( pde->d_name ); if( dname != "." && dname != ".." ) { Datei *pd = 0; switch( pde->d_type ) { case DT_REG: pd = new RegulaereDatei( dname ); break; case DT_DIR: { std::string vn( n ); if( vn[vn.size() - 1] != '/' ) vn += "/"; vn += dname; pd = new Verzeichnis( vn ); } break; case DT_FIFO: case DT_SOCK: pd = new KommunikationsDatei( dname ); break; case DT_CHR: case DT_BLK: pd = new GeraeteDatei( dname ); break; case DT_UNKNOWN: default: pd = new SonstigeDatei( dname ); break; } if( pd ) liste.push_back( pd ); } } closedir(dirp); } } Verzeichnis::~Verzeichnis() { for( Dateiliste::iterator it = liste.begin(); it != liste.end(); ++it ) delete *it; } void Verzeichnis::accept(Visitor& visitor) { visitor.visit(*this); for (auto& d : liste) d->accept(visitor); } /////////////////////////////////////////////////////////////////////////////// template<typename T> bool IsInstanceOf(const Datei* obj) noexcept { return dynamic_cast< const T* >( obj ) != nullptr; } ////////////////////////// class VisitorPrintFiles : public Visitor { public: VisitorPrintFiles() {}; ~VisitorPrintFiles() {}; VisitorPrintFiles(VisitorPrintFiles&& rv) = delete; void visit(Verzeichnis& v) override { std::cout << "verz:" << v.GibName() << std::endl; } void visit(Datei& d) override { std::cout << "datei:" << d.GibName() << std::endl; } }; class VisitorCountFiles : public Visitor { public: VisitorCountFiles() {}; ~VisitorCountFiles() {}; VisitorCountFiles(VisitorCountFiles&& rv) = delete; void visit(Verzeichnis& v) override { std::cout << v.GibName() << ":" << v.liste.size() << std::endl; } void visit(Datei& d) override { std::cout << "visit.datei" << std::endl; } }; class VisitorRecursiveCountVerzeichnisse : public Visitor { public: VisitorRecursiveCountVerzeichnisse() {}; ~VisitorRecursiveCountVerzeichnisse() {}; void visit(Verzeichnis& v) override { //m_countFiles += std::count_if(v.liste.begin(), v.liste.end(), [](Datei* d) { return IsInstanceOf<Verzeichnis>(d); }); m_countFiles++; } void visit(Datei& d) override { } int getCount() { return m_countFiles; } private: int m_countFiles = 0; }; /////////////////////////////// int main( int argc, char *argv[] ) { using namespace std; string verz( argc > 1 ? argv[1] : "." ); VisitorPrintFiles v; VisitorCountFiles vcf; VisitorRecursiveCountVerzeichnisse vrcf; Verzeichnis root( verz ); //root.accept(v); //root.accept(vcf); root.accept(vrcf); std::cout << "count of all files=" << vrcf.getCount() << std::endl; return 0; }
19.227273
122
0.54395
bruennijs
17fe91610e2bbb02caa8236a9718cbece2f06806
3,164
hpp
C++
src/Xi-Core/include/Xi/Blob.hpp
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
src/Xi-Core/include/Xi/Blob.hpp
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
src/Xi-Core/include/Xi/Blob.hpp
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
/* ============================================================================================== * * * * Galaxia Blockchain * * * * ---------------------------------------------------------------------------------------------- * * This file is part of the Xi framework. * * ---------------------------------------------------------------------------------------------- * * * * Copyright 2018-2019 Xi Project Developers <support.xiproject.io> * * * * This program is free software: you can redistribute it and/or modify it under the terms of the * * GNU General Public License as published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with this program. * * If not, see <https://www.gnu.org/licenses/>. * * * * ============================================================================================== */ #pragma once #include <cstring> #include "Xi/Span.hpp" #include "Xi/Byte.hh" namespace Xi { template <typename _T, size_t _Bytes> struct enable_blob_from_this : protected ByteArray<_Bytes> { using value_type = _T; using array_type = ByteArray<_Bytes>; static inline constexpr size_t bytes() { return _Bytes; } enable_blob_from_this() { this->fill(0); } explicit enable_blob_from_this(array_type raw) : array_type(std::move(raw)) {} using array_type::data; using array_type::fill; using array_type::size; using array_type::operator[]; ByteSpan span() { return ByteSpan{this->data(), this->size()}; } ConstByteSpan span() const { return ConstByteSpan{this->data(), this->size()}; } inline bool operator==(const value_type &rhs) { return ::std::memcmp(this->data(), rhs.data(), bytes()) == 0; } inline bool operator!=(const value_type &rhs) { return ::std::memcmp(this->data(), rhs.data(), bytes()) != 0; } }; } // namespace Xi
56.5
113
0.395702
ElSamaritan
aa05d2501398c889ec0090075642b4fa59d4b7a7
2,082
cpp
C++
Game/src/game/BulletManager.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
3
2019-10-04T19:44:44.000Z
2021-07-27T15:59:39.000Z
Game/src/game/BulletManager.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
1
2019-07-20T05:36:31.000Z
2019-07-20T22:22:49.000Z
Game/src/game/BulletManager.cpp
aminere/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
null
null
null
/* Amine Rehioui Created: November 18th 2011 */ #include "ShootTest.h" #include "BulletManager.h" #include "GameManager.h" namespace shoot { DEFINE_OBJECT(BulletManager); //! Constructor BulletManager::BulletManager() // properties : m_BulletPoolSize(4096) { } //! serializes the entity to/from a PropertyStream void BulletManager::Serialize(PropertyStream& stream) { super::Serialize(stream); if(stream.Serialize(PT_UInt, "BulletPoolSize", &m_BulletPoolSize)) { if(IsInitialized()) { m_Pool = snew MemoryPool(m_BulletPoolSize); m_Bullets.clear(); } } } //! called during the initialization of the entity void BulletManager::Init() { m_Pool = snew MemoryPool(m_BulletPoolSize); GraphicComponent* pGraphic = GetComponent<GraphicComponent>(); if(!pGraphic) { pGraphic = snew GraphicComponent(); pGraphic->SetRenderingPass(GraphicComponent::RP_Transparent3D); AddComponent(pGraphic, true); } super::Init(); } //! called during the update of the entity void BulletManager::Update() { VertexBuffer* pVB = GetComponent<GraphicComponent>()->GetVertexBuffer(); pVB->SetNumVertices(0); if(m_Bullets.size()) { u32 bulletIndex = 0; for(std::list<Bullet*>::iterator it = m_Bullets.begin(); it != m_Bullets.end();) { if((*it)->fLife > 0.0f && !GameManager::Instance()->IsOutOfPlayfield((*it)->vPosition)) { (*it)->vPosition += (*it)->vDirection*(*it)->fSpeed*g_fDeltaTime; SetupRendering((*it), bulletIndex++, pVB); (*it)->fLife -= g_fDeltaTime; ++it; } else { m_Pool->Free((*it)); it = m_Bullets.erase(it); } } pVB->SetDirty(true); } } //! Adds a bullet void BulletManager::AddBullet(const Bullet::BulletParams& params) { if(Bullet* pBullet = m_Pool->Alloc<Bullet>()) { pBullet->Init(params); m_Bullets.push_back(pBullet); } } //! clears the bullets void BulletManager::Clear() { for(std::list<Bullet*>::iterator it = m_Bullets.begin(); it != m_Bullets.end(); ++it) { (*it)->fLife = 0.0f; } } }
19.457944
91
0.653218
franticsoftware
aa0774141d71bc5d073660e069b33fb38c5f08f8
687
hpp
C++
src/util/handle.hpp
marvinwilliams/rantanplan
aadb4109a443a75881f610f45b710cd0532079fe
[ "MIT" ]
3
2021-09-07T08:45:30.000Z
2021-09-15T08:16:41.000Z
src/util/handle.hpp
marvinwilliams/rantanplan
aadb4109a443a75881f610f45b710cd0532079fe
[ "MIT" ]
null
null
null
src/util/handle.hpp
marvinwilliams/rantanplan
aadb4109a443a75881f610f45b710cd0532079fe
[ "MIT" ]
null
null
null
#ifndef HANDLE_HPP #define HANDLE_HPP namespace util { /* This class is intended to only be instantiatable by the base and represents a * pointer */ template <typename T, typename Base> class Handle { public: friend Base; Handle() = default; const T *get() { return p_; } const Base *get_base() { return base_; } const T &operator*() { return *p_; } const T *operator->() { return p_; } bool operator==(const Handle<T, Base> &other) const { return p_ == other.p_ && base_ == other.base_; } private: Handle(T *p, const Base *base) : p_{p}, base_{base} {} T *p_ = nullptr; const Base *base_ = nullptr; }; } #endif /* end of include guard: HANDLE_HPP */
20.818182
80
0.647744
marvinwilliams
aa0bd6d0f47af4c95f7f42945fb34176141d5494
4,413
hpp
C++
include/pcp/traits/point_traits.hpp
Q-Minh/octree
0c3fd5a791d660b37461daf968a68ffb1c80b965
[ "BSL-1.0" ]
2
2021-03-10T09:57:45.000Z
2021-04-13T21:19:57.000Z
include/pcp/traits/point_traits.hpp
Q-Minh/octree
0c3fd5a791d660b37461daf968a68ffb1c80b965
[ "BSL-1.0" ]
22
2020-12-07T20:09:39.000Z
2021-04-12T20:42:59.000Z
include/pcp/traits/point_traits.hpp
Q-Minh/octree
0c3fd5a791d660b37461daf968a68ffb1c80b965
[ "BSL-1.0" ]
null
null
null
#ifndef PCP_TRAITS_POINT_TRAITS_HPP #define PCP_TRAITS_POINT_TRAITS_HPP /** * @file * @ingroup traits */ #include <type_traits> namespace pcp { namespace traits { /** * @ingroup traits-geometry * @brief * PointView requirements: * - coordinate_type type member * - copy constructible * - copy assignable * - move constructible * - move assignable * - x,y,z getters * - x,y,z setters * - equality/inequality operator * @tparam PointView Type to inspect */ template <class PointView, class = void> struct is_point_view : std::false_type { }; template <class PointView> struct is_point_view< PointView, std::void_t< typename PointView::coordinate_type, decltype(std::declval<PointView&>().x()), decltype(std::declval<PointView&>().y()), decltype(std::declval<PointView&>().z()), decltype(std::declval<PointView&>().x(std::declval<typename PointView::coordinate_type>())), decltype(std::declval<PointView&>().y(std::declval<typename PointView::coordinate_type>())), decltype(std::declval<PointView&>().z( std::declval<typename PointView::coordinate_type>()))>> : std::true_type { static_assert(std::is_copy_constructible_v<PointView>, "PointView must be copy constructible"); static_assert(std::is_copy_assignable_v<PointView>, "PointView must be copy assignable"); }; /** * @ingroup traits-geometry * @brief * Compile-time check for PointView concept * @tparam PointView */ template <class PointView> static constexpr bool is_point_view_v = is_point_view<PointView>::value; /** * @ingroup traits-geometry * @brief * Point requirements (refines PointView): * - default constructible * - parameter constructor from x,y,z * - *,/,+,- operators */ template <class Point, class = void> struct is_point : std::false_type { }; template <class Point> struct is_point< Point, std::void_t< decltype(std::declval<typename Point::coordinate_type>() * std::declval<Point&>()), decltype(std::declval<Point&>() / std::declval<typename Point::coordinate_type>()), decltype(std::declval<Point&>() + std::declval<Point&>()), decltype(std::declval<Point&>() - std::declval<Point&>()), decltype(-std::declval<Point&>())>> : is_point_view<Point> { static_assert(std::is_default_constructible_v<Point>, "Point must be default constructible"); static_assert( std::is_constructible_v< Point, typename Point::coordinate_type, typename Point::coordinate_type, typename Point::coordinate_type>, "Point must be constructible from (x,y,z) coordinates"); }; /** * @ingroup traits-geometry * @brief * Compile-time check for Point concept * @tparam Point */ template <class Point> static constexpr bool is_point_v = is_point<Point>::value; template <class PointView1, class PointView2, class = void> struct is_point_view_equality_comparable_to : std::false_type { }; template <class PointView1, class PointView2> struct is_point_view_equality_comparable_to< PointView1, PointView2, std::void_t< decltype(std::declval<PointView1&>() == std::declval<PointView2&>()), decltype(std::declval<PointView1&>() != std::declval<PointView2&>())>> : std::true_type { }; /** * @ingroup traits * @brief * Compile-time check to verify if PointView1 is equality/inequality comparable to PointView2 * @tparam PointView1 * @tparam PointView2 */ template <class PointView1, class PointView2> static constexpr bool is_point_view_equality_comparable_to_v = is_point_view_equality_comparable_to<PointView1, PointView2>::value; template <class PointView1, class PointView2, class = void> struct is_point_view_assignable_from : std::false_type { }; template <class PointView1, class PointView2> struct is_point_view_assignable_from< PointView1, PointView2, std::void_t<decltype(std::declval<PointView1&>() = std::declval<PointView2&>())>> : std::true_type { }; /** * @ingroup traits * @brief * Compile-time check to verify is PointView1 is assignable from PointView2 * @tparam PointView1 * @tparam PointView2 */ template <class PointView1, class PointView2> static constexpr bool is_point_view_assignable_from_v = is_point_view_assignable_from<PointView1, PointView2>::value; } // namespace traits } // namespace pcp #endif // PCP_TRAITS_POINT_TRAITS_HPP
28.470968
100
0.705189
Q-Minh
aa0c7e6891cfc4be9ee61d0bf1b89cdb595959cd
5,952
cpp
C++
QuadratureAnalyserAnalyzer.cpp
Marcus10110/Quadrature-Saleae-Analyser
384ae08811864ac80fd207e28e6de41fc52b8386
[ "Apache-2.0" ]
9
2015-03-23T20:05:22.000Z
2020-12-06T04:50:53.000Z
QuadratureAnalyserAnalyzer.cpp
Marcus10110/Quadrature-Saleae-Analyser
384ae08811864ac80fd207e28e6de41fc52b8386
[ "Apache-2.0" ]
1
2018-12-06T08:57:13.000Z
2018-12-06T19:10:45.000Z
QuadratureAnalyserAnalyzer.cpp
Marcus10110/Quadrature-Saleae-Analyser
384ae08811864ac80fd207e28e6de41fc52b8386
[ "Apache-2.0" ]
2
2018-12-05T22:17:40.000Z
2019-11-03T12:11:33.000Z
/* Copyright 2011 Dirk-Willem van Gulik, All Rights Reserved. * dirkx(at)webweaving(dot)org * * 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. * * $Id: QuadratureAnalyserAnalyzer.cpp 1037 2011-09-12 09:49:58Z dirkx $ */ #include "QuadratureAnalyserAnalyzer.h" #include "QuadratureAnalyserAnalyzerSettings.h" #include <AnalyzerChannelData.h> static change_t qe_decode(unsigned char olda, unsigned char oldb, unsigned char newa, unsigned char newb) { change_t oldnew[16] = { // AB -> AB which is (old state) --> (new state) STANDSTILL , // 00 -> 00 CLOCKWISE , // 00 -> 01 -1 COUNTERCW , // 00 -> 10 +1 GLITCH , // 00 -> 11 COUNTERCW , // 01 -> 00 +1 STANDSTILL , // 01 -> 01 GLITCH , // 01 -> 10 CLOCKWISE , // 01 -> 11 -1 CLOCKWISE , // 10 -> 00 -1 GLITCH , // 10 -> 01 STANDSTILL , // 10 -> 10 COUNTERCW , // 10 -> 11 +1 GLITCH , // 11 -> 00 COUNTERCW , // 11 -> 01 +1 CLOCKWISE , // 11 -> 10 -1 STANDSTILL , // 11 -> 11 }; unsigned char state = 0; state += olda ? 1 : 0; state += oldb ? 2 : 0; state += newa ? 4 : 0; state += newb ? 8 : 0; return oldnew[state]; } QuadratureAnalyserAnalyzer::QuadratureAnalyserAnalyzer() : Analyzer(), mSettings( new QuadratureAnalyserAnalyzerSettings() ) { SetAnalyzerSettings( mSettings.get() ); } QuadratureAnalyserAnalyzer::~QuadratureAnalyserAnalyzer() { KillThread(); } void QuadratureAnalyserAnalyzer::WorkerThread() { mResults.reset( new QuadratureAnalyserAnalyzerResults( this, mSettings.get() ) ); SetAnalyzerResults( mResults.get() ); if (mSettings->mInputChannelA != UNDEFINED_CHANNEL) mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannelA ); if (mSettings->mInputChannelB != UNDEFINED_CHANNEL) mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannelB ); AnalyzerChannelData * mChannelA = GetAnalyzerChannelData( mSettings->mInputChannelA ); AnalyzerChannelData * mChannelB = GetAnalyzerChannelData( mSettings->mInputChannelB ); U8 mLastA = mChannelA->GetBitState() == BIT_HIGH ? 1 : 0; U8 mLastB = mChannelB->GetBitState() == BIT_HIGH ? 1 : 0; change_t lastDir = GLITCH; U64 lastStart = mChannelA->GetSampleNumber(); U64 lastEnd = mChannelA->GetSampleNumber(); U64 curEnd = mChannelA->GetSampleNumber(); U32 glitchCount = 0; U32 tickCount = 0; int64_t posCount = 0; for( ; ; ) { AnalyzerResults::MarkerType m; int result = 0; U64 a,b,c; #if 0 mChannelA->Advance(1); mChannelB->Advance(1); U8 mNewA = mChannelA->GetBitState() == BIT_HIGH ? 1 : 0; U8 mNewB = mChannelB->GetBitState() == BIT_HIGH ? 1 : 0; #else a = mChannelA->GetSampleNumber(); b = mChannelB->GetSampleNumber(); if (a<=b) { mChannelA->AdvanceToNextEdge(); }; if (b<=a) { mChannelB->AdvanceToNextEdge(); }; a = mChannelA->GetSampleNumber(); b = mChannelB->GetSampleNumber(); U8 mNewA = mLastA; U8 mNewB = mLastB; if (a<=b) { mNewA = mChannelA->GetBitState() == BIT_HIGH ? 1 : 0; c = a; }; if (b<=a) { mNewB = mChannelB->GetBitState() == BIT_HIGH ? 1 : 0; c = b; }; #endif change_t dir = qe_decode(mLastA, mLastB, mNewA, mNewB); mLastA = mNewA; mLastB = mNewB; if (dir == STANDSTILL) continue; switch(dir) { case CLOCKWISE: case COUNTERCW: m = (dir == CLOCKWISE) ? AnalyzerResults::DownArrow : AnalyzerResults::UpArrow; mResults->AddMarker( c, m, mSettings->mInputChannelA ); mResults->AddMarker( c, m, mSettings->mInputChannelB ); result ++; tickCount++; posCount += (m == CLOCKWISE) ? -1 : 1; lastEnd = curEnd; curEnd = c; break; default: glitchCount++; break; }; if (dir != lastDir) { // skip any initial glitches. We're not sure what they are anyway. // if (glitchCount != 0 || lastDir != GLITCH) { Frame frame; frame.mData1 = (posCount << 32) | lastDir; frame.mData2 = ((U64)tickCount << 32) | (glitchCount << 0); frame.mFlags = 0; frame.mStartingSampleInclusive = lastStart; frame.mEndingSampleInclusive = lastEnd; mResults->AddFrame( frame ); } lastStart = curEnd; lastDir = dir; result ++; tickCount = 0; glitchCount = 0; }; if (result) { mResults->CommitResults(); ReportProgress(c); }; } } bool QuadratureAnalyserAnalyzer::NeedsRerun() { return false; } U32 QuadratureAnalyserAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels ) { mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() ); return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels ); } U32 QuadratureAnalyserAnalyzer::GetMinimumSampleRateHz() { return SCANRATE; } const char* QuadratureAnalyserAnalyzer::GetAnalyzerName() const { return "Quadrature Decoder"; } const char* GetAnalyzerName() { // return MYVERSION; return "Quadrature Decoder"; } Analyzer* CreateAnalyzer() { return new QuadratureAnalyserAnalyzer(); } void DestroyAnalyzer( Analyzer* analyzer ) { delete analyzer; }
28.075472
158
0.641633
Marcus10110
aa0ed280387e135370d559b9ead9bb90c26b7b6a
678
cc
C++
brightray/common/application_info_win.cc
SeanMercy/Pro1
43aa555d647d181265bde59570e2fdd7704cf83f
[ "MIT" ]
7
2018-02-05T11:43:49.000Z
2022-02-09T20:28:20.000Z
brightray/common/application_info_win.cc
SeanMercy/Pro1
43aa555d647d181265bde59570e2fdd7704cf83f
[ "MIT" ]
null
null
null
brightray/common/application_info_win.cc
SeanMercy/Pro1
43aa555d647d181265bde59570e2fdd7704cf83f
[ "MIT" ]
2
2017-08-25T18:58:44.000Z
2019-10-22T14:59:04.000Z
#include "brightray/common/application_info.h" #include <memory> #include "base/file_version_info.h" #include "base/strings/utf_string_conversions.h" namespace brightray { std::string GetApplicationName() { auto module = GetModuleHandle(nullptr); std::unique_ptr<FileVersionInfo> info( FileVersionInfo::CreateFileVersionInfoForModule(module)); return base::UTF16ToUTF8(info->product_name()); } std::string GetApplicationVersion() { auto module = GetModuleHandle(nullptr); std::unique_ptr<FileVersionInfo> info( FileVersionInfo::CreateFileVersionInfoForModule(module)); return base::UTF16ToUTF8(info->product_version()); } } // namespace brightray
27.12
63
0.769912
SeanMercy
aa10fa15812e90565409cc49a77918ccadec35b7
11,309
cc
C++
Controllers/Flatground/utils/funcs/kin/mex/LeftToeJoint_mex.cc
EngineeringIV/CASSIE_MPC
fcbf5559bfd11dbdbb241565585fa22ccdaa5499
[ "BSD-3-Clause" ]
61
2019-02-21T09:32:55.000Z
2022-03-29T02:30:18.000Z
Controllers/Flatground/utils/funcs/kin/mex/LeftToeJoint_mex.cc
EngineeringIV/CASSIE_MPC
fcbf5559bfd11dbdbb241565585fa22ccdaa5499
[ "BSD-3-Clause" ]
3
2019-02-22T08:01:40.000Z
2022-01-20T09:16:40.000Z
Controllers/Flatground/utils/funcs/kin/mex/LeftToeJoint_mex.cc
EngineeringIV/CASSIE_MPC
fcbf5559bfd11dbdbb241565585fa22ccdaa5499
[ "BSD-3-Clause" ]
28
2019-02-04T19:47:35.000Z
2022-02-23T08:28:23.000Z
/* * Automatically Generated from Mathematica. * Mon 25 Jun 2018 14:53:24 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1) { double t2124; double t2089; double t2134; double t2101; double t2138; double t328; double t2109; double t2149; double t2160; double t2181; double t2185; double t2186; double t2213; double t2244; double t2249; double t2251; double t2258; double t2238; double t2240; double t2243; double t2324; double t2413; double t2416; double t2421; double t2426; double t2393; double t2395; double t2406; double t2435; double t2439; double t2442; double t2492; double t2496; double t2510; double t2528; double t2555; double t2557; double t2566; double t2605; double t2610; double t2613; double t2621; double t2625; double t2627; double t2635; double t2645; double t2647; double t2652; double t2674; double t2681; double t2689; double t2691; double t2705; double t2710; double t2721; double t2741; double t2750; double t2755; double t2820; double t2824; double t2828; double t2837; double t2839; double t2842; double t2846; double t2871; double t2872; double t2878; double t2903; double t2906; double t2919; double t1962; double t2015; double t2028; double t2050; double t2219; double t2223; double t2963; double t2967; double t2969; double t2982; double t2985; double t2990; double t2255; double t2262; double t2272; double t2338; double t2344; double t2345; double t2998; double t3000; double t3003; double t2424; double t2428; double t2432; double t2454; double t2465; double t2481; double t2514; double t2531; double t2545; double t3030; double t3031; double t3035; double t3049; double t3051; double t3056; double t2583; double t2594; double t2599; double t2631; double t2640; double t2642; double t3064; double t3069; double t3072; double t3080; double t3093; double t3102; double t2661; double t2664; double t2670; double t2717; double t2736; double t2737; double t3115; double t3116; double t3123; double t3137; double t3138; double t3142; double t2773; double t2779; double t2802; double t2845; double t2852; double t2866; double t3150; double t3151; double t3154; double t3158; double t3159; double t3160; double t2890; double t2892; double t2896; double t3169; double t3172; double t3176; double t3182; double t3186; double t3195; double t3239; double t3242; double t3248; double t3280; double t3284; double t3287; double t3296; double t3299; double t3303; double t3308; double t3310; double t3312; double t3316; double t3317; double t3325; double t3334; double t3335; double t3337; double t3341; double t3343; double t3344; double t3354; double t3355; double t3359; double t3365; double t3370; double t3371; double t3378; double t3379; double t3382; double t3386; double t3389; double t3392; t2124 = Cos(var1[3]); t2089 = Cos(var1[5]); t2134 = Sin(var1[4]); t2101 = Sin(var1[3]); t2138 = Sin(var1[5]); t328 = Cos(var1[6]); t2109 = -1.*t2089*t2101; t2149 = t2124*t2134*t2138; t2160 = t2109 + t2149; t2181 = t2124*t2089*t2134; t2185 = t2101*t2138; t2186 = t2181 + t2185; t2213 = Sin(var1[6]); t2244 = Cos(var1[7]); t2249 = -1.*t2244; t2251 = 1. + t2249; t2258 = Sin(var1[7]); t2238 = t328*t2160; t2240 = t2186*t2213; t2243 = t2238 + t2240; t2324 = Cos(var1[4]); t2413 = Cos(var1[8]); t2416 = -1.*t2413; t2421 = 1. + t2416; t2426 = Sin(var1[8]); t2393 = t2124*t2324*t2244; t2395 = t2243*t2258; t2406 = t2393 + t2395; t2435 = t328*t2186; t2439 = -1.*t2160*t2213; t2442 = t2435 + t2439; t2492 = Cos(var1[9]); t2496 = -1.*t2492; t2510 = 1. + t2496; t2528 = Sin(var1[9]); t2555 = t2413*t2406; t2557 = t2442*t2426; t2566 = t2555 + t2557; t2605 = t2413*t2442; t2610 = -1.*t2406*t2426; t2613 = t2605 + t2610; t2621 = Cos(var1[10]); t2625 = -1.*t2621; t2627 = 1. + t2625; t2635 = Sin(var1[10]); t2645 = -1.*t2528*t2566; t2647 = t2492*t2613; t2652 = t2645 + t2647; t2674 = t2492*t2566; t2681 = t2528*t2613; t2689 = t2674 + t2681; t2691 = Cos(var1[11]); t2705 = -1.*t2691; t2710 = 1. + t2705; t2721 = Sin(var1[11]); t2741 = t2635*t2652; t2750 = t2621*t2689; t2755 = t2741 + t2750; t2820 = t2621*t2652; t2824 = -1.*t2635*t2689; t2828 = t2820 + t2824; t2837 = Cos(var1[12]); t2839 = -1.*t2837; t2842 = 1. + t2839; t2846 = Sin(var1[12]); t2871 = -1.*t2721*t2755; t2872 = t2691*t2828; t2878 = t2871 + t2872; t2903 = t2691*t2755; t2906 = t2721*t2828; t2919 = t2903 + t2906; t1962 = -1.*t328; t2015 = 1. + t1962; t2028 = 0.135*t2015; t2050 = 0. + t2028; t2219 = -0.135*t2213; t2223 = 0. + t2219; t2963 = t2124*t2089; t2967 = t2101*t2134*t2138; t2969 = t2963 + t2967; t2982 = t2089*t2101*t2134; t2985 = -1.*t2124*t2138; t2990 = t2982 + t2985; t2255 = 0.135*t2251; t2262 = 0.049*t2258; t2272 = 0. + t2255 + t2262; t2338 = -0.049*t2251; t2344 = 0.135*t2258; t2345 = 0. + t2338 + t2344; t2998 = t328*t2969; t3000 = t2990*t2213; t3003 = t2998 + t3000; t2424 = -0.049*t2421; t2428 = -0.09*t2426; t2432 = 0. + t2424 + t2428; t2454 = -0.09*t2421; t2465 = 0.049*t2426; t2481 = 0. + t2454 + t2465; t2514 = -0.049*t2510; t2531 = -0.21*t2528; t2545 = 0. + t2514 + t2531; t3030 = t2324*t2244*t2101; t3031 = t3003*t2258; t3035 = t3030 + t3031; t3049 = t328*t2990; t3051 = -1.*t2969*t2213; t3056 = t3049 + t3051; t2583 = -0.21*t2510; t2594 = 0.049*t2528; t2599 = 0. + t2583 + t2594; t2631 = -0.2707*t2627; t2640 = 0.0016*t2635; t2642 = 0. + t2631 + t2640; t3064 = t2413*t3035; t3069 = t3056*t2426; t3072 = t3064 + t3069; t3080 = t2413*t3056; t3093 = -1.*t3035*t2426; t3102 = t3080 + t3093; t2661 = -0.0016*t2627; t2664 = -0.2707*t2635; t2670 = 0. + t2661 + t2664; t2717 = 0.0184*t2710; t2736 = -0.7055*t2721; t2737 = 0. + t2717 + t2736; t3115 = -1.*t2528*t3072; t3116 = t2492*t3102; t3123 = t3115 + t3116; t3137 = t2492*t3072; t3138 = t2528*t3102; t3142 = t3137 + t3138; t2773 = -0.7055*t2710; t2779 = -0.0184*t2721; t2802 = 0. + t2773 + t2779; t2845 = -1.1135*t2842; t2852 = 0.0216*t2846; t2866 = 0. + t2845 + t2852; t3150 = t2635*t3123; t3151 = t2621*t3142; t3154 = t3150 + t3151; t3158 = t2621*t3123; t3159 = -1.*t2635*t3142; t3160 = t3158 + t3159; t2890 = -0.0216*t2842; t2892 = -1.1135*t2846; t2896 = 0. + t2890 + t2892; t3169 = -1.*t2721*t3154; t3172 = t2691*t3160; t3176 = t3169 + t3172; t3182 = t2691*t3154; t3186 = t2721*t3160; t3195 = t3182 + t3186; t3239 = t2324*t328*t2138; t3242 = t2324*t2089*t2213; t3248 = t3239 + t3242; t3280 = -1.*t2244*t2134; t3284 = t3248*t2258; t3287 = t3280 + t3284; t3296 = t2324*t2089*t328; t3299 = -1.*t2324*t2138*t2213; t3303 = t3296 + t3299; t3308 = t2413*t3287; t3310 = t3303*t2426; t3312 = t3308 + t3310; t3316 = t2413*t3303; t3317 = -1.*t3287*t2426; t3325 = t3316 + t3317; t3334 = -1.*t2528*t3312; t3335 = t2492*t3325; t3337 = t3334 + t3335; t3341 = t2492*t3312; t3343 = t2528*t3325; t3344 = t3341 + t3343; t3354 = t2635*t3337; t3355 = t2621*t3344; t3359 = t3354 + t3355; t3365 = t2621*t3337; t3370 = -1.*t2635*t3344; t3371 = t3365 + t3370; t3378 = -1.*t2721*t3359; t3379 = t2691*t3371; t3382 = t3378 + t3379; t3386 = t2691*t3359; t3389 = t2721*t3371; t3392 = t3386 + t3389; p_output1[0]=0. + t2050*t2160 + t2186*t2223 + t2243*t2272 + 0.1305*(t2243*t2244 - 1.*t2124*t2258*t2324) + t2124*t2324*t2345 + t2406*t2432 + t2442*t2481 + t2545*t2566 + t2599*t2613 + t2642*t2652 + t2670*t2689 + t2737*t2755 + t2802*t2828 + t2866*t2878 + t2896*t2919 - 0.0216*(t2846*t2878 + t2837*t2919) - 1.1135*(t2837*t2878 - 1.*t2846*t2919) + var1[0]; p_output1[1]=0. + t2101*t2324*t2345 + t2050*t2969 + t2223*t2990 + t2272*t3003 + 0.1305*(-1.*t2101*t2258*t2324 + t2244*t3003) + t2432*t3035 + t2481*t3056 + t2545*t3072 + t2599*t3102 + t2642*t3123 + t2670*t3142 + t2737*t3154 + t2802*t3160 + t2866*t3176 + t2896*t3195 - 0.0216*(t2846*t3176 + t2837*t3195) - 1.1135*(t2837*t3176 - 1.*t2846*t3195) + var1[1]; p_output1[2]=0. + t2050*t2138*t2324 + t2089*t2223*t2324 - 1.*t2134*t2345 + t2272*t3248 + 0.1305*(t2134*t2258 + t2244*t3248) + t2432*t3287 + t2481*t3303 + t2545*t3312 + t2599*t3325 + t2642*t3337 + t2670*t3344 + t2737*t3359 + t2802*t3371 + t2866*t3382 + t2896*t3392 - 0.0216*(t2846*t3382 + t2837*t3392) - 1.1135*(t2837*t3382 - 1.*t2846*t3392) + var1[2]; } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 20 && ncols == 1) && !(mrows == 1 && ncols == 20))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 3, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1); } #else // MATLAB_MEX_FILE #include "LeftToeJoint_mex.hh" namespace SymExpression { void LeftToeJoint_mex_raw(double *p_output1, const double *var1) { // Call Subroutines output1(p_output1, var1); } } #endif // MATLAB_MEX_FILE
22.939148
354
0.646299
EngineeringIV
aa13e698baea8aaa85d1688784209c652df80ef9
1,517
cpp
C++
gwen/UnitTest/ComboBox.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/UnitTest/ComboBox.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/UnitTest/ComboBox.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
#include "Gwen/UnitTest/UnitTest.h" #include "Gwen/Controls/ComboBox.h" using namespace Gwen; class ComboBox : public GUnit { public: GWEN_CONTROL_INLINE(ComboBox, GUnit) { { Gwen::Controls::ComboBox* combo = new Gwen::Controls::ComboBox(this); combo->SetPos(50, 50); combo->SetWidth(200); combo->AddItem("Option One", "one"); combo->AddItem("Number Two", "two"); combo->AddItem("Door Three", "three"); combo->AddItem("Four Legs", "four"); combo->AddItem("Five Birds", "five"); combo->onSelection.Add(this, &ComboBox::OnComboSelect); } { // Empty.. Gwen::Controls::ComboBox* combo = new Gwen::Controls::ComboBox(this); combo->SetPos(50, 80); combo->SetWidth(200); } { // Empty.. Gwen::Controls::ComboBox* combo = new Gwen::Controls::ComboBox(this); combo->SetPos(50, 110); combo->SetWidth(200); for (int i = 0; i < 500; i++) { combo->AddItem("Lots Of Options"); } } } void OnComboSelect(Gwen::Controls::Base* pControl) { Gwen::Controls::ComboBox* combo = (Gwen::Controls::ComboBox*)pControl; UnitPrint(Utility::Format("Combo Changed: %s", combo->GetSelectedItem()->GetText().c_str())); } }; DEFINE_UNIT_TEST(ComboBox, "ComboBox");
28.622642
81
0.523401
Oipo
aa15ddb1f5fab1254d31980991e9c27d436ac9b5
3,822
cpp
C++
client/client_query.cpp
RubenAGSilva/deneva
538f18d296e926055e50cf819c6988a340105476
[ "Apache-2.0" ]
1
2021-12-15T12:31:18.000Z
2021-12-15T12:31:18.000Z
client/client_query.cpp
RubenAGSilva/deneva
538f18d296e926055e50cf819c6988a340105476
[ "Apache-2.0" ]
null
null
null
client/client_query.cpp
RubenAGSilva/deneva
538f18d296e926055e50cf819c6988a340105476
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Massachusetts Institute of Technology 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 "client_query.h" #include "mem_alloc.h" #include "wl.h" #include "table.h" #include "ycsb_query.h" #include "tpcc_query.h" #include "pps_query.h" /*************************************************/ // class Query_queue /*************************************************/ void Client_query_queue::init(Workload * h_wl) { _wl = h_wl; #if SERVER_GENERATE_QUERIES if(ISCLIENT) return; size = g_thread_cnt; #else size = g_servers_per_client; #endif query_cnt = new uint64_t * [size]; for ( UInt32 id = 0; id < size; id ++) { std::vector<BaseQuery*> new_queries(g_max_txn_per_part+4,NULL); queries.push_back(new_queries); query_cnt[id] = (uint64_t*)mem_allocator.align_alloc(sizeof(uint64_t)); } next_tid = 0; pthread_t * p_thds = new pthread_t[g_init_parallelism - 1]; for (UInt32 i = 0; i < g_init_parallelism - 1; i++) { pthread_create(&p_thds[i], NULL, initQueriesHelper, this); } initQueriesHelper(this); for (uint32_t i = 0; i < g_init_parallelism - 1; i++) { pthread_join(p_thds[i], NULL); } } void * Client_query_queue::initQueriesHelper(void * context) { ((Client_query_queue*)context)->initQueriesParallel(); return NULL; } void Client_query_queue::initQueriesParallel() { UInt32 tid = ATOM_FETCH_ADD(next_tid, 1); uint64_t request_cnt; request_cnt = g_max_txn_per_part + 4; uint32_t final_request; if (tid == g_init_parallelism-1) { final_request = request_cnt; } else { final_request = request_cnt / g_init_parallelism * (tid+1); } #if WORKLOAD == YCSB YCSBQueryGenerator * gen = new YCSBQueryGenerator; gen->init(); #elif WORKLOAD == TPCC TPCCQueryGenerator * gen = new TPCCQueryGenerator; #elif WORKLOAD == PPS PPSQueryGenerator * gen = new PPSQueryGenerator; #endif #if SERVER_GENERATE_QUERIES for ( UInt32 thread_id = 0; thread_id < g_thread_cnt; thread_id ++) { for (UInt32 query_id = request_cnt / g_init_parallelism * tid; query_id < final_request; query_id ++) { queries[thread_id][query_id] = gen->create_query(_wl,g_node_id); } } #else for ( UInt32 server_id = 0; server_id < g_servers_per_client; server_id ++) { for (UInt32 query_id = request_cnt / g_init_parallelism * tid; query_id < final_request; query_id ++) { queries[server_id][query_id] = gen->create_query(_wl,server_id+g_server_start_node); // --- test // if((query_id + server_id) % 2 == 0){ // queries[server_id][query_id] = gen->gen_requests_zipf(server_id+g_server_start_node, _wl, RD); // }else{ // queries[server_id][query_id] = gen->gen_requests_zipf(server_id+g_server_start_node, _wl, WR); // } } } #endif } bool Client_query_queue::done() { return false; } BaseQuery * Client_query_queue::get_next_query(uint64_t server_id,uint64_t thread_id) { assert(server_id < size); uint64_t query_id = __sync_fetch_and_add(query_cnt[server_id], 1); if(query_id > g_max_txn_per_part) { __sync_bool_compare_and_swap(query_cnt[server_id],query_id+1,0); query_id = __sync_fetch_and_add(query_cnt[server_id], 1); } BaseQuery * query = queries[server_id][query_id]; return query; }
29.627907
107
0.682889
RubenAGSilva
aa17c9640e398bf244ec15b8347076acc6d681d9
60,623
cpp
C++
src/inst_riscv_bit.cpp
msyksphinz/swimmer_riscv
065cf3e0dcdcd00cd9bd976285a307d371253ba9
[ "BSD-3-Clause" ]
33
2015-08-23T02:45:07.000Z
2019-11-06T23:34:51.000Z
src/inst_riscv_bit.cpp
msyksphinz-self/swimmer_riscv
065cf3e0dcdcd00cd9bd976285a307d371253ba9
[ "BSD-3-Clause" ]
11
2015-10-11T15:52:42.000Z
2019-09-20T14:30:35.000Z
src/inst_riscv_bit.cpp
msyksphinz/swimmer_riscv
065cf3e0dcdcd00cd9bd976285a307d371253ba9
[ "BSD-3-Clause" ]
5
2015-02-14T10:07:44.000Z
2019-09-20T06:37:38.000Z
/* * Copyright (c) 2015, msyksphinz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <gmpxx.h> #include <iostream> #include <iomanip> #include "inst_list_riscv.hpp" #include "dec_utils_riscv.hpp" #include "softfloat.h" #include "riscv_pe_thread.hpp" #include "inst_riscv.hpp" #include "riscv_sysreg_impl.hpp" #include "inst_ops.hpp" #include "riscv_sysreg_bitdef.hpp" uint32_t shuffle32_stage(uint32_t src, uint32_t maskL, uint32_t maskR, int N) { uint32_t x = src & ~(maskL | maskR); x |= ((src << N) & maskL) | ((src >> N) & maskR); return x; } uint32_t shfl32(uint32_t rs1, uint32_t rs2) { uint32_t x = rs1; int shamt = rs2 & 15; if (shamt & 8) x = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8); if (shamt & 4) x = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4); if (shamt & 2) x = shuffle32_stage(x, 0x30303030, 0x0c0c0c0c, 2); if (shamt & 1) x = shuffle32_stage(x, 0x44444444, 0x22222222, 1); return x; } uint32_t unshfl32(uint32_t rs1, uint32_t rs2) { uint32_t x = rs1; int shamt = rs2 & 15; if (shamt & 1) x = shuffle32_stage(x, 0x44444444, 0x22222222, 1); if (shamt & 2) x = shuffle32_stage(x, 0x30303030, 0x0c0c0c0c, 2); if (shamt & 4) x = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4); if (shamt & 8) x = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8); return x; } UDWord_t shuffle64_stage(UDWord_t src, UDWord_t maskL, UDWord_t maskR, int N) { UDWord_t x = src & ~(maskL | maskR); x |= ((src << N) & maskL) | ((src >> N) & maskR); return x; } UDWord_t shfl64(UDWord_t rs1_val, UDWord_t rs2_val) { UDWord_t x = rs1_val; int shamt = rs2_val & 31; if (shamt & 16) x = shuffle64_stage(x, 0x0000ffff00000000LL, 0x00000000ffff0000LL, 16); if (shamt & 8) x = shuffle64_stage(x, 0x00ff000000ff0000LL, 0x0000ff000000ff00LL, 8); if (shamt & 4) x = shuffle64_stage(x, 0x0f000f000f000f00LL, 0x00f000f000f000f0LL, 4); if (shamt & 2) x = shuffle64_stage(x, 0x3030303030303030LL, 0x0c0c0c0c0c0c0c0cLL, 2); if (shamt & 1) x = shuffle64_stage(x, 0x4444444444444444LL, 0x2222222222222222LL, 1); return x; } UDWord_t unshfl64(UDWord_t rs1_val, UDWord_t rs2_val) { UDWord_t x = rs1_val; int shamt = rs2_val & 31; if (shamt & 1) x = shuffle64_stage(x, 0x4444444444444444LL, 0x2222222222222222LL, 1); if (shamt & 2) x = shuffle64_stage(x, 0x3030303030303030LL, 0x0c0c0c0c0c0c0c0cLL, 2); if (shamt & 4) x = shuffle64_stage(x, 0x0f000f000f000f00LL, 0x00f000f000f000f0LL, 4); if (shamt & 8) x = shuffle64_stage(x, 0x00ff000000ff0000LL, 0x0000ff000000ff00LL, 8); if (shamt & 16) x = shuffle64_stage(x, 0x0000ffff00000000LL, 0x00000000ffff0000LL, 16); return x; } UDWord_t slo(UDWord_t rs1, UDWord_t rs2, int xlen) { int shamt = rs2 & (xlen - 1); return ~(~rs1 << shamt); } void InstEnv::RISCV_INST_SLO (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = ~(~rs1_val << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SRO (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = ~(~rs1_val >> shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_ROL (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = (rs1_val << shamt) | (rs1_val >> ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1))); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_ROR (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1))); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBCLR (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = rs1_val & ~(UDWord_t(1) << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBSET (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = rs1_val | (UDWord_t(1) << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBINV (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = rs1_val ^ (UDWord_t(1) << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBEXT (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = 1 & (rs1_val >> shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GORC (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); DWord_t res = 0; if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) { UWord_t x = rs1_val; int shamt = rs2_val & 31; if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); res = x; } else if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit64) { UDWord_t x = rs1_val; int shamt = rs2_val & 63; if (shamt & 1) x |= ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); if (shamt & 2) x |= ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); if (shamt & 4) x |= ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); if (shamt & 8) x |= ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); if (shamt & 16) x |= ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); if (shamt & 32) x |= ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); res = x; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GREV (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t res = 0; for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) { int j = (i ^ rs2_val) & (m_pe_thread->GetBitModeInt()-1); res |= ((rs1_val >> i) & 1) << j; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SLOI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = ~(~rs1_val << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SROI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t imm = ExtractBitField (inst_hex, 26, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UDWord_t res = ~(~rs1_val >> shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_RORI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1))); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBCLRI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); int shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = rs1_val & ~(UDWord_t(1) << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBSETI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); int shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = rs1_val | (UDWord_t(1) << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBINVI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); int shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = rs1_val ^ (UDWord_t(1) << shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBEXTI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); int shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = 1 & (rs1_val >> shamt); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GORCI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); // int shamt = imm & (m_pe_thread->GetBitModeInt() - 1); DWord_t res = 0; if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) { UWord_t x = rs1_val; int shamt = imm & 31; if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); res = x; } else if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit64) { UDWord_t x = rs1_val; int shamt = imm & 63; if (shamt & 1) x |= ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); if (shamt & 2) x |= ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); if (shamt & 4) x |= ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); if (shamt & 8) x |= ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); if (shamt & 16) x |= ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); if (shamt & 32) x |= ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); res = x; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GREVI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 26, 20); UDWord_t res = 0; for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) { int j = (i ^ imm) & (m_pe_thread->GetBitModeInt()-1); res |= ((rs1_val >> i) & 1) << j; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CMIX (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr)); UDWord_t res = (rs1_val & rs2_val) | (rs3_val & ~rs2_val); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CMOV (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr)); UDWord_t res = rs2_val ? rs1_val : rs3_val; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_FSL (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr)); uint32_t shamt = rs2_val & (2*m_pe_thread->GetBitModeInt() - 1); UDWord_t A = rs1_val, B = rs3_val; if (shamt >= m_pe_thread->GetBitModeInt()) { shamt -= m_pe_thread->GetBitModeInt(); A = rs3_val; B = rs1_val; } UDWord_t res = shamt ? (A << shamt) | (B >> (m_pe_thread->GetBitModeInt()-shamt)) : A; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_FSR (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr)); uint32_t shamt = rs2_val & (2*m_pe_thread->GetBitModeInt() - 1); UDWord_t A = rs1_val, B = rs3_val; if (shamt >= m_pe_thread->GetBitModeInt()) { shamt -= m_pe_thread->GetBitModeInt(); A = rs3_val; B = rs1_val; } UDWord_t res = shamt ? (A >> shamt) | (B << (m_pe_thread->GetBitModeInt()-shamt)) : A; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_FSRI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr)); UDWord_t imm = ExtractBitField (inst_hex, 25, 20); uint32_t shamt = imm & (2 * m_pe_thread->GetBitModeInt() - 1); UDWord_t A = rs1_val, B = rs3_val; if (shamt >= m_pe_thread->GetBitModeInt()) { shamt -= m_pe_thread->GetBitModeInt(); A = rs3_val; B = rs1_val; } UDWord_t res = shamt ? (A >> shamt) | (B << (m_pe_thread->GetBitModeInt()-shamt)) : A; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLZ (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t res = m_pe_thread->GetBitModeInt(); for (uint32_t count = 0; count < m_pe_thread->GetBitModeInt(); count++) { if ((rs1_val << count) >> (m_pe_thread->GetBitModeInt() - 1)) { res = count; break; } } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CTZ (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t res = m_pe_thread->GetBitModeInt(); for (uint32_t count = 0; count < m_pe_thread->GetBitModeInt(); count++) { if ((rs1_val >> count) & 1) { res = count; break; } } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PCNT (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); int count = 0; for (uint32_t index = 0; index < m_pe_thread->GetBitModeInt(); index++) count += (rs1_val >> index) & 1; DWord_t res = count; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_BMATFLIP (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t x = rs1_val; x = shfl64(x, 31); x = shfl64(x, 31); x = shfl64(x, 31); DWord_t res = x; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SEXT_B (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t res = DWord_t(rs1_val << (m_pe_thread->GetBitModeInt()-8)) >> (m_pe_thread->GetBitModeInt()-8); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SEXT_H (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t res = DWord_t(rs1_val << (m_pe_thread->GetBitModeInt()-16)) >> (m_pe_thread->GetBitModeInt()-16); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32_B (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32(rs1_val, 8); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32_H (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32(rs1_val, 16); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); DWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32(rs1_val, 32); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32_D (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); DWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); DWord_t res = m_pe_thread->crc32(rs1_val, 64); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32C_B (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32_c(rs1_val, 8); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32C_H (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32_c(rs1_val, 16); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32C_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32_c(rs1_val, 32); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CRC32C_D (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->ReadGReg<UDWord_t> (rs1_addr); UDWord_t res = m_pe_thread->crc32_c(rs1_val, 64); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLMUL (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t res = 0; for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) if ((rs2_val >> i) & 1) res ^= rs1_val << i; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLMULR (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t res = 0; for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) if ((rs2_val >> i) & 1) res ^= rs1_val >> (m_pe_thread->GetBitModeInt()-i-1); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLMULH (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t res = 0; for (uint32_t i = 1; i < m_pe_thread->GetBitModeInt(); i++) if ((rs2_val >> i) & 1) res ^= rs1_val >> (m_pe_thread->GetBitModeInt()-i); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SHFL (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) { UDWord_t res = shfl32(rs1_val, rs2_val); m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } else { UDWord_t res = shfl64(rs1_val, rs2_val); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } } void InstEnv::RISCV_INST_UNSHFL (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) { UDWord_t res = unshfl32(rs1_val, rs2_val); m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } else { UDWord_t res = unshfl64(rs1_val, rs2_val); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } } void InstEnv::RISCV_INST_BDEP (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t res = 0; for (uint32_t i = 0, j = 0; i < m_pe_thread->GetBitModeInt(); i++) if ((rs2_val >> i) & 1) { if ((rs1_val >> j) & 1) res |= UDWord_t(1) << i; j++; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_BEXT (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t res = 0; for (uint32_t i = 0, j = 0; i < m_pe_thread->GetBitModeInt(); i++) if ((rs2_val >> i) & 1) { if ((rs1_val >> i) & 1) res |= UDWord_t(1) << j; j++; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PACK (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t lower = (rs1_val << m_pe_thread->GetBitModeInt()/2) >> m_pe_thread->GetBitModeInt()/2; UDWord_t upper = rs2_val << m_pe_thread->GetBitModeInt()/2; UDWord_t res = lower | upper; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PACKU (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t lower = rs1_val >> m_pe_thread->GetBitModeInt()/2; UDWord_t upper = (rs2_val >> m_pe_thread->GetBitModeInt()/2) << m_pe_thread->GetBitModeInt()/2; UDWord_t res = lower | upper; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } UDWord_t bmatflip(UDWord_t rs1) { UDWord_t x = rs1; x = shfl64(x, 31); x = shfl64(x, 31); x = shfl64(x, 31); return x; } void InstEnv::RISCV_INST_BMATOR (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); // transpose of rs2 UDWord_t rs2t = bmatflip(rs2_val); uint8_t u[8]; // rows of rs1 uint8_t v[8]; // cols of rs2 for (int i = 0; i < 8; i++) { u[i] = rs1_val >> (i*8); v[i] = rs2t >> (i*8); } UDWord_t res = 0; for (int i = 0; i < 64; i++) { if ((u[i / 8] & v[i % 8]) != 0) res |= 1LL << i; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } UDWord_t pcnt(UDWord_t rs1, unsigned int xlen) { int count = 0; for (uint32_t index = 0; index < xlen; index++) count += (rs1 >> index) & 1; return count; } void InstEnv::RISCV_INST_BMATXOR (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); // transpose of rs2 UDWord_t rs2t = bmatflip(rs2_val); uint8_t u[8]; // rows of rs1 uint8_t v[8]; // cols of rs2 for (int i = 0; i < 8; i++) { u[i] = rs1_val >> (i*8); v[i] = rs2t >> (i*8); } UDWord_t res = 0; for (int i = 0; i < 64; i++) { if (pcnt(u[i / 8] & v[i % 8], m_pe_thread->GetBitModeInt()) & 1) res |= 1LL << i; } m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PACKH (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t lower = rs1_val & 255; UDWord_t upper = (rs2_val & 255) << 8; UDWord_t res = lower | upper; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_BFP (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t cfg = rs2_val >> (m_pe_thread->GetBitModeInt()/2); if ((cfg >> 30) == 2) cfg = cfg >> 16; int len = (cfg >> 8) & (m_pe_thread->GetBitModeInt()/2-1); int off = cfg & (m_pe_thread->GetBitModeInt()-1); len = len ? len : m_pe_thread->GetBitModeInt()/2; UDWord_t mask = slo(0, len, m_pe_thread->GetBitModeInt()) << off; UDWord_t data = rs2_val << off; DWord_t res = (data & mask) | (rs1_val & ~mask); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SHFLI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 25, 20); if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) { UDWord_t res = shfl32(rs1_val, imm); m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } else { UDWord_t res = shfl64(rs1_val, imm); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } } void InstEnv::RISCV_INST_UNSHFLI (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 25, 20); if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) { UDWord_t res = unshfl32(rs1_val, imm); m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } else { UDWord_t res = unshfl64(rs1_val, imm); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } } void InstEnv::RISCV_INST_ADDIWU (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 25, 20); UDWord_t result64 = rs1_val + imm; UWord_t res = (uint32_t)result64; m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } void InstEnv::RISCV_INST_ADDWU (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t result64 = rs1_val + rs2_val; UWord_t res = (uint32_t)result64; m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } void InstEnv::RISCV_INST_SUBWU (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t result64 = rs1_val - rs2_val; UWord_t res = (uint32_t)result64; m_pe_thread->WriteGReg<Word_t> (rd_addr, res); } void InstEnv::RISCV_INST_ADDU_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t rs2u = (uint32_t)rs2_val; UDWord_t res = rs1_val + rs2u; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SUBU_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr)); UDWord_t rs2u = (uint32_t)rs2_val; UDWord_t res = rs1_val - rs2u; m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SLOW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); Word_t res_32 = ~(~rs1_val << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SROW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = ~(~rs1_val >> shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_ROLW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = (rs1_val << shamt) | (rs1_val >> ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1))); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_RORW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1))); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SH1ADDU_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = (rs1_val << 1) + rs2_val; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SH2ADDU_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); Word_t res_32 = (rs1_val << 2) + rs2_val; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SH3ADDU_W (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); Word_t res_32 = (rs1_val << 3) + rs2_val; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBCLRW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); Word_t res_32 = rs1_val & ~(UWord_t(1) << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBSETW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); Word_t res_32 = rs1_val | (UWord_t(1) << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBINVW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); Word_t res_32 = rs1_val ^ (UWord_t(1) << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBEXTW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); Word_t res_32 = 1 & (rs1_val >> shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GORCW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); Word_t res_32 = 0; uint32_t x = rs1_val; uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1); if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); res_32 = x; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GREVW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = 0; for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) { int j = (i ^ rs2_val) & (m_pe_thread->GetBitModeInt()-1); res_32 |= ((rs1_val >> i) & 1) << j; } UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SLOIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr)); DWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); Word_t res_32 = ~(~rs1_val << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SROIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = ~(~rs1_val >> shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_RORIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1))); DWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBCLRIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 26, 20); int shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = rs1_val & ~(UWord_t(1) << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBSETIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = rs1_val | (UWord_t(1) << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SBINVIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = rs1_val ^ (UWord_t(1) << shamt); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GORCIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1); UWord_t res_32 = 0; UWord_t x = rs1_val; if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); res_32 = x; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_GREVIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr); DWord_t imm = ExtractBitField (inst_hex, 24, 20); UWord_t res_32 = 0; for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) { int j = (i ^ imm) & (m_pe_thread->GetBitModeInt()-1); res_32 |= ((rs1_val >> i) & 1) << j; } UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_FSLW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t rs3_val = m_pe_thread->ReadGReg<UWord_t> (rs3_addr); uint32_t actual_xlen = 32; uint32_t shamt = rs2_val & (2 * actual_xlen - 1); UWord_t A = rs1_val, B = rs3_val; if (shamt >= actual_xlen) { shamt -= actual_xlen; A = rs3_val; B = rs1_val; } UWord_t res_32 = shamt ? (A << shamt) | (B >> (actual_xlen-shamt)) : A; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_FSRW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs3_val = m_pe_thread->ReadGReg<UWord_t> (rs3_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); uint32_t actual_xlen = 32; uint32_t shamt = rs2_val & ( 2 *actual_xlen - 1); UDWord_t A = rs1_val, B = rs3_val; if (shamt >= actual_xlen) { shamt -= actual_xlen; A = rs3_val; B = rs1_val; } UWord_t res_32 = shamt ? (A >> shamt) | (B << (32-shamt)) : A; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_FSRIW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs3_addr = ExtractR3Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs3_val = m_pe_thread->ReadGReg<UWord_t> (rs3_addr); UWord_t imm = ExtractBitField (inst_hex, 24, 20); uint32_t actual_xlen = 32; uint32_t shamt = imm & (2*actual_xlen - 1); UWord_t A = rs1_val, B = rs3_val; if (shamt >= actual_xlen) { shamt -= actual_xlen; A = rs3_val; B = rs1_val; } UWord_t res_32 = shamt ? (A >> shamt) | (B << (32-shamt)) : A; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLZW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t res_32 = 32; for (int count = 0; count < 32; count++) { if ((rs1_val << count) >> 31) { res_32 = count; break; } } UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CTZW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); Word_t res_32 = 32; for (int count = 0; count < 32; count++) { if ((rs1_val >> count) & 1) { res_32 = count; break; } } UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PCNTW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); int count = 0; for (int index = 0; index < 32; index++) count += (rs1_val >> index) & 1; Word_t res_32 = count; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLMULW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = 0; for (int i = 0; i < 32; i++) if ((rs2_val >> i) & 1) res_32 ^= rs1_val << i; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLMULRW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = 0; for (int i = 0; i < 32; i++) if ((rs2_val >> i) & 1) res_32 ^= rs1_val >> (32-i-1); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_CLMULHW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = 0; for (int i = 1; i < 32; i++) if ((rs2_val >> i) & 1) res_32 ^= rs1_val >> (32-i); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_SHFLW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = shfl32(rs1_val, rs2_val); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_UNSHFLW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = unshfl32(rs1_val, rs2_val); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_BDEPW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = 0; for (int i = 0, j = 0; i < 32; i++) if ((rs2_val >> i) & 1) { if ((rs1_val >> j) & 1) res_32 |= UWord_t(1) << i; j++; } UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_BEXTW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t res_32 = 0; for (int i = 0, j = 0; i < 32; i++) if ((rs2_val >> i) & 1) { if ((rs1_val >> i) & 1) res_32 |= UWord_t(1) << j; j++; } UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PACKW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t lower = (rs1_val << 32/2) >> 32/2; UWord_t upper = rs2_val << 32/2; UWord_t res_32 = lower | upper; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_PACKUW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t lower = rs1_val >> 32/2; UWord_t upper = (rs2_val >> 32/2) << 32/2; UWord_t res_32 = lower | upper; UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); } void InstEnv::RISCV_INST_BFPW (InstWord_t inst_hex) { RegAddr_t rs1_addr = ExtractR1Field (inst_hex); RegAddr_t rs2_addr = ExtractR2Field (inst_hex); RegAddr_t rd_addr = ExtractRDField (inst_hex); UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr); UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr); UWord_t cfg = rs2_val >> (32/2); if ((cfg >> 30) == 2) cfg = cfg >> 16; int len = (cfg >> 8) & (32/2-1); int off = cfg & (32-1); len = len ? len : 32/2; UWord_t mask = slo(0, len, 32) << off; UWord_t data = rs2_val << off; Word_t res_32 = (data & mask) | (rs1_val & ~mask); UDWord_t res = ExtendSign(res_32, 31); m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res); }
32.418717
132
0.693994
msyksphinz
aa17ee08bdaa5f094a09f0682a73a05f8fca7537
1,153
hpp
C++
addons/modules/includes/moduleDeleteMarkerAttributes.hpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
1
2020-06-07T00:45:49.000Z
2020-06-07T00:45:49.000Z
addons/modules/includes/moduleDeleteMarkerAttributes.hpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
27
2020-05-24T11:09:56.000Z
2020-05-25T12:28:10.000Z
addons/modules/includes/moduleDeleteMarkerAttributes.hpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
2
2020-05-31T08:52:45.000Z
2021-04-16T23:16:37.000Z
class GVAR(deleteMarkerSettingsSubCategory): GVAR(moduleSubCategory) { displayName = CSTRING(Attributes_deleteMarkerSettingsSubCategory); property = QGVAR(deleteMarkerSettingsSubCategory); }; #ifndef MODULE_DELETEMARKER #define DELETEMARKER_COND ((_this getVariable QQGVAR(deleteMarker)) isEqualTo true) class GVAR(deleteMarker): GVAR(dynamicCheckbox) { displayName = CSTRING(Attributes_deleteMarker); tooltip = CSTRING(Attributes_deleteMarker_tooltip); property = QGVAR(deleteMarker); defaultValue = "false"; ATTRIBUTE_LOCAL; }; #else #define DELETEMARKER_COND (true) #endif class GVAR(deleteMarkerName): GVAR(dynamicEdit) { displayName = CSTRING(Attributes_deleteMarkerName); tooltip = CSTRING(Attributes_deleteMarkerName_tooltip); GVAR(description) = CSTRING(Attributes_deleteMarkerName_desc); property = QGVAR(deleteMarkerName); defaultValue = "''"; #ifndef MODULE_DELETEMARKER GVAR(conditionActive) = QUOTE(DELETEMARKER_COND); #endif ATTRIBUTE_LOCAL; }; #undef DELETEMARKER_COND #ifdef MODULE_DELETEMARKER #undef MODULE_DELETEMARKER #endif
32.027778
87
0.753686
Krzyciu
aa186fba4b7066a011e587db99253983e1b1cb0c
3,630
cpp
C++
examples_oldgl_glfw/129_CubeGridEdit/main.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
1
2020-07-18T17:03:36.000Z
2020-07-18T17:03:36.000Z
examples_oldgl_glfw/129_CubeGridEdit/main.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
null
null
null
examples_oldgl_glfw/129_CubeGridEdit/main.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cmath> #include <climits> #if defined(_WIN32) // windows # define NOMINMAX // to remove min,max macro # include <windows.h> // should be before glfw3.h #endif #define GL_SILENCE_DEPRECATION #include <GLFW/glfw3.h> #include "delfem2/cam_projection.h" #include "delfem2/cam_modelview.h" #include "delfem2/vec3.h" #include "delfem2/mshmisc.h" #include "delfem2/gridcube.h" #include "delfem2/glfw/viewer3.h" #include "delfem2/glfw/util.h" #include "delfem2/opengl/old/funcs.h" #include "delfem2/opengl/old/gridcube.h" #ifndef M_PI # define M_PI 3.141592653589793 #endif namespace dfm2 = delfem2; // ----------------------------------------- int main() { // ------------- class CViewer_CubeGrid : public dfm2::glfw::CViewer3 { public: CViewer_CubeGrid() : CViewer3(2.0) { aCubeGrid.emplace_back(0, 0, 0); org = dfm2::CVec3d(0, 0, 0); } void mouse_press(const float src[3], const float dir[3]) override { dfm2::CVec3d offsym(0, 0, 0); if (imode_sym == 2) { offsym.p[2] = -elen * 0.5; } double src_pick0[3] = {src[0], src[1], src[2]}; double dir_pick0[3] = {dir[0], dir[1], dir[2]}; double offsym0[3]; offsym.CopyTo(offsym0); Pick_CubeGrid( icube_picked, iface_picked, src_pick0, dir_pick0, elen, offsym0, aCubeGrid); if (edit_mode == EDIT_ADD) { int ivx1, ivy1, ivz1; Adj_CubeGrid( ivx1, ivy1, ivz1, icube_picked, iface_picked, aCubeGrid); Add_CubeGrid(aCubeGrid, ivx1, ivy1, ivz1); if (imode_sym == 1) { Add_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1 - 1); } if (imode_sym == 2) { Add_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1); } } if (edit_mode == EDIT_DELETE) { int ivx1 = aCubeGrid[icube_picked].ivx; int ivy1 = aCubeGrid[icube_picked].ivy; int ivz1 = aCubeGrid[icube_picked].ivz; Del_CubeGrid(aCubeGrid, ivx1, ivy1, ivz1); if (imode_sym == 1) { Del_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1 - 1); } if (imode_sym == 2) { Del_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1); } } } void key_press( int key, [[maybe_unused]] int mods) override { if (key == GLFW_KEY_A) { glfwSetWindowTitle(this->window, "Edit Mode: Add"); edit_mode = EDIT_ADD; } if (key == GLFW_KEY_D) { glfwSetWindowTitle(this->window, "Edit Mode: Delete"); edit_mode = EDIT_DELETE; } } void Draw() const { dfm2::CVec3d offsym(0, 0, 0); if (imode_sym == 2) { offsym.p[2] = -elen * 0.5; } for (unsigned int ic = 0; ic < aCubeGrid.size(); ++ic) { delfem2::opengl::Draw_CubeGrid( ic == icube_picked, iface_picked, elen, org + offsym, aCubeGrid[ic]); } } public: int imode_sym = 2; std::vector<dfm2::CCubeGrid> aCubeGrid; const double elen = 1.0; dfm2::CVec3d org; unsigned int icube_picked = UINT_MAX; int iface_picked = -1; enum EDIT_MODE { EDIT_NONE, EDIT_ADD, EDIT_DELETE, }; EDIT_MODE edit_mode = EDIT_ADD; } viewer; // dfm2::glfw::InitGLOld(); viewer.OpenWindow(); delfem2::opengl::setSomeLighting(); while (!glfwWindowShouldClose(viewer.window)) { viewer.DrawBegin_oldGL(); viewer.Draw(); glfwSwapBuffers(viewer.window); glfwPollEvents(); } glfwDestroyWindow(viewer.window); glfwTerminate(); exit(EXIT_SUCCESS); }
29.754098
79
0.609091
mmer547
aa1af73e2354a53447dcd2651873b45b7a1d1b2f
3,394
cpp
C++
classnote/HomeworkReferenceCode/HW1.cpp
Alex-Lin5/cpp_practice
c249362d6bbe932dc1eb4a4b8c51728d58db2aa7
[ "MIT" ]
null
null
null
classnote/HomeworkReferenceCode/HW1.cpp
Alex-Lin5/cpp_practice
c249362d6bbe932dc1eb4a4b8c51728d58db2aa7
[ "MIT" ]
null
null
null
classnote/HomeworkReferenceCode/HW1.cpp
Alex-Lin5/cpp_practice
c249362d6bbe932dc1eb4a4b8c51728d58db2aa7
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Node { public: int value; Node* next; Node(int i) { value = i; next = nullptr; } Node() { next = nullptr; } }; class LinkedList { public: Node* head; //Node* tail; LinkedList() { head = nullptr; } LinkedList(int m, int n);//You can use code from class lectures for this constructor. void print();//You can use code from class lecture for print. //*************************************************************************************************** //implement the following member functions group and bubbleSort: void group(); /* Group all occurrences of the same numbers together according to the order of appearance. For a list with values 7 6 12 4 33 12 6 6 7 , after grouping, it becomes 7 7 6 6 6 12 12 4 33 Note that in the original sequence, 7 appears before 6 before 12 before 4 before 33. You are only allowed to change "next" of a node, but not "value." Do not introduce additional functions. In-place implementation is required. External structures, such as arrays, are not allowed. For example, you are not allowed to copy linked list values to outside, and then process the data and copy them back to linked list. */ void bubbleSort(); //you are allowed change both value and next for bubbleSort. //Like function group, you are not allowed to use any external structures, such as arrays, to help. //No extra functions allowed }; LinkedList::LinkedList(int n, int m) { head = nullptr; for (int i = 0; i < n; ++i) { Node* p1 = new Node{ rand() % m }; p1->next = head; head = p1; } } void LinkedList::print() { Node* p1{ head }; while (p1) {//while (p1 != nullptr) cout << p1->value << " "; p1 = p1->next; } } void LinkedList::group() { if (!head || !head->next || !head->next->next) { return; } /*Node* pre = head->next->next, *p4 = pre->next, *p4nx = p4->next, *cur = head->next; head->next = p4; p4->next = cur; pre->next = p4nx;*/ Node* p = head; int num = p->value; do{ Node* cur = p->next; while (cur != nullptr && cur->value == p->value) { p = p->next; cur = cur->next; } Node* change = cur; if (cur == nullptr) { break; } while ( cur->next != nullptr) { if (cur->next->value == num) { Node* last = cur->next->next; p ->next = cur->next; cur->next->next = change; cur->next = last; p = p ->next; } else { cur = cur->next; } } p = change; num = p ->value; if (p ->next == nullptr) { break; } } while (p ->next->next != nullptr || p ->next != nullptr); } void LinkedList::bubbleSort() { if (!head || !head->next) { return; } Node* cur{ head }, * last{ nullptr }; while (last != head->next) { while (cur->next != last) { if (cur->value > cur->next->value) { swap(cur->value, cur->next->value); } cur = cur->next; } last = cur; cur = head; } /*int swaped =1; while (swaped) { Node* p1 = head; swaped = 0; while (p1->next != nullptr) { if (p1 -> value > p1->next->value) { swap(p1->value, p1->next->value); swaped = 1; } p1 = p1->next; } } */ } int main() {//During grading, different cases will be used. LinkedList L1(50,20); L1.print(); cout << endl; L1.group(); L1.print(); cout << endl; LinkedList L2(50, 25); L2.print(); cout << endl; L2.bubbleSort(); L2.print(); return 0; }
20.08284
112
0.581615
Alex-Lin5
aa1c4237ef52ee74da62534aedd97ea8b4d55f77
2,108
cpp
C++
src/optimizer/pushdown/pushdown_get.cpp
shenyunlong/duckdb
ecb90f22b36a50b051fdd8e0d681bade3365c430
[ "MIT" ]
null
null
null
src/optimizer/pushdown/pushdown_get.cpp
shenyunlong/duckdb
ecb90f22b36a50b051fdd8e0d681bade3365c430
[ "MIT" ]
7
2020-08-25T22:24:16.000Z
2020-09-06T00:16:49.000Z
src/optimizer/pushdown/pushdown_get.cpp
shenyunlong/duckdb
ecb90f22b36a50b051fdd8e0d681bade3365c430
[ "MIT" ]
null
null
null
#include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/storage/data_table.hpp" namespace duckdb { using namespace std; unique_ptr<LogicalOperator> FilterPushdown::PushdownGet(unique_ptr<LogicalOperator> op) { assert(op->type == LogicalOperatorType::GET); auto &get = (LogicalGet &)*op; if (!get.tableFilters.empty()) { if (!filters.empty()) { //! We didn't managed to push down all filters to table scan auto logicalFilter = make_unique<LogicalFilter>(); for (auto &f : filters) { logicalFilter->expressions.push_back(move(f->filter)); } logicalFilter->children.push_back(move(op)); return move(logicalFilter); } else { return op; } } //! FIXME: We only need to skip if the index is in the column being filtered if (!get.table || !get.table->storage->info->indexes.empty()) { //! now push any existing filters if (filters.empty()) { //! no filters to push return op; } auto filter = make_unique<LogicalFilter>(); for (auto &f : filters) { filter->expressions.push_back(move(f->filter)); } filter->children.push_back(move(op)); return move(filter); } PushFilters(); vector<unique_ptr<Filter>> filtersToPushDown; get.tableFilters = combiner.GenerateTableScanFilters( [&](unique_ptr<Expression> filter) { auto f = make_unique<Filter>(); f->filter = move(filter); f->ExtractBindings(); filtersToPushDown.push_back(move(f)); }, get.column_ids); for (auto &f : get.tableFilters) { f.column_index = get.column_ids[f.column_index]; } GenerateFilters(); for (auto &f : filtersToPushDown) { get.expressions.push_back(move(f->filter)); } if (!filters.empty()) { //! We didn't managed to push down all filters to table scan auto logicalFilter = make_unique<LogicalFilter>(); for (auto &f : filters) { logicalFilter->expressions.push_back(move(f->filter)); } logicalFilter->children.push_back(move(op)); return move(logicalFilter); } return op; } } // namespace duckdb
29.690141
89
0.694497
shenyunlong
aa2c65c36843ad34cde6e738b55267fc856cd3e4
2,232
cpp
C++
compute/perf/perf_host_sort.cpp
atksh/mimalloc-lgb
add692a5ef9a91cad0bc78fa18a051d43a8c930e
[ "MIT" ]
null
null
null
compute/perf/perf_host_sort.cpp
atksh/mimalloc-lgb
add692a5ef9a91cad0bc78fa18a051d43a8c930e
[ "MIT" ]
null
null
null
compute/perf/perf_host_sort.cpp
atksh/mimalloc-lgb
add692a5ef9a91cad0bc78fa18a051d43a8c930e
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------// // Copyright (c) 2013-2014 Kyle Lutz <[email protected]> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #include <algorithm> #include <iostream> #include <vector> #include <mimalloc.h> #include <boost/timer/timer.hpp> #include <boost/compute/system.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/algorithm/sort.hpp> #include <boost/compute/container/vector.hpp> #include "perf.hpp" int main(int argc, char *argv[]) { perf_parse_args(argc, argv); std::cout << "size: " << PERF_N << std::endl; // setup context and queue for the default device boost::compute::device device = boost::compute::system::default_device(); boost::compute::context context(device); boost::compute::command_queue queue(context, device); std::cout << "device: " << device.name() << std::endl; // create vector of random numbers on the host std::vector<int, mi_stl_allocator<int>> random_vector(PERF_N); std::generate(random_vector.begin(), random_vector.end(), rand); // create input vector for gpu std::vector<int, mi_stl_allocator<int>> gpu_vector = random_vector; // sort vector on gpu boost::timer::cpu_timer t; boost::compute::sort( gpu_vector.begin(), gpu_vector.end(), queue); queue.finish(); std::cout << "time: " << t.elapsed().wall / 1e6 << " ms" << std::endl; // create input vector for host std::vector<int, mi_stl_allocator<int>> host_vector = random_vector; // sort vector on host t.start(); std::sort(host_vector.begin(), host_vector.end()); std::cout << "host time: " << t.elapsed().wall / 1e6 << " ms" << std::endl; // ensure that both sorted vectors are equal if (!std::equal(gpu_vector.begin(), gpu_vector.end(), host_vector.begin())) { std::cerr << "ERROR: sorted vectors not the same" << std::endl; return -1; } return 0; }
33.313433
79
0.616935
atksh
a8f7d1a77b271ec8e555251fbf18029debded219
1,330
hpp
C++
engine/src/events/InputEvents.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-01T20:22:41.000Z
2021-11-01T20:22:41.000Z
engine/src/events/InputEvents.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-02T12:45:20.000Z
2021-11-02T12:45:20.000Z
engine/src/events/InputEvents.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-02T12:28:58.000Z
2021-11-02T12:28:58.000Z
#pragma once #include "events/Event.hpp" namespace Birdy3d::events { class InputScrollEvent : public Event { public: const double xoffset; const double yoffset; InputScrollEvent(double xoffset, double yoffset) : xoffset(xoffset) , yoffset(yoffset) { } }; class InputClickEvent : public Event { public: const int button; const int action; const int mods; InputClickEvent(int button, int action, int mods) : button(button) , action(action) , mods(mods) { } }; class InputKeyEvent : public Event { public: const int key; const int scancode; const int action; const int mods; InputKeyEvent(int key, int scancode, int action, int mods) : key(key) , scancode(scancode) , action(action) , mods(mods) { } bool check_options(std::any options) override { int key_option = std::any_cast<int>(options); return key_option == key && action == 1; // GLFW_PRESS } }; class InputCharEvent : public Event { public: const unsigned int codepoint; InputCharEvent(unsigned int codepoint) : codepoint(codepoint) { } }; }
23.333333
66
0.558647
Birdy2014
a8f91bc2cb2c0d7ad83b7d619f728dee4f4c8b0a
1,796
cpp
C++
src/crypto/arc4.cpp
Iglu47/innoextract
660546ad796bb7619ff0e99a6cd61c4e01e4e241
[ "Zlib" ]
526
2015-01-01T17:52:24.000Z
2022-03-30T10:16:25.000Z
src/crypto/arc4.cpp
Iglu47/innoextract
660546ad796bb7619ff0e99a6cd61c4e01e4e241
[ "Zlib" ]
104
2015-01-01T11:48:51.000Z
2022-03-11T17:25:58.000Z
src/crypto/arc4.cpp
Iglu47/innoextract
660546ad796bb7619ff0e99a6cd61c4e01e4e241
[ "Zlib" ]
83
2015-02-10T15:51:37.000Z
2022-03-08T13:11:12.000Z
/* * Copyright (C) 2018 Daniel Scharrer * * This software is provided 'as-is', without any express or implied * warranty. In no event will the author(s) be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "crypto/arc4.hpp" #include <algorithm> #include "util/endian.hpp" namespace crypto { void arc4::init(const char * key, size_t length) { a = b = 0; for(size_t i = 0; i < sizeof(state); i++){ state[i] = boost::uint8_t(i); } size_t j = 0; for(size_t i = 0; i < sizeof(state); i++) { j = (j + state[i] + boost::uint8_t(key[i % length])) % sizeof(state); std::swap(state[i], state[j]); } } void arc4::update() { a = (a + 1) % sizeof(state); b = (b + state[a]) % sizeof(state); std::swap(state[a], state[b]); } void arc4::discard(size_t length) { for(size_t i = 0; i < length; i++) { update(); } } void arc4::crypt(const char * in, char * out, size_t length) { for(size_t i = 0; i < length; i++) { update(); out[i] = char(state[size_t(state[a] + state[b]) % sizeof(state)] ^ boost::uint8_t(in[i])); } } } // namespace crypto
24.944444
92
0.658686
Iglu47
a8fce2a00b2b29a6e74ad3a33d412aa1e6183b19
1,159
hh
C++
src/main/c++/novemberizing/io/reactor.hh
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
1
2020-10-10T11:57:15.000Z
2020-10-10T11:57:15.000Z
src/main/c++/novemberizing/io/reactor.hh
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
null
null
null
src/main/c++/novemberizing/io/reactor.hh
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
null
null
null
#ifndef __NOVEMBERIZING_IO__REACTOR__HH__ #define __NOVEMBERIZING_IO__REACTOR__HH__ #include <sys/epoll.h> #include <unistd.h> #include <novemberizing/util/log.hh> #include <novemberizing/ds.hh> #include <novemberizing/ds/cyclable.hh> #include <novemberizing/ds/concurrent.set.hh> #include <novemberizing/io.hh> #include <novemberizing/io/descriptor.hh> namespace novemberizing { namespace io { using namespace util; using namespace ds; class Reactor : public Cyclable { public: static const int DefaultDescriptorSize = 1024; public: static const int DefaultTimeout = 10; private: ConcurrentSet<Descriptor *> __descriptors; private: int __descriptor; private: int __max; private: int __reserved; private: int __timeout; private: struct epoll_event * __events; public: virtual int add(Descriptor * descriptor); public: virtual int del(Descriptor * descriptor); public: virtual int mod(Descriptor * descriptor); public: virtual void onecycle(void); private: virtual void initialize(void); public: Reactor(void); public: virtual ~Reactor(void); }; } } #endif // __NOVEMBERIZING_IO__REACTOR__HH__
26.953488
58
0.750647
iticworld
d104354102fd114bdc29eff8f74902da42a0cb51
6,110
cpp
C++
winsdkfb/winsdkfb/winsdkfb.Shared/FacebookProfilePictureControl.xaml.cpp
omer-ispl/winsdkfb1
e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b
[ "MIT" ]
197
2015-07-14T22:33:14.000Z
2019-05-05T15:26:15.000Z
winsdkfb/winsdkfb/winsdkfb.Shared/FacebookProfilePictureControl.xaml.cpp
omer-ispl/winsdkfb1
e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b
[ "MIT" ]
209
2015-07-15T14:49:48.000Z
2019-02-15T14:39:48.000Z
winsdkfb/winsdkfb/winsdkfb.Shared/FacebookProfilePictureControl.xaml.cpp
omer-ispl/winsdkfb1
e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b
[ "MIT" ]
115
2015-07-15T06:57:34.000Z
2019-01-12T08:55:15.000Z
//****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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. // //****************************************************************************** // // ProfilePictureControl.xaml.cpp // Implementation of the ProfilePictureControl class // #include "pch.h" #include "FacebookProfilePictureControl.xaml.h" #include "FBSingleValue.h" #include <string> using namespace concurrency; using namespace winsdkfb; using namespace winsdkfb::Graph; using namespace Platform; using namespace Windows::ApplicationModel::Core; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::Xaml::Media::Imaging; using namespace Windows::UI::Xaml::Interop; // At least enough characters to hold a string representation of 32-bit int, // in decimal. Used for width and height of profile picture. #define INT_STRING_LENGTH 16 #define ProfilePictureSillhouetteImage \ "ms-appx:///winsdkfb/Images/fb_blank_profile_portrait.png" DependencyProperty^ ProfilePictureControl::_userIdProperty = DependencyProperty::Register( L"UserId", TypeName(String::typeid), TypeName(ProfilePictureControl::typeid), ref new PropertyMetadata( nullptr, ref new PropertyChangedCallback(&ProfilePictureControl::UserIdPropertyChanged))); ProfilePictureControl::ProfilePictureControl() : _CropMode(CroppingType::Square) { InitializeComponent(); Update(); } void ProfilePictureControl::UserIdPropertyChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e) { ProfilePictureControl^ instance = static_cast<ProfilePictureControl^>(d); instance->UserId = static_cast<String^>(e->NewValue); } String^ ProfilePictureControl::UserId::get() { return safe_cast<String^>(GetValue(_userIdProperty)); } void ProfilePictureControl::UserId::set(String^ value) { SetValue(_userIdProperty, value); Update(); } CroppingType ProfilePictureControl::CropMode::get() { return _CropMode; } void ProfilePictureControl::CropMode::set(CroppingType value) { if (_CropMode != value) { _CropMode = value; Update(); } } void ProfilePictureControl::SetImageSourceFromUserId() { int height = -1; // specify height == width for square. If user wants original aspect ratio, // only specify width, and FB graph API will scale and preserve ratio. if (CropMode == CroppingType::Square) { height = (int)this->Width; } create_task(GetProfilePictureInfo((int)this->Width, height)) .then([=](FBResult^ result) { FBProfilePicture^ info = nullptr; if (result && (result->Succeeded)) { info = static_cast<FBProfilePicture^>(result->Object); } return info; }) .then([=](FBProfilePicture^ info) { Windows::UI::Core::CoreWindow^ wnd = CoreApplication::MainView->CoreWindow; if (wnd) { wnd->Dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler([info, this]() { if (info) { ProfilePic->Stretch = Stretch::Uniform; ProfilePic->Source = ref new BitmapImage(ref new Uri(info->Url)); } })); } }); } void ProfilePictureControl::SetImageSourceFromResource() { Windows::UI::Core::CoreWindow^ wnd = CoreApplication::MainView->CoreWindow; if (wnd) { wnd->Dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler([=]() { Uri^ u = ref new Uri(ProfilePictureSillhouetteImage); ProfilePic->Stretch = Stretch::Uniform; ProfilePic->Source = ref new BitmapImage(u); })); } } void ProfilePictureControl::Update() { if (UserId) { SetImageSourceFromUserId(); } else { SetImageSourceFromResource(); } } task<FBResult^> ProfilePictureControl::GetProfilePictureInfo( int width, int height ) { PropertySet^ parameters = ref new PropertySet(); wchar_t whBuffer[INT_STRING_LENGTH]; task<FBResult^> result; parameters->Insert(L"redirect", L"false"); if (width > -1) { if (!_itow_s(width, whBuffer, INT_STRING_LENGTH, 10)) { String^ Value = ref new String(whBuffer); parameters->Insert(L"width", Value); } } if (height > -1) { if (!_itow_s(height, whBuffer, INT_STRING_LENGTH, 10)) { String^ Value = ref new String(whBuffer); parameters->Insert(L"height", Value); } } if (UserId) { String^ path = UserId + L"/picture"; FBSingleValue^ value = ref new FBSingleValue( path, parameters, ref new FBJsonClassFactory([](String^ JsonText) -> Object^ { return FBProfilePicture::FromJson(JsonText); })); result = create_task(value->GetAsync()); } return result; }
28.287037
109
0.642881
omer-ispl
d104c774952e0b052fc9eb7f4410b13c11603495
1,196
inl
C++
Breakout/MacOS-Demo/Glm/gtx/vector_access.inl
CoderYQ/LearnOpenGL
2fbb251d939df0d9d23d92346aa5d46a0ba6f91f
[ "MIT" ]
455
2015-02-04T01:39:12.000Z
2022-03-18T17:28:34.000Z
Breakout/MacOS-Demo/Glm/gtx/vector_access.inl
CoderYQ/LearnOpenGL
2fbb251d939df0d9d23d92346aa5d46a0ba6f91f
[ "MIT" ]
9
2016-09-12T05:00:23.000Z
2021-05-14T18:38:51.000Z
Breakout/MacOS-Demo/Glm/gtx/vector_access.inl
CoderYQ/LearnOpenGL
2fbb251d939df0d9d23d92346aa5d46a0ba6f91f
[ "MIT" ]
117
2015-01-30T10:13:54.000Z
2022-03-08T03:46:42.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-01-16 // Updated : 2008-10-07 // Licence : This source is under MIT License // File : glm/gtx/vector_access.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm { template <typename valType> GLM_FUNC_QUALIFIER void set ( detail::tvec2<valType>& v, valType const & x, valType const & y ) { v.x = x; v.y = y; } template <typename valType> GLM_FUNC_QUALIFIER void set ( detail::tvec3<valType>& v, valType const & x, valType const & y, valType const & z ) { v.x = x; v.y = y; v.z = z; } template <typename valType> GLM_FUNC_QUALIFIER void set ( detail::tvec4<valType>& v, valType const & x, valType const & y, valType const & z, valType const & w ) { v.x = x; v.y = y; v.z = z; v.w = w; } }//namespace glm
22.148148
100
0.43311
CoderYQ
d104e822805402d917967d9d57602ed38ab66986
7,577
cpp
C++
test/blockchain/pop/pop_vbk_block_tree_test.cpp
overcookedpanda/alt-integration-cpp
7932e79a77d9514ca0e0354636e77fba1845d707
[ "MIT" ]
null
null
null
test/blockchain/pop/pop_vbk_block_tree_test.cpp
overcookedpanda/alt-integration-cpp
7932e79a77d9514ca0e0354636e77fba1845d707
[ "MIT" ]
null
null
null
test/blockchain/pop/pop_vbk_block_tree_test.cpp
overcookedpanda/alt-integration-cpp
7932e79a77d9514ca0e0354636e77fba1845d707
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <exception> #include <memory> #include "util/pop_test_fixture.hpp" #include "veriblock/blockchain/pop/fork_resolution.hpp" using namespace altintegration; struct VbkBlockTreeTestFixture : public ::testing::Test { MockMiner popminer; void endorseVBK(size_t height) { auto* endorsedIndex = popminer.vbk().getBestChain()[(int32_t)height]; ASSERT_TRUE(endorsedIndex); auto btctx = popminer.createBtcTxEndorsingVbkBlock(*endorsedIndex->header); auto btccontaining = popminer.mineBtcBlocks(1); auto vbkpoptx = popminer.createVbkPopTxEndorsingVbkBlock( *btccontaining->header, btctx, *endorsedIndex->header, popminer.getBtcParams().getGenesisBlock().getHash()); popminer.mineVbkBlocks(1); } VbkPopTx generatePopTx(const VbkBlock& endorsedBlock) { auto Btctx = popminer.createBtcTxEndorsingVbkBlock(endorsedBlock); auto* btcBlockTip = popminer.mineBtcBlocks(1); return popminer.createVbkPopTxEndorsingVbkBlock( *btcBlockTip->header, Btctx, endorsedBlock, popminer.getBtcParams().getGenesisBlock().getHash()); } }; TEST_F(VbkBlockTreeTestFixture, FilterChainForForkResolution) { using namespace internal; size_t numVbkBlocks = 200ull; ASSERT_EQ(popminer.vbk().getComparator().getIndex(), popminer.vbk().getBestChain().tip()); popminer.mineVbkBlocks(numVbkBlocks); auto& best = popminer.vbk().getBestChain(); ASSERT_EQ(best.blocksCount(), numVbkBlocks + 1); endorseVBK(176); endorseVBK(166); endorseVBK(169); endorseVBK(143); endorseVBK(143); endorseVBK(87); endorseVBK(87); endorseVBK(91); endorseVBK(91); ASSERT_EQ(best.blocksCount(), numVbkBlocks + 10); popminer.mineVbkBlocks(1); ASSERT_EQ(best.blocksCount(), numVbkBlocks + 11); auto protoContext = getProtoKeystoneContext(best, popminer.btc(), popminer.getVbkParams()); EXPECT_EQ(protoContext.size(), numVbkBlocks / popminer.getVbkParams().getKeystoneInterval()); EXPECT_EQ(protoContext[0].blockHeight, 20); EXPECT_EQ(protoContext[0].referencedByBlocks.size(), 0); EXPECT_EQ(protoContext[1].blockHeight, 40); EXPECT_EQ(protoContext[1].referencedByBlocks.size(), 0); EXPECT_EQ(protoContext[2].blockHeight, 60); EXPECT_EQ(protoContext[2].referencedByBlocks.size(), 0); EXPECT_EQ(protoContext[3].blockHeight, 80); EXPECT_EQ(protoContext[3].referencedByBlocks.size(), 4); EXPECT_EQ(protoContext[4].blockHeight, 100); EXPECT_EQ(protoContext[4].referencedByBlocks.size(), 0); EXPECT_EQ(protoContext[5].blockHeight, 120); EXPECT_EQ(protoContext[5].referencedByBlocks.size(), 0); EXPECT_EQ(protoContext[6].blockHeight, 140); EXPECT_EQ(protoContext[6].referencedByBlocks.size(), 2); EXPECT_EQ(protoContext[7].blockHeight, 160); EXPECT_EQ(protoContext[7].referencedByBlocks.size(), 3); auto keystoneContext = getKeystoneContext(protoContext, popminer.btc()); EXPECT_EQ(keystoneContext.size(), numVbkBlocks / popminer.getVbkParams().getKeystoneInterval()); auto max = std::numeric_limits<int32_t>::max(); EXPECT_EQ(keystoneContext[0].blockHeight, 20); EXPECT_EQ(keystoneContext[0].firstBlockPublicationHeight, max); EXPECT_EQ(keystoneContext[1].blockHeight, 40); EXPECT_EQ(keystoneContext[1].firstBlockPublicationHeight, max); EXPECT_EQ(keystoneContext[2].blockHeight, 60); EXPECT_EQ(keystoneContext[2].firstBlockPublicationHeight, max); EXPECT_EQ(keystoneContext[3].blockHeight, 80); EXPECT_EQ(keystoneContext[3].firstBlockPublicationHeight, 6); EXPECT_EQ(keystoneContext[4].blockHeight, 100); EXPECT_EQ(keystoneContext[4].firstBlockPublicationHeight, max); EXPECT_EQ(keystoneContext[5].blockHeight, 120); EXPECT_EQ(keystoneContext[5].firstBlockPublicationHeight, max); EXPECT_EQ(keystoneContext[6].blockHeight, 140); EXPECT_EQ(keystoneContext[6].firstBlockPublicationHeight, 4); EXPECT_EQ(keystoneContext[7].blockHeight, 160); EXPECT_EQ(keystoneContext[7].firstBlockPublicationHeight, 1); } TEST_F(VbkBlockTreeTestFixture, addAllPayloads_failure_test) { // start with 30 BTC blocks auto* btcBlockTip = popminer.mineBtcBlocks(30); ASSERT_EQ(btcBlockTip->getHash(), popminer.btc().getBestChain().tip()->getHash()); // start with 65 VBK blocks auto* vbkBlockTip = popminer.mineVbkBlocks(65); ASSERT_EQ(popminer.vbk().getBestChain().tip()->getHash(), vbkBlockTip->getHash()); // Make 5 endorsements valid endorsements auto* endorsedVbkBlock1 = vbkBlockTip->getAncestor(vbkBlockTip->height - 11); ASSERT_EQ(endorsedVbkBlock1->endorsedBy.size(), 0); auto* endorsedVbkBlock2 = vbkBlockTip->getAncestor(vbkBlockTip->height - 12); ASSERT_EQ(endorsedVbkBlock2->endorsedBy.size(), 0); auto* endorsedVbkBlock3 = vbkBlockTip->getAncestor(vbkBlockTip->height - 13); ASSERT_EQ(endorsedVbkBlock3->endorsedBy.size(), 0); auto* endorsedVbkBlock4 = vbkBlockTip->getAncestor(vbkBlockTip->height - 14); ASSERT_EQ(endorsedVbkBlock4->endorsedBy.size(), 0); auto* endorsedVbkBlock5 = vbkBlockTip->getAncestor(vbkBlockTip->height - 15); ASSERT_EQ(endorsedVbkBlock5->endorsedBy.size(), 0); generatePopTx(*endorsedVbkBlock1->header); generatePopTx(*endorsedVbkBlock2->header); generatePopTx(*endorsedVbkBlock3->header); generatePopTx(*endorsedVbkBlock4->header); generatePopTx(*endorsedVbkBlock5->header); ASSERT_EQ(popminer.vbkmempool.size(), 5); vbkBlockTip = popminer.mineVbkBlocks(1); ASSERT_EQ(popminer.vbk().getBestChain().tip()->getHash(), vbkBlockTip->getHash()); // check that we have endorsements to the VbBlocks ASSERT_EQ(endorsedVbkBlock1->endorsedBy.size(), 1); ASSERT_EQ(endorsedVbkBlock2->endorsedBy.size(), 1); ASSERT_EQ(endorsedVbkBlock3->endorsedBy.size(), 1); ASSERT_EQ(endorsedVbkBlock4->endorsedBy.size(), 1); ASSERT_EQ(endorsedVbkBlock5->endorsedBy.size(), 1); // mine 40 Vbk blocks vbkBlockTip = popminer.mineVbkBlocks(40); ASSERT_EQ(popminer.vbk().getBestChain().tip()->getHash(), vbkBlockTip->getHash()); // Make 5 endorsements valid endorsements endorsedVbkBlock1 = vbkBlockTip->getAncestor(vbkBlockTip->height - 11); ASSERT_EQ(endorsedVbkBlock1->endorsedBy.size(), 0); endorsedVbkBlock2 = vbkBlockTip->getAncestor(vbkBlockTip->height - 12); ASSERT_EQ(endorsedVbkBlock2->endorsedBy.size(), 0); endorsedVbkBlock3 = vbkBlockTip->getAncestor(vbkBlockTip->height - 13); ASSERT_EQ(endorsedVbkBlock3->endorsedBy.size(), 0); endorsedVbkBlock4 = vbkBlockTip->getAncestor(vbkBlockTip->height - 14); ASSERT_EQ(endorsedVbkBlock4->endorsedBy.size(), 0); endorsedVbkBlock5 = vbkBlockTip->getAncestor(vbkBlockTip->height - 15); ASSERT_EQ(endorsedVbkBlock5->endorsedBy.size(), 0); generatePopTx(*endorsedVbkBlock1->header); generatePopTx(*endorsedVbkBlock2->header); generatePopTx(*endorsedVbkBlock3->header); generatePopTx(*endorsedVbkBlock4->header); generatePopTx(*endorsedVbkBlock5->header); ASSERT_EQ(popminer.vbkmempool.size(), 5); // corrupt one of the endorsement std::vector<uint8_t> new_hash = {1, 2, 3}; popminer.vbkmempool[0].blockOfProof.previousBlock = uint256(new_hash); EXPECT_THROW(popminer.mineVbkBlocks(1), std::domain_error); // check that all endorsement have not been applied ASSERT_EQ(endorsedVbkBlock1->endorsedBy.size(), 0); ASSERT_EQ(endorsedVbkBlock2->endorsedBy.size(), 0); ASSERT_EQ(endorsedVbkBlock3->endorsedBy.size(), 0); ASSERT_EQ(endorsedVbkBlock4->endorsedBy.size(), 0); ASSERT_EQ(endorsedVbkBlock5->endorsedBy.size(), 0); }
40.089947
79
0.749901
overcookedpanda
d105bba5b5a279a10438e98316d36bba376f6309
7,084
cpp
C++
shadow/operators/kernels/pooling.cpp
junluan/shadow
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
[ "Apache-2.0" ]
20
2017-07-04T11:22:47.000Z
2022-01-16T03:58:32.000Z
shadow/operators/kernels/pooling.cpp
junluan/shadow
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
[ "Apache-2.0" ]
2
2017-12-03T13:07:39.000Z
2021-01-13T11:11:52.000Z
shadow/operators/kernels/pooling.cpp
junluan/shadow
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
[ "Apache-2.0" ]
10
2017-09-30T05:06:30.000Z
2020-11-13T05:43:44.000Z
#include "pooling.hpp" namespace Shadow { namespace Vision { template <> void Pooling2D<DeviceType::kCPU, float>(const float* in_data, const VecInt& in_shape, int pool_type, int kernel_size_h, int kernel_size_w, int stride_h, int stride_w, int pad_h, int pad_w, const VecInt& out_shape, float* out_data, Context* context) { int batch = in_shape[0], channel = in_shape[1]; int in_h = in_shape[2], in_w = in_shape[3]; int out_h = out_shape[2], out_w = out_shape[3]; for (int b = 0; b < batch; ++b) { for (int c = 0; c < channel; ++c, in_data += in_h * in_w) { for (int h = 0; h < out_h; ++h) { for (int w = 0; w < out_w; ++w) { int hstart = h * stride_h - pad_h; int wstart = w * stride_w - pad_w; int hend = std::min(hstart + kernel_size_h, in_h + pad_h); int wend = std::min(wstart + kernel_size_w, in_w + pad_w); int pool_size = (hend - hstart) * (wend - wstart); hstart = std::max(hstart, 0), wstart = std::max(wstart, 0); hend = std::min(hend, in_h), wend = std::min(wend, in_w); auto max_val = std::numeric_limits<float>::lowest(), sum_val = 0.f; for (int ph = hstart; ph < hend; ++ph) { for (int pw = wstart; pw < wend; ++pw) { auto value = in_data[ph * in_w + pw]; max_val = std::max(max_val, value); sum_val += value; } } *out_data++ = (pool_type == 0) ? max_val : sum_val / pool_size; } } } } } template <> void Pooling3D<DeviceType::kCPU, float>( const float* in_data, const VecInt& in_shape, int pool_type, int kernel_size_d, int kernel_size_h, int kernel_size_w, int stride_d, int stride_h, int stride_w, int pad_d, int pad_h, int pad_w, const VecInt& out_shape, float* out_data, Context* context) { int batch = in_shape[0], channel = in_shape[1]; int in_d = in_shape[2], in_h = in_shape[3], in_w = in_shape[4]; int out_d = out_shape[2], out_h = out_shape[3], out_w = out_shape[4]; for (int b = 0; b < batch; ++b) { for (int c = 0; c < channel; ++c, in_data += in_d * in_h * in_w) { for (int d = 0; d < out_d; ++d) { for (int h = 0; h < out_h; ++h) { for (int w = 0; w < out_w; ++w) { int dstart = d * stride_d - pad_d; int hstart = h * stride_h - pad_h; int wstart = w * stride_w - pad_w; int dend = std::min(dstart + kernel_size_d, in_d + pad_d); int hend = std::min(hstart + kernel_size_h, in_h + pad_h); int wend = std::min(wstart + kernel_size_w, in_w + pad_w); int pool_size = (dend - dstart) * (hend - hstart) * (wend - wstart); dstart = std::max(dstart, 0), hstart = std::max(hstart, 0), wstart = std::max(wstart, 0); dend = std::min(dend, in_d), hend = std::min(hend, in_h), wend = std::min(wend, in_w); auto max_val = std::numeric_limits<float>::lowest(), sum_val = 0.f; for (int pd = dstart; pd < dend; ++pd) { for (int ph = hstart; ph < hend; ++ph) { for (int pw = wstart; pw < wend; ++pw) { auto value = in_data[(pd * in_h + ph) * in_w + pw]; max_val = std::max(max_val, value); sum_val += value; } } } *out_data++ = (pool_type == 0) ? max_val : sum_val / pool_size; } } } } } } } // namespace Vision } // namespace Shadow namespace Shadow { REGISTER_OP_KERNEL_DEFAULT(PoolingCPU, PoolingKernelDefault<DeviceType::kCPU>); #if defined(USE_DNNL) class PoolingKernelDNNL : public PoolingKernel { public: PoolingKernelDNNL() { default_kernel_ = std::make_shared<PoolingKernelDefault<DeviceType::kCPU>>(); } void Run(const std::shared_ptr<Blob>& input, std::shared_ptr<Blob>& output, Workspace* ws, int pool_type, int kernel_size_h, int kernel_size_w, int stride_h, int stride_w, int pad_h, int pad_w, bool full_pooling) override { if (full_pooling) { default_kernel_->Run(input, output, ws, pool_type, kernel_size_h, kernel_size_w, stride_h, stride_w, pad_h, pad_w, full_pooling); } else { const auto& src_desc = idnnl::create_memory_desc<float>( input->shape(), dnnl::memory::format_tag::nchw); const auto& dst_desc = idnnl::create_memory_desc<float>( output->shape(), dnnl::memory::format_tag::nchw); idnnl::common_forward<dnnl::pooling_forward>( ws->Ctx()->dnnl_handle(), dnnl::pooling_forward::desc( dnnl::prop_kind::forward_inference, get_algorithm(pool_type), src_desc, dst_desc, {stride_h, stride_w}, {kernel_size_h, kernel_size_w}, {pad_h, pad_w}, {pad_h, pad_w}), input->data<float>(), output->mutable_data<float>()); } } void Run(const std::shared_ptr<Blob>& input, std::shared_ptr<Blob>& output, Workspace* ws, int pool_type, int kernel_size_d, int kernel_size_h, int kernel_size_w, int stride_d, int stride_h, int stride_w, int pad_d, int pad_h, int pad_w, bool full_pooling) override { if (full_pooling) { default_kernel_->Run(input, output, ws, pool_type, kernel_size_d, kernel_size_h, kernel_size_w, stride_d, stride_h, stride_w, pad_d, pad_h, pad_w, full_pooling); } else { const auto& src_desc = idnnl::create_memory_desc<float>( input->shape(), dnnl::memory::format_tag::ncdhw); const auto& dst_desc = idnnl::create_memory_desc<float>( output->shape(), dnnl::memory::format_tag::ncdhw); idnnl::common_forward<dnnl::pooling_forward>( ws->Ctx()->dnnl_handle(), dnnl::pooling_forward::desc( dnnl::prop_kind::forward_inference, get_algorithm(pool_type), src_desc, dst_desc, {stride_d, stride_h, stride_w}, {kernel_size_d, kernel_size_h, kernel_size_w}, {pad_d, pad_h, pad_w}, {pad_d, pad_h, pad_w}), input->data<float>(), output->mutable_data<float>()); } } DeviceType device_type() const override { return DeviceType::kCPU; } std::string kernel_type() const override { return "DNNL"; } private: static dnnl::algorithm get_algorithm(int pool_type) { switch (pool_type) { case 0: return dnnl::algorithm::pooling_max; case 1: return dnnl::algorithm::pooling_avg_include_padding; default: return dnnl::algorithm::undef; } } std::shared_ptr<PoolingKernelDefault<DeviceType::kCPU>> default_kernel_ = nullptr; }; REGISTER_OP_KERNEL_DNNL(PoolingCPU, PoolingKernelDNNL); #endif } // namespace Shadow
40.022599
80
0.571429
junluan
d1069101a8af09186c744a8c372719a30d026858
13,059
cpp
C++
NanoTest/Source/Nano/Types/TRange.cpp
refnum/Nano
dceb0907061f7845d8a3c662f309ca164e932e6f
[ "BSD-3-Clause" ]
23
2019-11-12T09:31:11.000Z
2021-09-13T08:59:37.000Z
NanoTest/Source/Nano/Types/TRange.cpp
refnum/nano
dceb0907061f7845d8a3c662f309ca164e932e6f
[ "BSD-3-Clause" ]
1
2020-10-30T09:54:12.000Z
2020-10-30T09:54:12.000Z
NanoTest/Source/Nano/Types/TRange.cpp
refnum/Nano
dceb0907061f7845d8a3c662f309ca164e932e6f
[ "BSD-3-Clause" ]
3
2015-09-08T11:00:02.000Z
2017-09-11T05:42:30.000Z
/* NAME: TRange.cpp DESCRIPTION: NRange tests. COPYRIGHT: Copyright (c) 2006-2021, refNum Software All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ___________________________________________________________________________ */ //============================================================================= // Includes //----------------------------------------------------------------------------- // Nano #include "NFormat.h" #include "NRange.h" #include "NTestFixture.h" //============================================================================= // Internal Constants //----------------------------------------------------------------------------- static const NRange kTestRange1{0, 5}; static const NRange kTestRange2{3, 7}; static const NRange kTestRange3{3, 4}; //============================================================================= // Fixture //----------------------------------------------------------------------------- NANO_FIXTURE(TRange) { NRange theRange; }; //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "Default") { // Perform the test REQUIRE(theRange.GetLocation() == 0); REQUIRE(theRange.GetSize() == 0); REQUIRE(kNRangeNone.GetLocation() == kNNotFound); REQUIRE(kNRangeNone.GetSize() == 0); REQUIRE(kNRangeAll.GetLocation() == 0); REQUIRE(kNRangeAll.GetSize() == kNNotFound); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "Intersects") { // Perform the test REQUIRE(NRange(4, 3).Intersects(NRange(6, 2))); // 456 ~ 67 = true (after) REQUIRE(!NRange(4, 3).Intersects(NRange(8, 2))); // 456 ~ 89 = false (after gap) REQUIRE(NRange(4, 3).Intersects(NRange(3, 2))); // 456 ~ 34 = true (before) REQUIRE(!NRange(4, 3).Intersects(NRange(1, 2))); // 456 ~ 12 = false (before gap) REQUIRE(!NRange(4, 3).Intersects(NRange(0, 0))); // 456 ~ . = false (empty) REQUIRE(!NRange(4, 3).Intersects(NRange(3, 0))); // 456 ~ . = false (empty) } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "Contains") { // Perform the test REQUIRE(!NRange(4, 3).Contains(3)); // 456 ~ 3 = false (before) REQUIRE(NRange(4, 3).Contains(4)); // 456 ~ 4 = true (first) REQUIRE(NRange(4, 3).Contains(5)); // 456 ~ 5 = true (inside) REQUIRE(NRange(4, 3).Contains(6)); // 456 ~ 6 = true (last) REQUIRE(!NRange(4, 3).Contains(7)); // 456 ~ 7 = false (after) REQUIRE(!NRange(4, 0).Contains(3)); // . ~ 3 = false (never) REQUIRE(!NRange(4, 0).Contains(4)); // . ~ 4 = false (never) REQUIRE(!NRange(4, 0).Contains(5)); // . ~ 5 = false (never) } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "IsMeta") { // Perform the test REQUIRE(!kTestRange1.IsMeta()); REQUIRE(!kTestRange2.IsMeta()); REQUIRE(kNRangeNone.IsMeta()); REQUIRE(kNRangeAll.IsMeta()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "IsEmpty") { // Perform the test REQUIRE(kNRangeNone.IsEmpty()); REQUIRE(!NRange(4, 3).IsEmpty()); REQUIRE(NRange(4, 0).IsEmpty()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "GetLocation") { // Perform the test theRange = kTestRange1; REQUIRE(theRange.GetLocation() == kTestRange1.GetLocation()); theRange.SetLocation(theRange.GetLocation() + 1); REQUIRE(theRange.GetLocation() != kTestRange1.GetLocation()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "AddOffset") { // Perform the test theRange.SetRange(0, 3); theRange.AddOffset(0); REQUIRE(theRange == NRange(0, 3)); theRange.SetRange(0, 3); theRange.AddOffset(1); REQUIRE(theRange == NRange(1, 3)); theRange.SetRange(0, 3); theRange.AddOffset(2); REQUIRE(theRange == NRange(2, 3)); theRange.SetRange(1, 3); theRange.AddOffset(0); REQUIRE(theRange == NRange(1, 3)); theRange.SetRange(2, 3); theRange.AddOffset(1); REQUIRE(theRange == NRange(3, 3)); theRange.SetRange(3, 3); theRange.AddOffset(2); REQUIRE(theRange == NRange(5, 3)); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "GetSize") { // Perform the test theRange = kTestRange1; REQUIRE(theRange.GetSize() == kTestRange1.GetSize()); theRange.SetSize(theRange.GetSize() + 1); REQUIRE(theRange.GetSize() != kTestRange1.GetSize()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "Contents") { // Perform the test REQUIRE(kTestRange1.GetLocation() == 0); REQUIRE(kTestRange1.GetSize() == 5); REQUIRE(kTestRange1.GetPosition(0) == kTestRange1.GetFirst()); REQUIRE(kTestRange1.GetPosition(1) == kTestRange1.GetFirst() + 1); REQUIRE(kTestRange1.GetPosition(2) == kTestRange1.GetFirst() + 2); REQUIRE(kTestRange1.GetFirst() == 0); REQUIRE(kTestRange1.GetLast() == 4); REQUIRE(kTestRange1.GetNext() == 5); // Perform the test REQUIRE(kTestRange2.GetLocation() == 3); REQUIRE(kTestRange2.GetSize() == 7); REQUIRE(kTestRange2.GetPosition(0) == kTestRange2.GetFirst()); REQUIRE(kTestRange2.GetPosition(1) == kTestRange2.GetFirst() + 1); REQUIRE(kTestRange2.GetPosition(2) == kTestRange2.GetFirst() + 2); REQUIRE(kTestRange2.GetFirst() == 3); REQUIRE(kTestRange2.GetLast() == 9); REQUIRE(kTestRange2.GetNext() == 10); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "GetOffset") { // Perform the test REQUIRE(NRange(0, 3).GetOffset(0) == NRange(0, 3)); REQUIRE(NRange(0, 3).GetOffset(1) == NRange(1, 3)); REQUIRE(NRange(0, 3).GetOffset(2) == NRange(2, 3)); REQUIRE(NRange(1, 3).GetOffset(0) == NRange(1, 3)); REQUIRE(NRange(2, 3).GetOffset(1) == NRange(3, 3)); REQUIRE(NRange(3, 3).GetOffset(2) == NRange(5, 3)); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "GetUnion") { // Perform the test REQUIRE(NRange(4, 3).GetUnion(NRange(6, 2)) == NRange(4, 4)); // 456 + 67 = 4567 (after) REQUIRE(NRange(4, 3).GetUnion(NRange(8, 2)) == NRange(4, 6)); // 456 + 89 = 456789 (after gap) REQUIRE(NRange(4, 3).GetUnion(NRange(3, 2)) == NRange(3, 4)); // 456 + 34 = 3456 (before) REQUIRE(NRange(4, 3).GetUnion(NRange(1, 2)) == NRange(1, 6)); // 456 + 12 = 123456 (before gap) REQUIRE(NRange(4, 3).GetUnion(NRange(0, 0)) == NRange(4, 3)); // 456 + . = 456 (empty) REQUIRE(NRange(4, 3).GetUnion(NRange(3, 0)) == NRange(4, 3)); // 456 + . = 456 (empty) } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "GetIntersection") { // Perform the test REQUIRE(NRange(4, 3).GetIntersection(NRange(6, 2)) == NRange(6, 1)); // 456 ~ 67 = 6 (end) REQUIRE(NRange(4, 3).GetIntersection(NRange(8, 2)) == NRange(0, 0)); // 456 ~ 89 = . (after) REQUIRE(NRange(4, 3).GetIntersection(NRange(3, 2)) == NRange(4, 1)); // 456 ~ 34 = 4 (start) REQUIRE(NRange(4, 3).GetIntersection(NRange(1, 2)) == NRange(0, 0)); // 456 ~ 12 = . (before) REQUIRE(NRange(4, 3).GetIntersection(NRange(5, 1)) == NRange(5, 1)); // 456 ~ 5 = 5 (inside) REQUIRE(NRange(4, 3).GetIntersection(NRange(3, 5)) == NRange(4, 3)); // 456 ~ 34567 = 456 (within) REQUIRE(NRange(4, 3).GetIntersection(NRange(1, 0)) == NRange(0, 0)); // 456 ~ . = . (empty) REQUIRE(NRange(0, 0).GetIntersection(NRange(1, 2)) == NRange(0, 0)); // . ~ 12 = . (empty) REQUIRE(NRange(4, 0).GetIntersection(NRange(1, 0)) == NRange(0, 0)); // . ~ . = . (empty) } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "GetNormalized") { // Perform the test theRange = kNRangeNone.GetNormalized(10); REQUIRE((theRange.GetLocation() == 0 && theRange.GetSize() == 0)); // Meta (none) theRange = kNRangeAll.GetNormalized(10); REQUIRE((theRange.GetLocation() == 0 && theRange.GetSize() == 10)); // Meta (all) theRange = NRange(3, 7).GetNormalized(10); REQUIRE( (theRange.GetLocation() == 3 && theRange.GetSize() == 7)); // Within (non-zero length) theRange = NRange(3, 9).GetNormalized(10); REQUIRE((theRange.GetLocation() == 3 && theRange.GetSize() == 7)); // Within (clamped length) theRange = NRange(3, 0).GetNormalized(10); REQUIRE((theRange.GetLocation() == 3 && theRange.GetSize() == 0)); // Within (zero length) theRange = NRange(30, 7).GetNormalized(10); REQUIRE( (theRange.GetLocation() == 30 && theRange.GetSize() == 0)); // Outside (non-zero length) theRange = NRange(30, 0).GetNormalized(0); REQUIRE((theRange.GetLocation() == 30 && theRange.GetSize() == 0)); // Outside (zero length) } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "CompareEqual") { // Perform the test REQUIRE(kTestRange1 == kTestRange1); REQUIRE(kTestRange1 != kTestRange2); REQUIRE(kNRangeNone == kNRangeNone); REQUIRE(kNRangeNone != kNRangeAll); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "CompareOrder") { // Perform the test REQUIRE(kTestRange1 <= kTestRange1); REQUIRE(kTestRange1 < kTestRange2); REQUIRE(kTestRange1 < kTestRange3); REQUIRE(kTestRange2 > kTestRange1); REQUIRE(kTestRange2 >= kTestRange2); REQUIRE(kTestRange2 > kTestRange3); REQUIRE(kTestRange3 > kTestRange1); REQUIRE(kTestRange3 < kTestRange2); REQUIRE(kTestRange3 >= kTestRange3); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TRange, "Format") { // Perform the test REQUIRE(NFormat("{}", kTestRange1) == "{location = 0, size = 5}"); REQUIRE(NFormat("{}", kTestRange2) == "{location = 3, size = 7}"); REQUIRE(NFormat("{}", kTestRange3) == "{location = 3, size = 4}"); }
28.575492
97
0.50402
refnum
d10ae5fba69de104b27f9d9f39f7a59fa0c850af
27,033
cpp
C++
soundlib/tuning.cpp
sitomani/openmpt
913396209c22a1fc6dfb29f0e34893dfb0ffa591
[ "BSD-3-Clause" ]
null
null
null
soundlib/tuning.cpp
sitomani/openmpt
913396209c22a1fc6dfb29f0e34893dfb0ffa591
[ "BSD-3-Clause" ]
null
null
null
soundlib/tuning.cpp
sitomani/openmpt
913396209c22a1fc6dfb29f0e34893dfb0ffa591
[ "BSD-3-Clause" ]
null
null
null
/* * tuning.cpp * ---------- * Purpose: Alternative sample tuning. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "tuning.h" #include "../common/mptIO.h" #include "../common/serialization_utils.h" #include "../common/misc_util.h" #include <string> #include <cmath> OPENMPT_NAMESPACE_BEGIN namespace Tuning { namespace CTuningS11n { void ReadStr(std::istream &iStrm, mpt::ustring &ustr, const std::size_t dummy, mpt::Charset charset); void ReadNoteMap(std::istream &iStrm, std::map<NOTEINDEXTYPE, mpt::ustring> &m, const std::size_t dummy, mpt::Charset charset); void ReadRatioTable(std::istream& iStrm, std::vector<RATIOTYPE>& v, const size_t); void WriteNoteMap(std::ostream &oStrm, const std::map<NOTEINDEXTYPE, mpt::ustring> &m); void WriteStr(std::ostream &oStrm, const mpt::ustring &ustr); struct RatioWriter { RatioWriter(uint16 nWriteCount = s_nDefaultWriteCount) : m_nWriteCount(nWriteCount) {} void operator()(std::ostream& oStrm, const std::vector<float>& v); uint16 m_nWriteCount; enum : uint16 { s_nDefaultWriteCount = (uint16_max >> 2) }; }; } using namespace CTuningS11n; /* Version history: 4->5: Lots of changes, finestep interpretation revamp, fileformat revamp. 3->4: Changed sizetypes in serialisation from size_t(uint32) to smaller types (uint8, USTEPTYPE) (March 2007) */ /* Version changes: 3->4: Finetune related internal structure and serialization revamp. 2->3: The type for the size_type in the serialisation changed from default(size_t, uint32) to unsigned STEPTYPE. (March 2007) */ static_assert(CTuning::s_RatioTableFineSizeMaxDefault < static_cast<USTEPINDEXTYPE>(FINESTEPCOUNT_MAX)); CTuning::CTuning() : m_TuningType(Type::GENERAL) , m_FineStepCount(0) { m_RatioTable.clear(); m_NoteMin = s_NoteMinDefault; m_RatioTable.resize(s_RatioTableSizeDefault, 1); m_GroupSize = 0; m_GroupRatio = 0; m_RatioTableFine.clear(); } bool CTuning::CreateGroupGeometric(const NOTEINDEXTYPE &s, const RATIOTYPE &r, const NOTEINDEXTYPE &startindex) { if(s < 1 || !IsValidRatio(r) || startindex < GetNoteRange().first) { return false; } std::vector<RATIOTYPE> v; v.reserve(s); for(NOTEINDEXTYPE i = startindex; i < startindex + s; i++) { v.push_back(GetRatio(i)); } return CreateGroupGeometric(v, r, GetNoteRange(), startindex); } bool CTuning::CreateGroupGeometric(const std::vector<RATIOTYPE> &v, const RATIOTYPE &r, const NoteRange &range, const NOTEINDEXTYPE &ratiostartpos) { if(range.first > range.last || v.size() == 0) { return false; } if(ratiostartpos < range.first || range.last < ratiostartpos || static_cast<UNOTEINDEXTYPE>(range.last - ratiostartpos) < static_cast<UNOTEINDEXTYPE>(v.size() - 1)) { return false; } if(GetFineStepCount() > FINESTEPCOUNT_MAX) { return false; } for(size_t i = 0; i < v.size(); i++) { if(v[i] < 0) { return false; } } if(r <= 0) { return false; } m_TuningType = Type::GROUPGEOMETRIC; m_NoteMin = range.first; m_GroupSize = mpt::saturate_cast<NOTEINDEXTYPE>(v.size()); m_GroupRatio = std::fabs(r); m_RatioTable.resize(range.last - range.first + 1); std::copy(v.begin(), v.end(), m_RatioTable.begin() + (ratiostartpos - range.first)); for(int32 i = ratiostartpos - 1; i >= m_NoteMin && ratiostartpos > NOTEINDEXTYPE_MIN; i--) { m_RatioTable[i - m_NoteMin] = m_RatioTable[i - m_NoteMin + m_GroupSize] / m_GroupRatio; } for(int32 i = ratiostartpos + m_GroupSize; i <= range.last && ratiostartpos <= (NOTEINDEXTYPE_MAX - m_GroupSize); i++) { m_RatioTable[i - m_NoteMin] = m_GroupRatio * m_RatioTable[i - m_NoteMin - m_GroupSize]; } UpdateFineStepTable(); return true; } bool CTuning::CreateGeometric(const UNOTEINDEXTYPE &p, const RATIOTYPE &r) { return CreateGeometric(p, r, GetNoteRange()); } bool CTuning::CreateGeometric(const UNOTEINDEXTYPE &s, const RATIOTYPE &r, const NoteRange &range) { if(range.first > range.last) { return false; } if(s < 1 || !IsValidRatio(r)) { return false; } if(range.last - range.first + 1 > NOTEINDEXTYPE_MAX) { return false; } m_TuningType = Type::GEOMETRIC; m_RatioTable.clear(); m_NoteMin = s_NoteMinDefault; m_RatioTable.resize(s_RatioTableSizeDefault, static_cast<RATIOTYPE>(1.0)); m_GroupSize = 0; m_GroupRatio = 0; m_RatioTableFine.clear(); m_NoteMin = range.first; m_GroupSize = mpt::saturate_cast<NOTEINDEXTYPE>(s); m_GroupRatio = std::fabs(r); const RATIOTYPE stepRatio = std::pow(m_GroupRatio, static_cast<RATIOTYPE>(1.0) / static_cast<RATIOTYPE>(m_GroupSize)); m_RatioTable.resize(range.last - range.first + 1); for(int32 i = range.first; i <= range.last; i++) { m_RatioTable[i - m_NoteMin] = std::pow(stepRatio, static_cast<RATIOTYPE>(i)); } UpdateFineStepTable(); return true; } mpt::ustring CTuning::GetNoteName(const NOTEINDEXTYPE &x, bool addOctave) const { if(!IsValidNote(x)) { return mpt::ustring(); } if(GetGroupSize() < 1) { const auto i = m_NoteNameMap.find(x); if(i != m_NoteNameMap.end()) return i->second; else return mpt::ufmt::val(x); } else { const NOTEINDEXTYPE pos = static_cast<NOTEINDEXTYPE>(mpt::wrapping_modulo(x, m_GroupSize)); const NOTEINDEXTYPE middlePeriodNumber = 5; mpt::ustring rValue; const auto nmi = m_NoteNameMap.find(pos); if(nmi != m_NoteNameMap.end()) { rValue = nmi->second; if(addOctave) { rValue += mpt::ufmt::val(middlePeriodNumber + mpt::wrapping_divide(x, m_GroupSize)); } } else { //By default, using notation nnP for notes; nn <-> note character starting //from 'A' with char ':' as fill char, and P is period integer. For example: //C:5, D:3, R:7 if(m_GroupSize <= 26) { rValue = mpt::ToUnicode(mpt::Charset::UTF8, std::string(1, static_cast<char>(pos + 'A'))); rValue += UL_(":"); } else { rValue = mpt::ufmt::HEX0<1>(pos % 16) + mpt::ufmt::HEX0<1>((pos / 16) % 16); if(pos > 0xff) { rValue = mpt::ToUnicode(mpt::Charset::UTF8, mpt::ToLowerCaseAscii(mpt::ToCharset(mpt::Charset::UTF8, rValue))); } } if(addOctave) { rValue += mpt::ufmt::val(middlePeriodNumber + mpt::wrapping_divide(x, m_GroupSize)); } } return rValue; } } void CTuning::SetNoteName(const NOTEINDEXTYPE &n, const mpt::ustring &str) { const NOTEINDEXTYPE pos = (GetGroupSize() < 1) ? n : static_cast<NOTEINDEXTYPE>(mpt::wrapping_modulo(n, m_GroupSize)); if(!str.empty()) { m_NoteNameMap[pos] = str; } else { const auto iter = m_NoteNameMap.find(pos); if(iter != m_NoteNameMap.end()) { m_NoteNameMap.erase(iter); } } } // Without finetune RATIOTYPE CTuning::GetRatio(const NOTEINDEXTYPE note) const { if(!IsValidNote(note)) { return s_DefaultFallbackRatio; } return m_RatioTable[note - m_NoteMin]; } // With finetune RATIOTYPE CTuning::GetRatio(const NOTEINDEXTYPE baseNote, const STEPINDEXTYPE baseFineSteps) const { const STEPINDEXTYPE fineStepCount = static_cast<STEPINDEXTYPE>(GetFineStepCount()); if(fineStepCount == 0 || baseFineSteps == 0) { return GetRatio(static_cast<NOTEINDEXTYPE>(baseNote + baseFineSteps)); } // If baseFineSteps is more than the number of finesteps between notes, note is increased. // So first figuring out what note and fineStep values to actually use. // Interpreting finestep==-1 on note x so that it is the same as finestep==fineStepCount on note x-1. // Note: If fineStepCount is n, n+1 steps are needed to get to next note. const NOTEINDEXTYPE note = static_cast<NOTEINDEXTYPE>(baseNote + mpt::wrapping_divide(baseFineSteps, (fineStepCount + 1))); const STEPINDEXTYPE fineStep = mpt::wrapping_modulo(baseFineSteps, (fineStepCount + 1)); if(!IsValidNote(note)) { return s_DefaultFallbackRatio; } if(fineStep == 0) { return m_RatioTable[note - m_NoteMin]; } RATIOTYPE fineRatio = static_cast<RATIOTYPE>(1.0); if(GetType() == Type::GEOMETRIC && m_RatioTableFine.size() > 0) { fineRatio = m_RatioTableFine[fineStep - 1]; } else if(GetType() == Type::GROUPGEOMETRIC && m_RatioTableFine.size() > 0) { fineRatio = m_RatioTableFine[GetRefNote(note) * fineStepCount + fineStep - 1]; } else { // Geometric finestepping fineRatio = std::pow(GetRatio(note + 1) / GetRatio(note), static_cast<RATIOTYPE>(fineStep) / (fineStepCount + 1)); } return m_RatioTable[note - m_NoteMin] * fineRatio; } bool CTuning::SetRatio(const NOTEINDEXTYPE& s, const RATIOTYPE& r) { if(GetType() != Type::GROUPGEOMETRIC && GetType() != Type::GENERAL) { return false; } //Creating ratio table if doesn't exist. if(m_RatioTable.empty()) { m_RatioTable.assign(s_RatioTableSizeDefault, 1); m_NoteMin = s_NoteMinDefault; } if(!IsValidNote(s)) { return false; } m_RatioTable[s - m_NoteMin] = std::fabs(r); if(GetType() == Type::GROUPGEOMETRIC) { // update other groups for(NOTEINDEXTYPE n = m_NoteMin; n < m_NoteMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n) { if(n == s) { // nothing } else if(std::abs(n - s) % m_GroupSize == 0) { m_RatioTable[n - m_NoteMin] = std::pow(m_GroupRatio, static_cast<RATIOTYPE>(n - s) / static_cast<RATIOTYPE>(m_GroupSize)) * m_RatioTable[s - m_NoteMin]; } } UpdateFineStepTable(); } return true; } void CTuning::SetFineStepCount(const USTEPINDEXTYPE& fs) { m_FineStepCount = std::clamp(mpt::saturate_cast<STEPINDEXTYPE>(fs), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX); UpdateFineStepTable(); } void CTuning::UpdateFineStepTable() { if(m_FineStepCount <= 0) { m_RatioTableFine.clear(); return; } if(GetType() == Type::GEOMETRIC) { if(m_FineStepCount > s_RatioTableFineSizeMaxDefault) { m_RatioTableFine.clear(); return; } m_RatioTableFine.resize(m_FineStepCount); const RATIOTYPE q = GetRatio(GetNoteRange().first + 1) / GetRatio(GetNoteRange().first); const RATIOTYPE rFineStep = std::pow(q, static_cast<RATIOTYPE>(1)/(m_FineStepCount+1)); for(USTEPINDEXTYPE i = 1; i<=m_FineStepCount; i++) m_RatioTableFine[i-1] = std::pow(rFineStep, static_cast<RATIOTYPE>(i)); return; } if(GetType() == Type::GROUPGEOMETRIC) { const UNOTEINDEXTYPE p = GetGroupSize(); if(p > s_RatioTableFineSizeMaxDefault / m_FineStepCount) { //In case fineratiotable would become too large, not using //table for it. m_RatioTableFine.clear(); return; } else { //Creating 'geometric' finestepping between notes. m_RatioTableFine.resize(p * m_FineStepCount); const NOTEINDEXTYPE startnote = GetRefNote(GetNoteRange().first); for(UNOTEINDEXTYPE i = 0; i<p; i++) { const NOTEINDEXTYPE refnote = GetRefNote(startnote+i); const RATIOTYPE rFineStep = std::pow(GetRatio(refnote+1) / GetRatio(refnote), static_cast<RATIOTYPE>(1)/(m_FineStepCount+1)); for(UNOTEINDEXTYPE j = 1; j<=m_FineStepCount; j++) { m_RatioTableFine[m_FineStepCount * refnote + (j-1)] = std::pow(rFineStep, static_cast<RATIOTYPE>(j)); } } return; } } if(GetType() == Type::GENERAL) { //Not using table with tuning of type general. m_RatioTableFine.clear(); return; } //Should not reach here. m_RatioTableFine.clear(); m_FineStepCount = 0; } bool CTuning::Multiply(const RATIOTYPE r) { if(!IsValidRatio(r)) { return false; } for(auto & ratio : m_RatioTable) { ratio *= r; } return true; } bool CTuning::ChangeGroupsize(const NOTEINDEXTYPE& s) { if(s < 1) return false; if(m_TuningType == Type::GROUPGEOMETRIC) return CreateGroupGeometric(s, GetGroupRatio(), 0); if(m_TuningType == Type::GEOMETRIC) return CreateGeometric(s, GetGroupRatio()); return false; } bool CTuning::ChangeGroupRatio(const RATIOTYPE& r) { if(!IsValidRatio(r)) return false; if(m_TuningType == Type::GROUPGEOMETRIC) return CreateGroupGeometric(GetGroupSize(), r, 0); if(m_TuningType == Type::GEOMETRIC) return CreateGeometric(GetGroupSize(), r); return false; } SerializationResult CTuning::InitDeserialize(std::istream &iStrm, mpt::Charset defaultCharset) { // Note: OpenMPT since at least r323 writes version number (4<<24)+4 while it // reads version number (5<<24)+4 or earlier. // We keep this behaviour. if(iStrm.fail()) return SerializationResult::Failure; srlztn::SsbRead ssb(iStrm); ssb.BeginRead("CTB244RTI", (5 << 24) + 4); // version int8 use_utf8 = 0; ssb.ReadItem(use_utf8, "UTF8"); const mpt::Charset charset = use_utf8 ? mpt::Charset::UTF8 : defaultCharset; ssb.ReadItem(m_TuningName, "0", [charset](std::istream &iStrm, mpt::ustring &ustr, const std::size_t dummy){ return ReadStr(iStrm, ustr, dummy, charset); }); uint16 dummyEditMask = 0xffff; ssb.ReadItem(dummyEditMask, "1"); std::underlying_type<Type>::type type = 0; ssb.ReadItem(type, "2"); m_TuningType = static_cast<Type>(type); ssb.ReadItem(m_NoteNameMap, "3", [charset](std::istream &iStrm, std::map<NOTEINDEXTYPE, mpt::ustring> &m, const std::size_t dummy){ return ReadNoteMap(iStrm, m, dummy, charset); }); ssb.ReadItem(m_FineStepCount, "4"); // RTI entries. ssb.ReadItem(m_RatioTable, "RTI0", ReadRatioTable); ssb.ReadItem(m_NoteMin, "RTI1"); ssb.ReadItem(m_GroupSize, "RTI2"); ssb.ReadItem(m_GroupRatio, "RTI3"); UNOTEINDEXTYPE ratiotableSize = 0; ssb.ReadItem(ratiotableSize, "RTI4"); // If reader status is ok and m_NoteMin is somewhat reasonable, process data. if(!((ssb.GetStatus() & srlztn::SNT_FAILURE) == 0 && m_NoteMin >= -300 && m_NoteMin <= 300)) { return SerializationResult::Failure; } // reject unknown types if(m_TuningType != Type::GENERAL && m_TuningType != Type::GROUPGEOMETRIC && m_TuningType != Type::GEOMETRIC) { return SerializationResult::Failure; } if(m_GroupSize < 0) { return SerializationResult::Failure; } m_FineStepCount = std::clamp(mpt::saturate_cast<STEPINDEXTYPE>(m_FineStepCount), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX); if(m_RatioTable.size() > static_cast<size_t>(NOTEINDEXTYPE_MAX)) { return SerializationResult::Failure; } if((GetType() == Type::GROUPGEOMETRIC) || (GetType() == Type::GEOMETRIC)) { if(ratiotableSize < 1 || ratiotableSize > NOTEINDEXTYPE_MAX) { return SerializationResult::Failure; } if(GetType() == Type::GEOMETRIC) { if(!CreateGeometric(GetGroupSize(), GetGroupRatio(), NoteRange{m_NoteMin, static_cast<NOTEINDEXTYPE>(m_NoteMin + ratiotableSize - 1)})) { return SerializationResult::Failure; } } else { if(!CreateGroupGeometric(m_RatioTable, GetGroupRatio(), NoteRange{m_NoteMin, static_cast<NOTEINDEXTYPE>(m_NoteMin + ratiotableSize - 1)}, m_NoteMin)) { return SerializationResult::Failure; } } } else { UpdateFineStepTable(); } return SerializationResult::Success; } template<class T, class SIZETYPE, class Tdst> static bool VectorFromBinaryStream(std::istream& inStrm, std::vector<Tdst>& v, const SIZETYPE maxSize = (std::numeric_limits<SIZETYPE>::max)()) { if(!inStrm.good()) return false; SIZETYPE size = 0; mpt::IO::ReadIntLE<SIZETYPE>(inStrm, size); if(size > maxSize) return false; v.resize(size); for(std::size_t i = 0; i<size; i++) { T tmp = T(); mpt::IO::Read(inStrm, tmp); v[i] = tmp; } return inStrm.good(); } SerializationResult CTuning::InitDeserializeOLD(std::istream &inStrm, mpt::Charset defaultCharset) { if(!inStrm.good()) return SerializationResult::Failure; const std::streamoff startPos = inStrm.tellg(); //First checking is there expected begin sequence. char begin[8]; MemsetZero(begin); inStrm.read(begin, sizeof(begin)); if(std::memcmp(begin, "CTRTI_B.", 8)) { //Returning stream position if beginmarker was not found. inStrm.seekg(startPos); return SerializationResult::Failure; } //Version int16 version = 0; mpt::IO::ReadIntLE<int16>(inStrm, version); if(version != 2 && version != 3) return SerializationResult::Failure; char begin2[8]; MemsetZero(begin2); inStrm.read(begin2, sizeof(begin2)); if(std::memcmp(begin2, "CT<sfs>B", 8)) { return SerializationResult::Failure; } int16 version2 = 0; mpt::IO::ReadIntLE<int16>(inStrm, version2); if(version2 != 3 && version2 != 4) { return SerializationResult::Failure; } //Tuning name if(version2 <= 3) { std::string tmpName; if(!mpt::IO::ReadSizedStringLE<uint32>(inStrm, tmpName, 0xffff)) { return SerializationResult::Failure; } m_TuningName = mpt::ToUnicode(defaultCharset, tmpName); } else { std::string tmpName; if(!mpt::IO::ReadSizedStringLE<uint8>(inStrm, tmpName)) { return SerializationResult::Failure; } m_TuningName = mpt::ToUnicode(defaultCharset, tmpName); } //Const mask int16 em = 0; mpt::IO::ReadIntLE<int16>(inStrm, em); //Tuning type int16 tt = 0; mpt::IO::ReadIntLE<int16>(inStrm, tt); m_TuningType = static_cast<Type>(tt); //Notemap uint16 size = 0; if(version2 <= 3) { uint32 tempsize = 0; mpt::IO::ReadIntLE<uint32>(inStrm, tempsize); if(tempsize > 0xffff) { return SerializationResult::Failure; } size = mpt::saturate_cast<uint16>(tempsize); } else { mpt::IO::ReadIntLE<uint16>(inStrm, size); } for(UNOTEINDEXTYPE i = 0; i<size; i++) { std::string str; int16 n = 0; mpt::IO::ReadIntLE<int16>(inStrm, n); if(version2 <= 3) { if(!mpt::IO::ReadSizedStringLE<uint32>(inStrm, str, 0xffff)) { return SerializationResult::Failure; } } else { if(!mpt::IO::ReadSizedStringLE<uint8>(inStrm, str)) { return SerializationResult::Failure; } } m_NoteNameMap[n] = mpt::ToUnicode(defaultCharset, str); } //End marker char end2[8]; MemsetZero(end2); inStrm.read(end2, sizeof(end2)); if(std::memcmp(end2, "CT<sfs>E", 8)) { return SerializationResult::Failure; } // reject unknown types if(m_TuningType != Type::GENERAL && m_TuningType != Type::GROUPGEOMETRIC && m_TuningType != Type::GEOMETRIC) { return SerializationResult::Failure; } //Ratiotable if(version <= 2) { if(!VectorFromBinaryStream<IEEE754binary32LE, uint32>(inStrm, m_RatioTable, 0xffff)) { return SerializationResult::Failure; } } else { if(!VectorFromBinaryStream<IEEE754binary32LE, uint16>(inStrm, m_RatioTable)) { return SerializationResult::Failure; } } //Fineratios if(version <= 2) { if(!VectorFromBinaryStream<IEEE754binary32LE, uint32>(inStrm, m_RatioTableFine, 0xffff)) { return SerializationResult::Failure; } } else { if(!VectorFromBinaryStream<IEEE754binary32LE, uint16>(inStrm, m_RatioTableFine)) { return SerializationResult::Failure; } } m_FineStepCount = mpt::saturate_cast<USTEPINDEXTYPE>(m_RatioTableFine.size()); // m_NoteMin int16 notemin = 0; mpt::IO::ReadIntLE<int16>(inStrm, notemin); m_NoteMin = notemin; if(m_NoteMin < -200 || m_NoteMin > 200) { return SerializationResult::Failure; } //m_GroupSize int16 groupsize = 0; mpt::IO::ReadIntLE<int16>(inStrm, groupsize); m_GroupSize = groupsize; if(m_GroupSize < 0) { return SerializationResult::Failure; } //m_GroupRatio IEEE754binary32LE groupratio = IEEE754binary32LE(0.0f); mpt::IO::Read(inStrm, groupratio); m_GroupRatio = groupratio; if(m_GroupRatio < 0) { return SerializationResult::Failure; } char end[8]; MemsetZero(end); inStrm.read(reinterpret_cast<char*>(&end), sizeof(end)); if(std::memcmp(end, "CTRTI_E.", 8)) { return SerializationResult::Failure; } // reject corrupt tunings if(m_RatioTable.size() > static_cast<std::size_t>(NOTEINDEXTYPE_MAX)) { return SerializationResult::Failure; } if((m_GroupSize <= 0 || m_GroupRatio <= 0) && m_TuningType != Type::GENERAL) { return SerializationResult::Failure; } if(m_TuningType == Type::GROUPGEOMETRIC || m_TuningType == Type::GEOMETRIC) { if(m_RatioTable.size() < static_cast<std::size_t>(m_GroupSize)) { return SerializationResult::Failure; } } // convert old finestepcount if(m_FineStepCount > 0) { m_FineStepCount -= 1; } m_FineStepCount = std::clamp(mpt::saturate_cast<STEPINDEXTYPE>(m_FineStepCount), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX); UpdateFineStepTable(); if(m_TuningType == Type::GEOMETRIC) { // Convert old geometric to new groupgeometric because old geometric tunings // can have ratio(0) != 1.0, which would get lost when saving nowadays. if(mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()) >= m_GroupSize - m_NoteMin) { std::vector<RATIOTYPE> ratios; for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n) { ratios.push_back(m_RatioTable[n - m_NoteMin]); } CreateGroupGeometric(ratios, m_GroupRatio, GetNoteRange(), 0); } } return SerializationResult::Success; } Tuning::SerializationResult CTuning::Serialize(std::ostream& outStrm) const { // Note: OpenMPT since at least r323 writes version number (4<<24)+4 while it // reads version number (5<<24)+4. // We keep this behaviour. srlztn::SsbWrite ssb(outStrm); ssb.BeginWrite("CTB244RTI", (4 << 24) + 4); // version ssb.WriteItem(int8(1), "UTF8"); if (m_TuningName.length() > 0) ssb.WriteItem(m_TuningName, "0", WriteStr); uint16 dummyEditMask = 0xffff; ssb.WriteItem(dummyEditMask, "1"); ssb.WriteItem(static_cast<std::underlying_type<Type>::type>(m_TuningType), "2"); if (m_NoteNameMap.size() > 0) ssb.WriteItem(m_NoteNameMap, "3", WriteNoteMap); if (GetFineStepCount() > 0) ssb.WriteItem(m_FineStepCount, "4"); const Tuning::Type tt = GetType(); if (GetGroupRatio() > 0) ssb.WriteItem(m_GroupRatio, "RTI3"); if (tt == Type::GROUPGEOMETRIC) ssb.WriteItem(m_RatioTable, "RTI0", RatioWriter(GetGroupSize())); if (tt == Type::GENERAL) ssb.WriteItem(m_RatioTable, "RTI0", RatioWriter()); if (tt == Type::GEOMETRIC) ssb.WriteItem(m_GroupSize, "RTI2"); if(tt == Type::GEOMETRIC || tt == Type::GROUPGEOMETRIC) { //For Groupgeometric this data is the number of ratios in ratiotable. UNOTEINDEXTYPE ratiotableSize = static_cast<UNOTEINDEXTYPE>(m_RatioTable.size()); ssb.WriteItem(ratiotableSize, "RTI4"); } // m_NoteMin ssb.WriteItem(m_NoteMin, "RTI1"); ssb.FinishWrite(); return ((ssb.GetStatus() & srlztn::SNT_FAILURE) != 0) ? Tuning::SerializationResult::Failure : Tuning::SerializationResult::Success; } #ifdef MODPLUG_TRACKER bool CTuning::WriteSCL(std::ostream &f, const mpt::PathString &filename) const { mpt::IO::WriteTextCRLF(f, MPT_FORMAT("! {}")(mpt::ToCharset(mpt::Charset::ISO8859_1, (filename.GetFileName() + filename.GetFileExt()).ToUnicode()))); mpt::IO::WriteTextCRLF(f, "!"); std::string name = mpt::ToCharset(mpt::Charset::ISO8859_1, GetName()); for(auto & c : name) { if(static_cast<uint8>(c) < 32) c = ' '; } // remove control characters if(name.length() >= 1 && name[0] == '!') name[0] = '?'; // do not confuse description with comment mpt::IO::WriteTextCRLF(f, name); if(GetType() == Type::GEOMETRIC) { mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {}")(m_GroupSize)); mpt::IO::WriteTextCRLF(f, "!"); for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n) { double ratio = std::pow(static_cast<double>(m_GroupRatio), static_cast<double>(n + 1) / static_cast<double>(m_GroupSize)); double cents = std::log2(ratio) * 1200.0; mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {} ! {}")( mpt::fmt::fix(cents), mpt::ToCharset(mpt::Charset::ISO8859_1, GetNoteName((n + 1) % m_GroupSize, false)) )); } } else if(GetType() == Type::GROUPGEOMETRIC) { mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {}")(m_GroupSize)); mpt::IO::WriteTextCRLF(f, "!"); for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n) { bool last = (n == (m_GroupSize - 1)); double baseratio = static_cast<double>(GetRatio(0)); double ratio = static_cast<double>(last ? m_GroupRatio : GetRatio(n + 1)) / baseratio; double cents = std::log2(ratio) * 1200.0; mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {} ! {}")( mpt::fmt::fix(cents), mpt::ToCharset(mpt::Charset::ISO8859_1, GetNoteName((n + 1) % m_GroupSize, false)) )); } } else if(GetType() == Type::GENERAL) { mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {}")(m_RatioTable.size() + 1)); mpt::IO::WriteTextCRLF(f, "!"); double baseratio = 1.0; for(NOTEINDEXTYPE n = 0; n < mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n) { baseratio = std::min(baseratio, static_cast<double>(m_RatioTable[n])); } for(NOTEINDEXTYPE n = 0; n < mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n) { double ratio = static_cast<double>(m_RatioTable[n]) / baseratio; double cents = std::log2(ratio) * 1200.0; mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {} ! {}")( mpt::fmt::fix(cents), mpt::ToCharset(mpt::Charset::ISO8859_1, GetNoteName(n + m_NoteMin, false)) )); } mpt::IO::WriteTextCRLF(f, MPT_FORMAT(" {} ! {}")( mpt::fmt::val(1), std::string() )); } else { return false; } return true; } #endif namespace CTuningS11n { void RatioWriter::operator()(std::ostream& oStrm, const std::vector<float>& v) { const std::size_t nWriteCount = std::min(v.size(), static_cast<std::size_t>(m_nWriteCount)); mpt::IO::WriteAdaptiveInt64LE(oStrm, nWriteCount); for(size_t i = 0; i < nWriteCount; i++) mpt::IO::Write(oStrm, IEEE754binary32LE(v[i])); } void ReadNoteMap(std::istream &iStrm, std::map<NOTEINDEXTYPE, mpt::ustring> &m, const std::size_t dummy, mpt::Charset charset) { MPT_UNREFERENCED_PARAMETER(dummy); uint64 val; mpt::IO::ReadAdaptiveInt64LE(iStrm, val); LimitMax(val, 256u); // Read 256 at max. for(size_t i = 0; i < val; i++) { int16 key; mpt::IO::ReadIntLE<int16>(iStrm, key); std::string str; mpt::IO::ReadSizedStringLE<uint8>(iStrm, str); m[key] = mpt::ToUnicode(charset, str); } } void ReadRatioTable(std::istream& iStrm, std::vector<RATIOTYPE>& v, const size_t) { uint64 val; mpt::IO::ReadAdaptiveInt64LE(iStrm, val); v.resize(std::min(mpt::saturate_cast<std::size_t>(val), std::size_t(256))); // Read 256 vals at max. for(size_t i = 0; i < v.size(); i++) { IEEE754binary32LE tmp(0.0f); mpt::IO::Read(iStrm, tmp); v[i] = tmp; } } void ReadStr(std::istream &iStrm, mpt::ustring &ustr, const std::size_t dummy, mpt::Charset charset) { MPT_UNREFERENCED_PARAMETER(dummy); std::string str; uint64 val; mpt::IO::ReadAdaptiveInt64LE(iStrm, val); size_t nSize = (val > 255) ? 255 : static_cast<size_t>(val); // Read 255 characters at max. str.clear(); str.resize(nSize); for(size_t i = 0; i < nSize; i++) mpt::IO::ReadIntLE(iStrm, str[i]); if(str.find_first_of('\0') != std::string::npos) { // trim \0 at the end str.resize(str.find_first_of('\0')); } ustr = mpt::ToUnicode(charset, str); } void WriteNoteMap(std::ostream &oStrm, const std::map<NOTEINDEXTYPE, mpt::ustring> &m) { mpt::IO::WriteAdaptiveInt64LE(oStrm, m.size()); for(auto &mi : m) { mpt::IO::WriteIntLE<int16>(oStrm, mi.first); mpt::IO::WriteSizedStringLE<uint8>(oStrm, mpt::ToCharset(mpt::Charset::UTF8, mi.second)); } } void WriteStr(std::ostream &oStrm, const mpt::ustring &ustr) { std::string str = mpt::ToCharset(mpt::Charset::UTF8, ustr); mpt::IO::WriteAdaptiveInt64LE(oStrm, str.size()); oStrm.write(str.c_str(), str.size()); } } // namespace CTuningS11n. } // namespace Tuning OPENMPT_NAMESPACE_END
27.556575
182
0.693449
sitomani
d11a0dafe97ebc1495c91642b9e8c182c6e54f88
916
cpp
C++
TallerProgra/Introduccion/A_HolidayOfEquality.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
TallerProgra/Introduccion/A_HolidayOfEquality.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
TallerProgra/Introduccion/A_HolidayOfEquality.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
/* Pensemos en cuánto va a tener cada persona despues de darles el dinero Como quiero dar lo menos posible, quiero que esta altura sea minima esta altura puede ser la de la persona con mas dinero no puede ser menos porque tendria que quitarle dinero a esta persona y si fuera mayor que esta, involucraría dar más dinero Reto: hazlo con memoria O(1), es decir, sin usar el arreglo */ #include <iostream> using namespace std; int main(){ int n; cin>>n; int welfare[n], maxWelfare; maxWelfare = 0; for(int i = 0; i < n; i++){ cin>>welfare[i]; maxWelfare = max(maxWelfare, welfare[i]); } //calculamos la cantidad de monedas que debemos dar int monedas, totalQueDoy = 0; for(int i = 0; i < n; ++i){ monedas = maxWelfare - welfare[i]; totalQueDoy += monedas; } cout<<totalQueDoy<<"\n"; return 0; }
24.756757
74
0.626638
CaDe27
d11a57104e47857ede1af0d7f2cc5eff68fef707
2,314
cpp
C++
geometry/barycentre_calculator_test.cpp
tinygrox/Principia
49a25646c673dcd84cefbc6295df410fc6d927d5
[ "MIT" ]
565
2015-01-04T21:47:18.000Z
2022-03-22T12:04:58.000Z
geometry/barycentre_calculator_test.cpp
tinygrox/Principia
49a25646c673dcd84cefbc6295df410fc6d927d5
[ "MIT" ]
1,019
2015-01-03T11:42:27.000Z
2022-03-29T21:02:15.000Z
geometry/barycentre_calculator_test.cpp
tinygrox/Principia
49a25646c673dcd84cefbc6295df410fc6d927d5
[ "MIT" ]
92
2015-02-11T23:08:58.000Z
2022-03-21T03:35:37.000Z
 #include "geometry/barycentre_calculator.hpp" #include <vector> #include "geometry/frame.hpp" #include "geometry/grassmann.hpp" #include "gtest/gtest.h" #include "quantities/named_quantities.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" namespace principia { using geometry::Frame; using quantities::Entropy; using quantities::KinematicViscosity; using testing_utilities::AlmostEquals; namespace si = quantities::si; namespace geometry { class BarycentreCalculatorTest : public testing::Test { protected: using World = Frame<enum class WorldTag>; BarycentreCalculatorTest() : b1_({1 * si::Unit<Entropy>, -2 * si::Unit<Entropy>, 3 * si::Unit<Entropy>}), b2_({-9 * si::Unit<Entropy>, 8 * si::Unit<Entropy>, 7 * si::Unit<Entropy>}), k1_(4 * si::Unit<KinematicViscosity>), k2_(5 * si::Unit<KinematicViscosity>) {} Bivector<Entropy, World> b1_; Bivector<Entropy, World> b2_; KinematicViscosity k1_; KinematicViscosity k2_; }; using BarycentreCalculatorDeathTest = BarycentreCalculatorTest; TEST_F(BarycentreCalculatorDeathTest, Error) { using Calculator = BarycentreCalculator<Bivector<Entropy, World>, double>; EXPECT_DEATH({ Calculator calculator; calculator.Get(); }, "Empty BarycentreCalculator"); } TEST_F(BarycentreCalculatorTest, Bivector) { BarycentreCalculator<Bivector<Entropy, World>, KinematicViscosity> barycentre_calculator; barycentre_calculator.Add(b1_, k1_); barycentre_calculator.Add(b2_, k2_); EXPECT_THAT(barycentre_calculator.Get(), AlmostEquals( Bivector<Entropy, World>({(-41.0 / 9.0) * si::Unit<Entropy>, (32.0 / 9.0) * si::Unit<Entropy>, (47.0 / 9.0) * si::Unit<Entropy>}), 0)); } TEST_F(BarycentreCalculatorTest, Scalar) { BarycentreCalculator<KinematicViscosity, double> barycentre_calculator; barycentre_calculator.Add(k1_, -3); barycentre_calculator.Add(k2_, 7); EXPECT_THAT(barycentre_calculator.Get(), AlmostEquals((23.0 / 4.0) * si::Unit<KinematicViscosity>, 0)); } } // namespace geometry } // namespace principia
30.051948
79
0.671997
tinygrox
d11a5f09e4d7dbc6725bf80f68773ecb9157fcac
555
hpp
C++
include/RED4ext/Types/generated/anim/PoseLink.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/anim/PoseLink.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/anim/PoseLink.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Handle.hpp> namespace RED4ext { namespace anim { struct AnimNode_Base; } namespace anim { struct PoseLink { static constexpr const char* NAME = "animPoseLink"; static constexpr const char* ALIAS = NAME; WeakHandle<anim::AnimNode_Base> node; // 00 uint8_t unk10[0x18 - 0x10]; // 10 }; RED4EXT_ASSERT_SIZE(PoseLink, 0x18); } // namespace anim } // namespace RED4ext
21.346154
57
0.724324
Cyberpunk-Extended-Development-Team
d1234c0f804861dc40b643f7929a0fa018642dec
45,488
cpp
C++
3rdparty/dshowbase/src/gmf/sink.cpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
97
2015-10-16T04:32:33.000Z
2022-03-29T07:04:02.000Z
3rdparty/dshowbase/src/gmf/sink.cpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
19
2016-07-01T16:37:02.000Z
2020-09-10T06:09:39.000Z
3rdparty/dshowbase/src/gmf/sink.cpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
41
2015-11-17T05:59:23.000Z
2022-02-16T09:30:28.000Z
// // GDCL Multigraph Framework // // Sink.cpp: implementation of sink filter and input pin // // Copyright (c) GDCL 2004. All Rights Reserved. // You are free to re-use this as the basis for your own filter development, // provided you retain this copyright notice in the source. // http://www.gdcl.co.uk #pragma warning(push) #pragma warning(disable:4312) #pragma warning(disable:4995) #include "litiv/3rdparty/dshowbase/streams.h" #include <comdef.h> _COM_SMARTPTR_TYPEDEF(IMemAllocator, IID_IMemAllocator); _COM_SMARTPTR_TYPEDEF(IGraphBuilder, IID_IGraphBuilder); _COM_SMARTPTR_TYPEDEF(IBaseFilter, IID_IBaseFilter); _COM_SMARTPTR_TYPEDEF(IEnumMediaTypes, IID_IEnumMediaTypes); _COM_SMARTPTR_TYPEDEF(IMediaSample, IID_IMediaSample); _COM_SMARTPTR_TYPEDEF(IMediaSample2, IID_IMediaSample2); _COM_SMARTPTR_TYPEDEF(IEnumFilters, IID_IEnumFilters); _COM_SMARTPTR_TYPEDEF(IQualityControl, IID_IQualityControl); _COM_SMARTPTR_TYPEDEF(IEnumPins, IID_IEnumPins); _COM_SMARTPTR_TYPEDEF(IPin, IID_IPin); _COM_SMARTPTR_TYPEDEF(IEnumMediaTypes, IID_IEnumMediaTypes); _COM_SMARTPTR_TYPEDEF(IMediaControl, IID_IMediaControl); _COM_SMARTPTR_TYPEDEF(IMediaSeeking, IID_IMediaSeeking); _COM_SMARTPTR_TYPEDEF(IVideoWindow, IID_IVideoWindow); _COM_SMARTPTR_TYPEDEF(IBasicVideo, IID_IBasicVideo); _COM_SMARTPTR_TYPEDEF(IPinConnection, IID_IPinConnection); #pragma warning(pop) #include "litiv/3rdparty/dshowbase/gmf/smartPtr.h" #include "litiv/3rdparty/dshowbase/gmf/bridge.h" #include "litiv/3rdparty/dshowbase/gmf/sink.h" #pragma warning(disable: 4786) // debug info truncated #include <list> using namespace std; #include <sstream> BridgeSink::BridgeSink(BridgeController* pController) : m_tFirst(0), m_bLastDiscarded(false), m_nEOS(0), m_dwROT(0), CBaseFilter(NAME("BridgeSink filter"), NULL, &m_csFilter, GUID_NULL) { HRESULT hr = S_OK; m_nPins = pController->StreamCount(); m_pPins = new smart_ptr<BridgeSinkInput>[m_nPins]; for(int n = 0; n < m_nPins; n++) { ostringstream strm; strm << "Input " << (n+1); _bstr_t strName = strm.str().c_str(); m_pPins[n] = new BridgeSinkInput(this, pController->GetStream(n), m_pLock, &hr, strName); } LOG((TEXT("Sink 0x%x has %d pins"), this, m_nPins)); } STDMETHODIMP BridgeSink::NonDelegatingQueryInterface(REFIID iid, void** ppv) { if (iid == IID_IMediaSeeking) { // implement IMediaSeeking directly ourselves, not via // a pass-through proxy, so that we can aggregate multiple input pins // (needed for WMV playback) return GetInterface((IMediaSeeking*)this, ppv); } else if (iid == __uuidof(IBridgeSink)) { return GetInterface((IBridgeSink*)this, ppv); } else { return CBaseFilter::NonDelegatingQueryInterface(iid, ppv); } } int BridgeSink::GetPinCount() { return m_nPins; } CBasePin* BridgeSink::GetPin(int n) { if ((n < 0) || (n >= m_nPins)) { return NULL; } return m_pPins[n]; } STDMETHODIMP BridgeSink::GetBridgePin(int nPin, BridgeSinkInput** ppPin) { if ((nPin < 0) || (nPin >= m_nPins)) { return E_INVALIDARG; } *ppPin = m_pPins[nPin]; return S_OK; } void BridgeSink::OnEOS(bool bConnected) { { CAutoLock lock(&m_csEOS); m_nEOS += 1; if (!IsAtEOS()) { LOG((TEXT("Sink 0x%x EOS discarded"), this)); return; } } if (bConnected) { BridgeController* pC = m_pPins[0]->GetStream()->GetController(); LOG((TEXT("Sink 0x%x EOS"), this)); pC->OnEndOfSegment(); } } STDMETHODIMP_(BOOL) BridgeSink::IsAtEOS() { CAutoLock lock(&m_csEOS); long nPins = 0; for (int n = 0; n < m_nPins; n++) { if (m_pPins[n]->IsConnected()) { nPins++; } } return (m_nEOS == nPins); } void BridgeSink::ResetEOSCount() { CAutoLock lock(&m_csEOS); m_nEOS = 0; m_tFirst = 0; m_bLastDiscarded = false; LOG((TEXT("Sink 0x%x ResetEOSCount"), this)); } STDMETHODIMP BridgeSink::Stop() { LOG((TEXT("Sink 0x%x Stop"), this)); HRESULT hr = CBaseFilter::Stop(); ResetEOSCount(); return hr; } void BridgeSink::Discard() { CAutoLock lock(&m_csEOS); m_bLastDiscarded = true; } void BridgeSink::AdjustTime(IMediaSample* pIn) { CAutoLock lock(&m_csEOS); REFERENCE_TIME tStart, tEnd; if (SUCCEEDED(pIn->GetTime(&tStart, &tEnd))) { if (m_bLastDiscarded) { LOG((TEXT("Sink 0x%x setting offset %d msecs"), this, long(tStart / 10000))); m_tFirst = tStart; m_bLastDiscarded = false; } if (m_tFirst != 0) { LOG((TEXT("Sink adjusting %d to %d msecs"), long(tStart/10000), long((tStart-m_tFirst)/10000))); } tStart -= m_tFirst; tEnd -= m_tFirst; pIn->SetTime(&tStart, &tEnd); } } // register in the running object table for graph debugging STDMETHODIMP BridgeSink::JoinFilterGraph(IFilterGraph * pGraph, LPCWSTR pName) { HRESULT hr = CBaseFilter::JoinFilterGraph(pGraph, pName); // for debugging, we register in the ROT so that you can use // Graphedt's Connect command to view the graphs // disabled by default owing to refcount leak issue if (false) //SUCCEEDED(hr)) { if (pGraph == NULL) { if (m_dwROT) { IRunningObjectTablePtr pROT; if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) { pROT->Revoke(m_dwROT); } } } else { IMonikerPtr pMoniker; IRunningObjectTablePtr pROT; if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) { ostringstream strm; DWORD graphaddress = (DWORD)((DWORD_PTR)(IUnknown*)pGraph) & 0xFFFFFFFF; strm << "FilterGraph " << hex << graphaddress << " pid " << hex << GetCurrentProcessId(); _bstr_t strName = strm.str().c_str(); HRESULT hr = CreateItemMoniker(L"!", strName, &pMoniker); if (SUCCEEDED(hr)) { hr = pROT->Register(0, pGraph, pMoniker, &m_dwROT); } } } } return hr; } // BridgeSink seeking implementation // holds all the input pins that support seeking class SeekingCollection { public: typedef list<IMediaSeeking*>::iterator iterator; // if bSet, only accept settable pins SeekingCollection(CBaseFilter* pFilter) { for (int i = 0; i < pFilter->GetPinCount(); i++) { CBasePin* pPin = pFilter->GetPin(i); PIN_DIRECTION pindir; pPin->QueryDirection(&pindir); if (pindir == PINDIR_INPUT) { IMediaSeekingPtr pSeek = pPin->GetConnected(); if (pSeek != NULL) { m_Pins.push_back(pSeek.Detach()); } } } } ~SeekingCollection() { while (!m_Pins.empty()) { IMediaSeekingPtr pSeek(m_Pins.front(), 0); m_Pins.pop_front(); pSeek = NULL; } } iterator Begin() { return m_Pins.begin(); } iterator End() { return m_Pins.end(); } private: list<IMediaSeeking*> m_Pins; }; // --- not implemented ------------- STDMETHODIMP BridgeSink::GetCurrentPosition(LONGLONG *pCurrent) { UNREFERENCED_PARAMETER(pCurrent); // implemented in graph manager using stream time return E_NOTIMPL; } // ---- by aggregation of input pin responses -------------- STDMETHODIMP BridgeSink::GetCapabilities(DWORD * pCapabilities) { SeekingCollection pins(this); DWORD caps = 0; for (SeekingCollection::iterator it = pins.Begin(); it != pins.End(); it++) { IMediaSeekingPtr pSeek = *it; DWORD capsThis; HRESULT hr = pSeek->GetCapabilities(&capsThis); if (SUCCEEDED(hr)) { caps |= capsThis; } } *pCapabilities = caps; return S_OK; } STDMETHODIMP BridgeSink::SetPositions(LONGLONG * pCurrent, DWORD dwCurrentFlags , LONGLONG * pStop, DWORD dwStopFlags) { // pass call to all pins. Fails if any fail. SeekingCollection pins(this); HRESULT hr = S_OK; for (SeekingCollection::iterator it = pins.Begin(); it != pins.End(); it++) { IMediaSeekingPtr pSeek = *it; if (pSeek->IsUsingTimeFormat(&TIME_FORMAT_MEDIA_TIME) == S_OK) { HRESULT hrThis = pSeek->SetPositions(pCurrent, dwCurrentFlags, pStop, dwStopFlags); if (FAILED(hrThis) && (hrThis != E_NOTIMPL) && SUCCEEDED(hr)) { hr = hrThis; } } } return hr; } STDMETHODIMP BridgeSink::GetPositions(LONGLONG * pCurrent, LONGLONG * pStop) { // cannot really aggregate this -- just return the // first one and assume they are all the same (they will // be if we set the params) SeekingCollection pins(this); HRESULT hr; if (pins.Begin() == pins.End()) { hr = E_NOINTERFACE; } else { IMediaSeekingPtr pSeek = *pins.Begin(); hr = pSeek->GetPositions(pCurrent, pStop); } return hr; } STDMETHODIMP BridgeSink::GetAvailable(LONGLONG * pEarliest, LONGLONG * pLatest) { // the available section reported is what is common to all inputs LONGLONG tEarly = 0; LONGLONG tLate = 0x7fffffffffffffff; SeekingCollection pins(this); for (SeekingCollection::iterator it = pins.Begin(); it != pins.End(); it++) { IMediaSeekingPtr pSeek = *it; LONGLONG tThisEarly, tThisLate; HRESULT hr = pSeek->GetAvailable(&tThisEarly, &tThisLate); if (SUCCEEDED(hr)) { if (tThisEarly > tEarly) { tEarly = tThisEarly; } if (tThisLate < tLate) { tLate = tThisLate; } } } *pEarliest = tEarly; *pLatest = tLate; return S_OK; } STDMETHODIMP BridgeSink::SetRate(double dRate) { // pass call to all pins. Fails if any fail. SeekingCollection pins(this); HRESULT hr = S_OK; for (SeekingCollection::iterator it = pins.Begin(); it != pins.End(); it++) { IMediaSeekingPtr pSeek = *it; HRESULT hrThis = pSeek->SetRate(dRate); if (FAILED(hrThis) && SUCCEEDED(hr)) { hr = hrThis; } } return hr; } STDMETHODIMP BridgeSink::GetRate(double * pdRate) { // cannot really aggregate this -- just return the // first one and assume they are all the same (they will // be if we set the params) SeekingCollection pins(this); HRESULT hr; if (pins.Begin() == pins.End()) { hr = E_NOINTERFACE; } else { IMediaSeekingPtr pSeek = *pins.Begin(); hr = pSeek->GetRate(pdRate); } return hr; } STDMETHODIMP BridgeSink::GetPreroll(LONGLONG * pllPreroll) { // the preroll requirement is the longest of any input SeekingCollection pins(this); LONGLONG tPreroll = 0; for (SeekingCollection::iterator it = pins.Begin(); it != pins.End(); it++) { IMediaSeekingPtr pSeek = *it; LONGLONG tThis; HRESULT hr = pSeek->GetPreroll(&tThis); if (SUCCEEDED(hr)) { if (tThis > tPreroll) { tPreroll = tThis; } } } *pllPreroll = tPreroll; return S_OK; } STDMETHODIMP BridgeSink::GetDuration(LONGLONG *pDuration) { // the duration we report is the longest of any input duration SeekingCollection pins(this); LONGLONG tDur = 0; for (SeekingCollection::iterator it = pins.Begin(); it != pins.End(); it++) { IMediaSeekingPtr pSeek = *it; LONGLONG tThis; HRESULT hr = pSeek->GetDuration(&tThis); if (SUCCEEDED(hr)) { if (tThis > tDur) { tDur = tThis; } } } *pDuration = tDur; return S_OK; } STDMETHODIMP BridgeSink::GetStopPosition(LONGLONG *pStop) { // cannot really aggregate this -- just return the // first one and assume they are all the same (they will // be if we set the params) SeekingCollection pins(this); HRESULT hr; if (pins.Begin() == pins.End()) { hr = E_NOINTERFACE; } else { IMediaSeekingPtr pSeek = *pins.Begin(); hr = pSeek->GetStopPosition(pStop); } return hr; } // -- implemented directly here -------------- STDMETHODIMP BridgeSink::CheckCapabilities(DWORD * pCapabilities ) { DWORD dwActual; GetCapabilities(&dwActual); if (*pCapabilities & (~dwActual)) { return S_FALSE; } return S_OK; } STDMETHODIMP BridgeSink::IsFormatSupported(const GUID * pFormat) { if (*pFormat == TIME_FORMAT_MEDIA_TIME) { return S_OK; } return S_FALSE; } STDMETHODIMP BridgeSink::QueryPreferredFormat(GUID * pFormat) { *pFormat = TIME_FORMAT_MEDIA_TIME; return S_OK; } STDMETHODIMP BridgeSink::GetTimeFormat(GUID *pFormat) { return QueryPreferredFormat(pFormat); } STDMETHODIMP BridgeSink::IsUsingTimeFormat(const GUID * pFormat) { GUID guidActual; HRESULT hr = GetTimeFormat(&guidActual); if (SUCCEEDED(hr) && (guidActual == *pFormat)) { return S_OK; } else { return S_FALSE; } } STDMETHODIMP BridgeSink::SetTimeFormat(const GUID * pFormat) { if ((*pFormat == TIME_FORMAT_MEDIA_TIME) || (*pFormat == TIME_FORMAT_NONE)) { return S_OK; } else { return E_NOTIMPL; } } STDMETHODIMP BridgeSink::ConvertTimeFormat(LONGLONG * pTarget, const GUID * pTargetFormat, LONGLONG Source, const GUID * pSourceFormat) { // since we only support TIME_FORMAT_MEDIA_TIME, we don't really // offer any conversions. if(pTargetFormat == 0 || *pTargetFormat == TIME_FORMAT_MEDIA_TIME) { if(pSourceFormat == 0 || *pSourceFormat == TIME_FORMAT_MEDIA_TIME) { *pTarget = Source; return S_OK; } } return E_INVALIDARG; } // --- input pin implementation -------------------------------- BridgeSinkInput::BridgeSinkInput( BridgeSink* pFilter, BridgeStream* pStream, CCritSec* pLock, HRESULT* phr, LPCWSTR pName) : CBaseInputPin(NAME("BridgeSinkInput"), pFilter, pLock, phr, pName), m_pStream(pStream), m_pRedirectedAlloc(NULL), m_bConnected(false), m_nDeliveryLocks(0), m_bSendDTC(false), m_bStoppedWhileConnected(false) { m_bAudio = !m_pStream->IsVideo(); m_hsemDelivery = CreateSemaphore(NULL, 1, 1, NULL); if (!m_pStream->DiscardMode()) { m_pRedirectedAlloc = new BridgeAllocator(this); m_pRedirectedAlloc->AddRef(); } } BridgeSinkInput::~BridgeSinkInput() { if (m_pRedirectedAlloc) { m_pRedirectedAlloc->Release(); } CloseHandle(m_hsemDelivery); } void BridgeSinkInput::LockIncremental() { // if there are multiple calls to this on separate // threads, there's a chance that the second one // will be left blocked on the semaphore when he should be seeing the // incremental indicator. To avoid this, timeout the semaphore and loop for (;;) { { CAutoLock lock(&m_csDelivery); if (m_nDeliveryLocks > 0) { // lock is incremental -- can add to it m_nDeliveryLocks++; return; } } // acquire exclusive lock DWORD dw = WaitForSingleObject(DeliveryLock(), 100); if (dw == WAIT_OBJECT_0) { break; } } // now mark it as incremental CAutoLock lock(&m_csDelivery); m_nDeliveryLocks++; } // if incremental, decrease count and release semaphore if 0. // if exclusive, release semaphore (count is 0) void BridgeSinkInput::Unlock() { CAutoLock lock(&m_csDelivery); if (m_nDeliveryLocks > 0) { // incremental lock m_nDeliveryLocks--; if (m_nDeliveryLocks > 0) { // not idle yet return; } } ReleaseSemaphore(m_hsemDelivery, 1, NULL); } // CBaseInputPin overrides STDMETHODIMP BridgeSinkInput::Receive(IMediaSample *pSampleIn) { LOG((TEXT("Pin 0x%x receive 0x%x"), this, pSampleIn)); // check state HRESULT hr = CBaseInputPin::Receive(pSampleIn); if (hr == S_OK) { // if not connected, do nothing. // For the "discard on not connected" option, this // is the correct behaviour. For the suspend on not connected option, // we should not get here since GetBuffer will suspend. { // restrict critsec -- don't hold over blocking call CAutoLock lock(&m_csConnect); if (!m_bConnected) { LOG((TEXT("Sink pin 0x%x disconnected: discarding 0x%x"), this, pSampleIn)); // remember that the segment is broken Filter()->Discard(); // just ignore this sample return S_OK; } } // we must hold a lock during receive. If upstream is using the proxy alloc, // then the lock is held by the proxy sample. If not, we should get a proxy sample // just for the duration of Receive so it will hold the lock IProxySamplePtr pProxy = pSampleIn; IMediaSamplePtr pInner; if (pProxy != NULL) { // already has proxy and lock -- extract inner pProxy->GetInner(&pInner); } else { // make new proxy to hold lock hr = S_OK; pProxy = new ProxySample(this, &hr); // we already have the inner pInner = pSampleIn; } LOG((TEXT("Pin 0x%x outer 0x%x, inner 0x%x"), this, pSampleIn, pInner)); // if we stopped while connected, our times will be reset to 0 // so we must notify the source if (m_bStoppedWhileConnected) { GetStream()->ResetOnStop(); m_bStoppedWhileConnected = false; } // before changing it, we must make a copy IMediaSamplePtr pLocal = pInner; hr = S_OK; if (GetStream()->GetController()->LiveTiming()) { // map to absolute clock time here // (and back in source graph) // depends on using a common clock. REFERENCE_TIME tStart, tStop; if (pLocal->GetTime(&tStart, &tStop) == S_OK) { REFERENCE_TIME tSTO = Filter()->STO(); tStart += tSTO; tStop += tSTO; pLocal->SetTime(&tStart, &tStop); pLocal->SetMediaTime(NULL, NULL); } } else { // if we are starting delivery after being disconnected, // the timestamps should begin at 0 // -- handled in filter to ensure common adjustment for all streams Filter()->AdjustTime(pLocal); } // check for media type change AM_MEDIA_TYPE* pmt; CMediaType mtFromUpstream; bool bTypeChange = false; if (pLocal->GetMediaType(&pmt) == S_OK) { CMediaType mt(*pmt); DeleteMediaType(pmt); // is this a new type? CMediaType mtDownstream; GetStream()->GetSelectedType(&mtDownstream); if (mt != mtDownstream) { // must be upstream-originated GetStream()->SetSelectedType(&mt); mtFromUpstream = mt; bTypeChange = true; } } else if (pProxy->GetType(&mtFromUpstream) == S_OK) { LOG((TEXT("Using DTC from proxy"))); // type change was attached to sample in GetBuffer // but then erased in upstream filter //re-attach to inner sample pLocal->SetMediaType(&mtFromUpstream); CMediaType mtDownstream; GetStream()->GetSelectedType(&mtDownstream); if (mtFromUpstream != mtDownstream) { // must be upstream-originated GetStream()->SetSelectedType(&mtFromUpstream); bTypeChange = true; } } else if (m_bSendDTC) { // the type of the input needs to be passed downstream. LOG((TEXT("Type change sample lost -- setting on next sample"))); m_bSendDTC = false; mtFromUpstream = m_mt; bTypeChange = true; pLocal->SetMediaType(&m_mt); } // if we are in "discard" mode, we are not using the // same allocator, so we must copy here if (m_bUsingProxyAllocator) { hr = GetStream()->Deliver(pLocal); } else { // need to copy. For audio this might mean a repeated copy int cIn = pLocal->GetActualDataLength(); int cOffset = 0; while (cOffset < cIn) { IMediaSamplePtr pOut; if (m_pCopyAllocator == NULL) { return VFW_E_NO_ALLOCATOR; } hr = m_pCopyAllocator->GetBuffer(&pOut, NULL, NULL, 0); if (SUCCEEDED(hr)) { hr = CopySample(pLocal, pOut, cOffset, cIn - cOffset); cOffset += pOut->GetActualDataLength(); } if (SUCCEEDED(hr)) { if (bTypeChange) { pOut->SetMediaType(&mtFromUpstream); bTypeChange = false; } hr = GetStream()->Deliver(pOut == NULL? pLocal : pOut); } if (FAILED(hr)) { return hr; } } } } return hr; } // copy a portion of the input buffer to the output. Copy times and flags on first portion // only. HRESULT BridgeSinkInput::CopySample(IMediaSample* pIn, IMediaSample* pOut, int cOffset, int cLength) { BYTE* pDest; pOut->GetPointer(&pDest); BYTE* pSrc; pIn->GetPointer(&pSrc); pSrc += cOffset; long cOut = pOut->GetSize(); long cIn = pIn->GetActualDataLength(); cLength = min(cLength, cOut); // ensure we copy whole samples if audio if ((*m_mt.Type() == MEDIATYPE_Audio) && (*m_mt.FormatType() == FORMAT_WaveFormatEx)) { WAVEFORMATEX* pwfx = (WAVEFORMATEX*)m_mt.Format(); cLength -= cLength % pwfx->nBlockAlign; } if ((cOffset + cLength) > cIn) { return VFW_E_BUFFER_OVERFLOW; } CopyMemory(pDest, pSrc, cLength); pOut->SetActualDataLength(cLength); // properties are set on first buffer only if (cOffset == 0) { REFERENCE_TIME tStart, tEnd; if (SUCCEEDED(pIn->GetTime(&tStart, &tEnd))) { pOut->SetTime(&tStart, &tEnd); } if (SUCCEEDED(pIn->GetMediaTime(&tStart, &tEnd))) { pOut->SetMediaTime(&tStart, &tEnd); } if (pIn->IsSyncPoint() == S_OK) { pOut->SetSyncPoint(true); } if (pIn->IsDiscontinuity() == S_OK) { pOut->SetDiscontinuity(true); } if (pIn->IsPreroll() == S_OK) { pOut->SetPreroll(true); } } return S_OK; } STDMETHODIMP BridgeSinkInput::EndOfStream(void) { HRESULT hr = Filter()->NotifyEvent(EC_COMPLETE, S_OK, NULL); Filter()->OnEOS(m_bConnected); return CBaseInputPin::EndOfStream(); } HRESULT BridgeSinkInput::CheckMediaType(const CMediaType* pmt) { // do we insist on the decoder being in the upstream segment? if (GetStream()->AllowedTypes() == eUncompressed) { if (!IsUncompressed(pmt)) { return VFW_E_TYPE_NOT_ACCEPTED; } } else if (GetStream()->AllowedTypes() == eMuxInputs) { if (!IsAllowedMuxInput(pmt)) { return VFW_E_TYPE_NOT_ACCEPTED; } } // check with bridge stream -- type is fixed once output // stage has been built return GetStream()->CanReceiveType(pmt); } HRESULT BridgeSinkInput::GetMediaType(int iPosition, CMediaType* pmt) { UNREFERENCED_PARAMETER(iPosition); UNREFERENCED_PARAMETER(pmt); return VFW_S_NO_MORE_ITEMS; } HRESULT BridgeSinkInput::SetMediaType(const CMediaType* pmt) { HRESULT hr = CBaseInputPin::SetMediaType(pmt); if (SUCCEEDED(hr)) { CAutoLock lock(&m_csConnect); if (m_bConnected) { GetStream()->SetSelectedType(pmt); } } return hr; } bool BridgeSinkInput::IsUncompressed(const CMediaType* pmt) { if (m_bAudio) { if (*pmt->Type() != MEDIATYPE_Audio) { return false; } if (*pmt->FormatType() != FORMAT_WaveFormatEx) { return false; } WAVEFORMATEX* pwfx = (WAVEFORMATEX*)pmt->Format(); if (pwfx->wFormatTag != WAVE_FORMAT_PCM) { return false; } return true; } else { if (*pmt->Type() != MEDIATYPE_Video) { return false; } if ( (*pmt->Subtype() == MEDIASUBTYPE_ARGB32)|| (*pmt->Subtype() == MEDIASUBTYPE_RGB32) || (*pmt->Subtype() == MEDIASUBTYPE_RGB24) || (*pmt->Subtype() == MEDIASUBTYPE_YUY2) || (*pmt->Subtype() == MEDIASUBTYPE_UYVY) || (*pmt->Subtype() == MEDIASUBTYPE_Y41P) || (*pmt->Subtype() == MEDIASUBTYPE_RGB555) || (*pmt->Subtype() == MEDIASUBTYPE_RGB565) || (*pmt->Subtype() == MEDIASUBTYPE_RGB8) ) { return true; } } return false; } bool BridgeSinkInput::IsAllowedMuxInput(const CMediaType* pmt) { // the AVI Mux only accepts certain formats -- we // must check for them at the sink. if (*pmt->Type() == MEDIATYPE_Video) { //must be either VideoInfo or DvInfo if (*pmt->FormatType() == FORMAT_VideoInfo) { // for VideoInfo, must have no target rect and no negative height VIDEOINFOHEADER* pvi = (VIDEOINFOHEADER*)pmt->Format(); if ((pvi->bmiHeader.biHeight < 0) || (pvi->rcTarget.left != 0) || ((pvi->rcTarget.right != 0) && (pvi->rcTarget.right != pvi->bmiHeader.biWidth))) { return false; } } else if (*pmt->FormatType() != FORMAT_DvInfo) { return false; } } else if (*pmt->Type() == MEDIATYPE_Audio) { // audio must be WaveFormatEx with a valid nBlockAlign if (*pmt->FormatType() != FORMAT_WaveFormatEx) { return false; } WAVEFORMATEX* pwfx = (WAVEFORMATEX*)pmt->Format(); if (pwfx->nBlockAlign == 0) { return false; } } else { return false; } return true; } STDMETHODIMP BridgeSinkInput::GetAllocator(IMemAllocator **ppAllocator) { /// if not connected, should we discard? HRESULT hr; if (GetStream()->DiscardMode()) { // yes -- so we must use a standard allocator // (which will still work when not connected hr = CBaseInputPin::GetAllocator(ppAllocator); } else { // prefer our allocator since this handles dynamic type changes // as well as preventing copies hr = m_pRedirectedAlloc->QueryInterface(IID_IMemAllocator, (void**)ppAllocator); } return hr; } STDMETHODIMP BridgeSinkInput::NotifyAllocator(IMemAllocator * pAllocator, BOOL bReadOnly) { if (!GetStream()->DiscardMode()) { // insist on our allocator IUnknownPtr pOurs = m_pRedirectedAlloc; IUnknownPtr pNotified = pAllocator; if (pOurs == pNotified) { m_bUsingProxyAllocator = true; } else { m_bUsingProxyAllocator = false; // for video, we must use the proxy alloc or we can't handle // type switching. // for audio, we could allow this, but we would need to add // code in Receive, since currently we rely on the allocator blocking // until connected -- with a foreign allocator, we would need to block in receive instead. // This would be a benefit in some DV cases where the audio buffer size is an issue and // hard to renegotiate between clips. // error code is not quite ideal, but at least points at the offending object return VFW_E_NO_ALLOCATOR; } } else { m_bUsingProxyAllocator = false; } return CBaseInputPin::NotifyAllocator(pAllocator, bReadOnly); } STDMETHODIMP BridgeSinkInput::BeginFlush() { LOG((TEXT("Pin 0x%x BeginFlush"), this)); HRESULT hr = CBaseInputPin::BeginFlush(); // allocator must fail without blocking while flushing - this is // the same as decommit state if (m_pRedirectedAlloc && m_bUsingProxyAllocator) { m_pRedirectedAlloc->Decommit(); } // pass on to the downstream graph if connected CAutoLock lock(&m_csConnect); if (m_bConnected) { hr = GetStream()->BeginFlush(); } return hr; } STDMETHODIMP BridgeSinkInput::EndFlush() { LOG((TEXT("Pin 0x%x EndFlush"), this)); HRESULT hr = CBaseInputPin::EndFlush(); // reset end-of-stream if delivered Filter()->ResetEOSCount(); // undo the Decommit done during BeginFlush if (m_pRedirectedAlloc && m_bUsingProxyAllocator) { m_pRedirectedAlloc->Commit(); } // pass on to the downstream graph if connected CAutoLock lock(&m_csConnect); if (m_bConnected) { hr = GetStream()->EndFlush(); } return hr; } // we are now the selected source for the downstream // graph. HRESULT BridgeSinkInput::MakeBridge(IMemAllocator* pAlloc) { LOG((TEXT("Pin 0x%x Bridge to alloc 0x%x"), this, pAlloc)); CAutoLock lock(&m_csConnect); m_bStoppedWhileConnected = false; m_bConnected = true; HRESULT hr = S_OK; if (m_bUsingProxyAllocator) { // the previous source graph or the renderer may have // made a type change -- ensure this is on the first sample // -- so we set it before enabling the GetBuffer CMediaType mt; GetStream()->GetSelectedType(&mt); // is it compatible? if (mt != m_mt) { // dynamic changes sent upstream with GetBuffer only work reliably with video if (*m_mt.Type() == MEDIATYPE_Video) { hr = CanDeliverType(&mt); if (hr == S_OK) { // sadly, many codecs do not check the size // they are offered, and will claim to output anything hr = BridgeStream::CheckMismatchedVideo(&mt, &m_mt); } } else { hr = E_FAIL; } if (hr == S_OK) { // switch our source to this type by attaching at // next GetBuffer LOG((TEXT("Switching source to stream type"))); m_pRedirectedAlloc->ForceDTC(&mt); } else if ((*m_mt.Type() == MEDIATYPE_Video)) { // don't switch back to the previously connected type, or the VR might // see an extended stride as part of the video. Instead, enumerate // the preferred formats from the source and try those. However, stick to // the same subtype. hr = VFW_E_TYPE_NOT_ACCEPTED; IEnumMediaTypesPtr pEnum; GetConnected()->EnumMediaTypes(&pEnum); AM_MEDIA_TYPE* pmt; while(pEnum->Next(1, &pmt, NULL) == S_OK) { CMediaType mtEnum(*pmt); DeleteMediaType(pmt); if ((CanDeliverType(&mtEnum) == S_OK) && (*mtEnum.Subtype() == *m_mt.Subtype()) && GetStream()->CanSwitchTo(&mtEnum)) { LOG((TEXT("ReceiveConnect to enumerated source type"))); m_pRedirectedAlloc->SwitchFormatTo(&mtEnum); hr = S_OK; break; } } if (hr != S_OK) { LOG((TEXT("No suitable video type - failing bridge"))); return hr; } } else { // attempt a dynamic switch downstream to the format // that our source is using LOG((TEXT("Switching downstream to source type"))); m_pRedirectedAlloc->ForceDTC(&m_mt); // the type change is attached to a buffer from our GetBuffer, // and we need to pass it downstream, even if that sample is discarded // or the mt is cleared. So we set a flag here indicating that // we need to set the type onto the next incoming sample. m_bSendDTC = true; } } // redirect allocator hr = m_pRedirectedAlloc->SetDownstreamAlloc(pAlloc); } else { m_pCopyAllocator = pAlloc; } return hr; } // we are now disconnected from downstream HRESULT BridgeSinkInput::DisconnectBridge() { LOG((TEXT("Pin 0x%x disconnect"), this)); if (m_pRedirectedAlloc && m_bUsingProxyAllocator) { m_pRedirectedAlloc->SetDownstreamAlloc(NULL); } CAutoLock lock(&m_csConnect); // if we are in mid-flush, remember that the endflush will // not be passed on if (m_bFlushing && m_bConnected) { LOG((TEXT("Pin 0x%x disconnect when mid-flush"), this)); GetStream()->EndFlush(); } m_bConnected = false; m_bStoppedWhileConnected = false; return S_OK; } HRESULT BridgeSinkInput::GetBufferProps(long* pcBuffers, long* pcBytes) { // return whatever we have agreed, whether the bridge allocator or not HRESULT hr = VFW_E_NO_ALLOCATOR; if (m_pAllocator) { ALLOCATOR_PROPERTIES prop; hr = m_pAllocator->GetProperties(&prop); *pcBuffers = prop.cBuffers; *pcBytes = prop.cbBuffer; } return hr; } HRESULT BridgeSinkInput::CanDeliverType(const CMediaType* pmt) { // do we insist on the decoder being in the upstream segment? if (GetStream()->AllowedTypes() == eUncompressed) { if (!IsUncompressed(pmt)) { return VFW_E_TYPE_NOT_ACCEPTED; } } else if (GetStream()->AllowedTypes() == eMuxInputs) { if (!IsAllowedMuxInput(pmt)) { return VFW_E_TYPE_NOT_ACCEPTED; } } if (!IsConnected()) { return VFW_E_NOT_CONNECTED; } // query accept on upstream output pin return GetConnected()->QueryAccept(pmt); } HRESULT BridgeSinkInput::EnumOutputType(int iPosition, CMediaType* pmt) { // enumerate output types on upstream pin if (!IsConnected()) { return VFW_E_NOT_CONNECTED; } IEnumMediaTypesPtr pEnum; HRESULT hr = GetConnected()->EnumMediaTypes(&pEnum); if (SUCCEEDED(hr)) { pEnum->Skip(iPosition); AM_MEDIA_TYPE* amt; hr = pEnum->Next(1, &amt, NULL); if (hr == S_OK) { *pmt = *amt; DeleteMediaType(amt); } } return hr; } HRESULT BridgeSinkInput::Inactive() { if (Filter()->IsActive() && m_bConnected) { m_bStoppedWhileConnected = true; } return __super::Inactive(); } // --------- Redirecting allocator implementation -------------------------- BridgeAllocator::BridgeAllocator(BridgeSinkInput* pPin) : CUnknown(NAME("BridgeAllocator"), NULL), m_pPin(pPin), m_bForceDTC(false), m_bSwitchConnection(false), m_bCommitted(false), m_evNonBlocking(true) // manual reset { ZeroMemory(&m_props, sizeof(m_props)); // while not committed, we just reject calls, not block // (blocking is only when we are active, but not connected to // the downstream graph) m_evNonBlocking.Set(); } STDMETHODIMP BridgeAllocator::NonDelegatingQueryInterface(REFIID iid, void** ppv) { if (iid == IID_IMemAllocator) { return GetInterface((IMemAllocator*)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(iid, ppv); } } STDMETHODIMP BridgeAllocator::SetProperties( ALLOCATOR_PROPERTIES* pRequest, ALLOCATOR_PROPERTIES* pActual) { // requests are passed to the downstream allocator by // the BridgeSourceOutput pin when the downstream graph // is being built. CAutoLock lock(&m_csAlloc); m_props = *pRequest; // for uncompressed video, the buffer size will change as the output type changes // so we accept any properties HRESULT hr = S_OK; if (!m_pPin->GetStream()->IsVideo()) { // for audio, we should tell the caller what buffers are actually in use and // allow them to reject it. long cBuffers, cBytes; if (m_pPin->GetStream()->GetDownstreamBufferProps(&cBuffers, &cBytes)) { m_props.cbBuffer = cBytes; m_props.cBuffers = cBuffers; if (cBytes < pRequest->cbBuffer) { hr = VFW_E_BUFFER_UNDERFLOW; } } } *pActual = m_props; return hr; } STDMETHODIMP BridgeAllocator::GetProperties(ALLOCATOR_PROPERTIES *pProps) { // it's probably best to pass on the actual props if possible CAutoLock lock(&m_csAlloc); HRESULT hr = S_OK; if (m_pTarget == NULL) { *pProps = m_props; } else { hr = m_pTarget->GetProperties(pProps); } return hr; } STDMETHODIMP BridgeAllocator::ReleaseBuffer(IMediaSample *pSample) { UNREFERENCED_PARAMETER(pSample); // called via sample's pointer to originating allocator -- so // our implementation will never be called. return S_OK; } STDMETHODIMP BridgeAllocator::GetBuffer( IMediaSample **ppBuffer, REFERENCE_TIME *pStart, REFERENCE_TIME *pEnd, DWORD dwFlags) { LOG((TEXT("GetBuffer on sink pin 0x%x"), m_pPin)); IProxySamplePtr pProxy; // block until connected and committed for(;;) { // wait on the event, then grab the locks in // the right order. Then check that we are // connected/committed, and if not, release the locks and try again m_evNonBlocking.Wait(); // create a proxy -- locks the pin HRESULT hr = S_OK; pProxy = new ProxySample(m_pPin, &hr); // target-alloc critsec CAutoLock lock(&m_csAlloc); // committed? if (!m_bCommitted) { return VFW_E_NOT_COMMITTED; } // connected? if (m_pTarget != NULL) { break; } pProxy = NULL; } HRESULT hr = S_OK; if (m_bSwitchConnection) { hr = m_pPin->GetStream()->SwitchTo(&m_mtDTC); if (SUCCEEDED(hr)) { m_bForceDTC = true; m_bSwitchConnection = false; } } // call target allocator // target cannot change while we hold the semaphore IMediaSamplePtr pSample; if (SUCCEEDED(hr)) { hr = m_pTarget->GetBuffer(&pSample, pStart, pEnd, dwFlags); } // dynamic type changes? if (SUCCEEDED(hr)) { CAutoLock lock(&m_csAlloc); // check for dynamic type change from downstream AM_MEDIA_TYPE* pmt; if (pSample->GetMediaType(&pmt) == S_OK) { CMediaType mt(*pmt); DeleteMediaType(pmt); // notify controller that this sample has a type change // (the source will normally clear it before calling our Receive method). // If we were actually processing the data within the sink, we would // need to switch type when this exact sample reappears at the input // (although by then the media type will have been removed from the sample). // However, for our purposes, we can switch now. m_pPin->SetMediaType(&mt); } else if (m_bForceDTC) { // initiate a dynamic type change ourselves pSample->SetMediaType(&m_mtDTC); // attach to our proxy so that we can detect this type change // on the way downstream even if the upstream filter erases it pProxy->SetType(&m_mtDTC); // if this is a switch to a new format, tell the pin & stream m_pPin->SetMediaType(&m_mtDTC); } m_bForceDTC = false; } if (SUCCEEDED(hr)) { pProxy->SetInner(pSample); IMediaSamplePtr pOuter = pProxy; *ppBuffer = pOuter.Detach(); } if (hr != S_OK) { LOG((TEXT("GetBuffer on pin 0x%x returns 0x%x"), m_pPin, hr)); } return hr; } STDMETHODIMP BridgeAllocator::Commit() { // ensure that we block when active but disconnected CAutoLock lock(&m_csAlloc); m_bCommitted = true; if (m_pTarget == NULL) { m_evNonBlocking.Reset(); } LOG((TEXT("BridgeAlloc 0x%x commit, %s"), this, m_pTarget==NULL?TEXT("Disconnected"):TEXT("Connected"))); return S_OK; } STDMETHODIMP BridgeAllocator::Decommit() { // ensure that we block when active but disconnected // -- we are now inactive CAutoLock lock(&m_csAlloc); m_bCommitted = false; m_evNonBlocking.Set(); LOG((TEXT("BridgeAlloc 0x%x decommit, %s"), this, m_pTarget==NULL?TEXT("Disconnected"):TEXT("Connected"))); return S_OK; } HRESULT BridgeAllocator::SetDownstreamAlloc(IMemAllocator* pAlloc) { // lock cs *after* semaphore CAutoLock lock(&m_csAlloc); // target allocator -- could be null if disconnecting m_pTarget = pAlloc; // ensure non-blocking when connected or not active if ((m_pTarget != NULL) || !m_bCommitted) { m_evNonBlocking.Set(); } else { m_evNonBlocking.Reset(); } return S_OK; } // -- sample proxy implementation ------------------ ProxySample::ProxySample(BridgeSinkInput* pPin, HRESULT* phr) : CUnknown(NAME("ProxySample"), NULL, phr), m_pPin(pPin), m_bDTC(false) { // increment lock for each outstanding buffer m_pPin->LockIncremental(); } ProxySample::~ProxySample() { // release lock on deletion m_pPin->Unlock(); } STDMETHODIMP ProxySample::NonDelegatingQueryInterface(REFIID iid, void** ppv) { if ((iid == IID_IMediaSample) || (iid == IID_IMediaSample2)) { return GetInterface((IMediaSample2*)this, ppv); } else if (iid == __uuidof(IProxySample)) { return GetInterface((IProxySample*)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(iid, ppv); } } STDMETHODIMP ProxySample::SetInner(IMediaSample* pSample) { m_pInner = pSample; return S_OK; } STDMETHODIMP ProxySample::GetInner(IMediaSample** ppSample) { *ppSample = m_pInner; if (m_pInner != NULL) { m_pInner->AddRef(); return S_OK; } return S_FALSE; } STDMETHODIMP ProxySample::ReleaseInner() { m_pInner = NULL; return S_OK; } STDMETHODIMP ProxySample::SetType(const CMediaType* pType) { m_mtDTC = *pType; m_bDTC = true; return S_OK; } STDMETHODIMP ProxySample::GetType(CMediaType* pType) { if (m_bDTC) { *pType = m_mtDTC; return S_OK; } return S_FALSE; } STDMETHODIMP ProxySample::GetPointer(BYTE ** ppBuffer) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->GetPointer(ppBuffer); } STDMETHODIMP_(LONG) ProxySample::GetSize(void) { if (m_pInner == NULL) { return 0; } return m_pInner->GetSize(); } STDMETHODIMP ProxySample::GetTime( REFERENCE_TIME * pTimeStart, // put time here REFERENCE_TIME * pTimeEnd ) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->GetTime(pTimeStart, pTimeEnd); } STDMETHODIMP ProxySample::SetTime( REFERENCE_TIME * pTimeStart, // put time here REFERENCE_TIME * pTimeEnd ) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetTime(pTimeStart, pTimeEnd); } STDMETHODIMP ProxySample::IsSyncPoint(void) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->IsSyncPoint(); } STDMETHODIMP ProxySample::SetSyncPoint(BOOL bIsSyncPoint) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetSyncPoint(bIsSyncPoint); } STDMETHODIMP ProxySample::IsPreroll(void) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->IsPreroll(); } STDMETHODIMP ProxySample::SetPreroll(BOOL bIsPreroll) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetPreroll(bIsPreroll); } STDMETHODIMP_(LONG) ProxySample::GetActualDataLength(void) { if (m_pInner == NULL) { return 0; } return m_pInner->GetActualDataLength(); } STDMETHODIMP ProxySample::SetActualDataLength(LONG lActual) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetActualDataLength(lActual); } STDMETHODIMP ProxySample::GetMediaType(AM_MEDIA_TYPE **ppMediaType) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->GetMediaType(ppMediaType); } STDMETHODIMP ProxySample::SetMediaType(AM_MEDIA_TYPE *pMediaType) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetMediaType(pMediaType); } STDMETHODIMP ProxySample::IsDiscontinuity(void) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->IsDiscontinuity(); } STDMETHODIMP ProxySample::SetDiscontinuity(BOOL bDiscontinuity) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetDiscontinuity(bDiscontinuity); } STDMETHODIMP ProxySample::GetMediaTime( LONGLONG * pTimeStart, LONGLONG * pTimeEnd ) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->GetMediaTime(pTimeStart, pTimeEnd); } STDMETHODIMP ProxySample::SetMediaTime( LONGLONG * pTimeStart, LONGLONG * pTimeEnd ) { if (m_pInner == NULL) { return E_NOINTERFACE; } return m_pInner->SetMediaTime(pTimeStart, pTimeEnd); } STDMETHODIMP ProxySample::GetProperties( DWORD cbProperties, BYTE * pbProperties ) { IMediaSample2Ptr p2 = m_pInner; if (p2 == NULL) { return E_NOINTERFACE; } return p2->GetProperties(cbProperties, pbProperties); } STDMETHODIMP ProxySample::SetProperties( DWORD cbProperties, const BYTE * pbProperties ) { IMediaSample2Ptr p2 = m_pInner; if (p2 == NULL) { return E_NOINTERFACE; } return p2->SetProperties(cbProperties, pbProperties); }
24.535059
108
0.615767
jpjodoin
d127db0bd8c6ffd0cb6bd85b78870b89b178f4c8
68,099
cxx
C++
test/7cursor_primary.cxx
PositiveTechnologies/libfpta
57aff3aa85739fd9dce6a0b44955204d44e3c3b4
[ "Apache-2.0" ]
33
2017-07-13T10:38:11.000Z
2022-02-22T08:05:06.000Z
test/7cursor_primary.cxx
PositiveTechnologies/libfpta
57aff3aa85739fd9dce6a0b44955204d44e3c3b4
[ "Apache-2.0" ]
2
2017-07-13T21:25:16.000Z
2020-07-09T23:14:27.000Z
test/7cursor_primary.cxx
PositiveTechnologies/libfpta
57aff3aa85739fd9dce6a0b44955204d44e3c3b4
[ "Apache-2.0" ]
8
2017-10-04T20:07:41.000Z
2021-05-15T16:39:18.000Z
/* * Fast Positive Tables (libfpta), aka Позитивные Таблицы. * Copyright 2016-2020 Leonid Yuriev <[email protected]> * * 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 "fpta_test.h" #include "keygen.hpp" /* Кол-во проверочных точек в диапазонах значений индексируемых типов. * * Значение не может быть больше чем 65536, так как это предел кол-ва * уникальных значений для fptu_uint16. * * Использовать тут большие значения смысла нет. Время работы тестов * растет примерно линейно (чуть быстрее), тогда как вероятность * проявления каких-либо ошибок растет в лучшем случае как Log(NNN), * а скорее даже как SquareRoot(Log(NNN)). */ #ifdef FPTA_CURSOR_UT_LONG static cxx11_constexp_varr int NNN = 65521; // около 1-2 минуты в /dev/shm/ #else static cxx11_constexpr_var int NNN = 509; // менее секунды в /dev/shm/ #endif static const char testdb_name[] = TEST_DB_DIR "ut_cursor_primary.fpta"; static const char testdb_name_lck[] = TEST_DB_DIR "ut_cursor_primary.fpta" MDBX_LOCK_SUFFIX; class CursorPrimary : public ::testing::TestWithParam<GTEST_TUPLE_NAMESPACE_::tuple< fptu_type, fpta_index_type, fpta_cursor_options>> { public: fptu_type type; fpta_index_type index; fpta_cursor_options ordering; bool valid_index_ops; bool valid_cursor_ops; bool skipped; scoped_db_guard db_quard; scoped_txn_guard txn_guard; scoped_cursor_guard cursor_guard; std::string pk_col_name; fpta_name table, col_pk, col_order, col_dup_id, col_t1ha; static cxx11_constexpr_var int n_dups = 5; int n_records; std::unordered_map<int, int> reorder; static int mesh(int n) { return (int)((163 + (unsigned)n * 42101) % NNN); } void CheckPosition(int linear, int dup_id, int expected_n_dups = 0, bool check_dup_id = true) { if (linear < 0) { /* для удобства и выразительности теста linear = -1 здесь * означает последнюю запись, -2 = предпоследнюю и т.д. */ linear += (int)reorder.size(); } if (dup_id < 0) { /* для удобства и выразительности теста dup_id = -1 здесь * означает последний дубликат, -2 = предпоследний и т.д. */ dup_id += n_dups; } if (expected_n_dups == 0) { /* для краткости теста expected_n_dups = 0 здесь означает значение * по-умолчанию, когда строки-дубликаты не удаляются в ходе теста */ expected_n_dups = fpta_index_is_unique(index) ? 1 : n_dups; } SCOPED_TRACE("linear-order " + std::to_string(linear) + " [0..." + std::to_string(reorder.size() - 1) + "], linear-dup " + (check_dup_id ? std::to_string(dup_id) : "any")); ASSERT_EQ(1u, reorder.count(linear)); const auto expected_order = reorder.at(linear); /* Следует пояснить (в том числе напомнить себе), почему порядок * следования строк-дубликатов (с одинаковым значением PK) здесь * совпадает с dup_id: * - При формировании строк-дубликатов, их кортежи полностью совпадают, * за исключением поля dup_id. При этом dup_id отличается только * одним байтом. * - В случае primary-индекса данные, соответствующие одному значению * ключа, сортируются при помощи компаратора fptu_cmp_tuples(), что * формирует порядок по возрастанию dup_id. Однако, даже при * сравнении посредством memcmp(), различие только в одном байте * также сформирует порядок по возрастанию dup_id. * * Таким образом, физический порядок строк-дубликатов всегда по * возрастанию dup_id (причем нет видимых причин это как-либо менять). * * -------------------------------------------------------------------- * * Далее, для курсора с обратным порядком сортировки (descending) * видимый порядок строк будет изменен на обратный, включая порядок * строк-дубликатов. Предполагается что такая симметричность будет * более ожидаема и удобна, нежели если порядок дубликатов * сохранится (не будет обратным). * * Соответственно ниже для descending-курсора выполняется "переворот" * контрольного номера дубликата. */ const int expected_dup_id = fpta_index_is_unique(index) ? 42 : fpta_cursor_is_descending(ordering) ? n_dups - (dup_id + 1) : dup_id; SCOPED_TRACE("logical-order " + std::to_string(expected_order) + " [" + std::to_string(0) + "..." + std::to_string(NNN) + "), logical-dup " + (check_dup_id ? std::to_string(expected_dup_id) : "any")); ASSERT_EQ(FPTA_OK, fpta_cursor_eof(cursor_guard.get())); fptu_ro tuple; ASSERT_EQ(FPTA_OK, fpta_cursor_get(cursor_guard.get(), &tuple)); ASSERT_STREQ(nullptr, fptu::check(tuple)); int error; fpta_value key; ASSERT_EQ(FPTA_OK, fpta_cursor_key(cursor_guard.get(), &key)); SCOPED_TRACE("key: " + std::to_string(key.type) + ", length " + std::to_string(key.binary_length)); auto tuple_order = (int)fptu_get_sint(tuple, col_order.column.num, &error); ASSERT_EQ(FPTU_OK, error); ASSERT_EQ(expected_order, tuple_order); auto tuple_checksum = fptu_get_uint(tuple, col_t1ha.column.num, &error); ASSERT_EQ(FPTU_OK, error); auto checksum = order_checksum(tuple_order, type, index).uint; ASSERT_EQ(checksum, tuple_checksum); auto tuple_dup_id = (int)fptu_get_uint(tuple, col_dup_id.column.num, &error); ASSERT_EQ(FPTU_OK, error); if (check_dup_id || fpta_index_is_unique(index)) { EXPECT_EQ(expected_dup_id, tuple_dup_id); } size_t dups = 100500; ASSERT_EQ(FPTA_OK, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ(expected_n_dups, (int)dups); } virtual void Fill() { fptu_rw *row = fptu_alloc(4, fpta_max_keylen * 2 + 4 + 4); ASSERT_NE(nullptr, row); ASSERT_STREQ(nullptr, fptu::check(row)); fpta_txn *const txn = txn_guard.get(); any_keygen keygen(type, index); n_records = 0; for (int linear = 0; linear < NNN; ++linear) { int order = mesh(linear); SCOPED_TRACE("order " + std::to_string(order)); fpta_value value_pk = keygen.make(order, NNN); if (value_pk.type == fpta_end) break; if (value_pk.type == fpta_begin) continue; // теперь формируем кортеж ASSERT_EQ(FPTU_OK, fptu_clear(row)); ASSERT_STREQ(nullptr, fptu::check(row)); ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_order, fpta_value_sint(order))); ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_pk, value_pk)); // t1ha как "checksum" для order ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_t1ha, order_checksum(order, type, index))); if (fpta_index_is_unique(index)) { // вставляем одну запись с dup_id = 42 ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_dup_id, fpta_value_uint(42))); ASSERT_EQ(FPTA_OK, fpta_insert_row(txn, &table, fptu_take_noshrink(row))); ++n_records; } else { for (int dup_id = 0; dup_id < n_dups; ++dup_id) { ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_dup_id, fpta_value_sint(dup_id))); ASSERT_EQ(FPTA_OK, fpta_insert_row(txn, &table, fptu_take_noshrink(row))); ++n_records; } } } // разрушаем кортеж ASSERT_STREQ(nullptr, fptu::check(row)); free(row); } virtual void SetUp() { // нужно простое число, иначе сломается переупорядочивание ASSERT_TRUE(isPrime(NNN)); // иначе не сможем проверить fptu_uint16 ASSERT_GE(65535, NNN); type = GTEST_TUPLE_NAMESPACE_::get<0>(GetParam()); index = GTEST_TUPLE_NAMESPACE_::get<1>(GetParam()); ordering = GTEST_TUPLE_NAMESPACE_::get<2>(GetParam()); valid_index_ops = is_valid4primary(type, index); valid_cursor_ops = is_valid4cursor(index, ordering); SCOPED_TRACE( "type " + std::to_string(type) + ", index " + std::to_string(index) + (valid_index_ops ? ", (valid index case)" : ", (invalid index case)")); SCOPED_TRACE("ordering " + std::to_string(ordering) + ", index " + std::to_string(index) + (valid_cursor_ops ? ", (valid cursor case)" : ", (invalid cursor case)")); skipped = GTEST_IS_EXECUTION_TIMEOUT(); if (skipped) return; // инициализируем идентификаторы колонок ASSERT_EQ(FPTA_OK, fpta_table_init(&table, "table")); pk_col_name = "pk_" + std::to_string(type); ASSERT_EQ(FPTA_OK, fpta_column_init(&table, &col_pk, pk_col_name.c_str())); ASSERT_EQ(FPTA_OK, fpta_column_init(&table, &col_order, "order")); ASSERT_EQ(FPTA_OK, fpta_column_init(&table, &col_dup_id, "dup_id")); ASSERT_EQ(FPTA_OK, fpta_column_init(&table, &col_t1ha, "t1ha")); // создаем четыре колонки: pk, order, t1ha и dup_id fpta_column_set def; fpta_column_set_init(&def); if (!valid_index_ops) { EXPECT_NE(FPTA_OK, fpta_column_describe(pk_col_name.c_str(), type, index, &def)); EXPECT_EQ(FPTA_OK, fpta_column_describe("order", fptu_int32, fpta_index_none, &def)); ASSERT_NE(FPTA_OK, fpta_column_set_validate(&def)); // разрушаем описание таблицы EXPECT_EQ(FPTA_OK, fpta_column_set_destroy(&def)); EXPECT_NE(FPTA_OK, fpta_column_set_validate(&def)); return; } EXPECT_EQ(FPTA_OK, fpta_column_describe(pk_col_name.c_str(), type, index, &def)); EXPECT_EQ(FPTA_OK, fpta_column_describe("order", fptu_int32, fpta_index_none, &def)); EXPECT_EQ(FPTA_OK, fpta_column_describe("dup_id", fptu_uint16, fpta_noindex_nullable, &def)); EXPECT_EQ(FPTA_OK, fpta_column_describe("t1ha", fptu_uint64, fpta_index_none, &def)); ASSERT_EQ(FPTA_OK, fpta_column_set_validate(&def)); // чистим if (REMOVE_FILE(testdb_name) != 0) { ASSERT_EQ(ENOENT, errno); } if (REMOVE_FILE(testdb_name_lck) != 0) { ASSERT_EQ(ENOENT, errno); } #ifdef FPTA_CURSOR_UT_LONG // пытаемся обойтись меньшей базой, // но для строк потребуется больше места unsigned megabytes = 32; if (type > fptu_96) megabytes = 56; if (type > fptu_256) megabytes = 64; #else unsigned megabytes = 1; #endif /* В пике нужно примерно вдвое больше места, так как один из тестов * будет выполнять удаление до половины строк в случайном порядке, * и в результате может обновить почти каждую страницу БД. */ megabytes += megabytes; fpta_db *db = nullptr; ASSERT_EQ(FPTA_OK, test_db_open(testdb_name, fpta_weak, fpta_regime_default, megabytes, true, &db)); ASSERT_NE(nullptr, db); db_quard.reset(db); // создаем таблицу fpta_txn *txn = nullptr; EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db, fpta_schema, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); ASSERT_EQ(FPTA_OK, fpta_table_create(txn, "table", &def)); ASSERT_EQ(FPTA_OK, fpta_transaction_end(txn_guard.release(), false)); txn = nullptr; // разрушаем описание таблицы EXPECT_EQ(FPTA_OK, fpta_column_set_destroy(&def)); EXPECT_NE(FPTA_OK, fpta_column_set_validate(&def)); /* Для полноты тесты переоткрываем базу. В этом нет явной необходимости, * но только так можно проверить работу некоторых механизмов. * * В частности: * - внутри движка создание таблицы одновременно приводит к открытию её * dbi-хендла, с размещением его во внутренних структурах. * - причем этот хендл будет жив до закрытии всей базы, либо до удаления * таблицы. * - поэтому для проверки кода открывающего существующую таблицы * необходимо закрыть и повторно открыть всю базу. */ // закрываем базу ASSERT_EQ(FPTA_SUCCESS, fpta_db_close(db_quard.release())); db = nullptr; // открываем заново ASSERT_EQ(FPTA_OK, test_db_open(testdb_name, fpta_weak, fpta_regime_default, megabytes, false, &db)); ASSERT_NE(nullptr, db); db_quard.reset(db); //------------------------------------------------------------------------ // начинаем транзакцию записи EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db, fpta_write, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); // связываем идентификаторы с ранее созданной схемой ASSERT_EQ(FPTA_OK, fpta_name_refresh_couple(txn, &table, &col_pk)); ASSERT_EQ(FPTA_OK, fpta_name_refresh(txn, &col_order)); ASSERT_EQ(FPTA_OK, fpta_name_refresh(txn, &col_dup_id)); ASSERT_EQ(FPTA_OK, fpta_name_refresh(txn, &col_t1ha)); ASSERT_NO_FATAL_FAILURE(Fill()); // завершаем транзакцию ASSERT_EQ(FPTA_OK, fpta_transaction_end(txn_guard.release(), false)); txn = nullptr; //------------------------------------------------------------------------ // начинаем транзакцию чтения EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db, fpta_read, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); fpta_cursor *cursor; if (valid_cursor_ops) { EXPECT_EQ(FPTA_OK, fpta_cursor_open(txn, &col_pk, fpta_value_begin(), fpta_value_end(), nullptr, ordering, &cursor)); ASSERT_NE(nullptr, cursor); cursor_guard.reset(cursor); } else { EXPECT_EQ(FPTA_NO_INDEX, fpta_cursor_open(txn, &col_pk, fpta_value_begin(), fpta_value_end(), nullptr, ordering, &cursor)); cursor_guard.reset(cursor); ASSERT_EQ(nullptr, cursor); return; } // формируем линейную карту, чтобы проще проверять переходы reorder.clear(); reorder.reserve(NNN); int prev_order = -1; for (int linear = 0; fpta_cursor_eof(cursor) == FPTA_OK; ++linear) { fptu_ro tuple; EXPECT_EQ(FPTA_OK, fpta_cursor_get(cursor_guard.get(), &tuple)); ASSERT_STREQ(nullptr, fptu::check(tuple)); int error; auto tuple_order = (int)fptu_get_sint(tuple, col_order.column.num, &error); ASSERT_EQ(FPTU_OK, error); auto tuple_checksum = fptu_get_uint(tuple, col_t1ha.column.num, &error); ASSERT_EQ(FPTU_OK, error); auto checksum = order_checksum(tuple_order, type, index).uint; ASSERT_EQ(checksum, tuple_checksum); reorder[linear] = tuple_order; error = fpta_cursor_move(cursor, fpta_key_next); if (error == FPTA_NODATA) break; ASSERT_EQ(FPTA_SUCCESS, error); // проверяем упорядоченность if (fpta_cursor_is_ordered(ordering) && linear > 0) { if (fpta_cursor_is_ascending(ordering)) { ASSERT_LE(prev_order, tuple_order); } else { ASSERT_GE(prev_order, tuple_order); } } prev_order = tuple_order; } ASSERT_EQ(NNN, (int)reorder.size()); } virtual void TearDown() { if (skipped) return; // разрушаем привязанные идентификаторы fpta_name_destroy(&table); fpta_name_destroy(&col_pk); fpta_name_destroy(&col_order); fpta_name_destroy(&col_dup_id); fpta_name_destroy(&col_t1ha); // закрываем курсор и завершаем транзакцию if (cursor_guard) { EXPECT_EQ(FPTA_OK, fpta_cursor_close(cursor_guard.release())); } if (txn_guard) { ASSERT_EQ(FPTA_OK, fpta_transaction_end(txn_guard.release(), true)); } if (db_quard) { // закрываем и удаляем базу ASSERT_EQ(FPTA_SUCCESS, fpta_db_close(db_quard.release())); ASSERT_TRUE(REMOVE_FILE(testdb_name) == 0); ASSERT_TRUE(REMOVE_FILE(testdb_name_lck) == 0); } } }; cxx11_constexpr_var int CursorPrimary::n_dups; TEST_P(CursorPrimary, basicMoves) { /* Проверка базовых перемещений курсора по первичному (primary) индексу. * * Сценарий (общий для всех типов полей и всех видов первичных индексов): * 1. Создается тестовая база с одной таблицей, в которой четыре колонки: * - "col_pk" (primary key) с типом, для которого производится * тестирование работы индекса. * - Колонка "order", в которую записывается контрольный (ожидаемый) * порядковый номер следования строки, при сортировке по col_pk и * проверяемому виду индекса. * - Колонка "dup_id", которая используется для идентификации * дубликатов индексов допускающих не-уникальные ключи. * - Колонка "t1ha", в которую записывается "контрольная сумма" от * ожидаемого порядка строки, типа PK и вида индекса. * Принципиальной необходимости в этой колонке нет, она используется * как "утяжелитель", а также для дополнительного контроля. * * 2. Для валидных комбинаций вида индекса и типа данных col_pk таблица * заполняется строками, значение col_pk в которых генерируется * соответствующим генератором значений: * - Сами генераторы проверяются в одном из тестов 0corny. * - Для индексов без уникальности для каждого ключа вставляется * 5 строк с разным dup_id. * * 3. Перебираются все комбинации индексов, типов колонок и видов курсора. * Для НЕ валидных комбинаций контролируются коды ошибок. * * 4. Для валидных комбинаций индекса и типа курсора, после заполнения * в отдельной транзакции формируется "карта" верификации перемещений: * - "карта" строится как неупорядоченное отображение линейных номеров * строк в порядке просмотра через курсор, на ожидаемые (контрольные) * значения колонки "order". * - при построении "карты" все строки читаются последовательно через * проверяемый курсор. * - для построенной "карты" проверяется размер (что прочитали все * строки и только по одному разу) и соответствия порядка строк * типу курсора (возрастание/убывание). * * 5. После формирования "карты" верификации перемещений выполняется ряд * базовых перемещений курсора: * - переход к первой/последней строке. * - попытки перейти за последнюю и за первую строки. * - переход в начало с отступлением к концу. * - переход к концу с отступление к началу. * - при каждом перемещении проверяется корректность кода ошибки, * соответствие текущей строки ожидаемому порядку, включая * содержимое строки и номера дубликата. * * 6. Завершаются операции и освобождаются ресурсы. */ if (!valid_index_ops || !valid_cursor_ops || skipped) return; SCOPED_TRACE("type " + std::to_string(type) + ", index " + std::to_string(index) + (valid_index_ops ? ", (valid case)" : ", (invalid case)")); SCOPED_TRACE( "ordering " + std::to_string(ordering) + ", index " + std::to_string(index) + (valid_cursor_ops ? ", (valid cursor case)" : ", (invalid cursor case)")); ASSERT_LT(5, n_records); fpta_cursor *const cursor = cursor_guard.get(); ASSERT_NE(nullptr, cursor); // переходим туда-сюда и к первой строке ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); // пробуем уйти дальше последней строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_last)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_first)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); // пробуем выйти за первую строку ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_last)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_first)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); // идем в конец и проверяем назад/вперед ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_next)); // идем в начало и проверяем назад/вперед ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, -1)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, -1)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_prev)); } //---------------------------------------------------------------------------- /* Другое имя класса требуется для инстанцирования другого (меньшего) * набора комбинаций в INSTANTIATE_TEST_SUITE_P. */ class CursorPrimaryDups : public CursorPrimary {}; TEST_P(CursorPrimaryDups, dupMoves) { /* Проверка перемещений курсора по дубликатами в первичном (primary) * индексе. * * Сценарий (общий для всех типов полей и всех видов первичных индексов): * 1. Создается тестовая база с одной таблицей, в которой четыре колонки: * - "col_pk" (primary key) с типом, для которого производится * тестирование работы индекса. * - Колонка "order", в которую записывается контрольный (ожидаемый) * порядковый номер следования строки, при сортировке по col_pk и * проверяемому виду индекса. * - Колонка "dup_id", которая используется для нумерации дубликатов. * - Колонка "t1ha", в которую записывается "контрольная сумма" от * ожидаемого порядка строки, типа PK и вида индекса. Принципиальной * необходимости в этой колонке нет, она используется как * "утяжелитель", а также для дополнительного контроля. * * 2. Для валидных комбинаций вида индекса и типа данных col_pk таблица * заполняется строками, значение PK в которых генерируется * соответствующим генератором значений: * - Сами генераторы проверяются в одном из тестов 0corny. * - Для каждого значения ключа вставляется 5 строк с разным dup_id. * - FIXME: Дополнительно, для тестирования межстраничных переходов, * генерируется длинная серия повторов, которая более чем в три раза * превышает размер страницы БД. * * 3. Перебираются все комбинации индексов, типов колонок и видов курсора. * Для НЕ валидных комбинаций контролируются коды ошибок. * * 4. Для валидных комбинаций индекса и типа курсора, после заполнения * в отдельной транзакции формируется "карта" верификации перемещений: * - "карта" строится как неупорядоченное отображение линейных номеров * строк в порядке просмотра через курсор, на ожидаемые (контрольные) * значения колонки "order". * - при построении "карты" все строки читаются последовательно через * проверяемый курсор. * - для построенной "карты" проверяется размер (что прочитали все * строки и только по одному разу) и соответствия порядка строк * типу курсора (возрастание/убывание). * * 5. После формирования "карты" верификации перемещений выполняется ряд * базовых перемещений курсора по дубликатам: * - переход к первой/последней строке, * к первому и последнему дубликату. * - попытки перейти за последнюю и за первую строки, * за первый/последний дубликат. * - переход в начало с отступлением к концу. * - переход к концу с отступление к началу. * - при каждом перемещении проверяется корректность кода ошибки, * соответствие текущей строки ожидаемому порядку, включая * содержимое строки и номера дубликата. * * 6. Завершаются операции и освобождаются ресурсы. */ if (!valid_index_ops || !valid_cursor_ops || skipped || fpta_index_is_unique(index)) return; SCOPED_TRACE("type " + std::to_string(type) + ", index " + std::to_string(index) + (valid_index_ops ? ", (valid case)" : ", (invalid case)")); SCOPED_TRACE( "ordering " + std::to_string(ordering) + ", index " + std::to_string(index) + (valid_cursor_ops ? ", (valid cursor case)" : ", (invalid cursor case)")); ASSERT_LT(5, n_records); fpta_cursor *const cursor = cursor_guard.get(); ASSERT_NE(nullptr, cursor); /* переходим туда-сюда и к первой строке, такие переходы уже проверялись * в предыдущем тесте, здесь же для проверки жизнеспособности курсора. */ ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); // к последнему, затем к первому дубликату первой строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); // вперед по дубликатам первой строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 4)); // пробуем выйти за последний дубликат ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 4)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 4)); // назад по дубликатам первой строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); // пробуем выйти за первый дубликат ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); // вперед в обход дубликатов, ко второй строке, затем к третьей и четвертой ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(3, 0)); // назад в обход дубликатов, до первой строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, -1)); // пробуем выйти за первую строку ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); // последовательно вперед от начала по каждому дубликату ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(3, 0)); // последовательно назад к началу по каждому дубликату ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(0, 0)); // пробуем выйти за первую строку ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_prev)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); //-------------------------------------------------------------------------- // к последней строке ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); // к первому, затем к последнему дубликату последней строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_first)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_last)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); // назад по дубликатам последней строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); // пробуем выйти за первый дубликат ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); // вперед по дубликатам первой строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 4)); // пробуем выйти за последний дубликат ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_dup_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, -1)); // назад в обход дубликатов, к предпоследней строке, // затем к пред-предпоследней... ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, -1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-4, -1)); // вперед в обход дубликатов, до последней строки ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); // пробуем выйти за первую строку ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_key_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); // последовательно назад от конца по каждому дубликату ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 0)); // последовательно вперед до конца по каждому дубликату ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-3, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-2, 4)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 0)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 1)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 2)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 3)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_next)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 4)); // пробуем выйти за последнюю строку ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_move(cursor, fpta_next)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_prev)); ASSERT_NO_FATAL_FAILURE(CheckPosition(-1, 4)); } //---------------------------------------------------------------------------- TEST_P(CursorPrimary, locate_and_delele) { /* Проверка позиционирования курсора по первичному (primary) индексу. * * Сценарий (общий для всех типов полей и всех видов первичных индексов): * 1. Создается тестовая база с одной таблицей, в которой четыре колонки: * - "col_pk" (primary key) с типом, для которого производится * тестирование работы индекса. * - Колонка "order", в которую записывается контрольный (ожидаемый) * порядковый номер следования строки, при сортировке по col_pk и * проверяемому виду индекса. * - Колонка "dup_id", которая используется для идентификации * дубликатов индексов допускающих не-уникальные ключи. * - Колонка "t1ha", в которую записывается "контрольная сумма" от * ожидаемого порядка строки, типа PK и вида индекса. * Принципиальной необходимости в этой колонке нет, она используется * как "утяжелитель", а также для дополнительного контроля. * * 2. Для валидных комбинаций вида индекса и типа данных col_pk таблица * заполняется строками, значение col_pk в которых генерируется * соответствующим генератором значений: * - Сами генераторы проверяются в одном из тестов 0corny. * - Для индексов без уникальности для каждого ключа вставляется * 5 строк с разным dup_id. * * 3. Перебираются все комбинации индексов, типов колонок и видов курсора. * Для НЕ валидных комбинаций контролируются коды ошибок. * * 4. Для валидных комбинаций индекса и типа курсора, после заполнения * в отдельной транзакции формируется "карта" верификации перемещений: * - "карта" строится как неупорядоченное отображение линейных номеров * строк в порядке просмотра через курсор, на ожидаемые (контрольные) * значения колонки "order". * - при построении "карты" все строки читаются последовательно через * проверяемый курсор. * - для построенной "карты" проверяется размер (что прочитали все * строки и только по одному разу) и соответствия порядка строк * типу курсора (возрастание/убывание). * * 5. После формирования "карты" выполняются несколько проверочных * итераций, в конце каждой из которых часть записей удаляется: * - выполняется позиционирование на значение ключа для каждого * элемента проверочной "карты", которая была сформирована * на предыдущем шаге. * - проверяется успешность операции с учетом того был ли элемент * уже удален или еще нет. * - проверяется результирующая позиция курсора. * - удаляется часть строк: текущая транзакция чтения закрывается, * открывается пишущая, выполняется удаление, курсор переоткрывается. * - после каждого удаления проверяется что позиция курсора * соответствует ожиданиям (сделан переход к следующей записи * в порядке курсора). * - итерации повторяются пока не будут удалены все строки. * - при выполнении всех проверок и удалений строки выбираются * в стохастическом порядке. * * 6. Завершаются операции и освобождаются ресурсы. */ if (!valid_index_ops || !valid_cursor_ops || skipped) return; SCOPED_TRACE("type " + std::to_string(type) + ", index " + std::to_string(index) + (valid_index_ops ? ", (valid case)" : ", (invalid case)")); SCOPED_TRACE( "ordering " + std::to_string(ordering) + ", index " + std::to_string(index) + (valid_cursor_ops ? ", (valid cursor case)" : ", (invalid cursor case)")); ASSERT_LT(5, n_records); /* заполняем present "номерами" значений ключа существующих записей, * важно что эти "номера" через карту позволяют получить соответствующее * значения от генератора ключей */ std::vector<int> present; std::map<int, int> dups_countdown; for (const auto &pair : reorder) { present.push_back(pair.first); dups_countdown[pair.first] = fpta_index_is_unique(index) ? 1 : n_dups; } // сохраняем исходный полный набор auto initial = present; any_keygen keygen(type, index); for (;;) { SCOPED_TRACE("records left " + std::to_string(present.size())); // перемешиваем for (size_t i = 0; i < present.size(); ++i) { auto remix = (4201 + i * 2017) % present.size(); std::swap(present[i], present[remix]); } for (size_t i = 0; i < initial.size(); ++i) { auto remix = (44741 + i * 55001) % initial.size(); std::swap(initial[i], initial[remix]); } // начинаем транзакцию чтения если предыдущая закрыта fpta_txn *txn = txn_guard.get(); if (!txn_guard) { EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db_quard.get(), fpta_read, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); } // открываем курсор для чтения fpta_cursor *cursor = nullptr; EXPECT_EQ(FPTA_OK, fpta_cursor_open( txn_guard.get(), &col_pk, fpta_value_begin(), fpta_value_end(), nullptr, (fpta_cursor_options)(ordering | fpta_dont_fetch), &cursor)); ASSERT_NE(nullptr, cursor); cursor_guard.reset(cursor); // проверяем позиционирование for (size_t i = 0; i < initial.size(); ++i) { const auto linear = initial.at(i); ASSERT_EQ(1u, reorder.count(linear)); const auto order = reorder[linear]; int expected_dups = dups_countdown.count(linear) ? dups_countdown.at(linear) : 0; SCOPED_TRACE("linear " + std::to_string(linear) + ", order " + std::to_string(order) + (dups_countdown.count(linear) ? ", present" : ", deleted")); fpta_value key = keygen.make(order, NNN); size_t dups = 100500; switch (expected_dups) { case 0: /* все значения уже были удалены, * точный поиск (exactly=true) должен вернуть "нет данных" */ ASSERT_EQ(FPTA_NODATA, fpta_cursor_locate(cursor, true, &key, nullptr)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_ECURSOR, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ((size_t)FPTA_DEADBEEF, dups); if (present.size()) { /* но какие-то строки в таблице еще есть, поэтому неточный * поиск (exactly=false) должен вернуть "ОК" если: * - для курсора определен порядок строк. * - в порядке курсора есть строки "после" запрошенного значения * ключа (аналогично lower_bound и с учетом того, что строк * с заданным значением ключа уже нет). */ const auto lower_bound = dups_countdown.lower_bound(linear); if (fpta_cursor_is_ordered(ordering) && lower_bound != dups_countdown.end()) { const auto SCOPED_TRACE_ONLY expected_linear = lower_bound->first; const auto SCOPED_TRACE_ONLY expected_order = reorder[expected_linear]; expected_dups = lower_bound->second; SCOPED_TRACE("lower-bound: linear " + std::to_string(expected_linear) + ", order " + std::to_string(expected_order) + ", n-dups " + std::to_string(expected_dups)); ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); ASSERT_NO_FATAL_FAILURE( CheckPosition(expected_linear, /* см ниже пояснение о expected_dup_number */ n_dups - expected_dups, expected_dups)); } else { if (fpta_cursor_is_ordered(ordering) || !FPTA_PROHIBIT_NEARBY4UNORDERED) { ASSERT_EQ(FPTA_NODATA, fpta_cursor_locate(cursor, false, &key, nullptr)); } else { ASSERT_NE(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); } ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_ECURSOR, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ((size_t)FPTA_DEADBEEF, dups); } } else { if (fpta_cursor_is_ordered(ordering) || !FPTA_PROHIBIT_NEARBY4UNORDERED) { ASSERT_EQ(FPTA_NODATA, fpta_cursor_locate(cursor, false, &key, nullptr)); } else { ASSERT_NE(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); } ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_ECURSOR, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ((size_t)FPTA_DEADBEEF, dups); } continue; case 1: if (fpta_cursor_is_ordered(ordering) || !FPTA_PROHIBIT_NEARBY4UNORDERED) { ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); ASSERT_NO_FATAL_FAILURE(CheckPosition(linear, -1, 1)); } else { ASSERT_NE(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_ECURSOR, fpta_cursor_dups(cursor_guard.get(), &dups)); } ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, true, &key, nullptr)); ASSERT_NO_FATAL_FAILURE(CheckPosition(linear, -1, 1)); break; default: /* Пояснения о expected_dup_number: * - курсор позиционируется на первый дубликат в порядке сортировки * в соответствии с типом курсора; * - удаление записей (ниже по коду) выполняется после такого * позиционирования; * - соответственно, постепенно удаляются все дубликаты, * начиная с первого в порядке сортировки курсора. * * Таким образом, ожидаемое количество дубликатов также определяет * dup_id первой строки-дубликата, на которую должен встать курсор. */ int const expected_dup_number = n_dups - expected_dups; SCOPED_TRACE("multi-val: n-dups " + std::to_string(expected_dups) + ", here-dup " + std::to_string(expected_dup_number)); ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, true, &key, nullptr)); ASSERT_EQ(FPTA_OK, fpta_cursor_eof(cursor)); ASSERT_NO_FATAL_FAILURE( CheckPosition(linear, expected_dup_number, expected_dups)); if (fpta_cursor_is_ordered(ordering) || !FPTA_PROHIBIT_NEARBY4UNORDERED) { ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); ASSERT_NO_FATAL_FAILURE( CheckPosition(linear, expected_dup_number, expected_dups)); } else { ASSERT_NE(FPTA_OK, fpta_cursor_locate(cursor, false, &key, nullptr)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_ECURSOR, fpta_cursor_dups(cursor_guard.get(), &dups)); } break; } } // закрываем читающий курсор и транзакцию ASSERT_EQ(FPTA_OK, fpta_cursor_close(cursor_guard.release())); cursor = nullptr; ASSERT_EQ(FPTA_OK, fpta_transaction_end(txn_guard.release(), true)); txn = nullptr; if (present.size() == 0) break; // начинаем пишущую транзакцию для удаления EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db_quard.get(), fpta_write, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); // открываем курсор для удаления EXPECT_EQ(FPTA_OK, fpta_cursor_open(txn_guard.get(), &col_pk, fpta_value_begin(), fpta_value_end(), nullptr, ordering, &cursor)); ASSERT_NE(nullptr, cursor); cursor_guard.reset(cursor); // проверяем позиционирование и удаляем for (size_t i = present.size(); i > present.size() / 2;) { const auto linear = present.at(--i); const auto order = reorder.at(linear); int expected_dups = dups_countdown.at(linear); SCOPED_TRACE("delete: linear " + std::to_string(linear) + ", order " + std::to_string(order) + ", dups left " + std::to_string(expected_dups)); fpta_value key = keygen.make(order, NNN); ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, true, &key, nullptr)); ASSERT_EQ(0, fpta_cursor_eof(cursor)); size_t dups = 100500; ASSERT_EQ(FPTA_OK, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ(expected_dups, (int)dups); ASSERT_EQ(FPTA_OK, fpta_cursor_delete(cursor)); expected_dups = --dups_countdown.at(linear); if (expected_dups == 0) { present.erase(present.begin() + (int)i); dups_countdown.erase(linear); } // проверяем состояние курсора и его переход к следующей строке if (present.empty()) { ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ(0u, dups); } else if (expected_dups) { ASSERT_NO_FATAL_FAILURE( CheckPosition(linear, /* см выше пояснение о expected_dup_number */ n_dups - expected_dups, expected_dups)); } else if (fpta_cursor_is_ordered(ordering)) { const auto lower_bound = dups_countdown.lower_bound(linear); if (lower_bound != dups_countdown.end()) { const auto SCOPED_TRACE_ONLY expected_linear = lower_bound->first; const auto SCOPED_TRACE_ONLY expected_order = reorder[expected_linear]; expected_dups = lower_bound->second; SCOPED_TRACE("after-delete: linear " + std::to_string(expected_linear) + ", order " + std::to_string(expected_order) + ", n-dups " + std::to_string(expected_dups)); ASSERT_NO_FATAL_FAILURE( CheckPosition(expected_linear, /* см выше пояснение о expected_dup_number */ n_dups - expected_dups, expected_dups)); } else { ASSERT_EQ(FPTA_NODATA, fpta_cursor_eof(cursor)); ASSERT_EQ(FPTA_NODATA, fpta_cursor_dups(cursor_guard.get(), &dups)); ASSERT_EQ(0u, dups); } } } // завершаем транзакцию удаления ASSERT_EQ(FPTA_OK, fpta_cursor_close(cursor_guard.release())); cursor = nullptr; ASSERT_EQ(FPTA_OK, fpta_transaction_end(txn_guard.release(), false)); txn = nullptr; } } //---------------------------------------------------------------------------- TEST_P(CursorPrimary, update_and_KeyMismatch) { /* Проверка обновления через курсор, в том числе с попытками изменить * значение "курсорной" колонки. * * Сценарий (общий для всех типов полей и всех видов первичных индексов): * 1. Создается тестовая база с одной таблицей, в которой четыре колонки: * - "col_pk" (primary key) с типом, для которого производится * тестирование работы индекса. * - Колонка "order", в которую записывается контрольный (ожидаемый) * порядковый номер следования строки, при сортировке по col_pk и * проверяемому виду индекса. * - Колонка "dup_id", которая используется для идентификации * дубликатов индексов допускающих не-уникальные ключи. * - Колонка "t1ha", в которую записывается "контрольная сумма" от * ожидаемого порядка строки, типа PK и вида индекса. * Принципиальной необходимости в этой колонке нет, она используется * как "утяжелитель", а также для дополнительного контроля. * * 2. Для валидных комбинаций вида индекса и типа данных col_pk таблица * заполняется строками, значение col_pk в которых генерируется * соответствующим генератором значений: * - Сами генераторы проверяются в одном из тестов 0corny. * - Для индексов без уникальности для каждого ключа вставляется * 5 строк с разным dup_id. * * 3. Перебираются все комбинации индексов, типов колонок и видов курсора. * Для НЕ валидных комбинаций контролируются коды ошибок. * * 4. Для валидных комбинаций индекса и типа курсора, после заполнения * в отдельной транзакции формируется "карта" верификации перемещений: * - "карта" строится как неупорядоченное отображение линейных номеров * строк в порядке просмотра через курсор, на ожидаемые (контрольные) * значения колонки "order". * - при построении "карты" все строки читаются последовательно через * проверяемый курсор. * - для построенной "карты" проверяется размер (что прочитали все * строки и только по одному разу) и соответствия порядка строк * типу курсора (возрастание/убывание). * * 5. Примерно половина строк (без учета дубликатов) изменяется * через курсор: * - в качестве критерия изменять/не-менять используется * младший бит значения колонки "t1ha". * - в изменяемых строках инвертируется знак колонки "order", * а колонка "dup_id" устанавливается в 4242. * - при каждом реальном обновлении делается две попытки обновить * строку с изменением значения ключевой "курсорной" колонки. * * 6. Выполняется проверка всех строк, как исходных, так и измененных. * При наличии дубликатов, измененные строки ищутся по значению * колонки "dup_id". */ if (!valid_index_ops || !valid_cursor_ops || skipped) return; SCOPED_TRACE("type " + std::to_string(type) + ", index " + std::to_string(index) + (valid_index_ops ? ", (valid case)" : ", (invalid case)")); SCOPED_TRACE( "ordering " + std::to_string(ordering) + ", index " + std::to_string(index) + (valid_cursor_ops ? ", (valid cursor case)" : ", (invalid cursor case)")); any_keygen keygen(type, index); const int expected_dups = fpta_index_is_unique(index) ? 1 : n_dups; // закрываем читающий курсор и транзакцию ASSERT_EQ(FPTA_OK, fpta_cursor_close(cursor_guard.release())); ASSERT_EQ(FPTA_OK, fpta_transaction_end(txn_guard.release(), true)); // начинаем пишущую транзакцию для изменений fpta_txn *txn = nullptr; EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db_quard.get(), fpta_write, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); // открываем курсор для изменения fpta_cursor *cursor = nullptr; EXPECT_EQ(FPTA_OK, fpta_cursor_open(txn_guard.get(), &col_pk, fpta_value_begin(), fpta_value_end(), nullptr, ordering, &cursor)); ASSERT_NE(nullptr, cursor); cursor_guard.reset(cursor); // обновляем половину строк for (int order = 0; order < NNN; ++order) { SCOPED_TRACE("order " + std::to_string(order)); fpta_value value_pk = keygen.make(order, NNN); ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, true, &value_pk, nullptr)); ASSERT_EQ(FPTA_OK, fpta_cursor_eof(cursor_guard.get())); fptu_ro tuple; ASSERT_EQ(FPTA_OK, fpta_cursor_get(cursor_guard.get(), &tuple)); ASSERT_STREQ(nullptr, fptu::check(tuple)); int error; auto tuple_order = (int)fptu_get_sint(tuple, col_order.column.num, &error); ASSERT_EQ(FPTU_OK, error); ASSERT_EQ(order, tuple_order); auto tuple_checksum = fptu_get_uint(tuple, col_t1ha.column.num, &error); ASSERT_EQ(FPTU_OK, error); const auto checksum = order_checksum(tuple_order, type, index).uint; ASSERT_EQ(checksum, tuple_checksum); if (checksum & 1) { uint8_t buffer[(fpta_max_keylen + 4) * 4 + sizeof(fptu_rw)]; fptu_rw *row = fptu_fetch(tuple, buffer, sizeof(buffer), 1); ASSERT_NE(nullptr, row); ASSERT_STREQ(nullptr, fptu::check(row)); // инвертируем знак order и пытаемся обновить строку с изменением ключа ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_order, fpta_value_sint(-tuple_order))); value_pk = keygen.make((order + 42) % NNN, NNN); ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_pk, value_pk)); ASSERT_EQ(FPTA_KEY_MISMATCH, fpta_cursor_probe_and_update(cursor, fptu_take(row))); // восстанавливаем значение ключа и обновляем строку value_pk = keygen.make(order, NNN); ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_pk, value_pk)); // для простоты контроля среди дубликатов устанавливаем dup_id = 4242 ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_dup_id, fpta_value_sint(4242))); ASSERT_EQ(FPTA_OK, fpta_cursor_probe_and_update(cursor, fptu_take(row))); // для проверки еще раз пробуем "сломать" ключ value_pk = keygen.make((order + 24) % NNN, NNN); ASSERT_EQ(FPTA_OK, fpta_upsert_column(row, &col_pk, value_pk)); ASSERT_EQ(FPTA_KEY_MISMATCH, fpta_cursor_probe_and_update(cursor, fptu_take_noshrink(row))); size_t ndups; ASSERT_EQ(FPTA_OK, fpta_cursor_dups(cursor, &ndups)); ASSERT_EQ(expected_dups, (int)ndups); } } // завершаем транзакцию изменения ASSERT_EQ(FPTA_OK, fpta_cursor_close(cursor_guard.release())); cursor = nullptr; ASSERT_EQ(FPTA_OK, fpta_transaction_commit(txn_guard.release())); txn = nullptr; // начинаем транзакцию чтения если предыдущая закрыта EXPECT_EQ(FPTA_OK, fpta_transaction_begin(db_quard.get(), fpta_read, &txn)); ASSERT_NE(nullptr, txn); txn_guard.reset(txn); // открываем курсор для чтения EXPECT_EQ(FPTA_OK, fpta_cursor_open(txn_guard.get(), &col_pk, fpta_value_begin(), fpta_value_end(), nullptr, (fpta_cursor_options)(ordering | fpta_dont_fetch), &cursor)); ASSERT_NE(nullptr, cursor); cursor_guard.reset(cursor); // проверяем обновления for (int order = 0; order < NNN; ++order) { SCOPED_TRACE("order " + std::to_string(order)); const fpta_value value_pk = keygen.make(order, NNN); fptu_ro tuple; int error; ASSERT_EQ(FPTA_OK, fpta_cursor_locate(cursor, true, &value_pk, nullptr)); ASSERT_EQ(FPTA_OK, fpta_cursor_eof(cursor_guard.get())); size_t ndups; ASSERT_EQ(FPTA_OK, fpta_cursor_dups(cursor, &ndups)); ASSERT_EQ(expected_dups, (int)ndups); const auto checksum = order_checksum(order, type, index).uint; for (;;) { ASSERT_EQ(FPTA_OK, fpta_cursor_get(cursor_guard.get(), &tuple)); ASSERT_STREQ(nullptr, fptu::check(tuple)); auto tuple_checksum = fptu_get_uint(tuple, col_t1ha.column.num, &error); ASSERT_EQ(FPTU_OK, error); ASSERT_EQ(checksum, tuple_checksum); auto tuple_dup_id = (int)fptu_get_uint(tuple, col_dup_id.column.num, &error); ASSERT_EQ(FPTU_OK, error); // идем по строкам-дубликатом до той, которую обновляли if (tuple_dup_id != 4242 && (checksum & 1)) ASSERT_EQ(FPTA_OK, fpta_cursor_move(cursor, fpta_dup_next)); else break; } auto tuple_order = (int)fptu_get_sint(tuple, col_order.column.num, &error); ASSERT_EQ(FPTU_OK, error); int expected_order = order; if (checksum & 1) expected_order = -expected_order; EXPECT_EQ(expected_order, tuple_order); } } //---------------------------------------------------------------------------- #ifdef INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_SUITE_P( Combine, CursorPrimary, ::testing::Combine( ::testing::Values(fptu_null, fptu_uint16, fptu_int32, fptu_uint32, fptu_fp32, fptu_int64, fptu_uint64, fptu_fp64, fptu_datetime, fptu_96, fptu_128, fptu_160, fptu_256, fptu_cstr, fptu_opaque /*, fptu_nested, fptu_farray */), ::testing::Values(fpta_primary_unique_ordered_obverse, fpta_primary_unique_ordered_reverse, fpta_primary_withdups_ordered_obverse, fpta_primary_withdups_ordered_reverse, fpta_primary_unique_unordered, fpta_primary_withdups_unordered), ::testing::Values(fpta_unsorted, fpta_ascending, fpta_descending))); INSTANTIATE_TEST_SUITE_P( Combine, CursorPrimaryDups, ::testing::Combine( ::testing::Values(fptu_null, fptu_uint16, fptu_int32, fptu_uint32, fptu_fp32, fptu_int64, fptu_uint64, fptu_fp64, fptu_datetime, fptu_96, fptu_128, fptu_160, fptu_256, fptu_cstr, fptu_opaque /*, fptu_nested, fptu_farray */), ::testing::Values(fpta_primary_withdups_ordered_obverse, fpta_primary_withdups_ordered_reverse, fpta_primary_withdups_unordered), ::testing::Values(fpta_unsorted, fpta_ascending, fpta_descending))); #else INSTANTIATE_TEST_CASE_P( Combine, CursorPrimary, ::testing::Combine( ::testing::Values(fptu_null, fptu_uint16, fptu_int32, fptu_uint32, fptu_fp32, fptu_int64, fptu_uint64, fptu_fp64, fptu_datetime, fptu_96, fptu_128, fptu_160, fptu_256, fptu_cstr, fptu_opaque /*, fptu_nested, fptu_farray */), ::testing::Values(fpta_primary_unique_ordered_obverse, fpta_primary_unique_ordered_reverse, fpta_primary_withdups_ordered_obverse, fpta_primary_withdups_ordered_reverse, fpta_primary_unique_unordered, fpta_primary_withdups_unordered), ::testing::Values(fpta_unsorted, fpta_ascending, fpta_descending))); INSTANTIATE_TEST_CASE_P( Combine, CursorPrimaryDups, ::testing::Combine( ::testing::Values(fptu_null, fptu_uint16, fptu_int32, fptu_uint32, fptu_fp32, fptu_int64, fptu_uint64, fptu_fp64, fptu_datetime, fptu_96, fptu_128, fptu_160, fptu_256, fptu_cstr, fptu_opaque /*, fptu_nested, fptu_farray */), ::testing::Values(fpta_primary_withdups_ordered_obverse, fpta_primary_withdups_ordered_reverse, fpta_primary_withdups_unordered), ::testing::Values(fpta_unsorted, fpta_ascending, fpta_descending))); #endif int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
44.480078
80
0.68092
PositiveTechnologies
d1359829334d73316421b50e476485f93b7db421
12,315
cc
C++
cartographer/cloud/internal/map_builder_server.cc
sotnik-github/cartographer
73d18e5fc54bfa4e4e61fd7feb615b46834aa584
[ "Apache-2.0" ]
30
2017-08-12T21:44:47.000Z
2022-03-23T09:31:05.000Z
cartographer/cloud/internal/map_builder_server.cc
sotnik-github/cartographer
73d18e5fc54bfa4e4e61fd7feb615b46834aa584
[ "Apache-2.0" ]
17
2017-06-02T01:55:21.000Z
2022-03-02T01:52:58.000Z
cartographer/cloud/internal/map_builder_server.cc
sotnik-github/cartographer
73d18e5fc54bfa4e4e61fd7feb615b46834aa584
[ "Apache-2.0" ]
16
2018-04-12T18:35:59.000Z
2022-01-03T14:25:35.000Z
/* * Copyright 2017 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cartographer/cloud/internal/map_builder_server.h" #include "cartographer/cloud/internal/handlers/add_fixed_frame_pose_data_handler.h" #include "cartographer/cloud/internal/handlers/add_imu_data_handler.h" #include "cartographer/cloud/internal/handlers/add_landmark_data_handler.h" #include "cartographer/cloud/internal/handlers/add_odometry_data_handler.h" #include "cartographer/cloud/internal/handlers/add_rangefinder_data_handler.h" #include "cartographer/cloud/internal/handlers/add_sensor_data_batch_handler.h" #include "cartographer/cloud/internal/handlers/add_trajectory_handler.h" #include "cartographer/cloud/internal/handlers/finish_trajectory_handler.h" #include "cartographer/cloud/internal/handlers/get_all_submap_poses.h" #include "cartographer/cloud/internal/handlers/get_constraints_handler.h" #include "cartographer/cloud/internal/handlers/get_landmark_poses_handler.h" #include "cartographer/cloud/internal/handlers/get_local_to_global_transform_handler.h" #include "cartographer/cloud/internal/handlers/get_submap_handler.h" #include "cartographer/cloud/internal/handlers/get_trajectory_node_poses_handler.h" #include "cartographer/cloud/internal/handlers/is_trajectory_finished_handler.h" #include "cartographer/cloud/internal/handlers/is_trajectory_frozen_handler.h" #include "cartographer/cloud/internal/handlers/load_state_handler.h" #include "cartographer/cloud/internal/handlers/receive_global_slam_optimizations_handler.h" #include "cartographer/cloud/internal/handlers/receive_local_slam_results_handler.h" #include "cartographer/cloud/internal/handlers/run_final_optimization_handler.h" #include "cartographer/cloud/internal/handlers/set_landmark_pose_handler.h" #include "cartographer/cloud/internal/handlers/write_state_handler.h" #include "cartographer/cloud/internal/sensor/serialization.h" #include "glog/logging.h" namespace cartographer { namespace cloud { namespace { static auto* kIncomingDataQueueMetric = metrics::Gauge::Null(); const common::Duration kPopTimeout = common::FromMilliseconds(100); } // namespace MapBuilderServer::MapBuilderServer( const proto::MapBuilderServerOptions& map_builder_server_options, std::unique_ptr<mapping::MapBuilderInterface> map_builder) : map_builder_(std::move(map_builder)) { async_grpc::Server::Builder server_builder; server_builder.SetServerAddress(map_builder_server_options.server_address()); server_builder.SetNumGrpcThreads( map_builder_server_options.num_grpc_threads()); server_builder.SetNumEventThreads( map_builder_server_options.num_event_threads()); if (!map_builder_server_options.uplink_server_address().empty()) { local_trajectory_uploader_ = CreateLocalTrajectoryUploader( map_builder_server_options.uplink_server_address(), map_builder_server_options.upload_batch_size(), map_builder_server_options.enable_ssl_encryption()); } server_builder.RegisterHandler<handlers::AddTrajectoryHandler>(); server_builder.RegisterHandler<handlers::AddOdometryDataHandler>(); server_builder.RegisterHandler<handlers::AddImuDataHandler>(); server_builder.RegisterHandler<handlers::AddRangefinderDataHandler>(); server_builder.RegisterHandler<handlers::AddFixedFramePoseDataHandler>(); server_builder.RegisterHandler<handlers::AddLandmarkDataHandler>(); server_builder.RegisterHandler<handlers::AddSensorDataBatchHandler>(); server_builder.RegisterHandler<handlers::FinishTrajectoryHandler>(); server_builder .RegisterHandler<handlers::ReceiveGlobalSlamOptimizationsHandler>(); server_builder.RegisterHandler<handlers::ReceiveLocalSlamResultsHandler>(); server_builder.RegisterHandler<handlers::GetSubmapHandler>(); server_builder.RegisterHandler<handlers::GetTrajectoryNodePosesHandler>(); server_builder.RegisterHandler<handlers::GetLandmarkPosesHandler>(); server_builder.RegisterHandler<handlers::GetAllSubmapPosesHandler>(); server_builder.RegisterHandler<handlers::GetLocalToGlobalTransformHandler>(); server_builder.RegisterHandler<handlers::GetConstraintsHandler>(); server_builder.RegisterHandler<handlers::IsTrajectoryFinishedHandler>(); server_builder.RegisterHandler<handlers::IsTrajectoryFrozenHandler>(); server_builder.RegisterHandler<handlers::LoadStateHandler>(); server_builder.RegisterHandler<handlers::RunFinalOptimizationHandler>(); server_builder.RegisterHandler<handlers::WriteStateHandler>(); server_builder.RegisterHandler<handlers::SetLandmarkPoseHandler>(); grpc_server_ = server_builder.Build(); if (map_builder_server_options.map_builder_options() .use_trajectory_builder_2d()) { grpc_server_->SetExecutionContext( common::make_unique<MapBuilderContext<mapping::Submap2D>>(this)); } else if (map_builder_server_options.map_builder_options() .use_trajectory_builder_3d()) { grpc_server_->SetExecutionContext( common::make_unique<MapBuilderContext<mapping::Submap3D>>(this)); } else { LOG(FATAL) << "Set either use_trajectory_builder_2d or use_trajectory_builder_3d"; } map_builder_->pose_graph()->SetGlobalSlamOptimizationCallback( std::bind(&MapBuilderServer::OnGlobalSlamOptimizations, this, std::placeholders::_1, std::placeholders::_2)); } void MapBuilderServer::Start() { shutting_down_ = false; if (local_trajectory_uploader_) { local_trajectory_uploader_->Start(); } StartSlamThread(); grpc_server_->Start(); } void MapBuilderServer::WaitForShutdown() { grpc_server_->WaitForShutdown(); if (slam_thread_) { slam_thread_->join(); } if (local_trajectory_uploader_) { local_trajectory_uploader_->Shutdown(); } } void MapBuilderServer::Shutdown() { shutting_down_ = true; grpc_server_->Shutdown(); if (slam_thread_) { slam_thread_->join(); slam_thread_.reset(); } if (local_trajectory_uploader_) { local_trajectory_uploader_->Shutdown(); local_trajectory_uploader_.reset(); } } void MapBuilderServer::ProcessSensorDataQueue() { LOG(INFO) << "Starting SLAM thread."; while (!shutting_down_) { kIncomingDataQueueMetric->Set(incoming_data_queue_.Size()); std::unique_ptr<MapBuilderContextInterface::Data> sensor_data = incoming_data_queue_.PopWithTimeout(kPopTimeout); if (sensor_data) { grpc_server_->GetContext<MapBuilderContextInterface>() ->AddSensorDataToTrajectory(*sensor_data); } } } void MapBuilderServer::StartSlamThread() { CHECK(!slam_thread_); // Start the SLAM processing thread. slam_thread_ = common::make_unique<std::thread>( [this]() { this->ProcessSensorDataQueue(); }); } void MapBuilderServer::OnLocalSlamResult( int trajectory_id, common::Time time, transform::Rigid3d local_pose, sensor::RangeData range_data, std::unique_ptr<const mapping::TrajectoryBuilderInterface::InsertionResult> insertion_result) { auto shared_range_data = std::make_shared<sensor::RangeData>(std::move(range_data)); // If there is an uplink server and a submap insertion happened, enqueue this // local SLAM result for uploading. if (insertion_result && grpc_server_->GetUnsynchronizedContext<MapBuilderContextInterface>() ->local_trajectory_uploader()) { auto sensor_data = common::make_unique<proto::SensorData>(); auto sensor_id = grpc_server_->GetUnsynchronizedContext<MapBuilderContextInterface>() ->local_trajectory_uploader() ->GetLocalSlamResultSensorId(trajectory_id); CreateSensorDataForLocalSlamResult(sensor_id.id, trajectory_id, time, starting_submap_index_, *insertion_result, sensor_data.get()); // TODO(cschuet): Make this more robust. if (insertion_result->insertion_submaps.front()->finished()) { ++starting_submap_index_; } grpc_server_->GetUnsynchronizedContext<MapBuilderContextInterface>() ->local_trajectory_uploader() ->EnqueueSensorData(std::move(sensor_data)); } common::MutexLocker locker(&subscriptions_lock_); for (auto& entry : local_slam_subscriptions_[trajectory_id]) { auto copy_of_insertion_result = insertion_result ? common::make_unique< const mapping::TrajectoryBuilderInterface::InsertionResult>( *insertion_result) : nullptr; MapBuilderContextInterface::LocalSlamSubscriptionCallback callback = entry.second; if (!callback( common::make_unique<MapBuilderContextInterface::LocalSlamResult>( MapBuilderContextInterface::LocalSlamResult{ trajectory_id, time, local_pose, shared_range_data, std::move(copy_of_insertion_result)}))) { LOG(INFO) << "Removing subscription with index: " << entry.first; CHECK_EQ(local_slam_subscriptions_[trajectory_id].erase(entry.first), 1u); } } } void MapBuilderServer::OnGlobalSlamOptimizations( const std::map<int, mapping::SubmapId>& last_optimized_submap_ids, const std::map<int, mapping::NodeId>& last_optimized_node_ids) { common::MutexLocker locker(&subscriptions_lock_); for (auto& entry : global_slam_subscriptions_) { if (!entry.second(last_optimized_submap_ids, last_optimized_node_ids)) { LOG(INFO) << "Removing subscription with index: " << entry.first; CHECK_EQ(global_slam_subscriptions_.erase(entry.first), 1u); } } } MapBuilderContextInterface::LocalSlamSubscriptionId MapBuilderServer::SubscribeLocalSlamResults( int trajectory_id, MapBuilderContextInterface::LocalSlamSubscriptionCallback callback) { common::MutexLocker locker(&subscriptions_lock_); local_slam_subscriptions_[trajectory_id].emplace(current_subscription_index_, callback); return MapBuilderContextInterface::LocalSlamSubscriptionId{ trajectory_id, current_subscription_index_++}; } void MapBuilderServer::UnsubscribeLocalSlamResults( const MapBuilderContextInterface::LocalSlamSubscriptionId& subscription_id) { common::MutexLocker locker(&subscriptions_lock_); CHECK_EQ(local_slam_subscriptions_[subscription_id.trajectory_id].erase( subscription_id.subscription_index), 1u); } int MapBuilderServer::SubscribeGlobalSlamOptimizations( MapBuilderContextInterface::GlobalSlamOptimizationCallback callback) { common::MutexLocker locker(&subscriptions_lock_); global_slam_subscriptions_.emplace(current_subscription_index_, callback); return current_subscription_index_++; } void MapBuilderServer::UnsubscribeGlobalSlamOptimizations( int subscription_index) { common::MutexLocker locker(&subscriptions_lock_); CHECK_EQ(global_slam_subscriptions_.erase(subscription_index), 1u); } void MapBuilderServer::NotifyFinishTrajectory(int trajectory_id) { common::MutexLocker locker(&subscriptions_lock_); for (auto& entry : local_slam_subscriptions_[trajectory_id]) { MapBuilderContextInterface::LocalSlamSubscriptionCallback callback = entry.second; // 'nullptr' signals subscribers that the trajectory finished. callback(nullptr); } } void MapBuilderServer::WaitUntilIdle() { incoming_data_queue_.WaitUntilEmpty(); map_builder_->pose_graph()->RunFinalOptimization(); } void MapBuilderServer::RegisterMetrics(metrics::FamilyFactory* factory) { auto* queue_length = factory->NewGaugeFamily( "cloud_internal_map_builder_server_incoming_data_queue_length", "Incoming SLAM Data Queue length"); kIncomingDataQueueMetric = queue_length->Add({}); } } // namespace cloud } // namespace cartographer
43.515901
91
0.769306
sotnik-github
d136bcc92eef1f38d6d9e2da9fedf38a8857c027
15,235
cpp
C++
src/qos/monitoring_manager.cpp
poseidonos/poseidonos
1d4a72c823739ef3eaf86e65c57d166ef8f18919
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
src/qos/monitoring_manager.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
src/qos/monitoring_manager.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics 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 Samsung Electronics 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 AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "src/qos/monitoring_manager.h" #include "src/include/pos_event_id.hpp" #include "src/qos/qos_context.h" #include "src/qos/qos_manager.h" #include "src/spdk_wrapper/event_framework_api.h" #define VALID_ENTRY (1) #define INVALID_ENTRY (0) #define NVMF_CONNECT (0) #define NVMF_DISCONNECT (1) namespace pos { /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ QosMonitoringManager::QosMonitoringManager(QosContext* qosCtx, QosManager* qosManager, SpdkPosNvmfCaller* spdkPosNvmfCaller, AffinityManager* affinityManager) : qosContext(qosCtx), qosManager(qosManager), spdkPosNvmfCaller(spdkPosNvmfCaller), affinityManager(affinityManager) { nextManagerType = QosInternalManager_Unknown; for (uint32_t i = 0; i < MAX_ARRAY_COUNT; i++) { qosMonitoringManagerArray[i] = new QosMonitoringManagerArray(i, qosCtx, qosManager); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ QosMonitoringManager::~QosMonitoringManager(void) { for (uint32_t i = 0; i < MAX_ARRAY_COUNT; i++) { delete qosMonitoringManagerArray[i]; } if (spdkPosNvmfCaller != nullptr) { delete spdkPosNvmfCaller; } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::Execute(void) { if (qosManager->IsFeQosEnabled() == true) { _UpdateContextUserVolumePolicy(); if (true == _GatherActiveVolumeParameters()) { _ComputeTotalActiveConnection(); } _UpdateAllVolumeParameter(); } _UpdateContextUserRebuildPolicy(); _GatherActiveEventParameters(); _UpdateContextResourceDetails(); _SetNextManagerType(); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_ComputeTotalActiveConnection(void) { uint32_t totalConntection = 0; std::map<uint32_t, uint32_t> activeVolumeMap = qosContext->GetActiveVolumes(); std::map<uint32_t, map<uint32_t, uint32_t>> volReactorMap = qosContext->GetActiveVolumeReactors(); for (map<uint32_t, uint32_t>::iterator it = activeVolumeMap.begin(); it != activeVolumeMap.end(); it++) { uint32_t volId = it->first; for (map<uint32_t, uint32_t>::iterator it = volReactorMap[volId].begin(); it != volReactorMap[volId].end(); ++it) { totalConntection += it->second; } qosContext->SetTotalConnection(volId, totalConntection); totalConntection = 0; } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_UpdateContextUserVolumePolicy(void) { uint32_t maxArrays = qosManager->GetNumberOfArrays(); for (uint32_t i = 0; i < maxArrays; i++) { qosMonitoringManagerArray[i]->UpdateContextUserVolumePolicy(); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_UpdateContextUserRebuildPolicy(void) { for (uint32_t i = 0; i < MAX_ARRAY_COUNT; i++) { qosMonitoringManagerArray[i]->UpdateContextUserRebuildPolicy(); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_UpdateContextResourceDetails(void) { uint32_t maxArrays = qosManager->GetNumberOfArrays(); for (uint32_t i = 0; i < maxArrays; i++) { qosMonitoringManagerArray[i]->UpdateContextResourceDetails(); } QosResource& resourceDetails = qosContext->GetQosResource(); ResourceCpu& resourceCpu = resourceDetails.GetResourceCpu(); for (uint32_t event = 0; event < BackendEvent_Count; event++) { uint32_t pendingEventCount = qosManager->GetPendingBackendEvents(static_cast<BackendEvent>(event)); resourceCpu.SetEventPendingCpuCount(static_cast<BackendEvent>(event), pendingEventCount); uint32_t generatedCpuEvents = qosManager->GetEventLog(static_cast<BackendEvent>(event)); resourceCpu.SetTotalGeneratedEvents(static_cast<BackendEvent>(event), generatedCpuEvents); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_UpdateContextActiveVolumeReactors(std::map<uint32_t, map<uint32_t, uint32_t>> map, std::map<uint32_t, std::vector<uint32_t>> &inactiveReactors) { qosContext->InsertActiveVolumeReactor(map); qosContext->InsertInactiveReactors(inactiveReactors); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_UpdateAllVolumeParameter(void) { std::map<uint32_t, uint32_t> activeVolumeMap = qosContext->GetActiveVolumes(); for (map<uint32_t, uint32_t>::iterator it = activeVolumeMap.begin(); it != activeVolumeMap.end(); it++) { uint32_t volId = it->first; uint32_t arrVolId = volId % MAX_VOLUME_COUNT; uint32_t arrayId = volId / MAX_VOLUME_COUNT; qosMonitoringManagerArray[arrayId]->UpdateVolumeParameter(arrVolId); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ bool QosMonitoringManager::_GatherActiveVolumeParameters(void) { qosContext->ResetActiveVolume(); qosContext->ResetActiveReactorVolume(); qosContext->ResetAllReactorsProcessed(); QosCorrection& qosCorrection = qosContext->GetQosCorrection(); AllVolumeThrottle& allVolumeThrottle = qosCorrection.GetVolumeThrottlePolicy(); allVolumeThrottle.Reset(); QosParameters& qosParameters = qosContext->GetQosParameters(); AllVolumeParameter& allVolumeParameter = qosParameters.GetAllVolumeParameter(); allVolumeParameter.Reset(); QosParameters& qosParameter = qosContext->GetQosParameters(); qosParameter.Reset(); bool changeDetected = false; std::vector<uint32_t> reactorCoreList = qosContext->GetReactorCoreList(); std::unordered_map<int32_t, std::vector<int>> subsystemVolumeMap; std::map<uint32_t, vector<int>> volList[M_MAX_REACTORS]; while (!IsExitQosSet()) { if (true == qosContext->AllReactorsProcessed()) { break; } } const std::map<uint32_t, map<uint32_t, uint32_t>> lastVolReactorMap = volReactorMap; volReactorMap.clear(); reactorVolMap.clear(); inactiveReactors.clear(); bool reactorActive = false; for (auto& reactor : reactorCoreList) { reactorActive = false; volList[reactor].clear(); for (uint32_t arrayId = 0; arrayId < qosManager->GetNumberOfArrays(); arrayId++) { if (true == IsExitQosSet()) { break; } qosManager->GetSubsystemVolumeMap(subsystemVolumeMap, arrayId); for (auto& subsystemVolume : subsystemVolumeMap) { uint32_t subsystemId = subsystemVolume.first; if (spdkPosNvmfCaller->SpdkNvmfGetReactorSubsystemMapping(reactor, subsystemId) != INVALID_SUBSYSTEM) { volList[reactor][subsystemId] = qosManager->GetVolumeFromActiveSubsystem(subsystemId, arrayId); } std::vector<int> volumeList = volList[reactor][subsystemId]; for (auto& volumeId : volumeList) { bool validParam = false; reactorActive = false; while (true) { bool valid = qosMonitoringManagerArray[arrayId]->VolParamActivities(volumeId, reactor); if (valid == false) { break; } else { validParam = true; } } uint32_t globalVolId = arrayId * MAX_VOLUME_COUNT + volumeId; if (true == validParam) { reactorVolMap[reactor].insert({globalVolId, 1}); volReactorMap[globalVolId].insert({reactor, 1}); reactorActive = true; } if (reactorActive == false) { inactiveReactors[globalVolId].push_back(reactor); } } } } } if (lastVolReactorMap == volReactorMap) { changeDetected = false; } else { _UpdateContextActiveVolumeReactors(volReactorMap, inactiveReactors); changeDetected = true; } if (_CheckChangeInActiveVolumes() == true) { qosManager->ResetCorrection(); } return changeDetected; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ bool QosMonitoringManager::_CheckChangeInActiveVolumes(void) { static int stabilityCycleCheck = 0; std::map<uint32_t, uint32_t> activeVolumeMap = qosContext->GetActiveVolumes(); bool ret = false; if (stabilityCycleCheck == 0) { if (prevActiveVolumeMap == activeVolumeMap) { ret = false; } else { stabilityCycleCheck++; ret = false; } } else { if (prevActiveVolumeMap == activeVolumeMap) { stabilityCycleCheck++; if (stabilityCycleCheck == 10) { stabilityCycleCheck = 0; ret = true; } else { ret = false; } } else { stabilityCycleCheck = 0; ret = false; } } prevActiveVolumeMap = activeVolumeMap; return ret; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_UpdateEventParameter(BackendEvent event) { QosParameters& qosParam = qosContext->GetQosParameters(); AllEventParameter& allEventParam = qosParam.GetAllEventParameter(); bool eventFound = allEventParam.EventExists(event); if (true == eventFound) { EventParameter& eventParam = allEventParam.GetEventParameter(event); eventParam.IncreaseBandwidth(eventParams[event].currentBW); } else { EventParameter eventParam; eventParam.SetBandwidth(eventParams[event].currentBW); allEventParam.InsertEventParameter(event, eventParam); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_GatherActiveEventParameters(void) { cpu_set_t cpuSet = affinityManager->GetCpuSet(CoreType::UDD_IO_WORKER); uint32_t cpuCount = CPU_COUNT(&cpuSet); for (uint32_t workerId = 0; workerId < cpuCount; workerId++) { for (uint32_t event = 0; (BackendEvent)event < BackendEvent_Count; event++) { do { eventParams[event].valid = M_INVALID_ENTRY; eventParams[event] = qosManager->DequeueEventParams(workerId, (BackendEvent)event); if (eventParams[event].valid == M_VALID_ENTRY) { _UpdateEventParameter(static_cast<BackendEvent>(event)); } } while ((eventParams[event].valid == M_VALID_ENTRY) && (!IsExitQosSet())); } } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosMonitoringManager::_SetNextManagerType(void) { nextManagerType = QosInternalManager_Processing; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ QosInternalManagerType QosMonitoringManager::GetNextManagerType(void) { return nextManagerType; } } // namespace pos
32.209302
166
0.536856
poseidonos
d145ee7c85328ff055a3b40f3816d1740405559a
7,683
hpp
C++
lib/integral/Reference.hpp
aphenriques/integral
157b1e07905a88f7786d8823bde19a3546502912
[ "MIT" ]
40
2015-01-18T19:03:12.000Z
2022-03-06T19:16:16.000Z
lib/integral/Reference.hpp
aphenriques/integral
157b1e07905a88f7786d8823bde19a3546502912
[ "MIT" ]
7
2019-06-25T20:53:27.000Z
2021-01-16T14:14:52.000Z
lib/integral/Reference.hpp
aphenriques/integral
157b1e07905a88f7786d8823bde19a3546502912
[ "MIT" ]
7
2015-05-13T12:31:15.000Z
2019-07-23T20:22:50.000Z
// // Reference.hpp // integral // // MIT License // // Copyright (c) 2016, 2017, 2019, 2020, 2021 André Pereira Henriques (aphenriques (at) outlook (dot) com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef integral_Reference_hpp #define integral_Reference_hpp #include "ReferenceBase.hpp" #include "ArgumentException.hpp" #include "Caller.hpp" namespace integral::detail { template<typename K, typename C> class Reference : public ReferenceBase<Reference<K, C>> { public: template<typename L, typename D> inline Reference(L &&key, D &&chainedReference); inline lua_State * getLuaState() const; inline void push() const; bool isNil() const; template<typename T, typename ...A> Reference<K, C> & emplace(A &&...arguments); template<typename V> inline Reference<K, C> & set(V &&value); template<typename V> inline Reference<K, C> & operator=(V &&value); template<typename F, typename ...E, std::size_t ...I> inline Reference<K, C> & setFunction(F &&function, DefaultArgument<E, I> &&...defaultArguments); template<typename F> inline Reference<K, C> & setLuaFunction(F &&function); template<typename V> decltype(auto) get() const; // the conversion operator does not return a reference to an object // storing a reference to a Lua object is unsafe because it might be collected // Reference::get returns a reference to an object but it is not meant to be stored template<typename V> inline operator V() const; // the arguments are pushed by value onto the lua stack template<typename R, typename ...A> decltype(auto) call(A &&...arguments); }; //-- template<typename K, typename C> template<typename L, typename D> inline Reference<K, C>::Reference(L &&key, D &&chainedReference) : ReferenceBase<Reference<K, C>>(std::forward<L>(key), std::forward<D>(chainedReference)) {} template<typename K, typename C> inline lua_State * Reference<K, C>::getLuaState() const { return ReferenceBase<Reference<K, C>>::getChainedReference().getLuaState(); } template<typename K, typename C> inline void Reference<K, C>::push() const { ReferenceBase<Reference<K, C>>::getChainedReference().push(); ReferenceBase<Reference<K, C>>::pushValueFromTable(getLuaState()); } template<typename K, typename C> bool Reference<K, C>::isNil() const { push(); // stack: ? if (lua_isnil(getLuaState(), -1) == 0) { // stack: ? lua_pop(getLuaState(), 1); return false; } else { // stack: nil lua_pop(getLuaState(), 1); return true; } } template<typename K, typename C> template<typename T, typename ...A> Reference<K, C> & Reference<K, C>::emplace(A &&...arguments) { ReferenceBase<Reference<K, C>>::getChainedReference().push(); // stack: ? if (lua_istable(getLuaState(), -1) != 0) { // stack: chainedReferenceTable exchanger::push<K>(getLuaState(), ReferenceBase<Reference<K, C>>::getKey()); // stack: chainedReferenceTable | key exchanger::push<T>(getLuaState(), std::forward<A>(arguments)...); // stack: chainedReferenceTable | key | value lua_rawset(getLuaState(), -3); // stack: chainedReferenceTable lua_pop(getLuaState(), 1); // stack: return *this; } else { // stack: ? lua_pop(getLuaState(), 1); throw ReferenceException(__FILE__, __LINE__, __func__, std::string("[integral] reference ") + ReferenceBase<Reference<K, C>>::getReferenceString() + " is not a table"); } } template<typename K, typename C> template<typename V> inline Reference<K, C> & Reference<K, C>::set(V &&value) { return emplace<std::decay_t<V>>(std::forward<V>(value)); } template<typename K, typename C> template<typename V> inline Reference<K, C> & Reference<K, C>::operator=(V &&value) { return set(std::forward<V>(value)); } template<typename K, typename C> template<typename F, typename ...E, std::size_t ...I> inline Reference<K, C> & Reference<K, C>::setFunction(F &&function, DefaultArgument<E, I> &&...defaultArguments) { return set(makeFunctionWrapper(std::forward<F>(function), std::move(defaultArguments)...)); } template<typename K, typename C> template<typename F> inline Reference<K, C> & Reference<K, C>::setLuaFunction(F &&function) { return set(LuaFunctionWrapper(std::forward<F>(function))); } template<typename K, typename C> template<typename V> decltype(auto) Reference<K, C>::get() const { push(); // stack: ? try { decltype(auto) returnValue = exchanger::get<V>(getLuaState(), -1); // stack: value lua_pop(getLuaState(), 1); // stack: return returnValue; } catch (const ArgumentException &argumentException) { // stack: ? lua_pop(getLuaState(), 1); // stack: throw ReferenceException(__FILE__, __LINE__, __func__, std::string("[integral] invalid type getting reference " ) + ReferenceBase<Reference<K, C>>::getReferenceString() + ": " + argumentException.what()); } } template<typename K, typename C> template<typename V> inline Reference<K, C>::operator V() const { return get<V>(); } template<typename K, typename C> template<typename R, typename ...A> decltype(auto) Reference<K, C>::call(A &&...arguments) { push(); // stack: ? try { // detail::Caller<R, A...>::call pops the first element of the stack return detail::Caller<R, A...>::call(getLuaState(), std::forward<A>(arguments)...); } catch (const ArgumentException &argumentException) { throw ReferenceException(__FILE__, __LINE__, __func__, std::string("[integral] invalid type calling function reference " ) + ReferenceBase<Reference<K, C>>::getReferenceString() + ": " + argumentException.what()); } catch (const CallerException &callerException) { throw ReferenceException(__FILE__, __LINE__, __func__, std::string("[integral] error calling function reference " ) + ReferenceBase<Reference<K, C>>::getReferenceString() + ": " + callerException.what()); } } } #endif
39
225
0.62814
aphenriques
d14653eac2adba68e611977c15d3f59715e95c84
3,139
hpp
C++
vcd.hpp
matteo-maria-tommasini/polar
276b45a081af1b0dd0853fcb5111f8da1514bd18
[ "Apache-2.0" ]
null
null
null
vcd.hpp
matteo-maria-tommasini/polar
276b45a081af1b0dd0853fcb5111f8da1514bd18
[ "Apache-2.0" ]
null
null
null
vcd.hpp
matteo-maria-tommasini/polar
276b45a081af1b0dd0853fcb5111f8da1514bd18
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // // polar v1.0 - August the 15th 2019 // // // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // // Copyright 2019 Matteo Tommasini // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef VCD_H #define VCD_H #include "units.hpp" #include "gaussiandataset.hpp" #include "vibrasolver.hpp" /////////////////////////////////////////////////////////////////////////////////// // VCD is a legacy class meant to reproduce data provided in Gaussian09 output, // // namely dipole and rotatory strengths (in deprecated CGS units). // // The simulation of VCD spectra is taken care of by the vibpolarizability class // /////////////////////////////////////////////////////////////////////////////////// class VCD { private: Eigen::VectorXd intensities; std::vector<Eigen::Vector3d> dmu_dq, dm_dqdot; Eigen::VectorXd m10_robust; Eigen::VectorXd mu01_robust; public: VCD(); VCD(const VibraSolver&, const GaussianDataset&); // getters Eigen::VectorXd GetIntensities() const; Eigen::VectorXd Get_m10_Robust() const; Eigen::VectorXd Get_mu01_Robust() const; std::vector<Eigen::Vector3d> GetElectricDipoleDerivativesVsNormalCoordinates() const; std::vector<Eigen::Vector3d> GetMagneticDipoleDerivativesVsNormalCoordinates() const; // utility void ComputeElectricDipoleDerivativesVsNormalCoordinates(const VibraSolver&, const GaussianDataset&); void ComputeMagneticDipoleDerivativesVsNormalCoordinates(const VibraSolver&, const GaussianDataset&); }; #endif // VCD_H
48.292308
104
0.431029
matteo-maria-tommasini
d14744eb77fb83cdd6be425381731e385d7c1450
25,583
cpp
C++
include/HGJPathSmooth/pathSmoother.cpp
imbaguanxin/cppAstar
3dc53c1581064fe70e2cb4642d0b6f9fc24b0e10
[ "MIT" ]
1
2021-12-09T13:32:23.000Z
2021-12-09T13:32:23.000Z
include/HGJPathSmooth/pathSmoother.cpp
imbaguanxin/cppAstar
3dc53c1581064fe70e2cb4642d0b6f9fc24b0e10
[ "MIT" ]
null
null
null
include/HGJPathSmooth/pathSmoother.cpp
imbaguanxin/cppAstar
3dc53c1581064fe70e2cb4642d0b6f9fc24b0e10
[ "MIT" ]
null
null
null
// // Created by stumbo on 18-11-5. // #include <ilcplex/ilocplex.h> #include "pathSmoother.h" #include "tools.h" #include "TurnPoint.h" #include <iostream> #include <cmath> #include <map> #include <set> using namespace std; HGJ::pathPlanner::pathPlanner() = default; const HGJ::WayPoints & HGJ::pathPlanner::genCurv(WayPoints wayPoints, double ts, double maxErr, double beginSpdInput, double endSpdInput) { if (!wayPoints.empty()) { WayPoints modifiedWP; modifiedWP.reserve(wayPoints.size()); modifiedWP.push_back(wayPoints.front()); for (int i = 1; i < wayPoints.size() - 1; ++i) { if (wayPoints[i] == wayPoints[i - 1]) { continue; } if (isnan(TurnPoint{wayPoints[i-1], wayPoints[i], wayPoints[i+1]}.beta)) { continue; } modifiedWP.push_back(wayPoints[i]); } size_t i = wayPoints.size() - 1; if (wayPoints[i] != wayPoints[i - 1]) { modifiedWP.push_back(wayPoints[i]); } wayPoints.swap(modifiedWP); } /// load the setting pathPlanner::maxErr = maxErr; pathPlanner::ts = ts; pathPlanner::beginSpd = beginSpdInput; pathPlanner::endSpd = endSpdInput; /// cal the point count int64_t pointCount = wayPoints.size(); int64_t lineCount = pointCount - 1; int64_t cornerCount = pointCount - 2; /// clear the last calculation resDis = 0.0; answerCurve.clear(); /// only one(zero) point is inputed, return the point if (pointCount <= 1) { cerr << "you only add 1 point" << endl; answerCurve = wayPoints; return answerCurve; } /// only two points are added, smooth the line if (pointCount == 2) { cerr << "you only add 2 points" << endl; turnPoints.clear(); lineTypes.clear(); turnPoints.emplace_back(wayPoints[0], wayPoints[0], wayPoints[1]); /// the distance may be not long enough for the speed change double safeDis = calChangeSpdDistance(pathPlanner::beginSpd, pathPlanner::endSpd); double theDis = (wayPoints[1] - wayPoints[0]).len(); /// the distance is not long enough, the end speed need to be modified if (theDis < safeDis) { pathPlanner::endSpd = calBestSpdFromDistance( pathPlanner::beginSpd, theDis, (pathPlanner::endSpd >pathPlanner::beginSpd)); cerr << "the end spd is not possible, fall back to:" << pathPlanner::endSpd << endl; lineTypes.emplace_back(ONEACC, pathPlanner::endSpd); } else { lineTypes.push_back( calLineType(pathPlanner::beginSpd, pathPlanner::endSpd, theDis)); } assignLinePartPoints(0); return answerCurve; } /// cal the curveLength, not used for now curveLength = 0.0; for (uint64_t i = 1; i < pointCount; ++i) { curveLength += (wayPoints[i] - wayPoints[i-1]).len(); } /// init the containers lineTypes.clear(); lineTypes.reserve(static_cast<unsigned long>(lineCount)); lineTypes.assign(static_cast<unsigned long>(lineCount), make_pair(UNSET, 0)); turnPoints.clear(); turnPoints.reserve(static_cast<unsigned long>(cornerCount)); for (int64_t i = 0; i < cornerCount; i++) { /// in the constructor, parameters about the corner are all calculated turnPoints.emplace_back(wayPoints[i], wayPoints[i + 1], wayPoints[i + 2]); } /// the answers(d) will be stored in "turnPoints" lpSolveTheDs(turnPoints); /// firstly set the speed of every corner to max for (auto & corner : turnPoints) { corner.speed = corner.maxSpd; } /// check the speed of every corner continously until they are all ok. /** * the violations: the length between two turns can't satisfy the speed change between * two max speed. the results are stored in map(speed, turns) in order of speed */ map<double, vector<uint64_t>> violations; /// check the first and the end turn, to set a better max speed /// which solve the condition when the begin/end speed is too small for the first/end turn auto & firstTurn = turnPoints.front(); if (pathPlanner::beginSpd < firstTurn.speed) { auto safeSpd = calBestSpdFromDistance( pathPlanner::beginSpd, firstTurn.lenBefore - firstTurn.d); if (safeSpd < firstTurn.speed) { firstTurn.maxSpd = safeSpd; firstTurn.speed = safeSpd; } } auto & endTurn = turnPoints.back(); if (pathPlanner::endSpd < endTurn.speed) { auto safeSpd = calBestSpdFromDistance( pathPlanner::endSpd, endTurn.lenAfter - endTurn.d); if (safeSpd < endTurn.speed) { endTurn.maxSpd = safeSpd; endTurn.speed = safeSpd; } } /**check lenBefore of every turn * if lenBefore is not long enough for the speed change * record the slower spd and the index*/ for (uint64_t i = 1; i < turnPoints.size(); i++) { auto & thisTurn = turnPoints[i]; auto & lastTurn = turnPoints[i - 1]; auto minDis = calChangeSpdDistance(lastTurn.speed, thisTurn.speed); if (minDis > thisTurn.lenBefore - thisTurn.d - lastTurn.d) { if (thisTurn.speed < lastTurn.speed) { violations[thisTurn.speed].push_back(i); } else { violations[lastTurn.speed].push_back(i-1); } } } /// modify the speed continusly, from the slower to faster to ensure the plan is the best. /// in the progress, new violations might be added for (auto & vioVectorPair: violations) { /// the index which violated at speed of "vioVectorPair.first" auto & vioIndexVector = vioVectorPair.second; /// the size of the vioIndexVector may changed, C++11 for (:) CAN NOT be used for (uint64_t vector_i = 0; vector_i < vioIndexVector.size(); vector_i++) { auto indexOfTurns = vioIndexVector[vector_i]; auto & thisTurn = turnPoints[indexOfTurns]; /// this means that the turn has been modified, no need to do it again if (thisTurn.isSpdModifiedComplete()) { continue; } if (indexOfTurns != 0) { /// it's not the first turn, check the spd of perious turn auto & turnBefore = turnPoints[indexOfTurns - 1]; if (turnBefore.speed > thisTurn.speed) { auto safeSpd = calBestSpdFromDistance( thisTurn.speed, thisTurn.lenBefore - thisTurn.d - turnBefore.d); if (turnBefore.speed > safeSpd) { /// turnBefore.speed is too fast! turnBefore.speed = safeSpd; if (indexOfTurns > 1) { /// check if the BBfore Turn becomces violation auto & turnBBefore = turnPoints[indexOfTurns - 2]; if (turnBBefore.speed > turnBefore.speed) { auto safeDis = calChangeSpdDistance (turnBefore.speed, turnBBefore.speed); if (safeDis > turnBefore.lenBefore - (turnBBefore.d + turnBefore.d)) { violations[turnBefore.speed].push_back(indexOfTurns - 1); } } } } } } /// it's almost the same as last section if (indexOfTurns != cornerCount - 1) { auto & turnAfter = turnPoints[indexOfTurns + 1]; if (turnAfter.speed > thisTurn.speed) { auto safeSpd = calBestSpdFromDistance( thisTurn.speed, thisTurn.lenAfter - thisTurn.d - turnAfter.d); if (turnAfter.speed > safeSpd) { turnAfter.speed = safeSpd; if (indexOfTurns < cornerCount - 2) { auto & turnAAfter = turnPoints[indexOfTurns + 2]; if (turnAAfter.speed > turnAfter.speed) { auto safeDis = calChangeSpdDistance (turnAAfter.speed, turnAfter.speed); if (safeDis > turnAfter.lenAfter - (turnAAfter.d + turnAfter.d)) { violations[turnAfter.speed].push_back(indexOfTurns + 1); } } } } } } /// one turn may be modified twice thisTurn.completeSpdModify(); } } /// at here, the spd of every turn has been set to the fastest speed. /// if the beginSpd or the endSpd are too fast, they need to be slower down if (firstTurn.speed < pathPlanner::beginSpd) { auto safeDis = calChangeSpdDistance(firstTurn.speed, pathPlanner::beginSpd); auto theReadDis = firstTurn.lenBefore - firstTurn.d; if (safeDis > theReadDis) { auto safeSpd = calBestSpdFromDistance(firstTurn.speed, theReadDis); cerr << "[WARNING] the begin speed you set is not safe:" << pathPlanner::beginSpd << " ,the plan will use the max safe speed: " << safeSpd << endl; pathPlanner::beginSpd = safeSpd; } } if (endTurn.speed < pathPlanner::endSpd) { auto safeDis = calChangeSpdDistance(endTurn.speed, pathPlanner::endSpd); auto theReadDis = endTurn.lenAfter - endTurn.d; if (safeDis > theReadDis) { auto safeSpd = calBestSpdFromDistance(endTurn.speed, theReadDis); cerr << "[WARNING] the end speed you set is not safe:" << pathPlanner::endSpd << " ,the plan will use the max safe speed: " << safeSpd << endl; pathPlanner::endSpd = safeSpd; } } /** * cal the speed type of erery line progress */ lineTypes.front() = calLineType(pathPlanner::beginSpd, turnPoints.front().speed, turnPoints.front().lenBefore - turnPoints.front().d); for (uint64_t index_line = 1; index_line < lineTypes.size() - 1; ++index_line) { auto & beforeTurn = turnPoints[index_line - 1]; auto & afterTurn = turnPoints[index_line]; lineTypes[index_line] = calLineType(beforeTurn.speed, afterTurn.speed, beforeTurn.lenAfter - beforeTurn.d - afterTurn.d); } lineTypes.back() = calLineType(turnPoints.back().speed, pathPlanner::endSpd, turnPoints.back().lenAfter - turnPoints.back().d); /** * plan the speed according to the ts */ for (uint32_t i = 0; i < turnPoints.size(); ++i) { assignLinePartPoints(i); assignTurnPartPoints(turnPoints[i], true); assignTurnPartPoints(turnPoints[i], false); } assignLinePartPoints(lineTypes.size() - 1); return answerCurve; } void HGJ::pathPlanner::lpSolveTheDs(vector<TurnPoint> & turnPoints) { /** * start linear programing * using library IBM CPLEX */ int64_t cornerCount = turnPoints.size(); IloEnv env; IloModel model(env); /** * d[0] ~ d[cornerCount - 1] is d * d[cornerCount] is the max curvature */ IloNumVarArray d(env); /** * constrictions */ IloRangeArray constrictions(env); /** * the optimize target (-sum(d) - n*maxcurvature) minnest */ IloObjective optimizeTarget = IloMinimize(env); /// adding the d varibles for (int i = 0; i < cornerCount; i++) { double minLen = min(turnPoints[i].lenAfter, turnPoints[i].lenBefore); /// adding 0.45 for some speed change available in some situations d.add(IloNumVar(env, 0.0, minLen * 0.45)); } /// this is the max curvature d.add(IloNumVar(env, 0.0, +IloInfinity)); for (int i = 0; i < cornerCount; i++) { /// the curvature of every corner should be smaller than the max curvature constrictions.add(IloRange(env, -IloInfinity, 0.0)); double coeff_d2Kmax = turnPoints[i].coeff_d2Rmin; constrictions[i].setLinearCoef(d[i], -coeff_d2Kmax); constrictions[i].setLinearCoef(d[cornerCount], 1); /// the optimization target of Ds optimizeTarget.setLinearCoef(d[i], -coeff_d2Kmax); } /// the maxcurvature with coeff of n-1 optimizeTarget.setLinearCoef(d[cornerCount], - cornerCount + 1); double coeff_beta2d = c4 * maxErr; for (int i = 0; i < cornerCount; i++) { /// d should not be too big to bigger than the global max error constrictions.add(IloRange(env, -IloInfinity, coeff_beta2d / cos(turnPoints[i].beta))); constrictions[cornerCount + i].setLinearCoef(d[i], 1); } /// d0 + d1 <= len(p1p2), might be useless with 0.45 coeff for (int i = 0; i < cornerCount - 1; i++) { constrictions.add(IloRange(env, -IloInfinity , turnPoints[i].lenAfter)); constrictions[cornerCount * 2 + i].setLinearCoef(d[i], 1); constrictions[cornerCount * 2 + i].setLinearCoef(d[i + 1], 1); } /// d0 < len(p0p1) / 2 (leave the space for speed up constrictions.add(IloRange(env, -IloInfinity , turnPoints.front().lenBefore / 2.0)); constrictions[cornerCount * 3 - 1].setLinearCoef(d[0], 1); /// dn < len(pn pn+1) / 2 constrictions.add(IloRange(env, -IloInfinity , turnPoints.back().lenAfter / 2.0)); constrictions[cornerCount * 3].setLinearCoef(d[cornerCount - 1], 1); model.add(optimizeTarget); model.add(constrictions); IloCplex cplex(model); cplex.solve(); IloNumArray ds(env); cplex.getValues(ds, d); // env.out() << "Solution status = " << cplex.getStatus() << endl; // env.out() << "Solution value = " << cplex.getObjValue() << endl; env.out() << "Values = " << ds << endl; /// load the answers(d) for (int i = 0; i < ds.getSize() - 1; i++) { auto & tp = turnPoints[i]; tp.setD(static_cast<double>(ds[i]), spdMax, accMax); /// use precise len may speed up the progress. but not tested // tp.calPreciseHalfLen(); curveLength += 2 * (tp.halfLength - tp.d); } env.end(); } double HGJ::pathPlanner::calChangeSpdDuration(double dv) { dv = abs(dv); double t1 = 1.875 * dv / accMax; double t2 = 5.7735 * dv / jerkMax; t2 = sqrt(t2); return max(t1, t2); } double HGJ::pathPlanner::calChangeSpdDistance(double v0, double v1) { return (v0 + v1) / 2.0 * calChangeSpdDuration(v0 - v1); } /** * represent the maxJerk when speed change form v0 to v1 * f(v1) = v1^3 + v0v1^2 - v0^2v1 - v0^3 * @return f(v1) */ inline double calFunc(double v0, double v1) { return (v1 + v0) * (v1 - v0) * (v1 + v0); } /** * the gradient of the previous function * f(v1) = v1^3 + v0v1^2 - v0^2v1 - v0^3 * f'(v1) = 3v1^2 + 2v0v1 - v0^2 * @return f'(v1) */ inline double calSlope(double v0, double v1) { return (v1 + v0) * (3.0 * v1 - v0); } double HGJ::pathPlanner::calBestSpdFromDistance(double v0, double dist, bool faster) { if (!faster) { cout << "[calBestSpdFromDistance] slower example" << endl; } if (abs(dist) < 0.01) { return v0; } /// cal the vel from the accMax constract double tempSqrtDiff = 1.06666666666 * accMax * dist; double v1Acc; if (faster) { v1Acc = sqrt(v0 * v0 + tempSqrtDiff); } else { if (v0 * v0 - tempSqrtDiff > 0) { v1Acc = sqrt(v0 * v0 - tempSqrtDiff); } else{ v1Acc = 0; } } /// cal the vel from the jerkMax constract /// solve the qubic function using gradient descent /// targetY represent the speed related to the JerkMax double targetY = 0.69282 * dist * dist * jerkMax; if (!faster) { targetY = - targetY; /// the function cal the min jerk, there is a local min at v0/3 double minJerk = calFunc(v0, v0 / 3.0); /// if the min is small enough, the constraction is from the accMax, return the v1Acc if (minJerk < targetY) { return v1Acc; } } /// starting at v0, the gradient descent progress may be not fast double v1Jerk = v0; double currentY = 0; double threshold = targetY * 1e-5; while (abs(currentY - targetY) > threshold) { v1Jerk += (targetY - currentY) / calSlope(v0, v1Jerk); currentY = calFunc(v0, v1Jerk); } if (faster) { return min(v1Acc, v1Jerk); } else { return max(v1Acc, v1Jerk); } } pair<HGJ::pathPlanner::LinearSpdType, double> HGJ::pathPlanner::calLineType(double v0, double v1, double dist) { /// the min lenth means the speed change is only speed up or speed down from v0 to v1 double minDist = calChangeSpdDistance(v0, v1); if (dist <= minDist * 1.025) { return make_pair(ONEACC, max(v0, v1)); } /// the min dist needed if we want to speed up to spdMax double minDist2SpdMax = calLineSpdUpDownMinDistance(v0, v1, spdMax); double distDiff = minDist2SpdMax - dist; /** * if maxDist < dist, means we can speed up to the max speed in the line */ if (distDiff < 0) { return make_pair(TOMAXSPD, spdMax); } /// if not, using dichotomy to find the max speed we can reach double upperBound = spdMax; double lowerBound = max(v0, v1); double midSpd = (upperBound + lowerBound) / 2; double tollerance = dist / 1000.0; while (true) { distDiff = calLineSpdUpDownMinDistance(v0, v1, midSpd) - dist; /** * CaledDist > realDist ==> spd need to be slower */ if (distDiff > tollerance) { upperBound = midSpd; midSpd = (midSpd + lowerBound) / 2.0; } /** * CaledDist > realDist ==> spd can be higher */ else if(distDiff < 0) { lowerBound = midSpd; midSpd = (midSpd + upperBound) / 2.0; } else { break; } } return make_pair(SPDUPDOWN, midSpd); } double HGJ::pathPlanner::calLineSpdUpDownMinDistance(double v0, double v1, double vMid) { auto dist = calChangeSpdDistance(v0, vMid); dist += calChangeSpdDistance(vMid, v1); return dist; } double HGJ::pathPlanner::calChangeSpdPosition(double v0, double dv, double t, double sumT) { double tRatio = t / sumT; double ans = 2.5 - (3 - tRatio) * tRatio; ans = ans * tRatio * tRatio * tRatio * dv + v0; return ans * t; } void HGJ::pathPlanner::assignSpdChangePoints(double beginV, double endV, const vec3f & posBegin, const vec3f & posEnd) { auto unitVec = posEnd - posBegin; /// means there is noting to assign if (unitVec.len() == 0.0) { return; } unitVec /= unitVec.len(); double dv = endV - beginV; double sumT = calChangeSpdDuration(dv); /// at the begin of the whole progress, the progress t_init will be NAN double t = ts - resDis / beginV; if (beginV == 0.0) { t = 0.0; } double distProgress; /// build the points while (t < sumT) { distProgress = calChangeSpdPosition(beginV, dv, t, sumT); answerCurve.emplace_back(posBegin + unitVec * distProgress); t += ts; } if (!answerCurve.empty()) { resDis = (answerCurve.back() - posEnd).len(); } if (resDis < 0) { cerr << "[pathPlanner::calChangeSpdPosition] reDis:" << resDis <<" is smaller than 0!" << endl; } } void HGJ::pathPlanner::assignLinearConstantSpeedPoints(double spd, const vec3f & posBegin, const vec3f & posEnd) { auto unitVec = posEnd - posBegin; if (unitVec.len() == 0.0) { return; } double sumT = unitVec.len() / spd; unitVec /= unitVec.len(); double t = ts - resDis / spd; while (t < sumT) { answerCurve.emplace_back(t * spd * unitVec + posBegin); t += ts; } if (!answerCurve.empty()) { resDis = (answerCurve.back() - posEnd).len(); } if (resDis < 0) { cerr << "[pathPlanner::assignLinearConstantSpeedPoints] reDis:" << resDis <<" is smaller than ""0!" << endl; } } void HGJ::pathPlanner::assignTurnPartPoints(const TurnPoint & turnPoint, bool firstPart) { /// at the corner, the speed is constrant, so the point gap is constrant double ds = ts * turnPoint.speed; if (ds < resDis) { cerr << "[pathPlanner::assignTurnPartPoints] the first Inc is < 0 !\nfirst part:" << firstPart << endl; resDis = ds; } /// the dU between the gap is about ds/wholeLen double increaseU = ds / turnPoint.halfLength; double firstU = (ds - resDis) / turnPoint.halfLength; double lastU = 0.0; vec3f lastPoint; if (firstPart) { lastPoint = turnPoint.B1[0]; } else { lastPoint = turnPoint.B2[3]; } /// considering the res error, the first currentU, targetLen is different double currentU = firstU; vec3f currentPoint = turnPoint.calPoint(currentU, firstPart); double targetLen = ds - resDis; double lenNow = (currentPoint - lastPoint).len(); double error = targetLen - lenNow; double tolleranceError = ds / 20000.0; while (true) { while (abs(error) > tolleranceError) { /// we need to modify the current U /// de/du = -len(C0C1) / delta(U) double dedu = lenNow / (currentU - lastU); /// newU = lastU + error / (de/du) currentU = currentU + error / dedu; /// after climbing it is still over 1? the curve is finished if (currentU > 1.0) { if (firstPart) { resDis = (answerCurve.back() - turnPoint.B1[3]).len(); } else { resDis = (answerCurve.back() - turnPoint.B2[0]).len(); } return; } currentPoint = turnPoint.calPoint(currentU, firstPart); lenNow = (currentPoint - lastPoint).len(); error = targetLen - lenNow; } /// come to here, we reslove a U that is accurate to record lastPoint = currentPoint; answerCurve.emplace_back(currentPoint); targetLen = ds; lastU = currentU; currentU = lastU + increaseU; /// if U is bigger than 1.0, we set it to 1.0, /// if it can go smaller than 1, it is a good point if (currentU > 1.0) { currentU = 1.0; } currentPoint = turnPoint.calPoint(currentU, firstPart); lenNow = (currentPoint - lastPoint).len(); error = targetLen - lenNow; } } void HGJ::pathPlanner::assignLinePartPoints(uint64_t index) { vec3f beginPos, endPos; double beginSpd, endSpd; /// at the start point and the end point, the spd and pos are special if (index == 0) { beginPos = turnPoints.front().p0; beginSpd = pathPlanner::beginSpd; } else { beginPos = turnPoints[index - 1].B2[0]; beginSpd = turnPoints[index - 1].speed; } if (index == lineTypes.size() - 1) { endPos = turnPoints.back().p2; endSpd = pathPlanner::endSpd; } else { endPos = turnPoints[index].B1[0]; endSpd = turnPoints[index].speed; } auto lineType = lineTypes[index].first; auto lineMaxSpd = lineTypes[index].second; if (lineType == ONEACC) { assignSpdChangePoints(beginSpd, endSpd, beginPos, endPos); return; } else if (lineType == SPDUPDOWN || lineType == TOMAXSPD) { vec3f unitVec = (endPos - beginPos) / (endPos - beginPos).len(); auto firstMaxSpdDis = calChangeSpdDistance(beginSpd, lineMaxSpd); auto firstMaxSpdPos = (unitVec * firstMaxSpdDis) + beginPos; auto endSpdChangeDis = calChangeSpdDistance(lineMaxSpd, endSpd); auto endMaxSpdPos = endPos - unitVec * endSpdChangeDis; assignSpdChangePoints(beginSpd, lineMaxSpd, beginPos, firstMaxSpdPos); if (lineType == TOMAXSPD) { assignLinearConstantSpeedPoints(lineMaxSpd, firstMaxSpdPos, endMaxSpdPos); assignSpdChangePoints(lineMaxSpd, endSpd, endMaxSpdPos, endPos); } else { assignSpdChangePoints(lineMaxSpd, endSpd, firstMaxSpdPos, endPos); } return; } else if (lineType == UNSET) { cerr << "assign a line with UNSET type!" << endl; throw; } else { cerr << "assign a line with UNKNOW type!" << endl; throw; } } void HGJ::pathPlanner::setMaxJerk(double jerkMax) { if (jerkMax > 0) { pathPlanner::jerkMax = jerkMax; } } void HGJ::pathPlanner::setMaxAcc(double accMax) { if (accMax > 0) { pathPlanner::accMax = accMax; } } void HGJ::pathPlanner::setMaxSpeed(double spdMax) { if (spdMax > 0) { pathPlanner::spdMax = spdMax; } } void HGJ::pathPlanner::setMaxErr(double maxErr) { if (maxErr > 0) { pathPlanner::maxErr = maxErr; } } const HGJ::WayPoints & HGJ::pathPlanner::getLastGeneratedCurve() { return answerCurve; }
34.110667
96
0.580112
imbaguanxin
d14ba8938709afc49e46dc49efac3620599ec721
817
cpp
C++
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/08_DPCPP_Reduction/src/sum_single_task.cpp
yafshar/oneAPI-samples
592a2036e86e7083a05c0d6a1613fb826adf9a60
[ "MIT" ]
null
null
null
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/08_DPCPP_Reduction/src/sum_single_task.cpp
yafshar/oneAPI-samples
592a2036e86e7083a05c0d6a1613fb826adf9a60
[ "MIT" ]
null
null
null
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/08_DPCPP_Reduction/src/sum_single_task.cpp
yafshar/oneAPI-samples
592a2036e86e7083a05c0d6a1613fb826adf9a60
[ "MIT" ]
null
null
null
//============================================================== // Copyright © Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= #include <CL/sycl.hpp> using namespace sycl; static constexpr size_t N = 1024; // global size int main() { //# setup queue with in_order property queue q; std::cout << "Device : " << q.get_device().get_info<info::device::name>() << "\n"; //# initialize data array using usm auto data = malloc_shared<int>(N, q); for (int i = 0; i < N; i++) data[i] = i; //# user single_task to add all numbers q.single_task([=](){ int sum = 0; for(int i=0;i<N;i++){ sum += data[i]; } data[0] = sum; }).wait(); std::cout << "Sum = " << data[0] << "\n"; free(data, q); return 0; }
23.342857
84
0.47858
yafshar
d14c345bdd8aac1022127a4a00023565aeb2def9
1,434
hpp
C++
src/game/intro_screen.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/intro_screen.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/intro_screen.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
/** The intro screen that is shown when launching the game ******************* * * * Copyright (c) 2014 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include "../core/engine.hpp" #include <core/renderer/camera.hpp> #include "../core/renderer/texture.hpp" #include "../core/renderer/shader.hpp" #include "../core/renderer/vertex_object.hpp" #include "../core/renderer/primitives.hpp" #include "../core/renderer/text.hpp" #include <core/renderer/command_queue.hpp> namespace lux { class Intro_screen : public Screen { public: Intro_screen(Engine& game_engine); ~Intro_screen()noexcept = default; protected: void _update(Time delta_time)override; void _draw()override; void _on_enter(util::maybe<Screen&> prev) override; void _on_leave(util::maybe<Screen&> next) override; auto _prev_screen_policy()const noexcept -> Prev_screen_policy override { return Prev_screen_policy::discard; } private: util::Mailbox_collection _mailbox; renderer::Camera_2d _camera; renderer::Text_dynamic _debug_Text; renderer::Command_queue _render_queue; }; }
29.875
79
0.584379
lowkey42
d14c9fd13fc189e0c23007aa42ce17fe3ed35ca6
24,731
cpp
C++
arch/common/dbt/mc/x86/reverse-allocator.cpp
tspink/captive
9db853df410e06ddb6384dc5e319b92f90483065
[ "MIT" ]
24
2017-01-02T18:46:34.000Z
2022-01-10T09:37:58.000Z
arch/common/dbt/mc/x86/reverse-allocator.cpp
tspink/captive
9db853df410e06ddb6384dc5e319b92f90483065
[ "MIT" ]
4
2019-09-19T17:48:03.000Z
2020-09-17T11:01:29.000Z
arch/common/dbt/mc/x86/reverse-allocator.cpp
tspink/captive
9db853df410e06ddb6384dc5e319b92f90483065
[ "MIT" ]
8
2017-04-28T04:53:42.000Z
2022-01-10T10:11:29.000Z
/* SPDX-License-Identifier: MIT */ #include <dbt/mc/x86/reverse-allocator.h> #include <dbt/mc/x86/formatter.h> #include <dbt/util/list.h> //#define PDEBUG #define VERIFY #define SUPPORT_VOLATILE #define CLEVER_ALLOCATION_STRATEGY using namespace captive::arch::dbt::mc::x86; using namespace captive::arch::dbt::util; #define MAX_PHYS_REGISTERS 24 template<typename UnderlyingType = dbt_u64, int NrBits = sizeof(UnderlyingType) * 8 > struct BitSet { static_assert(NrBits <= sizeof(UnderlyingType) * 8, "NrBits does not fit within underlying data type"); typedef BitSet<UnderlyingType, NrBits> Self; typedef int IndexType; BitSet() : state(0) { } BitSet(const BitSet& _o) : state(_o.state) { } inline operator UnderlyingType() const { return state; } inline void wipe() { state = 0; } inline void set(IndexType i) { state |= ((UnderlyingType) 1u << i); } inline void clear(IndexType i) { state &= ~((UnderlyingType) 1u << i); } inline bool is_set(IndexType i) const { return !!(state & ((UnderlyingType) 1u << i)); } inline bool is_clear(IndexType i) const { return !(state & ((UnderlyingType) 1u << i)); } inline IndexType find_first_set() const { if (state == 0) return -1; return __builtin_ffsll(state) - 1; } inline IndexType find_first_clear() const { if (~state == 0) return -1; return __builtin_ffsll(~state) - 1; } inline IndexType find_first_set_via_mask(UnderlyingType mask) const { if (state & mask == 0) return -1; return __builtin_ffsll(state & mask) - 1; } inline IndexType find_first_clear_via_mask(UnderlyingType mask) const { if (((~state) & mask) == 0) return -1; return __builtin_ffsll((~state) & mask) - 1; } friend Self operator|(const Self& lhs, const Self& rhs) { Self r; r.state = lhs.state | rhs.state; return r; } void operator|=(const Self& other) { state |= other.state; } private: UnderlyingType state; }; struct VirtualRegister { Instruction *first_def, *last_use; dbt_u64 physical_register_index; BitSet<> interference; int last_control_flow_count; }; bool ReverseAllocator::allocate(Instruction* head) { const X86PhysicalRegister& invalid_reg = X86PhysicalRegisters::RIZ; if (!number_and_legalise_instructions(head)) return false; // Allocate the dense vreg map. dbt_u64 nr_vregs = _vreg_allocator.next_index(); if (nr_vregs > 20000) { _support.debug_printf("there are too many vregs: %lu\n", nr_vregs); _support.assertion_fail("too many vregs"); return false; } VirtualRegister *vregs = (VirtualRegister *) _support.alloc(sizeof(VirtualRegister) * nr_vregs, AllocClass::DATA); if (!vregs) return false; // Initialise the vreg map. for (unsigned int i = 0; i < nr_vregs; i++) { vregs[i].first_def = nullptr; vregs[i].last_use = nullptr; vregs[i].physical_register_index = invalid_reg.unique_index(); vregs[i].last_control_flow_count = 0; } // Calculate VREG live ranges if (!calculate_vreg_live_ranges(vregs, head)) { _support.free(vregs, AllocClass::DATA); return false; } // Make fake uses for volatile memory accesses #ifdef SUPPORT_VOLATILE for (unsigned int i = 0; i < nr_vregs; i++) { if (vregs[i].first_def != nullptr && vregs[i].last_use == nullptr) { #ifdef PDEBUG _support.debug_printf("dead live range for vreg %lu\n", i); #endif Instruction *insn = vregs[i].first_def; if (insn->is_volatile()) { #ifdef PDEBUG _support.debug_printf("volatile instruction, so creating fake use for vreg %lu\n", i); Formatter __fmt; _support.debug_printf("[%u] %s\n", insn->nr, __fmt.format_instruction(insn)); #endif if (insn->kind() != InstructionKind::MOV) { _support.assertion_fail("fake use: not a mov"); } auto vreg_operand = insn->get_operand(1); if (!vreg_operand.is_reg() || !vreg_operand.reg.reg.is_virtual()) { _support.assertion_fail("fake use: not a vreg operand"); } insn->set_operand(1, Operand::make_register(X86PhysicalRegisters::R14, vreg_operand.reg.width)); } } } #endif // Perform allocation if (!do_allocate(vregs, head)) { _support.free(vregs, AllocClass::DATA); return false; } if (!commit(head, vregs)) { _support.free(vregs, AllocClass::DATA); return false; } #ifdef VERIFY if (!verify(head)) { _support.free(vregs, AllocClass::DATA); return false; } #endif if (!fixup_calls(head)) { _support.free(vregs, AllocClass::DATA); } _support.free(vregs, AllocClass::DATA); return true; } bool ReverseAllocator::calculate_vreg_live_ranges(VirtualRegister *vregs, Instruction *head) { #ifdef PDEBUG VirtualRegister *last_vreg = nullptr; #endif int cur_control_flow_count = 0; Instruction *current = head; do { if (current->is_control_flow()) { cur_control_flow_count++; } Instruction::UseDefList usedeflist; current->get_usedefs(usedeflist); for (unsigned int use_def_index = 0; use_def_index < usedeflist.next; use_def_index++) { const auto& usedef = usedeflist.get(use_def_index); if (!usedef.is_valid()) continue; // Skip invalid usedefs if (!usedef.is_def()) continue; // Skip non-def usedefs if (!usedef.reg.is_virtual()) continue; // Skip non-virtual registers VirtualRegister *vreg = &vregs[usedef.reg.unique_index()]; #ifdef PDEBUG if (vreg > last_vreg) { last_vreg = vreg; } #endif if (vreg->first_def == nullptr) { #ifdef PDEBUG _support.debug_printf("new definition of vreg %u\n", usedef.reg.unique_index()); #endif vreg->first_def = current; vreg->last_control_flow_count = cur_control_flow_count; } else if (vreg->last_use == nullptr && !usedef.is_usedef()) { #ifdef PDEBUG _support.debug_printf("definition of vreg %u, without use (and not a usedef) lcfc=%u, ccfc=%u\n", usedef.reg.unique_index(), vreg->last_control_flow_count, cur_control_flow_count); #endif #if 1 // Was there any intermediate controlflow/uses? if (vreg->last_control_flow_count == cur_control_flow_count) { #ifdef PDEBUG _support.debug_printf(" no control flow! killing %u\n", vregs[usedef.reg.unique_index()].first_def->nr); #endif vreg->first_def->change_kind(InstructionKind::DEAD); vreg->first_def = current; } #endif } } for (unsigned int use_def_index = 0; use_def_index < usedeflist.next; use_def_index++) { const auto& usedef = usedeflist.get(use_def_index); if (!usedef.is_valid()) continue; // Skip invalid usedefs if (!usedef.is_use()) continue; // Skip non-use usedefs if (!usedef.reg.is_virtual()) continue; // Skip non-virtual registers VirtualRegister *vreg = &vregs[usedef.reg.unique_index()]; #ifdef PDEBUG if (vreg > last_vreg) { last_vreg = vreg; } #endif vreg->last_use = current; } current = current->next(); } while (current != head); #ifdef PDEBUG if (last_vreg != nullptr) { for (VirtualRegister *vreg = vregs; vreg != last_vreg + 1; vreg++) { if (vreg->first_def == nullptr && vreg->last_use == nullptr) continue; dbt_u64 fd = -1, lu = -1; if (vreg->first_def != nullptr) { fd = vreg->first_def->nr; } if (vreg->last_use != nullptr) { lu = vreg->last_use->nr; } _support.debug_printf("vreg %lu: start:%lu, end:%lu\n", (vreg - vregs), fd, lu); } } #endif return true; } #define GPR_MASK 0x0000FFFF #define SSE_MASK 0xFFFF0000 bool ReverseAllocator::do_allocate(VirtualRegister* vregs, Instruction* head) { dbt_u64 phys_reg_tracking[MAX_PHYS_REGISTERS]; BitSet<> live_phys_regs; // HACK live_phys_regs.set(X86PhysicalRegisters::R15.unique_index()); live_phys_regs.set(X86PhysicalRegisters::BP.unique_index()); live_phys_regs.set(X86PhysicalRegisters::SP.unique_index()); phys_reg_tracking[X86PhysicalRegisters::R15.unique_index()] = X86PhysicalRegisters::R15.unique_index(); phys_reg_tracking[X86PhysicalRegisters::BP.unique_index()] = X86PhysicalRegisters::BP.unique_index(); phys_reg_tracking[X86PhysicalRegisters::SP.unique_index()] = X86PhysicalRegisters::SP.unique_index(); Instruction *last = head->prev(); Instruction *current = last; do { #ifdef PDEBUG { Formatter __debug_formatter; _support.debug_printf("@ %lu = %s\n", current->nr, __debug_formatter.format_instruction(current)); } #endif Instruction::UseDefList usedeflist; current->get_usedefs(usedeflist); bool skip = false; for (unsigned int use_def_index = 0; use_def_index < usedeflist.next; use_def_index++) { const auto& usedef = usedeflist.get(use_def_index); if (!usedef.is_valid()) continue; // Skip invalid usedefs if (!usedef.is_def()) continue; // Skip non-def usedefs dbt_u64 register_index = usedef.reg.unique_index(); if (usedef.reg.is_virtual()) { // Definition of VREG VirtualRegister *vreg = &vregs[register_index]; if (vreg->first_def == current) { if (vreg->last_use == nullptr) { #ifdef PDEBUG _support.debug_printf("def of unused vreg %u\n", register_index); #endif skip = true; break; } else { // If this is the first def, then release the allocated vreg live_phys_regs.clear(vreg->physical_register_index); #ifdef PDEBUG _support.debug_printf("ending live-range of vreg %u in preg %u\n", register_index, vreg->physical_register_index); #endif } } } else { if (register_index > MAX_PHYS_REGISTERS) { _support.assertion_fail("definition of invalid preg"); return false; } // Definition of PREG if (live_phys_regs.is_set(register_index)) { live_phys_regs.clear(register_index); if (phys_reg_tracking[register_index] > MAX_PHYS_REGISTERS) { dbt_u64 conflicting_vreg_index = phys_reg_tracking[register_index]; VirtualRegister *conflicting_vreg = &vregs[conflicting_vreg_index]; #ifdef PDEBUG _support.debug_printf("def of preg %u, but it's tracking vreg %u!\n", register_index, conflicting_vreg_index); #endif // Find a new preg for the vreg dbt_u64 mask = usedef.reg.is_sse() ? SSE_MASK : GPR_MASK; dbt_u64 new_preg = conflicting_vreg->interference.find_first_clear_via_mask(mask); if (new_preg == (dbt_u64) - 1) { #ifdef PDEBUG _support.debug_printf("vreg %u interference=%08x\n", conflicting_vreg_index, (dbt_u64) conflicting_vreg->interference); #endif _support.assertion_fail("out of registers in re-assignment"); } #ifdef PDEBUG _support.debug_printf("re-assigning vreg %u to preg %u (%08x)\n", conflicting_vreg_index, new_preg, (dbt_u64) conflicting_vreg->interference); #endif conflicting_vreg->physical_register_index = new_preg; phys_reg_tracking[conflicting_vreg->physical_register_index] = conflicting_vreg_index; live_phys_regs.set(conflicting_vreg->physical_register_index); vregs[conflicting_vreg_index].interference = live_phys_regs; // Update ALL vreg interferences for (int i = 0; i < MAX_PHYS_REGISTERS; i++) { if (live_phys_regs.is_set(i)) { #ifdef PDEBUG _support.debug_printf(" updating preg=%u, vreg=%u, prev=%08x, cur=%08x\n", i, phys_reg_tracking[i], (dbt_u64) vregs[phys_reg_tracking[i]].interference, (dbt_u64) live_phys_regs); #endif vregs[phys_reg_tracking[i]].interference |= live_phys_regs; } } } #ifdef PDEBUG _support.debug_printf("ending live-range of preg %u, tracking %u\n", register_index, phys_reg_tracking[register_index]); #endif } } } if (!skip) { for (unsigned int use_def_index = 0; use_def_index < usedeflist.next; use_def_index++) { const auto& usedef = usedeflist.get(use_def_index); if (!usedef.is_valid()) continue; // Skip invalid usedefs if (!usedef.is_use()) continue; // Skip non-use usedefs dbt_u64 register_index = usedef.reg.unique_index(); if (usedef.reg.is_virtual()) { // Use of VREG VirtualRegister *vreg = &vregs[register_index]; if (vreg->last_use == current || vreg->physical_register_index == 32) { // If this is the last use, then allocate a register to start tracking this vreg #ifdef PDEBUG dbt_u64 xxx = (dbt_u64) live_phys_regs; #endif // Now, hold the phone. We need to find a register of the correct class. dbt_u64 mask = usedef.reg.is_sse() ? SSE_MASK : GPR_MASK; #ifdef CLEVER_ALLOCATION_STRATEGY // Try to be smart about this if (current->kind() == InstructionKind::MOV || current->kind() == InstructionKind::MOVZX) { auto& srcop = current->get_operand(0); auto& dstop = current->get_operand(1); if (srcop.is_reg() && srcop.reg.reg.is_virtual() && dstop.is_reg() && !dstop.reg.reg.is_special()) { if (dstop.reg.reg.is_virtual()) { #ifdef PDEBUG _support.debug_printf(" selecting register for mov vreg->vreg instruction\n"); #endif vreg->physical_register_index = live_phys_regs.find_first_clear_via_mask(mask); } else { #ifdef PDEBUG _support.debug_printf(" selecting register for mov vreg->preg instruction - want preg=%u\n", dstop.reg.reg.unique_index()); #endif if (live_phys_regs.is_clear(dstop.reg.reg.unique_index())) { #ifdef PDEBUG _support.debug_printf(" available!\n", dstop.reg.reg.unique_index()); #endif vreg->physical_register_index = dstop.reg.reg.unique_index(); } else { #ifdef PDEBUG _support.debug_printf(" not available!\n", dstop.reg.reg.unique_index()); #endif vreg->physical_register_index = live_phys_regs.find_first_clear_via_mask(mask); } } } else { vreg->physical_register_index = live_phys_regs.find_first_clear_via_mask(mask); } } else { #endif vreg->physical_register_index = live_phys_regs.find_first_clear_via_mask(mask); #ifdef CLEVER_ALLOCATION_STRATEGY } #endif if (vreg->physical_register_index < 0) { _support.assertion_fail("out of registers in allocation"); } phys_reg_tracking[vreg->physical_register_index] = register_index; live_phys_regs.set(vreg->physical_register_index); vregs[register_index].interference = live_phys_regs; // TODO: Update ALL vreg interferences for (int i = 0; i < MAX_PHYS_REGISTERS; i++) { if (live_phys_regs.is_set(i)) { #ifdef PDEBUG _support.debug_printf(" updating preg=%u, vreg=%u, prev=%08x, cur=%08x\n", i, phys_reg_tracking[i], (dbt_u64) vregs[phys_reg_tracking[i]].interference, (dbt_u64) live_phys_regs); #endif vregs[phys_reg_tracking[i]].interference |= live_phys_regs; } } #ifdef PDEBUG _support.debug_printf("starting live-range of vreg %u, allocated to preg %u (%08x, %08x)\n", register_index, vreg->physical_register_index, xxx, (dbt_u64) live_phys_regs); #endif } } else { if (register_index > 32) { _support.assertion_fail("use of invalid preg"); return false; } // Use of PREG if (live_phys_regs.is_set(register_index) && phys_reg_tracking[register_index] != register_index) { dbt_u64 conflicting_vreg_index = phys_reg_tracking[register_index]; VirtualRegister *conflicting_vreg = &vregs[conflicting_vreg_index]; #ifdef PDEBUG _support.debug_printf("conflicting use of preg %u, currently tracking %u\n", register_index, conflicting_vreg_index); #endif // Find a new preg for the vreg dbt_u64 mask = usedef.reg.is_sse() ? SSE_MASK : GPR_MASK; dbt_u64 new_preg = conflicting_vreg->interference.find_first_clear_via_mask(mask); if (new_preg == (dbt_u64) - 1) { #ifdef PDEBUG _support.debug_printf("vreg %u interference=%08x\n", conflicting_vreg_index, (dbt_u64) conflicting_vreg->interference); #endif _support.assertion_fail("out of registers in re-assignment"); } #ifdef PDEBUG _support.debug_printf("re-assigning vreg %u to preg %u (%08x)\n", conflicting_vreg_index, new_preg, (dbt_u64) conflicting_vreg->interference); #endif conflicting_vreg->physical_register_index = new_preg; phys_reg_tracking[conflicting_vreg->physical_register_index] = conflicting_vreg_index; live_phys_regs.set(conflicting_vreg->physical_register_index); vregs[conflicting_vreg_index].interference = live_phys_regs; // Update ALL vreg interferences for (int i = 0; i < MAX_PHYS_REGISTERS; i++) { if (live_phys_regs.is_set(i)) { #ifdef PDEBUG _support.debug_printf(" updating preg=%u, vreg=%u, prev=%08x, cur=%08x\n", i, phys_reg_tracking[i], (dbt_u64) vregs[phys_reg_tracking[i]].interference, (dbt_u64) live_phys_regs); #endif vregs[phys_reg_tracking[i]].interference |= live_phys_regs; } } phys_reg_tracking[register_index] = register_index; } else { phys_reg_tracking[register_index] = register_index; live_phys_regs.set(register_index); vregs[register_index].interference = live_phys_regs; // Update ALL vreg interferences for (int i = 0; i < MAX_PHYS_REGISTERS; i++) { if (live_phys_regs.is_set(i)) { #ifdef PDEBUG _support.debug_printf(" updating preg=%u, vreg=%u, prev=%08x, cur=%08x\n", i, phys_reg_tracking[i], (dbt_u64) vregs[phys_reg_tracking[i]].interference, (dbt_u64) live_phys_regs); #endif vregs[phys_reg_tracking[i]].interference |= live_phys_regs; } } #ifdef PDEBUG _support.debug_printf("starting live-range of preg %u (%08x)\n", register_index, (dbt_u64) live_phys_regs); #endif } } } } current = current->prev(); } while (current != last); return true; } bool ReverseAllocator::commit(Instruction* head, const VirtualRegister* vreg_to_preg) { static const X86PhysicalRegister * assignments[] = { &X86PhysicalRegisters::A, &X86PhysicalRegisters::C, &X86PhysicalRegisters::D, &X86PhysicalRegisters::B, &X86PhysicalRegisters::RIZ, &X86PhysicalRegisters::RIZ, &X86PhysicalRegisters::SI, &X86PhysicalRegisters::DI, &X86PhysicalRegisters::R8, &X86PhysicalRegisters::R9, &X86PhysicalRegisters::R10, &X86PhysicalRegisters::R11, &X86PhysicalRegisters::R12, &X86PhysicalRegisters::R13, &X86PhysicalRegisters::R14, &X86PhysicalRegisters::R15, &X86PhysicalRegisters::XMM0, &X86PhysicalRegisters::XMM1, &X86PhysicalRegisters::XMM2, &X86PhysicalRegisters::XMM3, &X86PhysicalRegisters::XMM4, &X86PhysicalRegisters::XMM5, &X86PhysicalRegisters::XMM6, &X86PhysicalRegisters::XMM7, }; Instruction *current = head; do { if (current->kind() != InstructionKind::DEAD) { for (unsigned int i = 0; i < Instruction::NR_OPERANDS; i++) { const auto& operand = current->get_operand(i); if (operand.is_reg()) { if (operand.reg.reg.is_virtual()) { dbt_u64 preg_index = vreg_to_preg[operand.reg.reg.unique_index()].physical_register_index; if (preg_index == X86PhysicalRegisters::RIZ.unique_index()) { current->change_kind(InstructionKind::DEAD); break; } if (preg_index >= (sizeof(assignments) / sizeof(assignments[0]))) { #ifdef PDEBUG _support.debug_printf("illegal vreg %u to preg %u @ %u (reg operand)\n", operand.reg.reg.unique_index(), preg_index, current->nr); #endif _support.assertion_fail("assignment of preg out of range"); } #ifdef PDEBUG _support.debug_printf("committing vreg %u to preg %u @ %u (reg operand)\n", operand.reg.reg.unique_index(), preg_index, current->nr); #endif current->get_operand_nc(i).reg.reg = *assignments[preg_index]; } } else if (operand.is_mem()) { if (operand.mem.base_register.is_virtual()) { dbt_u64 preg_index = vreg_to_preg[operand.mem.base_register.unique_index()].physical_register_index; if (preg_index >= (sizeof(assignments) / sizeof(assignments[0]))) { _support.assertion_fail("assignment of preg out of range"); } #ifdef PDEBUG _support.debug_printf("committing vreg %u to preg %u @ %u (mem base operand)\n", operand.reg.reg.unique_index(), preg_index, current->nr); #endif current->get_operand_nc(i).mem.base_register = *assignments[preg_index]; } if (operand.mem.index_register.is_virtual()) { dbt_u64 preg_index = vreg_to_preg[operand.mem.index_register.unique_index()].physical_register_index; if (preg_index >= (sizeof(assignments) / sizeof(assignments[0]))) { _support.assertion_fail("assignment of preg out of range"); } #ifdef PDEBUG _support.debug_printf("committing vreg %u to preg %u @ %u (mem idx operand)\n", operand.reg.reg.unique_index(), preg_index, current->nr); #endif current->get_operand_nc(i).mem.index_register = *assignments[preg_index]; } } } } switch (current->kind()) { case InstructionKind::MOV: case InstructionKind::MOVQ: case InstructionKind::MOVDQA: if (current->get_operand(0) == current->get_operand(1)) { current->change_kind(InstructionKind::DEAD); } break; default: break; } current = current->next(); } while (current != head); return true; } bool ReverseAllocator::verify(const Instruction* head) { const Instruction *current = head; do { #ifndef PDEBUG if (!verify_instruction(current)) { #endif Formatter __fmt; _support.debug_printf("[%u] %s\n", current->nr, __fmt.format_instruction(current)); #ifndef PDEBUG return false; } #endif current = current->next(); } while (current != head); return true; } bool ReverseAllocator::verify_instruction(const Instruction* insn) { if (insn->kind() == InstructionKind::DEAD) return true; for (int i = 0; i < Instruction::NR_OPERANDS; i++) { auto op = insn->get_operand(0); if (op.is_reg()) { if (op.reg.reg.is_virtual()) { _support.debug_printf("verification failed: instruction has virtual register operand\n"); return false; } } else if (op.is_mem()) { if (op.mem.base_register.is_virtual()) { _support.debug_printf("verification failed: instruction has virtual base register operand\n"); return false; } if (op.mem.index_register.is_virtual()) { _support.debug_printf("verification failed: instruction has virtual index register operand\n"); return false; } } } return true; } bool ReverseAllocator::decorate_call(Instruction *call_instruction, int nr_args) { static const X86PhysicalRegister * caller_saved[] = { // Caller Saved &X86PhysicalRegisters::A, &X86PhysicalRegisters::R10, &X86PhysicalRegisters::R11, // Function Arguments &X86PhysicalRegisters::R9, &X86PhysicalRegisters::R8, &X86PhysicalRegisters::C, &X86PhysicalRegisters::D, &X86PhysicalRegisters::SI, &X86PhysicalRegisters::DI }; for (int i = 0; i < (3 + (6 - nr_args)); i++) { auto reg = caller_saved[i]; auto push = _support.alloc_obj<Instruction>(InstructionKind::PUSH); auto pop = _support.alloc_obj<Instruction>(InstructionKind::POP); push->set_operand(0, Operand::make_register(*reg, 64)); pop->set_operand(0, Operand::make_register(*reg, 64)); call_instruction->prev()->insert_after(push); call_instruction->insert_after(pop); } return true; } bool ReverseAllocator::fixup_calls(Instruction *head) { Instruction *current = head; do { switch (current->kind()) { case InstructionKind::CALL: case InstructionKind::CALL0: case InstructionKind::CALL1: case InstructionKind::CALL2: case InstructionKind::CALL3: case InstructionKind::CALL4: case InstructionKind::CALL5: case InstructionKind::CALL6: if (!decorate_call(current, 0)) { return false; } break; default: break; } current = current->next(); } while (current != head); return true; } bool ReverseAllocator::number_and_legalise_instructions(Instruction *head) { dbt_u64 idx = 0; Instruction *current = head; do { // Number the instruction. current->nr = idx++; // Any mem -> mem instructions must be performed via a temporary register if (current->match2() == InstructionMatch::MEM_MEM) { auto op0 = current->get_operand(0); // auto op1 = current->get_operand(1); auto tmp = Operand::make_register(_vreg_allocator.alloc_vreg(X86RegisterClasses::GENERAL_PURPOSE), op0.mem.access_width); auto mov_to_tmp = _support.alloc_obj<Instruction>(InstructionKind::MOV); mov_to_tmp->set_operand(0, op0); mov_to_tmp->set_operand(1, tmp); current->prev()->insert_after(mov_to_tmp); current->set_operand(0, tmp); mov_to_tmp->nr = current->nr; current->nr = idx++; } else if (current->kind() == InstructionKind::JMP) { if (current->get_operand(0).label.target == current->next()) { current->change_kind(InstructionKind::DEAD); } } #ifdef PDEBUG { Formatter __fmt; _support.debug_printf("[%u] %s\n", current->nr, __fmt.format_instruction(current)); } #endif current = current->next(); } while (current != head); return true; }
29.868357
186
0.696009
tspink
d14f7e52a0543a55f8a96b7b4a6b8b9fe2130192
2,630
cpp
C++
examples/ga_binary.cpp
kogyblack/ime_machinelearning
10b9e9f40b3d0d8cee63d0f19fcf4cd8c429816e
[ "Zlib", "MIT" ]
1
2018-01-20T15:36:30.000Z
2018-01-20T15:36:30.000Z
examples/ga_binary.cpp
kogyblack/ime_machinelearning
10b9e9f40b3d0d8cee63d0f19fcf4cd8c429816e
[ "Zlib", "MIT" ]
null
null
null
examples/ga_binary.cpp
kogyblack/ime_machinelearning
10b9e9f40b3d0d8cee63d0f19fcf4cd8c429816e
[ "Zlib", "MIT" ]
null
null
null
#include <stack> #include <cmath> #include "geneticalgorithm/binarygenome.h" #include "geneticalgorithm/genalg.h" int genomeValue(const ga::BinaryGenome& genome) { auto decoded = genome.decode(4); std::stack<int> values; for (unsigned i = 0; i < decoded.size(); ++i) { unsigned d = decoded[i]; if (d <= 9) values.push(d); else if (d >= 13) continue; else if (values.size() >= 2) { int a = values.top(); values.pop(); int b = values.top(); values.pop(); if (d == 10) // Sum values.push(b + a); else if (d == 11) // Difference values.push(b - a); else if (d == 12) // Multiplication values.push(a * b); } } if (values.size() == 0) return 0; return values.top(); } double fitnessFunc(ga::BinaryGenome& genome) { return 1.0 / (double)(exp(abs(genomeValue(genome) - 42) / 21.0)); } void printGenome(const ga::BinaryGenome& genome) { auto decoded = genome.decode(4); for (unsigned i = 0; i < decoded.size(); ++i) { int d = decoded[i]; if (d <= 9) printf("%d ", d); else if (d >= 13) printf("x "); else { if (d == 10) // Sum printf("+ "); else if (d == 11) // Difference printf("- "); else if (d == 12) // Multiplication printf("* "); } } printf(" | "); for (unsigned i = 0; i < 32; ++i) printf("%d", genome.extract()[i]); printf("\n"); } int main(int argc, char** argv) { int population_size = 20, generations = 100; unsigned elite = 2; double mutation = 0.01, crossover = 0.7; if (argc > 1) population_size = atoi(argv[1]); if (argc > 2) generations = atoi(argv[2]); if (argc > 3) elite = atoi(argv[3]); if (argc > 4) mutation = atof(argv[4]); if (argc > 5) crossover = atof(argv[5]); ga::GeneticAlgorithm<ga::BinaryGenome> evolution (population_size, 32, elite, mutation, crossover, fitnessFunc); for (int i = 0; i < generations; ++i) { if (i > 0) evolution.epoch(); printf("generation %d:\n", evolution.generation()); printf("best:\n %d %.2f: ", genomeValue(evolution.get_best_of_all()), evolution.get_best_of_all().getFitness()); printGenome(evolution.get_best_of_all()); printf("\n"); auto population = evolution.population(); for (unsigned j = 0; j < population.size(); ++j) { printf("%3d %3d %1.2f: ", j, genomeValue(population[j]), population[j].getFitness()); printGenome(population[j]); } printf("\n"); } printf("Best of all: %d\n", genomeValue(evolution.get_best_of_all())); return 0; }
23.693694
120
0.564259
kogyblack
d15013344bce2531ca9d4090bd948f167799be63
506
hpp
C++
src/timer.hpp
aalin/synthz0r
ecf35b3fec39020e46732a15874b66f07a3e48e9
[ "MIT" ]
1
2021-12-23T21:14:37.000Z
2021-12-23T21:14:37.000Z
src/timer.hpp
aalin/synthz0r
ecf35b3fec39020e46732a15874b66f07a3e48e9
[ "MIT" ]
null
null
null
src/timer.hpp
aalin/synthz0r
ecf35b3fec39020e46732a15874b66f07a3e48e9
[ "MIT" ]
null
null
null
#ifndef TIMER_HPP #define TIMER_HPP class Timer { public: Timer(float sampleRate) : _ticks(0), _seconds(0.0), _sampleRate(sampleRate) {} float seconds() const { return _seconds; } unsigned long int ticks() const { return _ticks; } void update(const float &sampleRate) { _seconds = _ticks++ / sampleRate; } const float & sampleRate() const { return _sampleRate; } private: unsigned long int _ticks; float _seconds; const float _sampleRate; }; #endif
14.457143
40
0.662055
aalin
d1535016c4930684a9f9465fa42c728de581711b
1,610
cpp
C++
third party/openRTMFP-Cumulus/CumulusServer/sources/LUAAMFObjectWriter.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
5
2015-04-30T09:08:30.000Z
2018-08-13T05:00:39.000Z
third party/openRTMFP-Cumulus/CumulusServer/sources/LUAAMFObjectWriter.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
third party/openRTMFP-Cumulus/CumulusServer/sources/LUAAMFObjectWriter.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
/* Copyright 2010 OpenRTMFP This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License received along this program for more details (or else see http://www.gnu.org/licenses/). This file is a part of Cumulus. */ #include "LUAAMFObjectWriter.h" #include "AMFObjectWriter.h" using namespace Cumulus; const char* LUAAMFObjectWriter::Name="Cumulus::AMFObjectWriter"; int LUAAMFObjectWriter::Get(lua_State *pState) { SCRIPT_CALLBACK(AMFObjectWriter,LUAAMFObjectWriter,writer) SCRIPT_READ_STRING(name,"") if(name=="write") SCRIPT_WRITE_FUNCTION(&LUAAMFObjectWriter::Write) SCRIPT_CALLBACK_RETURN } int LUAAMFObjectWriter::Set(lua_State *pState) { SCRIPT_CALLBACK(AMFObjectWriter,LUAAMFObjectWriter,writer) SCRIPT_READ_STRING(name,"") lua_rawset(pState,1); // consumes key and value SCRIPT_CALLBACK_RETURN } int LUAAMFObjectWriter::Write(lua_State* pState) { SCRIPT_CALLBACK(AMFObjectWriter,LUAAMFObjectWriter,writer) SCRIPT_READ_STRING(name,"") if(SCRIPT_CAN_READ) { writer.writer.writePropertyName(name); Script::ReadAMF(pState,writer.writer,1); } else SCRIPT_ERROR("This function takes 2 parameters: name and value") SCRIPT_CALLBACK_RETURN }
32.2
72
0.775155
Patrick-Bay
d1558c651a06df869cc51ac3f987ce1671993103
3,907
cpp
C++
src/Utility/SharedStringBuilder.cpp
cpv-project/cpv-framework
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
[ "MIT" ]
86
2018-04-20T04:40:20.000Z
2022-02-09T08:36:28.000Z
src/Utility/SharedStringBuilder.cpp
cpv-project/cpv-framework
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
[ "MIT" ]
16
2018-04-25T09:34:40.000Z
2020-10-16T03:55:05.000Z
src/Utility/SharedStringBuilder.cpp
cpv-project/cpv-framework
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
[ "MIT" ]
10
2019-10-07T08:06:15.000Z
2021-07-26T18:46:11.000Z
#include <CPVFramework/Utility/SharedStringBuilder.hpp> namespace cpv { namespace { /** Get max string size of integer, doesn't include zero terminator */ template <class IntType> constexpr std::size_t getMaxStringSize(std::size_t base) { IntType max = std::numeric_limits<IntType>::max(); std::size_t result = 1; // the first digit if (std::numeric_limits<IntType>::is_signed) { ++result; // the sign } while (static_cast<std::make_unsigned_t<IntType>>(max) >= base) { ++result; max /= base; } return result; } /** For appending integer */ static const char DecimalDigits[] = "0123456789"; /** Remove tailing zero for string converted from double and append to builder */ template <class CharType> void trimTailingZeroAndAppend( BasicSharedStringBuilder<CharType>& builder, const char* data, std::size_t size) { const char* end = data + size; while (data < end && *(end - 1) == '0') { --end; } if (data < end && *(end - 1) == '.') { --end; } else { bool constantsDot = false; for (const char* begin = data; begin < end; ++begin) { constantsDot |= (*begin == '.'); } if (!constantsDot) { end = data + size; // should not trim 12300 to 123 } } CharType* ptr = builder.grow(end - data); while (data < end) { *ptr++ = static_cast<CharType>(*data++); } } } /** Append string representation of signed integer to end */ template <class CharType> BasicSharedStringBuilder<CharType>& BasicSharedStringBuilder<CharType>::appendImpl(std::intmax_t value) { static const constexpr std::size_t MaxSize = getMaxStringSize<std::intmax_t>(10); CharType* ptr = grow(MaxSize); if (value < 0) { *ptr++ = '-'; } CharType* ptrStart = ptr; do { int rem = value % 10; value /= 10; *ptr++ = static_cast<CharType>(DecimalDigits[rem >= 0 ? rem : -rem]); } while (value != 0); std::reverse(ptrStart, ptr); size_ = static_cast<std::size_t>(ptr - buffer_.data()); return *this; } /** Append string representation of unsigned integer to end */ template <class CharType> BasicSharedStringBuilder<CharType>& BasicSharedStringBuilder<CharType>::appendImpl(std::uintmax_t value) { static const constexpr std::size_t MaxSize = getMaxStringSize<std::uintmax_t>(10); CharType* ptr = grow(MaxSize); CharType* ptrStart = ptr; do { unsigned int rem = value % 10; value /= 10; *ptr++ = static_cast<CharType>(DecimalDigits[rem]); } while (value != 0); std::reverse(ptrStart, ptr); size_ = static_cast<std::size_t>(ptr - buffer_.data()); return *this; } /** Append string representation of double to end */ template <class CharType> BasicSharedStringBuilder<CharType>& BasicSharedStringBuilder<CharType>::appendImpl(double value) { // to_chars for float is not available in gcc 9, use snprintf now thread_local static std::array<char, 512> buffer; int size = std::snprintf(buffer.data(), buffer.size(), "%lf", value); if (CPV_LIKELY(size > 0)) { trimTailingZeroAndAppend(*this, buffer.data(), size); } else { std::string str = std::to_string(value); trimTailingZeroAndAppend(*this, str.data(), str.size()); } return *this; } /** Append string representation of long double to end */ template <class CharType> BasicSharedStringBuilder<CharType>& BasicSharedStringBuilder<CharType>::appendImpl(long double value) { // to_chars for float is not available in gcc 9, use snprintf now thread_local static std::array<char, 1024> buffer; int size = std::snprintf(buffer.data(), buffer.size(), "%Lf", value); if (CPV_LIKELY(size > 0)) { trimTailingZeroAndAppend(*this, buffer.data(), size); } else { std::string str = std::to_string(value); trimTailingZeroAndAppend(*this, str.data(), str.size()); } return *this; } // Template instatiations template class BasicSharedStringBuilder<char>; }
32.02459
85
0.668288
cpv-project
d15807a15a00ed306d3cfdacc35322432ec8ab60
2,078
cpp
C++
SOLVER/src/core/point/WindowSum.cpp
chaindl/AxiSEM-3D
0251f301c79c676fb37792209d6e24f107773b3d
[ "MIT" ]
null
null
null
SOLVER/src/core/point/WindowSum.cpp
chaindl/AxiSEM-3D
0251f301c79c676fb37792209d6e24f107773b3d
[ "MIT" ]
null
null
null
SOLVER/src/core/point/WindowSum.cpp
chaindl/AxiSEM-3D
0251f301c79c676fb37792209d6e24f107773b3d
[ "MIT" ]
null
null
null
#include "WindowSum.hpp" template <> void SFWindowSum<3>::feedComm(eigen::CColX &buffer, int &row) const { if (mStiffR.rows() > 0) { buffer.block(row, 0, mStiffR.size(), 1).real() = Eigen::Map<const eigen::RColX>(mStiffR.data(), mStiffR.size()); row += mStiffR.size(); } else if (mStiff.rows() > 0) { buffer.block(row, 0, mStiff.size(), 1) = Eigen::Map<const eigen::CColX>(mStiff.data(), mStiff.size()); row += mStiff.size(); } else { throw std::runtime_error("SolidWindowSum::feedComm || Buffer allocation failed."); } }; template <> void SFWindowSum<1>::feedComm(eigen::CColX &buffer, int &row) const { if (mStiffR.rows() > 0) { buffer.block(row, 0, mStiffR.rows(), 1).real() = mStiffR; row += mStiffR.rows(); } else if (mStiff.rows() > 0) { buffer.block(row, 0, mStiff.rows(), 1) = mStiff; row += mStiff.rows(); } else { throw std::runtime_error("FluidWindowSum::feedComm || Buffer allocation failed."); } }; template <> void SFWindowSum<3>::extractComm(const eigen::CColX &buffer, int &row) { if (mStiffR.rows() > 0) { mStiffR += Eigen::Map<const CMat>(&buffer(row), mStiffR.rows(), 3).real(); row += mStiffR.size(); } else if (mStiff.rows() > 0) { mStiff += Eigen::Map<const CMat>(&buffer(row), mStiff.rows(), 3); row += mStiff.size(); } else { throw std::runtime_error("SolidWindowSum::extractComm || Buffer allocation failed."); } }; template <> void SFWindowSum<1>::extractComm(const eigen::CColX &buffer, int &row) { if (mStiffR.rows() > 0) { mStiffR += buffer.block(row, 0, mStiffR.rows(), 1).real(); row += mStiffR.rows(); } else if (mStiff.rows() > 0) { mStiff += buffer.block(row, 0, mStiff.rows(), 1); row += mStiff.rows(); } else { throw std::runtime_error("FluidWindowSum::extractComm || Buffer allocation failed."); } };
34.633333
93
0.554379
chaindl