hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3361323f5c35081f893c08be1a29c97eb884ff7 | 31,957 | cpp | C++ | ta_sdl_game.cpp | Christof-Sigel/TA_SDL | 72638ba1601300783628a5dc09bb547b703a39fe | [
"MIT"
] | null | null | null | ta_sdl_game.cpp | Christof-Sigel/TA_SDL | 72638ba1601300783628a5dc09bb547b703a39fe | [
"MIT"
] | null | null | null | ta_sdl_game.cpp | Christof-Sigel/TA_SDL | 72638ba1601300783628a5dc09bb547b703a39fe | [
"MIT"
] | null | null | null | #include <stdio.h>
#pragma warning(push)
#pragma warning(disable: 4668 4820)
#include <SDL2/SDL.h>
#pragma warning(pop)
#ifdef __LINUX__
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <time.h>
#else
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#include <SDL2/SDL_opengl.h>
#include "ta_sdl_game.h"
#include "platform_code.cpp"
#include "GL.cpp"
#include "file_formats.cpp"
#include "ta_sdl_game_load.cpp"
internal void DisplayMissions(TAUIElement * Root, CampaignList * Campaigns, MemoryArena * TempArena)
{
Assert(Root->ElementType == TAG_UI_CONTAINER);
TAUIElement * CoreButton = GetElementByName(ELEMENT_NAME_CORE, Root);
TAUIElement * CampaignElement = GetElementByName(ELEMENT_NAME_CAMPAIGN, Root);
TAUIListBox * CampaignListBox = &CampaignElement->ListBox;
TAUIElement * MissionElement = GetElementByName(ELEMENT_NAME_MISSIONS, Root);
TAUIListBox * MissionListBox = &MissionElement->ListBox;
MissionListBox->NumberOfDisplayableItems = 4;
Campaign * Campaign;
s32 CampaignIndex = CampaignListBox->SelectedIndex;
if(CoreButton->Button.Pressed)
{
Campaign = &Campaigns->CORECampaigns[CampaignIndex];
}
else
{
Campaign = &Campaigns->ARMCampaigns[CampaignIndex];
}
MissionListBox->NumberOfItems = Campaign->NumberOfMissions;
MissionListBox->ItemStrings = PushArray(TempArena, MissionListBox->NumberOfItems, char*);
for(s32 i=0;i<MissionListBox->NumberOfItems;i++)
{
MissionListBox->ItemStrings[i] = Campaign->Missions[i].MissionName;
}
}
internal void DisplayCampaigns(TAUIElement * Root, CampaignList * Campaigns, MemoryArena * TempArena)
{
Assert(Root->ElementType == TAG_UI_CONTAINER);
TAUIElement * ArmButton = GetElementByName(ELEMENT_NAME_ARM,Root);
TAUIElement * CoreButton = GetElementByName(ELEMENT_NAME_CORE, Root);
TAUIElement * CampaignElement = GetElementByName(ELEMENT_NAME_CAMPAIGN, Root);
TAUIListBox * CampaignListBox = &CampaignElement->ListBox;
CampaignListBox->NumberOfDisplayableItems = 3;
if(CoreButton->Button.Pressed)
{
CampaignListBox->NumberOfItems = Campaigns->NumberOfCORECampaigns;
CampaignListBox->ItemStrings = PushArray(TempArena, CampaignListBox->NumberOfItems, char*);
for(s32 i=0;i<Campaigns->NumberOfCORECampaigns;i++)
{
CampaignListBox->ItemStrings[i] = Campaigns->CORECampaigns[i].CampaignName;
}
}
else
{
ArmButton->Button.Pressed = 1;
GetElementByName(ELEMENT_NAME_SIDE_0,Root)->Button.Pressed =1;
CampaignListBox->NumberOfItems = Campaigns->NumberOfARMCampaigns;
CampaignListBox->ItemStrings = PushArray(TempArena, CampaignListBox->NumberOfItems, char*);
for(s32 i=0;i<Campaigns->NumberOfARMCampaigns;i++)
{
CampaignListBox->ItemStrings[i] = Campaigns->ARMCampaigns[i].CampaignName;
}
}
DisplayMissions(Root, Campaigns , TempArena);
}
internal Matrix FPSViewMatrix(float * eye, float pitch, float yaw);
internal void HandleInput(InputState * Input, GameState * CurrentGameState)
{
b32 MouseButtonDown = !!Input->MouseButtons & SDL_BUTTON(SDL_BUTTON_LEFT);
b32 MouseButtonWasDown = !!Input->LastMouseButtons & SDL_BUTTON(SDL_BUTTON_LEFT);
switch(CurrentGameState->State)
{
case STATE_RUNNING:
case STATE_PAUSED:
{
Matrix ViewRotation = FPSViewMatrix(CurrentGameState->CameraTranslation, CurrentGameState->CameraXRotation, CurrentGameState->CameraYRotation);
// ViewRotation.Rotate(1,0,0, CurrentGameState->CameraXRotation);
// ViewRotation.Rotate(0,1,0, CurrentGameState->CameraYRotation);
const float CameraTranslation = 5.0;
float DX[3] = { ViewRotation.Contents[0*4+0] * CameraTranslation + ViewRotation.Contents[3*4+0],
ViewRotation.Contents[0*4+1] * CameraTranslation + ViewRotation.Contents[3*4+1],
ViewRotation.Contents[0*4+2] * CameraTranslation + ViewRotation.Contents[3*4+2]};
float DY[3] = { ViewRotation.Contents[1*4+0] * CameraTranslation + ViewRotation.Contents[3*4+0],
ViewRotation.Contents[1*4+1] * CameraTranslation + ViewRotation.Contents[3*4+1],
ViewRotation.Contents[1*4+2] * CameraTranslation + ViewRotation.Contents[3*4+2]};
float DZ[3] = { ViewRotation.Contents[2*4+0] * CameraTranslation + ViewRotation.Contents[3*4+0],
ViewRotation.Contents[2*4+1] * CameraTranslation + ViewRotation.Contents[3*4+1],
ViewRotation.Contents[2*4+2] * CameraTranslation + ViewRotation.Contents[3*4+2]};
if(Input->KeyIsDown[SDLK_p]&& !Input->KeyWasDown[SDLK_p])
{
if(CurrentGameState->State == STATE_RUNNING)
{
CurrentGameState->State = STATE_PAUSED;
}
else if(CurrentGameState->State == STATE_PAUSED)
{
CurrentGameState->State = STATE_RUNNING;
}
}
if(Input->KeyIsDown[SDLK_ESCAPE] && !Input->KeyWasDown[SDLK_ESCAPE] )
{
if(CurrentGameState->State == STATE_RUNNING || CurrentGameState->State == STATE_PAUSED)
CurrentGameState->State = STATE_MAIN_MENU;
else
CurrentGameState->State = STATE_RUNNING;
}
//HACK: FIX THIS SHIT
if(Input->KeyIsDown[SDLK_UP&255])
{
CurrentGameState->CameraXRotation += 0.01f;
}
if(Input->KeyIsDown[SDLK_DOWN&255])
{
CurrentGameState->CameraXRotation -= 0.01f;
}
if(Input->KeyIsDown[SDLK_LEFT&255])
{
CurrentGameState->CameraYRotation +=0.01f;
}
if(Input->KeyIsDown[SDLK_RIGHT&255])
{
CurrentGameState->CameraYRotation -=0.01f;
}
if(Input->KeyIsDown[SDLK_w])
{
for(int i=0;i<3;i++)
CurrentGameState->CameraTranslation[i]+=DY[i];
}
if(Input->KeyIsDown[SDLK_s])
{
for(int i=0;i<3;i++)
CurrentGameState->CameraTranslation[i]-=DY[i];
}
if(Input->KeyIsDown[SDLK_a])
{
for(int i=0;i<3;i++)
CurrentGameState->CameraTranslation[i]-=DX[i];
}
if(Input->KeyIsDown[SDLK_d])
{
for(int i=0;i<3;i++)
CurrentGameState->CameraTranslation[i]+=DX[i];
}
if(Input->KeyIsDown[SDLK_q])
{
for(int i=0;i<3;i++)
CurrentGameState->CameraTranslation[i]-=DZ[i];
}
if(Input->KeyIsDown[SDLK_e])
{
for(int i=0;i<3;i++)
CurrentGameState->CameraTranslation[i]+=DZ[i];
}
}
break;
case STATE_MAIN_MENU:
{
TAUIElement * Element = ProcessMouse(&CurrentGameState->MainMenu, Input->MouseX, Input->MouseY, MouseButtonDown,MouseButtonWasDown, (CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2);
if( Element)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
switch(Element->ElementName)
{
case ELEMENT_NAME_EXIT:
CurrentGameState->State = STATE_QUIT;
break;
case ELEMENT_NAME_SINGLEPLAYER:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
case ELEMENT_NAME_MULTIPLAYER:
//TODO
break;
case ELEMENT_NAME_INTRO:
//TODO
break;
}
#pragma clang diagnostic pop
}
}
break;
case STATE_SINGLEPLAYER_MENU:
{
TAUIElement * Element = ProcessMouse(&CurrentGameState->SinglePlayerMenu, Input->MouseX, Input->MouseY, MouseButtonDown,MouseButtonWasDown, (CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2);
if( Element)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
switch(Element->ElementName)
{
case ELEMENT_NAME_PREVIOUS_MENU:
CurrentGameState->State = STATE_MAIN_MENU;
break;
case ELEMENT_NAME_OPTIONS:
CurrentGameState->State = STATE_OPTIONS_MENU;
break;
case ELEMENT_NAME_NEW_CAMPAIGN:
CurrentGameState->State = STATE_CAMPAIGN_MENU;
DisplayCampaigns(&CurrentGameState->CampaignMenu, &CurrentGameState->CampaignList, &CurrentGameState->TempArena);
break;
case ELEMENT_NAME_SKIRMISH:
CurrentGameState->State = STATE_SKIRMISH_MENU;
break;
case ELEMENT_NAME_LOAD_GAME:
CurrentGameState->State = STATE_LOAD_GAME_MENU;
break;
}
#pragma clang diagnostic pop
}
}
break;
case STATE_OPTIONS_MENU:
{
TAUIElement * Element = ProcessMouse(&CurrentGameState->OptionsMenu, Input->MouseX, Input->MouseY, MouseButtonDown,MouseButtonWasDown, (CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2);
if( Element)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
switch(Element->ElementName)
{
case ELEMENT_NAME_PREVIOUS_MENU:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
case ELEMENT_NAME_CANCEL:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
}
#pragma clang diagnostic pop
}
}
break;
case STATE_CAMPAIGN_MENU:
{
TAUIElement * Element = ProcessMouse(&CurrentGameState->CampaignMenu, Input->MouseX, Input->MouseY, MouseButtonDown,MouseButtonWasDown, (CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2);
if(Element)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
switch(Element->ElementName)
{
case ELEMENT_NAME_PREVIOUS_MENU:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
case ELEMENT_NAME_START:
{
TAUIElement * CoreButton = GetElementByName(ELEMENT_NAME_CORE, &CurrentGameState->CampaignMenu);
TAUIElement * CampaignElement = GetElementByName(ELEMENT_NAME_CAMPAIGN, &CurrentGameState->CampaignMenu);
TAUIListBox * CampaignListBox = &CampaignElement->ListBox;
TAUIElement * MissionElement = GetElementByName(ELEMENT_NAME_MISSIONS, &CurrentGameState->CampaignMenu);
TAUIListBox * MissionListBox = &MissionElement->ListBox;
MissionListBox->NumberOfDisplayableItems = 4;
Campaign * Campaign;
s32 CampaignIndex = CampaignListBox->SelectedIndex;
if(CoreButton->Button.Pressed)
{
Campaign = &CurrentGameState->CampaignList.CORECampaigns[CampaignIndex];
}
else
{
Campaign = &CurrentGameState->CampaignList.ARMCampaigns[CampaignIndex];
}
CurrentGameState->NumberOfUnits=0;
LoadAllUnitTypes(&CurrentGameState->UnitTypeList, &CurrentGameState->GameArena,&CurrentGameState->TempArena,&CurrentGameState->GlobalArchiveCollection, &CurrentGameState->UnitTextures);
Position StartingLoc = LoadCampaignMap(&CurrentGameState->Map,Campaign->Missions[MissionListBox->SelectedIndex].MissionFile,&CurrentGameState->GlobalArchiveCollection, &CurrentGameState->TempArena,CurrentGameState->PaletteData, &CurrentGameState->GameArena,CurrentGameState->UnitList, & CurrentGameState->NumberOfUnits, &CurrentGameState->UnitTypeList, &CurrentGameState->UnitShaderDetails,CurrentGameState->MapSeaLevelLocation);
CurrentGameState->CameraTranslation[0] = StartingLoc.X;
CurrentGameState->CameraTranslation[2] = StartingLoc.Y;
}
CurrentGameState->State = STATE_RUNNING;
break;
case ELEMENT_NAME_SIDE_0:
case ELEMENT_NAME_ARM:
{
TAUIElement * E = GetElementByName(ELEMENT_NAME_SIDE_0,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 1;
E = GetElementByName(ELEMENT_NAME_ARM,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 1;
E = GetElementByName(ELEMENT_NAME_SIDE_1,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 0;
E = GetElementByName(ELEMENT_NAME_CORE,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 0;
DisplayCampaigns(&CurrentGameState->CampaignMenu, &CurrentGameState->CampaignList,&CurrentGameState->TempArena);
}
break;
case ELEMENT_NAME_SIDE_1:
case ELEMENT_NAME_CORE:
{
TAUIElement * E = GetElementByName(ELEMENT_NAME_SIDE_1,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 1;
E = GetElementByName(ELEMENT_NAME_CORE,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 1;
E = GetElementByName(ELEMENT_NAME_SIDE_0,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 0;
E = GetElementByName(ELEMENT_NAME_ARM,&CurrentGameState->CampaignMenu);
E->Button.Pressed = 0;
DisplayCampaigns(&CurrentGameState->CampaignMenu, &CurrentGameState->CampaignList, &CurrentGameState->TempArena);
}
break;
case ELEMENT_NAME_CAMPAIGN:
DisplayMissions(&CurrentGameState->CampaignMenu, &CurrentGameState->CampaignList, &CurrentGameState->TempArena);
break;
}
#pragma clang diagnostic pop
}
}
break;
case STATE_SKIRMISH_MENU:
{
TAUIElement * Element = ProcessMouse(&CurrentGameState->SkirmishMenu, Input->MouseX, Input->MouseY, MouseButtonDown,MouseButtonWasDown, (CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2);
if(Element)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
switch(Element->ElementName)
{
case ELEMENT_NAME_PREVIOUS_MENU:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
}
#pragma clang diagnostic pop
}
}
break;
case STATE_LOAD_GAME_MENU:
{
TAUIElement * Element = ProcessMouse(&CurrentGameState->LoadGameMenu, Input->MouseX, Input->MouseY, MouseButtonDown,MouseButtonWasDown, (CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2);
if(Element)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
switch(Element->ElementName )
{
case ELEMENT_NAME_LOAD:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
case ELEMENT_NAME_CANCEL:
CurrentGameState->State = STATE_SINGLEPLAYER_MENU;
break;
}
#pragma clang diagnostic pop
}
}
break;
case STATE_QUIT:
//NOTE(Christof): nothing to do, simply to silence warning
break;
}
CurrentGameState->MouseX = Input->MouseX;
CurrentGameState->MouseY = Input->MouseY;
}
internal void SetupDebugRectBuffer(GLuint * DebugRectBuffer)
{
GLfloat RenderData[6*(2+4)];//6 Vert (2 triangles) each 2 position coords and 4 distance to edge "coords"
glGenVertexArrays(1,DebugRectBuffer);
GLfloat Vertices[]={0,0, 1,0, 1,1, 0,1};
GLfloat EdgeDistance[]={0,1,1,0, 0,0,1,1, 1,0,0,1, 1,1,0,0};
int Indexes1[]={0,3,1};
for(int i=0;i<3;i++)
{
RenderData[i*(2+4)+0]=Vertices[Indexes1[i]*2+0];
RenderData[i*(2+4)+1]=Vertices[Indexes1[i]*2+1];
RenderData[i*(2+4)+2]=EdgeDistance[Indexes1[i]*4+0];
RenderData[i*(2+4)+3]=EdgeDistance[Indexes1[i]*4+1];
RenderData[i*(2+4)+4]=EdgeDistance[Indexes1[i]*4+2];
RenderData[i*(2+4)+5]=EdgeDistance[Indexes1[i]*4+3];
}
int Indexes2[]={1,3,2};
for(int i=0;i<3;i++)
{
RenderData[6*3+i*(2+4)+0]=Vertices[Indexes2[i]*2+0];
RenderData[6*3+i*(2+4)+1]=Vertices[Indexes2[i]*2+1];
RenderData[6*3+i*(2+4)+2]=EdgeDistance[Indexes2[i]*4+0];
RenderData[6*3+i*(2+4)+3]=EdgeDistance[Indexes2[i]*4+1];
RenderData[6*3+i*(2+4)+4]=EdgeDistance[Indexes2[i]*4+2];
RenderData[6*3+i*(2+4)+5]=EdgeDistance[Indexes2[i]*4+3];
}
glBindVertexArray(*DebugRectBuffer);
GLuint VertexBuffer;
glGenBuffers(1,&VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*6*(2+4),RenderData,GL_STATIC_DRAW);
glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*6,0);
glVertexAttribPointer(1,4,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*6,(GLvoid*)(sizeof(GLfloat)*2));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindVertexArray(0);
glDeleteBuffers(1,&VertexBuffer);
}
internal void SetupDebugAxisBuffer(GLuint * DebugAxisBuffer)
{
//Setup Debug axis buffer details:
GLfloat LineData[3*2 * (3+2+3)];
int CurrentLine =0;
const int SCALE = 3;
LineData[CurrentLine*2*8 + 0] = 0;
LineData[CurrentLine*2*8 + 1]= 0;
LineData[CurrentLine*2*8 + 2]= 0;
LineData[CurrentLine*2*8 + 3]= -1*SCALE;
LineData[CurrentLine*2*8 + 4]= -1*SCALE;
LineData[CurrentLine*2*8 + 5]= 1*SCALE;
LineData[CurrentLine*2*8 + 6]= 0;
LineData[CurrentLine*2*8 + 7]= 0;
LineData[CurrentLine*2*8 + 8] = 1*SCALE;
LineData[CurrentLine*2*8 + 9]= 0;
LineData[CurrentLine*2*8 + 10]= 0;
LineData[CurrentLine*2*8 + 11]= -1*SCALE;
LineData[CurrentLine*2*8 + 12]= -1*SCALE;
LineData[CurrentLine*2*8 + 13]= 1*SCALE;
LineData[CurrentLine*2*8 + 14]= 0;
LineData[CurrentLine*2*8 + 15]= 0;
CurrentLine++;
LineData[CurrentLine*2*8 + 0] = 0;
LineData[CurrentLine*2*8 + 1]= 0;
LineData[CurrentLine*2*8 + 2]= 0;
LineData[CurrentLine*2*8 + 3]= -1*SCALE;
LineData[CurrentLine*2*8 + 4]= -1*SCALE;
LineData[CurrentLine*2*8 + 5]= 0;
LineData[CurrentLine*2*8 + 6]= 1*SCALE;
LineData[CurrentLine*2*8 + 7]= 0;
LineData[CurrentLine*2*8 + 8] = 0;
LineData[CurrentLine*2*8 + 9]= 1*SCALE;
LineData[CurrentLine*2*8 + 10]= 0;
LineData[CurrentLine*2*8 + 11]= -1*SCALE;
LineData[CurrentLine*2*8 + 12]= -1*SCALE;
LineData[CurrentLine*2*8 + 13]= 0;
LineData[CurrentLine*2*8 + 14]= 1*SCALE;
LineData[CurrentLine*2*8 + 15]= 0;
CurrentLine++;
LineData[CurrentLine*2*8 + 0] = 0;
LineData[CurrentLine*2*8 + 1]= 0;
LineData[CurrentLine*2*8 + 2]= 0;
LineData[CurrentLine*2*8 + 3]= -1*SCALE;
LineData[CurrentLine*2*8 + 4]= -1*SCALE;
LineData[CurrentLine*2*8 + 5]= 0;
LineData[CurrentLine*2*8 + 6]= 0;
LineData[CurrentLine*2*8 + 7]= 1*SCALE;
LineData[CurrentLine*2*8 + 8] = 0;
LineData[CurrentLine*2*8 + 9]= 0;
LineData[CurrentLine*2*8 + 10]= 1*SCALE;
LineData[CurrentLine*2*8 + 11]= -1*SCALE;
LineData[CurrentLine*2*8 + 12]= -1*SCALE;
LineData[CurrentLine*2*8 + 13]= 0;
LineData[CurrentLine*2*8 + 14]= 0;
LineData[CurrentLine*2*8 + 15]= 1*SCALE;
CurrentLine++;
GLuint VertexBuffer;
glGenVertexArrays(1,DebugAxisBuffer);
glBindVertexArray(*DebugAxisBuffer);
glGenBuffers(1,&VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*3*(3+2+3)*2,LineData,GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),0);
glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),(GLvoid*)(sizeof(GLfloat)*3));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*(3+2+3),(GLvoid*)(sizeof(GLfloat)*5));
glEnableVertexAttribArray(2);
glBindVertexArray(0);
glDeleteBuffers(1,&VertexBuffer);
}
internal void SetupGameState( GameState * CurrentGameState)
{
CurrentGameState->ProjectionMatrix.SetProjection(60,float(CurrentGameState->ScreenWidth)/CurrentGameState->ScreenHeight,1.0,10000.0);
// CurrentGameState->ViewMatrix->SetTranslation(1,-2.5,2);
// CurrentGameState->ViewMatrix->Rotate(0,1,0, (float)PI*0.75f);
CurrentGameState->CameraYRotation = 0;//1.25*PI;
// CurrentGameState->CameraXRotation += 0.1f;
CurrentGameState->CameraTranslation[0] =4.0f;
CurrentGameState->CameraTranslation[2] =50.0f;
CurrentGameState->CameraTranslation[1] = 280.0f;
//GL Setup:
glClearColor( 0.f, 0.f,0.f, 0.f );
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
//glDisable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
SetupDebugAxisBuffer(&CurrentGameState->DebugAxisBuffer);
}
internal void InitialiseGame(Memory * GameMemory)
{
GameState * CurrentGameState = (GameState*)GameMemory->PermanentStore;
CurrentGameState->IsInitialised=1;
InitializeArena(&CurrentGameState->GameArena,GameMemory->PermanentStoreSize-sizeof(GameState),GameMemory->PermanentStore+sizeof(GameState));
InitializeArena(&CurrentGameState->TempArena,GameMemory->TransientStoreSize,GameMemory->TransientStore);
SetupGameState(CurrentGameState);
}
internal float dot3(float * v1, float * v2)
{
return v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2];
}
internal Matrix FPSViewMatrix(float * eye, float pitch, float yaw)
{
float cosPitch = (float)cos(pitch);
float sinPitch = (float)sin(pitch);
float cosYaw = (float)cos(yaw);
float sinYaw = (float)sin(yaw);
float xaxis[3] = { cosYaw, 0, -sinYaw };
float yaxis[3] = { sinYaw * sinPitch, cosPitch, cosYaw * sinPitch };
float zaxis[3] = { sinYaw * cosPitch, -sinPitch, cosPitch * cosYaw };
// Create a 4x4 view matrix from the right, up, forward and eye position vectors
Matrix viewMatrix;
float MatDeets[]={
xaxis[0], yaxis[0], zaxis[0], 0 ,
xaxis[1], yaxis[1], zaxis[1], 0 ,
xaxis[2], yaxis[2], zaxis[2], 0 ,
-dot3( xaxis, eye ), -dot3( yaxis, eye ), -dot3( zaxis, eye ), 1
};
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
viewMatrix.Contents[i*4+j]=MatDeets[j*4+i];
}
return viewMatrix;
}
extern "C"
{
void GameUpdateAndRender(InputState * Input, Memory * GameMemory);
void GameUpdateAndRender(InputState * Input, Memory * GameMemory)
{
LoadGLProcs();
GameState * CurrentGameState = (GameState*)GameMemory->PermanentStore;
if(!CurrentGameState->IsInitialised)
{
InitialiseGame(GameMemory);
}
HandleInput(Input,CurrentGameState);
glEnable(GL_CULL_FACE);
// glDisable(GL_CULL_FACE);
// glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
b32 Animate = CurrentGameState->NumberOfFrames%10==0;
switch(CurrentGameState->State)
{
case STATE_RUNNING:
{
//CurrentGameState->CameraXRotation = -0.5f * PI;
//CurrentGameState->CameraYRotation = 0.0;
if(CurrentGameState->CameraTranslation[1] <0)
CurrentGameState->CameraTranslation[1] =0;
CurrentGameState->ViewMatrix = FPSViewMatrix(CurrentGameState->CameraTranslation, CurrentGameState->CameraXRotation, CurrentGameState->CameraYRotation);
glUseProgram(CurrentGameState->UnitShaderDetails.Shader->ProgramID);
glBindTexture(GL_TEXTURE_2D,CurrentGameState->UnitTextures.Texture);
CurrentGameState->ViewMatrix.Upload(CurrentGameState->UnitShaderDetails.ViewMatrixLocation);
CurrentGameState->ProjectionMatrix.Upload(CurrentGameState->UnitShaderDetails.ProjectionMatrixLocation);
//TODO(Christof): Update game state
#if 0
Matrix ModelMatrix;
for(s32 x=0;x<CurrentGameState->Map.Width;x+=2)
{
for(s32 y=0;y<CurrentGameState->Map.Height;y+=2)
{
ModelMatrix.SetTranslation(x*GL_UNIT_PER_MAP_TILE,CurrentGameState->Map.HeightMap[x+y*CurrentGameState->Map.Width],y*GL_UNIT_PER_MAP_TILE);
ModelMatrix.Upload(CurrentGameState->UnitShaderDetails.ModelMatrixLocation);
//Debug Axis rendering
glBindVertexArray(CurrentGameState->DebugAxisBuffer);
glDrawArrays(GL_LINES, 0, 3*2);
}
}
#endif
for(s32 i=0;i<CurrentGameState->NumberOfUnits;i++)
{
UpdateAndRenderUnit(&CurrentGameState->UnitList[i], Animate, &CurrentGameState->UnitShaderDetails, CurrentGameState->PaletteData, &CurrentGameState->UnitTextures, &CurrentGameState->TempArena, CurrentGameState->DebugAxisBuffer);
}
}
[[clang::fallthrough]];
case STATE_PAUSED:
{
glUseProgram(CurrentGameState->MapShader->ProgramID);
CurrentGameState->ProjectionMatrix.Upload(GetUniformLocation(CurrentGameState->MapShader,"Projection"));
CurrentGameState->ViewMatrix.Upload(GetUniformLocation(CurrentGameState->MapShader,"View"));
RenderMap(&CurrentGameState->Map,CurrentGameState->MapShader);
}
break;
default:
break;
}
//NOTE(Christof): All 2D Rendering to be done after this, all 3D before
//TODO(Christof): Make the division here clearer?
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND); // Turn Blending on
glDisable(GL_DEPTH_TEST); //Turn Depth Testing off
#define DEBUG_DRAW_STATS 1
switch(CurrentGameState->State)
{
case STATE_PAUSED:
case STATE_RUNNING:
{
r32 X = 128;
s32 SideOffset = 0;
DrawDebugRect(&CurrentGameState->DebugRectDetails, 0 , 0, 128, (r32)CurrentGameState->ScreenHeight, {{0.0,0.0,0}} , 2.0f, 1.0f, {{0.0,0.0,0}} , 1.0f );
while (X< CurrentGameState->ScreenWidth)
{
DrawGafTexture(X,0,"panelbot", &CurrentGameState->ArmInterfaceTextures, &CurrentGameState->DrawTextureShaderDetails);
DrawGafTexture(X,(r32)CurrentGameState->ScreenHeight - 33,"panelbot", &CurrentGameState->ArmInterfaceTextures, &CurrentGameState->DrawTextureShaderDetails);
X+= 513.0f;
}
DrawGafTexture(128,0,"paneltop", &CurrentGameState->ArmInterfaceTextures, &CurrentGameState->DrawTextureShaderDetails);
DrawGafTexture(0,0,"panelside2", &CurrentGameState->ArmInterfaceTextures, &CurrentGameState->DrawTextureShaderDetails);
DrawGafTexture(128,0,"32xlogos", &CurrentGameState->UnitTextures, &CurrentGameState->DrawTextureShaderDetails, SideOffset);
FNTFont * SmallFont = GetFont(&CurrentGameState->LoadedFonts, "SMLFont", &CurrentGameState->GlobalArchiveCollection, &CurrentGameState->TempArena);
u32 EnergyMax = 1000, EnergyCurrent = 500, MetalMax =1000, MetalCurrent = 500;
r32 EnergyProd = 1427, EnergyUse = 139, MetalProd = 11.6f, MetalUse = 17.5f;
EnergyProd = EnergyUse = MetalUse = MetalProd = 0;
for(s32 i = 0;i<CurrentGameState->NumberOfUnits;i++)
{
if(CurrentGameState->UnitList[i].Side == 0)
{
EnergyProd += CurrentGameState->UnitList[i].Type->Details.GetFloat("EnergyMake");
EnergyUse += CurrentGameState->UnitList[i].Type->Details.GetFloat("EnergyUse");
MetalProd += CurrentGameState->UnitList[i].Type->Details.GetFloat("MetalMake");
MetalUse += CurrentGameState->UnitList[i].Type->Details.GetFloat("MetalUse");
EnergyMax += CurrentGameState->UnitList[i].Type->Details.GetInt("EnergyStorage");
MetalMax += CurrentGameState->UnitList[i].Type->Details.GetInt("MetalStorage");
}
}
const s32 MAX_STRING = 12;
char Temp[MAX_STRING];
snprintf(Temp, MAX_STRING, "%d",MetalMax);
DrawFNTText( 320,0, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails);
snprintf(Temp, MAX_STRING, "%d",MetalCurrent);
DrawFNTText( 270,15, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails);
DrawFNTText( 220,0, "0", SmallFont, &CurrentGameState->DrawTextureShaderDetails);
DrawDebugRect(&CurrentGameState->DebugRectDetails, 220 , 12, 125 * ((r32)MetalCurrent/MetalMax), 2.0f, {{0.8f,0.8f,1}} , 2.0f );
snprintf(Temp, MAX_STRING, "%.1f",MetalProd);
DrawFNTText( 357,4, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails, {{83/255.0f,223/255.0f,79/255.0f}} );
snprintf(Temp, MAX_STRING, "%.1f",MetalUse);
DrawFNTText( 357,16, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails, {{255/255.0f,71/255.0f,0}});
snprintf(Temp, MAX_STRING, "%d",EnergyMax);
DrawFNTText( 570,0, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails);
snprintf(Temp, MAX_STRING, "%d",EnergyCurrent);
DrawFNTText( 520,15, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails);
DrawFNTText( 470,0, "0", SmallFont, &CurrentGameState->DrawTextureShaderDetails);
snprintf(Temp, MAX_STRING, "%.0f",EnergyProd);
DrawFNTText( 608,4, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails, {{83/255.0f,223/255.0f,79/255.0f}} );
snprintf(Temp, MAX_STRING, "%.0f",EnergyUse);
DrawFNTText( 608,16, Temp, SmallFont, &CurrentGameState->DrawTextureShaderDetails, {{255/255.0f,71/255.0f,0}});
DrawDebugRect(&CurrentGameState->DebugRectDetails, 470 , 12, 125* ((r32)EnergyCurrent/EnergyMax), 2, {{1,1,0}} , 2.0f );
DrawMiniMap(&CurrentGameState->Map, 0,0,128,128, {{1,1,1}}, 0.8f, &CurrentGameState->DrawTextureShaderDetails);
}
break;
case STATE_MAIN_MENU:
RenderTAUIElement(&CurrentGameState->MainMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11, &CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
break;
case STATE_SINGLEPLAYER_MENU:
RenderTAUIElement(&CurrentGameState->SinglePlayerMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11,&CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
break;
case STATE_CAMPAIGN_MENU:
RenderTAUIElement(&CurrentGameState->CampaignMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11,&CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
break;
case STATE_LOAD_GAME_MENU:
RenderTAUIElement(&CurrentGameState->SinglePlayerMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11,&CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
RenderTAUIElement(&CurrentGameState->LoadGameMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11,&CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
break;
case STATE_SKIRMISH_MENU:
RenderTAUIElement(&CurrentGameState->SkirmishMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11,&CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
break;
case STATE_OPTIONS_MENU:
RenderTAUIElement(&CurrentGameState->OptionsMenu,(CurrentGameState->ScreenWidth - CurrentGameState->MainMenu.Width)/2,(CurrentGameState->ScreenHeight - CurrentGameState->MainMenu.Height)/2,&CurrentGameState->DrawTextureShaderDetails, &CurrentGameState->Font11,&CurrentGameState->Font12, &CurrentGameState->CommonGUITextures, &CurrentGameState->DebugRectDetails);
break;
case STATE_QUIT:
//NOTE(Christof): nothing to do, simply to silence warning
break;
}
//Debug Stats - FPS/Memory usage at present
#if DEBUG_DRAW_STATS
static u64 CurrentFrameTime = 0;
static u64 LastFrameTime =0;
static float CurrentFPS = 0;
CurrentFrameTime = GetTimeMillis(CurrentGameState->PerformanceCounterFrequency);
const float FramesToCount = 30.0f;
CurrentFPS = (CurrentFPS*(FramesToCount-1) + 1.0f/((CurrentFrameTime - LastFrameTime)/1000.0f))/FramesToCount;
LastFrameTime = CurrentFrameTime;
char MemoryUsageText[128];
snprintf(MemoryUsageText, 128, "FPS: %0.2f\nGame Arena: %.2fMB of %.2fMB (%.2f%% free)\nTemp Arena: %.2fMB of %.2fMB (%.2f%% free)", CurrentFPS,
CurrentGameState->GameArena.Used/(1024.0f*1024), CurrentGameState->GameArena.Size/(1024.0f*1024),
float(CurrentGameState->GameArena.Size - CurrentGameState->GameArena.Used)/CurrentGameState->GameArena.Size*100.0f,
CurrentGameState->TempArena.Used/(1024.0f*1024), CurrentGameState->TempArena.Size/(1024.0f*1024),
float(CurrentGameState->TempArena.Size - CurrentGameState->TempArena.Used)/CurrentGameState->TempArena.Size*100.0f);
DrawTextureFontText(MemoryUsageText, CurrentGameState->ScreenWidth-TextSizeInPixels(MemoryUsageText, &CurrentGameState->Font12).Width, 0,&CurrentGameState->Font12,&CurrentGameState->DrawTextureShaderDetails, 1.0f);
#endif
CurrentGameState->NumberOfFrames++;
}
}
| 38.180406 | 431 | 0.732297 | [
"3d"
] |
c338218f3f7638d6716aacbc8072c6c019b1dedb | 806 | cc | C++ | warhol/platform/path.cc | cristiandonosoc/GNTest | d90b571a7c4e42f51bb8d5dbffe48f681b9aae5e | [
"Zlib",
"Unlicense",
"MIT",
"BSL-1.0",
"BSD-4-Clause"
] | null | null | null | warhol/platform/path.cc | cristiandonosoc/GNTest | d90b571a7c4e42f51bb8d5dbffe48f681b9aae5e | [
"Zlib",
"Unlicense",
"MIT",
"BSL-1.0",
"BSD-4-Clause"
] | null | null | null | warhol/platform/path.cc | cristiandonosoc/GNTest | d90b571a7c4e42f51bb8d5dbffe48f681b9aae5e | [
"Zlib",
"Unlicense",
"MIT",
"BSL-1.0",
"BSD-4-Clause"
] | 1 | 2019-06-04T04:43:24.000Z | 2019-06-04T04:43:24.000Z | // Copyright 2018, Cristián Donoso.
// This code has a BSD license. See LICENSE.
#include "warhol/platform/path.h"
#include "warhol/utils/string.h"
namespace warhol {
// TODO(Cristian): Use std::filesystem (C++17) for this eventually.
std::string PathJoin(std::vector<std::string_view> paths) {
std::vector<std::string> pieces;
pieces.reserve(2 * paths.size() - 1);
for (size_t i = 0; i < paths.size(); i++) {
pieces.emplace_back(std::move(paths[i]));
// We add a "/".
if (i < paths.size() - 1)
pieces.emplace_back("/");
}
return Concatenate(std::move(pieces));
}
std::string GetBasename(const std::string& path) {
size_t separator = path.rfind('/');
if (separator == std::string::npos)
return path;
return path.substr(separator + 1);
}
} // namespace warhol
| 24.424242 | 67 | 0.648883 | [
"vector"
] |
c33f4cd39172239b4c53577c6afed1dad1b175b0 | 766 | cpp | C++ | questions/51261464/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 302 | 2017-03-04T00:05:23.000Z | 2022-03-28T22:51:29.000Z | questions/51261464/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 30 | 2017-12-02T19:26:43.000Z | 2022-03-28T07:40:36.000Z | questions/51261464/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 388 | 2017-07-04T16:53:12.000Z | 2022-03-18T22:20:19.000Z | #include "model.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc, char *argv[]) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QVariantList modelist;
for (int i = 0; i < 10; i++) {
AnimalModel *model = new AnimalModel;
model->addAnimal(Animal("Wolf", "Medium"));
model->addAnimal(Animal("Polar bear", "Large"));
model->addAnimal(Animal("Quoll", "Small"));
modelist << QVariant::fromValue(model);
}
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("modelist", modelist);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
| 26.413793 | 65 | 0.691906 | [
"model"
] |
c34b2b0b5c3113b9adeed5f2a0823d635c13a241 | 4,499 | cpp | C++ | QTDelivery1/ZurullitoPaint/filloutline.cpp | MarcFly/AdvancedGraphicsProgramming | 9ea749dbe036743a4b8a9450a3ae69941e1ed951 | [
"MIT"
] | null | null | null | QTDelivery1/ZurullitoPaint/filloutline.cpp | MarcFly/AdvancedGraphicsProgramming | 9ea749dbe036743a4b8a9450a3ae69941e1ed951 | [
"MIT"
] | null | null | null | QTDelivery1/ZurullitoPaint/filloutline.cpp | MarcFly/AdvancedGraphicsProgramming | 9ea749dbe036743a4b8a9450a3ae69941e1ed951 | [
"MIT"
] | null | null | null | #include "filloutline.h"
#include <QPainter>
#include <QHBoxLayout>
#include <QLabel>
#include <QComboBox>
#include <QSpinBox>
#include <QColorDialog>
//===================================================================
canvasShow::canvasShow(bool is_fp, QWidget* parent) : QWidget(parent), fp(is_fp)
{
cd = new QColorDialog();
setAutoFillBackground(true);
b = new QBrush();
p = new QPen();
b->setStyle(Qt::BrushStyle::NoBrush);
p->setStyle(Qt::PenStyle::NoPen);
}
canvasShow::~canvasShow()
{
delete b;
delete p;
delete cd;
}
QSize canvasShow::minimumSizeHint() const
{
return QSize(16,16);
}
QSize canvasShow::sizeHint() const
{
return QSize(64,64);
}
void canvasShow::mousePressEvent(QMouseEvent *event)
{
click = true;
}
void canvasShow::mouseReleaseEvent(QMouseEvent *event)
{
if(click)
{
cd->open(this, SLOT(SetColor(const QColor&)));
}
click = false;
}
void canvasShow::SetColor(const QColor& rgb)
{
b->setColor(rgb);
p->setColor(rgb);
sendUpdate();
}
void canvasShow::paintEvent(QPaintEvent *ev)
{
QPainter painter(this);
QSize s = this->size();
// Draw White background
QPen wp;
QBrush wb;
wb.setColor(QColor::fromRgb(255,255,255));
wb.setStyle(Qt::BrushStyle::SolidPattern);
wp.setColor(QColor::fromRgb(0,0,0));
wp.setStyle(Qt::PenStyle::NoPen);
painter.setPen(wp);
painter.setBrush(wb);
painter.drawRect(0,0, s.width(), s.height());
// Draw intended result
painter.setPen(*p);
painter.setBrush(*b);
if(fp)
painter.drawRect(0,0, s.width(), s.height());
else
painter.drawLine(0,0, s.width(), s.height());
}
//===================================================================
FillOutline::FillOutline(bool is_fp, QWidget *parent) : QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout();
title = new QLabel((is_fp) ? "Fill" : "Outline" ,this);
layout->addWidget(title);
QStringList strings;
if(is_fp)
{
strings.push_back("NoFill");
strings.push_back("Solid");
strings.push_back("Dense1");
strings.push_back("Dense2");
strings.push_back("Dense3");
strings.push_back("Dense4");
strings.push_back("Dense5");
strings.push_back("Dense6");
strings.push_back("Dense7");
strings.push_back("Horizontal");
strings.push_back("Vertical");
strings.push_back("Cross");
strings.push_back("Up Diagonal");
strings.push_back("Down Diagonal");
strings.push_back("Cross Diagonal");
}
else
{
strings.push_back("No Outline");
strings.push_back("Solid");
strings.push_back("Dash");
strings.push_back("Dot");
strings.push_back("Dash Dot");
strings.push_back("Dash Dot Dot");
}
types = new QComboBox(this);
types->addItems(strings);
layout->addWidget(types);
width = new QSpinBox(this);
width->hide();
if(!is_fp)
{
width->show();
width->setRange(1,999999);
//width->setValue(1);
layout->addWidget(width);
}
expo = new canvasShow(is_fp, this);
layout->addWidget(expo);
setLayout(layout);
// Connect intern components
connect(types, SIGNAL(currentIndexChanged(int)), this, SLOT(change_fp(int)));
connect(expo, SIGNAL(sendUpdate()), this, SIGNAL(sendUpdate()));
connect(this, SIGNAL(SRepaint()), expo, SLOT(repaint()));
connect(width, SIGNAL(valueChanged(int)), this, SLOT(change_pw(int)));
}
FillOutline::~FillOutline()
{
delete expo;
delete types;
delete title;
delete width;
}
void FillOutline::change_fp(int val)
{
if(expo->fp )
expo->b->setStyle((Qt::BrushStyle)val);
else
expo->p->setStyle((Qt::PenStyle)val);
expo->repaint();
sendUpdate();
}
void FillOutline::change_pw(int val)
{
if(!expo->fp)
{
expo->p->setWidth(val);
expo->repaint();
sendUpdate();
}
}
void FillOutline::Update(const QBrush &b, const QPen &p)
{
if(expo->fp)
{
expo->b->setColor(b.color());
expo->b->setStyle(b.style());
types->setCurrentIndex((int)b.style());
}
else
{
width->setValue(p.width());
expo->p->setWidth(p.width());
expo->p->setColor(p.color());
expo->p->setStyle(p.style());
types->setCurrentIndex((int)p.style());
}
repaint();
}
| 21.526316 | 81 | 0.585241 | [
"solid"
] |
c350b8b8973fe86343a104fc99bbacfa337e5f7d | 6,184 | hpp | C++ | src/grid/dof_mapper_periodic_distributed.hpp | simonpp/2dBoltzmann | bc6b7bbeffa242ce80937947444383b416ba3fc9 | [
"BSD-3-Clause"
] | null | null | null | src/grid/dof_mapper_periodic_distributed.hpp | simonpp/2dBoltzmann | bc6b7bbeffa242ce80937947444383b416ba3fc9 | [
"BSD-3-Clause"
] | null | null | null | src/grid/dof_mapper_periodic_distributed.hpp | simonpp/2dBoltzmann | bc6b7bbeffa242ce80937947444383b416ba3fc9 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
// own includes -----------------------------------------------------------
#include "dof_mapper_periodic.hpp"
// system includes --------------------------------------------------------
#include <ostream>
#include <vector>
// debug
#include <iostream>
#include <stdexcept>
// deal.II includes -------------------------------------------------------
#include <deal.II/base/exceptions.h>
#include <deal.II/base/index_set.h>
#include <deal.II/base/utilities.h>
namespace boltzmann {
/**
*
* This class lives on the *physical* grid
*
* @param dh
* @param nprocs
*/
template <typename Mapper_T = DoFMapperPeriodic>
class DoFMapperPeriodicDistributed
{
public:
typedef unsigned int index_t;
typedef dealii::IndexSet index_set_t;
public:
void init(const dealii::DoFHandler<2>& dh, const int nprocs);
/**
* @brief Returns locally relevant DoFs (restricted enumeration)
* on subdomain i
*
* @param i Processor id
*
* @return
*/
const index_set_t& relevant_dofs(int i) const;
/**
* @brief Returns locally owned DoFs (restriced enumeration)
*
* @param i Processor id
*
* @return
*/
const index_set_t& owned_dofs(int i) const;
/**
* @brief Maps physical grid (full) DoF to periodic enumeration
*
* @param unrestriced_idx
*
* @return
*/
index_t operator[](const index_t unrestriced_idx) const;
/**
* @brief Returns #DoFs on the *physical* periodic grid
*
*
* @return
*/
index_t n_dofs() const;
void print_permutation(std::ostream& out)
{
for (unsigned int i = 0; i < permutation_.size(); ++i) {
out << permutation_[i] << std::endl;
}
}
private:
Mapper_T periodic_mapper;
/// permutation of dofs on restricted domain
/// used as a prox to DoFMapperPeriodic
std::vector<unsigned int> permutation_;
//@{
/// IndexSets on restricted grid for each subdomain
std::vector<index_set_t> locally_relevant_dofs_;
std::vector<index_set_t> locally_owned_dofs_;
//@}
};
// ----------------------------------------------------------------------
template <typename Mapper_T>
const typename DoFMapperPeriodicDistributed<Mapper_T>::index_set_t&
DoFMapperPeriodicDistributed<Mapper_T>::relevant_dofs(int i) const
{
return locally_relevant_dofs_[i];
}
// ----------------------------------------------------------------------
template <typename Mapper_T>
const typename DoFMapperPeriodicDistributed<Mapper_T>::index_set_t&
DoFMapperPeriodicDistributed<Mapper_T>::owned_dofs(int i) const
{
return locally_owned_dofs_[i];
}
// ----------------------------------------------------------------------
template <typename Mapper_T>
typename DoFMapperPeriodicDistributed<Mapper_T>::index_t DoFMapperPeriodicDistributed<Mapper_T>::
operator[](const index_t unrestriced_idx) const
{
return permutation_[periodic_mapper[unrestriced_idx]];
}
// ----------------------------------------------------------------------
template <typename Mapper_T>
typename DoFMapperPeriodicDistributed<Mapper_T>::index_t
DoFMapperPeriodicDistributed<Mapper_T>::n_dofs() const
{
return periodic_mapper.size();
}
// ----------------------------------------------------------------------
template <typename Mapper_T>
void
DoFMapperPeriodicDistributed<Mapper_T>::init(const dealii::DoFHandler<2>& dh, const int nprocs)
{
periodic_mapper.init(dh);
std::vector<int> subd_assoc_restricted;
const unsigned int n_full_dofs = dh.n_dofs();
const unsigned int n_rest_dofs = periodic_mapper.size();
std::vector<unsigned int> subd_assoc(n_full_dofs);
dealii::DoFTools::get_subdomain_association(dh, subd_assoc);
subd_assoc_restricted.resize(periodic_mapper.size(), -1);
//
const auto& dof_map = periodic_mapper.dof_map();
for (unsigned int i = 0; i < n_full_dofs; ++i) {
auto it = dof_map.find(i);
if (it != dof_map.end()) {
// this is a slave dof
// use subdomain of master
const unsigned int master_idx = it->second;
subd_assoc_restricted[periodic_mapper[i]] = subd_assoc[master_idx];
} else {
// this is master dof
subd_assoc_restricted[periodic_mapper[i]] = subd_assoc[i];
}
}
// Renumbering (make the restriced DoFs contiguous across subdomains)
// write result to permutation_
permutation_.resize(n_rest_dofs);
std::vector<unsigned int> offsets(nprocs, 0);
for (unsigned int i = 0; i < n_rest_dofs; ++i) {
unsigned int color = subd_assoc_restricted[i];
assert(color >=0);
assert(color < nprocs);
permutation_[i] = offsets[color]++;
}
unsigned int offset = 0;
for (int i = 0; i < nprocs; ++i) {
unsigned int tmp = offsets[i];
offsets[i] = offset;
offset += tmp;
}
for (unsigned int i = 0; i < n_rest_dofs; ++i) {
unsigned int color = subd_assoc_restricted[i];
permutation_[i] += offsets[color];
}
locally_owned_dofs_.resize(nprocs);
locally_relevant_dofs_.resize(nprocs);
// build IndexSets of locally relevant and locally owned dofs
for (int dom = 0; dom < nprocs; ++dom) {
locally_owned_dofs_[dom].set_size(n_rest_dofs);
locally_relevant_dofs_[dom].set_size(n_rest_dofs);
auto index_set = dealii::DoFTools::dof_indices_with_subdomain_association(dh, dom);
std::vector<bool> locally_relevant_phys_indices(n_full_dofs);
index_set.fill_binary_vector(locally_relevant_phys_indices);
for (unsigned int i = 0; i < n_full_dofs; ++i) {
if (locally_relevant_phys_indices[i])
locally_relevant_dofs_[dom].add_index(this->operator[](i));
if (subd_assoc_restricted[this->operator[](i)] == dom)
locally_owned_dofs_[dom].add_index(this->operator[](i));
}
locally_relevant_dofs_[dom].compress();
locally_owned_dofs_[dom].compress();
}
#ifdef DEBUG
for (int i = 0; i < nprocs; ++i) {
for (int j = i+1; j < nprocs; ++j) {
for (auto it = locally_owned_dofs_[i].begin(); it != locally_owned_dofs_[i].end(); ++it) {
if (locally_owned_dofs_[j].is_element(*it)) {
throw std::runtime_error("ooops index" + std::to_string(*it) + " is contained in set " + std::to_string(j));
}
}
}
}
#endif //DEBUG
}
} // end namespace boltzmann
| 29.874396 | 118 | 0.634864 | [
"vector"
] |
c3515372dbd39c6926c6d1988b6bf39ff7ec711b | 4,716 | cpp | C++ | Engine/W_Project.cpp | SOLID-TEAM/SOLID_ENGINE | 7fa9eccc28217d49a937fcf1dcfc052716825d30 | [
"MIT"
] | 2 | 2019-11-22T23:34:36.000Z | 2019-11-27T10:27:35.000Z | Engine/W_Project.cpp | SOLID-TEAM/SOLID_ENGINE | 7fa9eccc28217d49a937fcf1dcfc052716825d30 | [
"MIT"
] | null | null | null | Engine/W_Project.cpp | SOLID-TEAM/SOLID_ENGINE | 7fa9eccc28217d49a937fcf1dcfc052716825d30 | [
"MIT"
] | null | null | null | #include "W_Project.h"
#include "Application.h"
#include "ModuleFileSystem.h"
#include "ModuleEditor.h"
#include "ImGui/imgui.h"
#include "ImGui/imgui_internal.h"
#include "IconFontAwesome/IconsFontAwesome5.h"
#include "Viewport.h"
#include <string>
W_Project::W_Project(std::string name, bool active) : Window(name, active)
{
};
void W_Project::Draw()
{
// Set selected resource ---------------------------
if (App->editor->IsSelectedObjectValid(SelectedObject::Type::RESOURCE))
{
selected_resource = (Resource*)App->editor->GetSelectedObject().data;
}
else
{
selected_resource = nullptr;
}
// Draw Window -------------------------------------
ImGui::PushStyleVar(ImGuiStyleVar_::ImGuiStyleVar_WindowPadding, ImVec2(0.f, 0.f));
if (ImGui::Begin(" " ICON_FA_FOLDER " Project", &active, ImGuiWindowFlags_::ImGuiWindowFlags_MenuBar))
{
if (ImGui::BeginMenuBar())
{
ImGui::EndMenuBar();
}
ImGui::PushStyleColor(ImGuiCol_::ImGuiCol_ChildWindowBg, ImVec4(.2f,.2f,.2f,2.f));
ImGui::PushStyleVar(ImGuiStyleVar_::ImGuiStyleVar_WindowPadding, ImVec2(3.f, 3.f));
static bool init_width = true;
ImGui::BeginColumns("project_columns", 2);
if (init_width)
{
ImGui::SetColumnWidth(0, ImGui::GetWindowSize().x * 0.15f);
init_width = false;
}
// Draw tree ----------------------------
if (ImGui::BeginChild("##project_tree", { 0 , 0 }, ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysUseWindowPadding))
{
ImGui::Spacing();
DrawTree();
ImGui::EndChild();
};
ImGui::PopStyleColor();
ImGui::NextColumn();
folder_column_width = ImGui::GetColumnWidth();
// Draw inside folder --------------------
ImGui::PopStyleVar();
ImGui::PushStyleVar(ImGuiStyleVar_::ImGuiStyleVar_WindowPadding, ImVec2(10.f, 10.f));
if (ImGui::BeginChild("##project_view", { 0 , 0 }, ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysUseWindowPadding))
{
DrawFolder();
ImGui::EndChild();
}
ImGui::EndColumns();
ImGui::PopStyleVar();
}
ImGui::End();
ImGui::PopStyleVar();
}
void W_Project::DrawTree()
{
static char* assets[] = { "All Models", "All Meshes", "All Materials" ,"All Textures" };
static char* selected = "Nothing";
for (uint i = 0; i < 4; ++i)
{
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_Leaf;
if (selected == assets[i])
{
flags |= ImGuiTreeNodeFlags_Selected;
}
std::string title(ICON_FA_SEARCH " ");
title += assets[i];
bool open = ImGui::TreeNodeEx(title.c_str() , flags);
if (ImGui::IsItemClicked())
{
selected = assets[i];
if (selected == "All Models") resource_type = Resource::Type::MODEL;
else if (selected == "All Meshes") resource_type = Resource::Type::MESH;
else if (selected == "All Materials") resource_type = Resource::Type::MATERIAL;
else if (selected == "All Textures") resource_type = Resource::Type::TEXTURE;
visible_resources = App->resources->GetAllResourcesByType(resource_type); // TODO: Update with fix time this vector
}
if (open) ImGui::TreePop();
}
if (ImGui::IsMouseDown(0) && ImGui::IsAnyItemHovered() == false && ImGui::IsWindowHovered())
{
selected = "Nothing";
}
}
void W_Project::DrawFolder()
{
float total_width = folder_column_width;
float item_width = 80 , item_height = 80;
ImVec2 last_cursor_pos ={ 0,0 };
float width_amount = 0;
// Draw folder files ------------------------------
ImGui::Columns( max(1, int (folder_column_width / (item_width + 20.f) ) ), "project_folder_columns", false);
for (Resource* resource : visible_resources)
{
ImGui::PushID(resource);
ImGui::PushStyleColor(ImGuiCol_::ImGuiCol_Button, (resource == selected_resource) ? ImVec4(1.f, 0.75f, 0.f, 1.f) : ImVec4(0.f, 0.f, 0.f, 0.f));
// TODO: Change texture
ImGui::ImageButton((ImTextureID)App->scene->scene_viewport->GetTexture(), { item_width,item_height }, { 1,1 }, { 0,0 });
ImGui::PopStyleColor();
if (ImGui::IsItemClicked())
{
App->editor->SetSelectedObject(resource, SelectedObject::Type::RESOURCE);
// TODO: Select resource and show info
}
if (ImGui::IsMouseDoubleClicked(0))
{
// TODO:Create model
}
// Drag same as double click ?
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoDisableHover))
{
ImGui::SetDragDropPayload("resource_node", &resource, sizeof(Resource*), ImGuiCond_Once);
ImGui::Text(resource->GetName().c_str());
ImGui::EndDragDropSource();
}
ImGui::NewLine();
ImGui::SameLine();
ImGui::Text(resource->GetName().c_str());
ImGui::Spacing();
ImGui::NextColumn();
ImGui::PopID();
}
if (ImGui::IsMouseDown(0) && ImGui::IsAnyItemHovered() == false && ImGui::IsWindowHovered())
{
App->editor->DeselectSelectedObject();
}
}
| 26.948571 | 145 | 0.667727 | [
"mesh",
"vector",
"model"
] |
c3590efce3d181ef34268cf0440e9414b11c70da | 5,111 | cpp | C++ | core/src/comsci/travelling_salesman.cpp | emanuelmch/cpic | d31b977710865d28b87e66a419964200de197067 | [
"MIT"
] | null | null | null | core/src/comsci/travelling_salesman.cpp | emanuelmch/cpic | d31b977710865d28b87e66a419964200de197067 | [
"MIT"
] | 2 | 2021-05-06T15:08:44.000Z | 2022-02-09T00:51:11.000Z | core/src/comsci/travelling_salesman.cpp | emanuelmch/cpic | d31b977710865d28b87e66a419964200de197067 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2021 Emanuel Machado da Silva
*
* 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 "travelling_salesman.h"
#include "travelling_salesman_data.h"
#include "common/assertions.h"
#include "common/containers.h"
#include "common/ranges.h"
#include "comsci/genetic/crossover_strategies.h"
#include "comsci/genetic/genetic_algorithm.h"
#include "comsci/genetic/mutation_strategies.h"
#include <algorithm> // std::find_if, std::shuffle, std::swap
#include <array> // std::array
#include <limits> // std::numeric_limits
#include <random> // std::rand
using namespace pzl::comsci;
constexpr auto POPULATION_SIZE = 40;
constexpr auto ELITE_SIZE = 6;
constexpr auto MUTATION_CHANCE = 5;
namespace {
using GeneArray = std::array<uint8_t, CITY_COUNT>;
struct Chromosome {
GeneArray genes;
mutable uint8_t _fitness;
Chromosome() : genes{pzl::generate_array_iota<CITY_COUNT, uint8_t>()}, _fitness{0} {
std::shuffle(genes.begin(), genes.end(), std::random_device{});
ensure(isValid());
}
explicit Chromosome(GeneArray genes) : genes{genes}, _fitness{0} { ensure(isValid()); }
[[nodiscard]] constexpr bool isValid() const {
for (auto i = 0u; i < CITY_COUNT; ++i) {
if (pzl::ranges::contains(genes, i) == false) {
return false;
}
}
return true;
}
constexpr uint8_t fitness() const {
if (_fitness == 0) {
uint8_t distance = 0;
for (size_t i = 0; i < genes.size() - 1; ++i) {
auto from = genes[i];
auto to = genes[i + 1];
distance += DISTANCE_TABLE[from][to];
}
auto last = genes[genes.size() - 1];
auto first = genes[0];
distance += DISTANCE_TABLE[last][first];
_fitness = MAX_DISTANCE - distance;
}
ensure(_fitness > 0);
return _fitness;
}
constexpr bool operator<(const Chromosome &other) const { return this->fitness() < other.fitness(); }
};
}
inline Chromosome crossover(const Chromosome &left, const Chromosome &right) {
// TODO: These next two values should be randomly calculated
static const uint8_t CROSSOVER_CUTPOINT_LEFT = 1;
static const uint8_t CROSSOVER_CUTPOINT_RIGHT = 3;
static_assert(CROSSOVER_CUTPOINT_LEFT < CROSSOVER_CUTPOINT_RIGHT);
static_assert(CROSSOVER_CUTPOINT_RIGHT < CITY_COUNT);
GeneArray genes;
genes.fill(std::numeric_limits<GeneArray::value_type>::max());
ensure(left.isValid());
ensure(right.isValid());
for (auto i = CROSSOVER_CUTPOINT_LEFT; i < CROSSOVER_CUTPOINT_RIGHT; ++i) {
genes[i] = left.genes[i];
}
for (size_t i = 0; i < CITY_COUNT; ++i) {
if (i >= CROSSOVER_CUTPOINT_LEFT && i < CROSSOVER_CUTPOINT_RIGHT) continue;
auto it = std::find_if(right.genes.cbegin(), right.genes.cend(),
[&genes](const auto &it) { return pzl::ranges::contains(genes, it) == false; });
genes[i] = *it;
}
ensure(pzl::ranges::contains(genes, std::numeric_limits<GeneArray::value_type>::max()) == false);
return Chromosome(genes);
}
inline void mutate(Chromosome *chromosome) {
auto index1 = static_cast<size_t>(std::rand()) % CITY_COUNT;
auto index2 = static_cast<size_t>(std::rand()) % CITY_COUNT;
std::swap(chromosome->genes[index1], chromosome->genes[index2]);
ensure(chromosome->isValid());
// We should always be called on new Chromosomes, due to the way the crossover code works;
// Otherwise we would have to set it to 0 manually
ensure(chromosome->_fitness == 0);
}
ComSci::TravellingSalesman::Solution ComSci::TravellingSalesman::run() {
LambdaCrossoverStrategy<Chromosome> crossoverStrategy{crossover};
LambdaMutationStrategy<Chromosome, MUTATION_CHANCE> mutationStrategy{mutate};
auto geneticAlgorithm =
GeneticAlgorithm<Chromosome, POPULATION_SIZE>{ELITE_SIZE, crossoverStrategy, mutationStrategy};
auto [solution, generations] = geneticAlgorithm.runUntilGenerationsSinceLastImprovement(100000);
std::vector<uint8_t> shortestPath{solution.genes.begin(), solution.genes.end()};
return {shortestPath, static_cast<uint8_t>(MAX_DISTANCE - solution.fitness())};
}
| 35.493056 | 107 | 0.711015 | [
"vector"
] |
c371431655bd92123fc0816c75ff6b8af179a0f2 | 8,692 | cpp | C++ | firmware/Prototype_v4/libraries/Adafruit_SHTC3_Library/Adafruit_SHTC3.cpp | cave-42/ProjectApollo | 3381af9336f4da34c5bb367c045a15ac6c4202b0 | [
"MIT"
] | 42 | 2020-03-18T17:27:49.000Z | 2022-02-12T03:52:01.000Z | firmware/Prototype_v4/libraries/Adafruit_SHTC3_Library/Adafruit_SHTC3.cpp | cave-42/ProjectApollo | 3381af9336f4da34c5bb367c045a15ac6c4202b0 | [
"MIT"
] | 2 | 2021-04-28T00:44:10.000Z | 2021-07-13T13:36:47.000Z | firmware/Prototype_v4/libraries/Adafruit_SHTC3_Library/Adafruit_SHTC3.cpp | cave-42/ProjectApollo | 3381af9336f4da34c5bb367c045a15ac6c4202b0 | [
"MIT"
] | 26 | 2020-03-21T20:15:38.000Z | 2022-02-11T22:20:07.000Z | /*!
* @file Adafruit_SHTC3.cpp
*
* @mainpage Adafruit SHTC3 Digital Humidity & Temp Sensor
*
* @section intro_sec Introduction
*
* This is a library for the SHTC3 Digital Humidity & Temp Sensor
*
* Designed specifically to work with the SHTC3 Digital sensor from Adafruit
*
* Pick one up today in the adafruit shop!
* ------> https://www.adafruit.com/product/4636
*
* These sensors use I2C to communicate, 2 pins are required to interface
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* @section author Author
*
* Limor Fried/Ladyada (Adafruit Industries).
*
* @section license License
*
* BSD license, all text above must be included in any redistribution
*/
#include "Adafruit_SHTC3.h"
/*!
* @brief SHTC3 constructor
*/
Adafruit_SHTC3::Adafruit_SHTC3(void) {}
/*!
* @brief SHTC3 destructor
*/
Adafruit_SHTC3::~Adafruit_SHTC3(void) {
if (temp_sensor) {
delete temp_sensor;
}
if (humidity_sensor) {
delete humidity_sensor;
}
}
/**
* Initialises the I2C bus, and assigns the I2C address to us.
*
* @param theWire The I2C bus to use, defaults to &Wire
*
* @return True if initialisation was successful, otherwise False.
*/
bool Adafruit_SHTC3::begin(TwoWire *theWire) {
if (i2c_dev) {
delete i2c_dev; // remove old interface
}
i2c_dev = new Adafruit_I2CDevice(SHTC3_DEFAULT_ADDR, theWire);
if (!i2c_dev->begin()) {
return false;
}
reset();
sleep(false);
// read the ID
if ((readID() & 0x083F) != 0x807) {
return false;
}
humidity_sensor = new Adafruit_SHTC3_Humidity(this);
temp_sensor = new Adafruit_SHTC3_Temp(this);
return true;
}
/**
* @brief Brings the SHTC3 in or out of sleep mode
*
* @param sleepmode If true, go into sleep mode. Else, wakeup
*/
void Adafruit_SHTC3::sleep(bool sleepmode) {
if (sleepmode) {
writeCommand(SHTC3_SLEEP);
} else {
writeCommand(SHTC3_WAKEUP);
delayMicroseconds(250);
}
}
/**
* @brief Tells the SHTC3 to read future data in low power (fast) or normal
* (precise)
*
* @param readmode If true, use low power mode for reads
*/
void Adafruit_SHTC3::lowPowerMode(bool readmode) { _lpMode = readmode; }
/**
* Gets the ID register contents.
*
* @return The 16-bit ID register.
*/
uint16_t Adafruit_SHTC3::readID(void) {
uint8_t data[3];
readCommand(SHTC3_READID, data, 3);
uint16_t id = data[0];
id <<= 8;
id |= data[1];
return id;
}
/**
* Performs a reset of the sensor to put it into a known state.
*/
void Adafruit_SHTC3::reset(void) {
writeCommand(SHTC3_SOFTRESET);
delay(1);
}
/**************************************************************************/
/*!
@brief Gets the humidity sensor and temperature values as sensor events
@param humidity Sensor event object that will be populated with humidity
data
@param temp Sensor event object that will be populated with temp data
@returns true if the event data was read successfully
*/
/**************************************************************************/
bool Adafruit_SHTC3::getEvent(sensors_event_t *humidity,
sensors_event_t *temp) {
uint32_t t = millis();
uint8_t readbuffer[6];
sleep(false);
if (_lpMode) {
// low power
writeCommand(SHTC3_LOWPOW_MEAS_TFIRST);
delay(1);
} else {
writeCommand(SHTC3_NORMAL_MEAS_TFIRST);
delay(13);
}
while (!i2c_dev->read(readbuffer, sizeof(readbuffer))) {
delay(1);
}
if (readbuffer[2] != crc8(readbuffer, 2) ||
readbuffer[5] != crc8(readbuffer + 3, 2))
return false;
int32_t stemp = (int32_t)(((uint32_t)readbuffer[0] << 8) | readbuffer[1]);
// simplified (65536 instead of 65535) integer version of:
// temp = (stemp * 175.0f) / 65535.0f - 45.0f;
stemp = ((4375 * stemp) >> 14) - 4500;
_temperature = (float)stemp / 100.0f;
uint32_t shum = ((uint32_t)readbuffer[3] << 8) | readbuffer[4];
// simplified (65536 instead of 65535) integer version of:
// humidity = (shum * 100.0f) / 65535.0f;
shum = (625 * shum) >> 12;
_humidity = (float)shum / 100.0f;
sleep(true);
// use helpers to fill in the events
if (temp)
fillTempEvent(temp, t);
if (humidity)
fillHumidityEvent(humidity, t);
return true;
}
void Adafruit_SHTC3::fillTempEvent(sensors_event_t *temp, uint32_t timestamp) {
memset(temp, 0, sizeof(sensors_event_t));
temp->version = sizeof(sensors_event_t);
temp->sensor_id = _sensorid_temp;
temp->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
temp->timestamp = timestamp;
temp->temperature = _temperature;
}
void Adafruit_SHTC3::fillHumidityEvent(sensors_event_t *humidity,
uint32_t timestamp) {
memset(humidity, 0, sizeof(sensors_event_t));
humidity->version = sizeof(sensors_event_t);
humidity->sensor_id = _sensorid_humidity;
humidity->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
humidity->timestamp = timestamp;
humidity->relative_humidity = _humidity;
}
/**
* @brief Gets the Adafruit_Sensor object for the SHTC3's humidity sensor
*
* @return Adafruit_Sensor*
*/
Adafruit_Sensor *Adafruit_SHTC3::getHumiditySensor(void) {
return humidity_sensor;
}
/**
* @brief Gets the Adafruit_Sensor object for the SHTC3's humidity sensor
*
* @return Adafruit_Sensor*
*/
Adafruit_Sensor *Adafruit_SHTC3::getTemperatureSensor(void) {
return temp_sensor;
}
/**
* @brief Gets the sensor_t object describing the SHTC3's humidity sensor
*
* @param sensor The sensor_t object to be populated
*/
void Adafruit_SHTC3_Humidity::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy(sensor->name, "SHTC3_H", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name) - 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
sensor->min_delay = 0;
sensor->min_value = 0;
sensor->max_value = 100;
sensor->resolution = 2;
}
/**
@brief Gets the humidity as a standard sensor event
@param event Sensor event object that will be populated
@returns True
*/
bool Adafruit_SHTC3_Humidity::getEvent(sensors_event_t *event) {
_theSHTC3->getEvent(event, NULL);
return true;
}
/**
* @brief Gets the sensor_t object describing the SHTC3's tenperature sensor
*
* @param sensor The sensor_t object to be populated
*/
void Adafruit_SHTC3_Temp::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy(sensor->name, "SHTC3_T", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name) - 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
sensor->min_delay = 0;
sensor->min_value = -40;
sensor->max_value = 85;
sensor->resolution = 0.3; // depends on calibration data?
}
/*!
@brief Gets the temperature as a standard sensor event
@param event Sensor event object that will be populated
@returns true
*/
bool Adafruit_SHTC3_Temp::getEvent(sensors_event_t *event) {
_theSHTC3->getEvent(NULL, event);
return true;
}
/**
* Internal function to perform and I2C write.
*
* @param cmd The 16-bit command ID to send.
*/
bool Adafruit_SHTC3::writeCommand(uint16_t command) {
uint8_t cmd[2];
cmd[0] = command >> 8;
cmd[1] = command & 0xFF;
return i2c_dev->write(cmd, 2);
}
/**
* Internal function to perform an I2C read.
*
* @param cmd The 16-bit command ID to send.
*/
bool Adafruit_SHTC3::readCommand(uint16_t command, uint8_t *buffer,
uint8_t num_bytes) {
uint8_t cmd[2];
cmd[0] = command >> 8;
cmd[1] = command & 0xFF;
return i2c_dev->write_then_read(cmd, 2, buffer, num_bytes);
}
/**
* Performs a CRC8 calculation on the supplied values.
*
* @param data Pointer to the data to use when calculating the CRC8.
* @param len The number of bytes in 'data'.
*
* @return The computed CRC8 value.
*/
static uint8_t crc8(const uint8_t *data, int len) {
/*
*
* CRC-8 formula from page 14 of SHT spec pdf
*
* Test data 0xBE, 0xEF should yield 0x92
*
* Initialization data 0xFF
* Polynomial 0x31 (x8 + x5 +x4 +1)
* Final XOR 0x00
*/
const uint8_t POLYNOMIAL(0x31);
uint8_t crc(0xFF);
for (int j = len; j; --j) {
crc ^= *data++;
for (int i = 8; i; --i) {
crc = (crc & 0x80) ? (crc << 1) ^ POLYNOMIAL : (crc << 1);
}
}
return crc;
}
| 25.640118 | 79 | 0.665555 | [
"object"
] |
c379159305a1488ff7cf51cfa306589163feb3c3 | 1,648 | cpp | C++ | design_patterns/behavioral/visitor/c++/visitor.cpp | artbobrov/algorithms_and_data_structures | 799d301169da9f8507f8bb324859f9041caf1622 | [
"MIT"
] | null | null | null | design_patterns/behavioral/visitor/c++/visitor.cpp | artbobrov/algorithms_and_data_structures | 799d301169da9f8507f8bb324859f9041caf1622 | [
"MIT"
] | null | null | null | design_patterns/behavioral/visitor/c++/visitor.cpp | artbobrov/algorithms_and_data_structures | 799d301169da9f8507f8bb324859f9041caf1622 | [
"MIT"
] | 1 | 2021-03-08T14:22:51.000Z | 2021-03-08T14:22:51.000Z | #include <iostream>
#include <vector>
class PlanetAlderaan;
class PlanetCoruscant;
class PlanetTatooine;
class MoonJedah;
class PlanetVisitor {
public:
virtual void visit(PlanetAlderaan *) = 0;
virtual void visit(PlanetCoruscant *) = 0;
virtual void visit(PlanetTatooine *) = 0;
virtual void visit(MoonJedah *) = 0;
};
class Planet {
public:
virtual void accept(PlanetVisitor *visitor) = 0;
};
class MoonJedah: public Planet {
public:
void accept(PlanetVisitor *visitor) override { visitor->visit(this); }
};
class PlanetAlderaan: public Planet {
public:
void accept(PlanetVisitor *visitor) override { visitor->visit(this); }
};
class PlanetCoruscant: public Planet {
public:
void accept(PlanetVisitor *visitor) override { visitor->visit(this); }
};
class PlanetTatooine: public Planet {
public:
void accept(PlanetVisitor *visitor) override { visitor->visit(this); }
};
class NameVisitor: public PlanetVisitor {
public:
void visit(PlanetAlderaan *alderaan) override {
_name = "Alderaan";
}
void visit(PlanetCoruscant *coruscant) override {
_name = "Coruscant";
}
void visit(PlanetTatooine *tatooine) override {
_name = "Tatooine";
}
void visit(MoonJedah *jedah) override {
_name = "Jedah";
}
std::string name() const { return _name; }
private:
std::string _name = "";
};
int main() {
std::vector<Planet *> planets = {new MoonJedah, new PlanetTatooine, new PlanetCoruscant, new PlanetAlderaan};
for (auto &planet: planets) {
auto visitor = NameVisitor();
planet->accept(&visitor);
std::cout << "Visitor name: " << visitor.name() << std::endl;
}
for (auto &planet: planets)
delete planet;
return 0;
} | 22.888889 | 110 | 0.715413 | [
"vector"
] |
c37a2a33ec432e5245874b2e6da7f330bf29caf9 | 30,440 | cpp | C++ | atreyu/pozyxModule.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | 1 | 2019-02-07T12:24:51.000Z | 2019-02-07T12:24:51.000Z | atreyu/pozyxModule.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | null | null | null | atreyu/pozyxModule.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | 1 | 2020-07-06T10:33:10.000Z | 2020-07-06T10:33:10.000Z |
#include "pozyxModule.h"
#include "globalSettings.h"
#include <log.h>
#include <stdMessage.h>
using airt::Context;
using airt::GlobalSettings;
using airt::Log;
using airt::Message;
using airt::PozyxModule;
using boost::asio::ip::tcp;
using boost::asio::ip::udp;
#include <utils.h>
PozyxModule::PozyxModule(const std::string &cmdportname, const std::string &subportname, std::shared_ptr<Context> context) : Module(cmdportname, subportname, "", context)
{
assert(context);
std::string pozyx_ip = "";
if (!GlobalSettings::getValue("pozyx_ip", pozyx_ip))
{
Log::critical("PozyxModule: Undefined pozyx_ip");
throw std::runtime_error("PozyxModule: Undefined pozyx_ip");
}
int pozyx_httpport;
if (!GlobalSettings::getValue("pozyx_httpport", pozyx_httpport))
{
Log::critical("PozyxModule: Undefined pozyx_httpport");
throw std::runtime_error("PozyxModule: Undefined pozyx_httpport");
}
messageProcessor.setEndpoints(pozyx_ip, std::to_string(pozyx_httpport));
if (!GlobalSettings::getValue("pozyx_udpport", pozyx_udpport))
{
Log::critical("PozyxModule: Undefined pozyx_udpport");
throw std::runtime_error("PozyxModule: Undefined pozyx_udpport");
}
if (!GlobalSettings::getValue("pozyx_settings_file", pozyx_settingsfile_path))
{
Log::critical("PozyxModule: Undefined pozyx_settings_file");
throw std::runtime_error("PozyxModule: Undefined pozyx_settings_file");
}
// udp socket will attend at pozyx-server udp port
udp_socket = std::make_unique<udp::socket>(udp_io_service, udp::endpoint(udp::v4(), pozyx_udpport));
// close the tap to avoid the o.s. enqueues unrequired data
udp_socket->close();
// init
currentFrame = 0;
max_secs_for_data = 1.5;
ips_settings_updated = false;
}
bool PozyxModule::startDevice()
{
return true;
}
void PozyxModule::stopDevice()
{
}
bool PozyxModule::dataReady()
{
if (!ips_settings_updated || !udp_socket->is_open())
{
return false;
}
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - lastPosFrameTS;
// check max time
if (currentFrame >= 1 && udp_socket->available() == 0)
{
std::chrono::seconds elapsed_secs = std::chrono::duration_cast<std::chrono::seconds>(elapsed);
double secs = elapsed_secs.count();
if (secs > max_secs_for_data)
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_POSITIONING_STOPPED);
Log::critical("PozyxModule: Pozyx-server has STOPPED publishing IPS frames at UDP port for more than {} seconds. Stopping PozyxModule...", max_secs_for_data);
stopDevice();
deviceOn = false;
}
return false;
}
lastPosFramePeriodms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
// update
lastPosFrameTS = now;
// udp_remote_endpoint will be populated by receive_from()
nBytesReceivedFromPositioning = udp_socket->receive_from(boost::asio::buffer(recv_buf),
udp_remote_endpoint, 0, udp_error);
if (udp_error && udp_error != boost::asio::error::message_size)
{
Log::error("PozyxModule: Error in dataReady. Code: {}", boost::system::system_error(udp_error).what());
return false;
}
return true;
}
bool PozyxModule::quitDevice()
{
/*
PozyxResponses::ShortCommandResp cmdresp;
messageProcessor.requestStop(cmdresp);
if(!cmdresp.success)
{
// it is commonly 'already stopped'
Log::error("PozyxModule: pozyx-server failed stop. Error: {}", cmdresp.error);
}
*/
/*
// TODO: send kill command when pozyx-server does not crash when receiving kill command
PozyxResponses::ShortCommandResp cmdresp;
messageProcessor.requestKill(cmdresp);
if(!cmdresp.success)
{
// it is commonly 'already stopped'
Log::error("PozyxModule: pozyx-server failed kill. Error: {}", cmdresp.error);
}
*/
if (udp_socket->is_open())
{
udp_socket->close();
}
Log::info("PozyxModule: quitting");
return true;
}
bool PozyxModule::sendMessage()
{
// Get only valid data (not the whole buffer)
std::string frame_str(recv_buf.c_array(), nBytesReceivedFromPositioning);
PozyxResponses::PositioningFrame frame;
messageProcessor.extractPositioningFrame(frame_str, frame);
if (!frame.success)
{
Log::error("PozyxModule: invalid frame {}. Not sending it", currentFrame);
return false;
}
PositioningFrame posData;
posData.timestamp = frame.timestamp;
posData.x = frame.coordinates.x;
posData.y = frame.coordinates.y;
posData.z = frame.coordinates.z;
// pozyxserver is not providing pitch and roll (ignoring those incoming values)
posData.roll = 0.0;
posData.pitch = 0.0;
posData.yaw = frame.yaw;
Message msg;
msg.add_raw(&posData, sizeof(PositioningFrame));
pubsocket->send(msg);
Log::info("PozyxModule: totalFramesSent {} RPY {} {} {} XYZ {} {} {}, IPS-frame period from pozyxserver {} ms",
currentFrame,
posData.roll, posData.pitch, posData.yaw,
posData.x, posData.y, posData.z, lastPosFramePeriodms.count());
// update
currentFrame++;
nBytesReceivedFromPositioning = 0;
return true;
}
void PozyxModule::onMessage(const Message &m)
{
std::stringstream ss;
uint8_t module = airt::getMessageAction(m);
switch (module)
{
case StdMessage::IPS_SYSTEM:
Log::info("PozyxModule: received command IPS_SYSTEM");
if (messageProcessor.requestSystem(resp_system))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LOCALTAG_CONNECTED);
Log::info("PozyxModule: got system response: [status {}, rss {}, id {}, hexId {}, distance {}]",
resp_system.status,
resp_system.device.rss, resp_system.device.id,
resp_system.device.hexId, resp_system.device.distance);
}
else
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
}
break;
case StdMessage::IPS_DISCOVER:
Log::info("PozyxModule: received command IPS_DISCOVER");
if (messageProcessor.requestDiscoverFull(resp_discover))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_DISCOVERED);
ss.clear();
ss << "Tags found: " << resp_discover.tags.size() << ", ids [";
for (size_t i = 0; i < resp_discover.tags.size(); i++)
{
ss << resp_discover.tags[i].id << ", ";
}
ss << "]";
ss << ", Anchors found: " << resp_discover.anchors.size() << ", ids [";
for (size_t i = 0; i < resp_discover.anchors.size(); i++)
{
ss << resp_discover.anchors[i].id << ", ";
}
ss << "]";
Log::info("PozyxModule: got discover response: {}", ss.str());
sendAnchorsIDsList(resp_discover);
if (resp_discover.anchors.size() >= 8)
{
if (settings.anchors.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
break;
}
}
// send previous session anchors-locations (the ids might not be the same)
sendAnchorsLocations(settings);
}
}
else
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
}
break;
case StdMessage::IPS_ANCHOR_MANUAL_CONFIG:
{
Log::info("PozyxModule: received IPS_ANCHOR_MANUAL_CONFIG");
const PositioningAnchorManualConfigHdr *hdr = m.get<const PositioningAnchorManualConfigHdr *>(0);
if (hdr->numAnchors < 8)
{
Log::error("PozyxModule: not enough anchors-manual-config received from client: {}", hdr->numAnchors);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
else
{
for (size_t i = 1; i < m.parts(); i++)
{
const PositioningAnchorManualConfig *a = m.get<const PositioningAnchorManualConfig *>(i);
Log::info("PozyxModule: received anchor-manual-config: id {} order {} x {} y {} z {}",
a->id, a->order, a->x, a->y, a->z);
messageProcessor.setAnchorConfig(a->id, a->order, a->x, a->y, a->z, settings, resp_discover.anchors);
}
if (!messageProcessor.checkSettings(settings))
{
Log::error("PozyxModule: failed when checking settings after setAnchorConfig");
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
// backup
messageProcessor.saveSettings(pozyx_settingsfile_path + "." + airt::getTimeStamp() + ".bak", settings);
// override file
messageProcessor.saveSettings(pozyx_settingsfile_path, settings);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_ANCHORS_MANUAL_CONFIG_ACCEPTED);
Log::info("PozyxModule: sent IPS_ANCHORS_MANUAL_CONFIG_ACCEPTED");
}
}
break;
case StdMessage::IPS_ANCHOR_TOBE_AUTOCALIBRATED:
{
Log::info("PozyxModule: received IPS_ANCHOR_TOBE_AUTOCALIBRATED");
const PositioningAnchorTobeAutocalibratedHdr *hdr = m.get<const PositioningAnchorTobeAutocalibratedHdr *>(0);
if (hdr->numAnchors < 8)
{
Log::error("PozyxModule: not enough anchors-tobe-autocalibrated received from client: {}", hdr->numAnchors);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
else
{
std::vector<PozyxPayloads::AutocalibAnchorConfig> anchors_tobe_autocalibrated;
for (size_t i = 1; i < m.parts(); i++)
{
const PositioningAnchorTobeAutocalibrated *a = m.get<const PositioningAnchorTobeAutocalibrated *>(i);
Log::info("PozyxModule: received anchor-tobe-autocalibrated: id {} order {} x {} y {} z {}",
a->id, a->order, a->x, a->y, a->z);
PozyxPayloads::AutocalibAnchorConfig aac;
aac.id = std::to_string(a->id);
aac.order = a->order;
aac.coordinates.x = a->x;
aac.coordinates.y = a->y;
aac.coordinates.z = a->z;
anchors_tobe_autocalibrated.push_back(aac);
}
messageProcessor.buildAutocalib(anchors_tobe_autocalibrated, autocalib);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_ANCHORS_TOBE_AUTOCALIBRATED_ACCEPTED);
Log::info("PozyxModule: sent IPS_ANCHORS_TOBE_AUTOCALIBRATED_ACCEPTED");
}
}
break;
case StdMessage::IPS_AUTOCALIBRATE:
Log::info("PozyxModule: received command: IPS_AUTOCALIBRATE");
if (autocalib.anchors.size() == 0)
{
Log::error("PozyxModule: autocalibration payload does not have any anchor");
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
if (!messageProcessor.requestAutocalibrate(autocalib, resp_autocalibrate))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
else
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_AUTOCALIBRATED);
Log::info("PozyxModule: got autocalibrate response: succes {} score {} connectivity {}",
resp_autocalibrate.success, resp_autocalibrate.score, resp_autocalibrate.connectivity);
sendAnchorsLocations(resp_autocalibrate.anchors);
}
break;
case StdMessage::IPS_UPDATE_SETTINGS:
{
Log::info("PozyxModule: received command IPS_UPDATE_SETTINGS");
/*
if(currentFrame > 0)
{
Log::warn("PozyxModule: already receiving positioning frames, total {}, ignoring IPS_UPDATE_SETTINGS...", currentFrame);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_UPDATED_SETTINGS);
break;
}
*/
if (settings.anchors.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
}
if (!messageProcessor.requestUpdateSettings(settings, resp_updatesettings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_UPDATED_SETTINGS);
ips_settings_updated = true;
sendAnchorsLocations(settings);
// devices have changed to target channel, keep it for next session
messageProcessor.setAnchorsAndTagsToTargetUwb(settings.uwb, settings);
// backup
messageProcessor.saveSettings(pozyx_settingsfile_path + "." + airt::getTimeStamp() + ".bak", settings);
// override
messageProcessor.saveSettings(pozyx_settingsfile_path, settings);
ss.clear();
ss << "success: " << (resp_updatesettings.success ? "true " : "false ");
ss << ", tags [";
for (size_t i = 0; i < resp_updatesettings.tags_updated.size(); i++)
{
ss << " {" << resp_updatesettings.tags_updated[i].id << ", " << std::boolalpha << resp_updatesettings.tags_updated[i].success << "},";
}
ss << "]";
Log::info("PozyxModule: got updatesettings response: {}", ss.str());
break;
}
case StdMessage::IPS_START_POSITIONING:
{
Log::info("PozyxModule: received command IPS_START_POSITIONING");
if (!ips_settings_updated)
{
Log::error("PozyxModule: pozyx-settings have not been updated yet");
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
/*
if(currentFrame > 0)
{
Log::warn("PozyxModule: already receiving positioning frames, total {}, ignoring IPS_START_POSITIONING...", currentFrame);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_POSITIONING_STARTED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
*/
PozyxResponses::ShortCommandResp cmdresp;
messageProcessor.requestStart(cmdresp);
if (!cmdresp.success)
{
// it is commonly 'Already positioning'
// Log::error("PozyxModule: pozyx-server failed start. Error: {}", cmdresp.error);
}
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_POSITIONING_STARTED);
Log::info("PozyxModule: sent IPS_POSITIONING_STARTED");
// open the tap and start enqueing in the o.s queue
if (!udp_socket->is_open())
{
udp_socket->open(udp::v4());
udp_socket->bind(udp::endpoint(udp::v4(), pozyx_udpport));
}
// reset
nBytesReceivedFromPositioning = 0;
currentFrame = 0;
lastPosFrameTS = std::chrono::steady_clock::now();
Log::info("PozyxModule: starting... Current frame: {}", currentFrame);
}
break;
case StdMessage::IPS_STOP_POSITIONING:
{
Log::info("PozyxModule: received command IPS_STOP_POSITIONING");
// only stop receiving (not actually sending a stop request to pozyx-server)
// close the tap to avoid the o.s. enqueues unrequired data
if (udp_socket->is_open())
{
udp_socket->close();
}
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_POSITIONING_STOPPED);
Log::info("PozyxModule: stopping... Current frame: {}", currentFrame);
}
break;
case StdMessage::IPS_DISCOVER_DRONETAGS:
Log::info("PozyxModule: received command IPS_DISCOVER_DRONETAGS");
if (!messageProcessor.requestDiscoverFull(resp_discover)) // returns only non-local (non-connected to up2) tags
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
else
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_DISCOVERED);
ss.clear();
ss << "Tags found: " << resp_discover.tags.size() << ", ids [";
for (size_t i = 0; i < resp_discover.tags.size(); i++)
{
ss << resp_discover.tags[i].id << ", ";
}
ss << "]";
Log::info("PozyxModule: got discover response: {}", ss.str());
sendTagsIDsList(resp_discover.tags);
if (resp_discover.tags.size() >= 4) // (sw, nw, ne, se)
{
if (settings.tags.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
break;
}
}
// send previous session drone-tags (the ids might not be the same as the discovered)
sendDroneTags(settings);
}
}
break;
case StdMessage::IPS_DRONETAGS_MANUAL_CONFIG:
{
const PositioningDroneTagsManual *dtm = m.get<const PositioningDroneTagsManual *>(0);
Log::info("PozyxModule: received IPS_DRONETAGS_MANUAL_CONFIG: droneWidthmm {} droneHeightmm {} sw {} nw {} ne {} se {}",
dtm->droneWidthmm, dtm->droneHeightmm, dtm->swID, dtm->nwID, dtm->neID, dtm->seID);
if (settings.tags.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
}
messageProcessor.setDroneTagsConfig(dtm->droneWidthmm, dtm->droneHeightmm, dtm->swID, dtm->nwID, dtm->neID, dtm->seID, settings, resp_discover.tags);
// backup
messageProcessor.saveSettings(pozyx_settingsfile_path + "." + airt::getTimeStamp() + ".bak", settings);
// override file
messageProcessor.saveSettings(pozyx_settingsfile_path, settings);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_DRONETAGS_MANUAL_CONFIG_ACCEPTED);
Log::info("PozyxModule: sent IPS_DRONETAGS_MANUAL_CONFIG_ACCEPTED");
}
break;
case StdMessage::IPS_CLEAR_POZYXSETTINGS:
{
Log::info("PozyxModule: received command IPS_CLEAR_POZYXSETTINGS");
// if no loaded, load from file
if (settings.tags.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
}
messageProcessor.clearSettings(settings);
messageProcessor.saveSettings(pozyx_settingsfile_path, settings);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_POZYXSETTINGS_CLEARED);
Log::info("PozyxModule: pozyx-settings have been cleared and save to file");
}
break;
case StdMessage::IPS_GET_DRONEFILTER:
{
Log::info("PozyxModule: received command IPS_GET_DRONEFILTER");
// if no loaded, load from file
if (settings.tags.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
}
Message msg;
PositioningGetDroneFilterNotification gdf;
gdf.updatePeriod = settings.drone.options_filter_updatePeriod;
gdf.movementFreedom = settings.drone.options_filter_movementFreedom;
msg.add_raw(&gdf, sizeof(gdf));
pubsocket->send(msg);
Log::info("PozyxModule: sent DroneFilter: updatePeriod {} movementFreedom {} from settings",
settings.drone.options_filter_updatePeriod, settings.drone.options_filter_movementFreedom);
}
break;
case StdMessage::IPS_SET_DRONEFILTER:
{
const PositioningSetDroneFilter *sdf = m.get<const PositioningSetDroneFilter *>(0);
Log::info("PozyxModule: received IPS_SET_DRONEFILTER: updatePeriod {} movementFreedom {}",
sdf->updatePeriod, sdf->movementFreedom);
// if no loaded, load from file
if (settings.tags.size() == 0)
{
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
}
// updatePeriod: High update rate means a lower value
// movementFreedom: default value approximates a medium strength filter
if (!messageProcessor.setDroneFilter(sdf->updatePeriod, sdf->movementFreedom, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
messageProcessor.saveSettings(pozyx_settingsfile_path, settings);
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_SET_DRONEFILTER_NOTIFICATION);
Log::info("PozyxModule: sent IPS_SET_DRONEFILTER_NOTIFICATION");
}
break;
case StdMessage::IPS_GET_ANCHORS_FROM_FILE:
{
Log::info("PozyxModule: received IPS_GET_ANCHORS_FROM_FILE");
if (!messageProcessor.loadSettings(pozyx_settingsfile_path, settings))
{
airt::sendNotification(*pubsocket, StdMessage::POSITIONING_NOTIFICATIONS_MODULE, StdMessage::IPS_LAST_REQUEST_HAS_FAILED);
Log::error("PozyxModule: sent IPS_LAST_REQUEST_HAS_FAILED");
break;
}
sendAnchorsLocations(settings);
Log::info("PozyxModule: sent anchors-locations from {}", pozyx_settingsfile_path);
}
break;
default:
Log::error("PozyxModule: Unknown command: {}", airt::to_string(m));
break;
}
return;
}
bool PozyxModule::sendAnchorsIDsList(const PozyxResponses::Discover &discover)
{
Message msg;
positioningAnchorsListHdr listHdr;
std::vector<positioningAnchorsListItem> items;
listHdr.numAnchors = discover.anchors.size();
msg.add_raw(&listHdr, sizeof(listHdr));
for (size_t i = 0; i < discover.anchors.size(); i++)
{
positioningAnchorsListItem item;
item.id = std::stoi(discover.anchors[i].id);
items.push_back(item);
}
msg.add_raw(&items[0], sizeof(positioningAnchorsListItem) * items.size());
pubsocket->send(msg);
Log::info("PozyxModule: sending anchors IDs list. Num anchors: {}", items.size());
return true;
}
bool PozyxModule::sendAnchorsLocations(const std::vector<PozyxResponses::AutocalibratedAnchor> &anchors)
{
Message msg;
positioningAnchorLocationHeader locHdr;
locHdr.numAnchors = anchors.size();
msg.add_raw(&locHdr, sizeof(locHdr));
for (size_t i = 0; i < anchors.size(); i++)
{
positioningAnchorLocation loc;
loc.id = std::atoi(anchors[i].id.c_str());
loc.order = anchors[i].order;
loc.x = anchors[i].coordinates.x;
loc.y = anchors[i].coordinates.y;
loc.z = anchors[i].coordinates.z;
msg.add_raw(&loc, sizeof(loc));
Log::info("PozyxModule: sending anchor location from autocalibrate: id {} order {} x {} y {} z {}",
loc.id, loc.order, loc.x, loc.y, loc.z);
}
pubsocket->send(msg);
return true;
}
bool PozyxModule::sendAnchorsLocations(const PozyxPayloads::Settings &settings)
{
Message msg;
positioningAnchorLocationHeader locHdr;
locHdr.numAnchors = settings.anchors.size();
msg.add_raw(&locHdr, sizeof(locHdr));
for (size_t i = 0; i < settings.anchors.size(); i++)
{
positioningAnchorLocation loc;
loc.id = std::stoi(settings.anchors[i].id);
/*
Note:
anchors in settings must be organized like this:
first the 4 anchors at the bottom (origin, x, corner, y), order[0,3]
second the 4 anchors at the top (origin-top, x-top, corner-top, y-top), order[4,7]
Then we can get the order directly from the anchors array of the settings file
*/
loc.order = i;
loc.x = settings.anchors[i].coordinates.x;
loc.y = settings.anchors[i].coordinates.y;
loc.z = settings.anchors[i].coordinates.z;
msg.add_raw(&loc, sizeof(loc));
Log::info("PozyxModule: sending anchor location from settings: id {} order {} x {} y {} z {}",
loc.id, loc.order, loc.x, loc.y, loc.z);
}
pubsocket->send(msg);
return true;
}
bool PozyxModule::sendTagsIDsList(const std::vector<PozyxPayloads::Tag> &tags)
{
Message msg;
PositioningDroneTagsListHdr listHdr;
std::vector<PositioningDroneTagsListItem> items;
for (size_t i = 0; i < tags.size(); i++)
{
if (!tags[i].isLocal)
{
PositioningDroneTagsListItem item;
item.id = std::stoi(tags[i].id);
items.push_back(item);
}
}
listHdr.numTags = items.size();
msg.add_raw(&listHdr, sizeof(listHdr));
msg.add_raw(&items[0], sizeof(PositioningDroneTagsListItem) * items.size());
pubsocket->send(msg);
Log::info("PozyxModule: sending drone-tags IDs list. Num drone-tags (excluding local-tag): {}", items.size());
return true;
}
bool PozyxModule::sendDroneTags(const PozyxPayloads::Settings &settings)
{
// checking
int ntags_ok = 0;
for (size_t i = 0; i < settings.tags.size(); i++)
{
if (settings.tags[i].id == settings.drone.tag_sw ||
settings.tags[i].id == settings.drone.tag_nw ||
settings.tags[i].id == settings.drone.tag_ne ||
settings.tags[i].id == settings.drone.tag_se)
{
ntags_ok++;
}
}
if (ntags_ok != 4)
{
Log::critical("PozyxModule: sendDroneTags: settings are malformed, drone-tags (sw,nw,ne,se) ids are not the same as ids in tags[] array");
return false;
}
// sending message
Message msg;
PositioningDroneTags dt;
dt.droneWidthmm = settings.drone.droneWidthmm;
dt.droneHeightmm = settings.drone.droneHeightmm;
dt.swID = std::stoi(settings.drone.tag_sw);
dt.nwID = std::stoi(settings.drone.tag_nw);
dt.neID = std::stoi(settings.drone.tag_ne);
dt.seID = std::stoi(settings.drone.tag_se);
msg.add_raw(&dt, sizeof(dt));
pubsocket->send(msg);
Log::info("PozyxModule: sending dronetags from settings: droneWidthmm {} droneHeightmm {} sw {} nw {} ne {} se {}",
dt.droneWidthmm, dt.droneHeightmm, dt.swID, dt.nwID, dt.neID, dt.seID);
return true;
}
| 36.674699 | 170 | 0.631636 | [
"vector"
] |
c39508982567ea82d7c0b9c79f4fbaa3ace1e63d | 12,233 | cpp | C++ | project/examples/src/interleaved.cpp | SMG-Digital/libRETS | cdf8d74c446c7f0ca4dc35ac64220b356f69d73f | [
"ICU"
] | 98 | 2015-01-21T02:13:25.000Z | 2021-11-20T01:41:13.000Z | project/examples/src/interleaved.cpp | SMG-Digital/libRETS | cdf8d74c446c7f0ca4dc35ac64220b356f69d73f | [
"ICU"
] | 68 | 2015-01-28T15:37:23.000Z | 2022-03-24T23:02:14.000Z | project/examples/src/interleaved.cpp | SMG-Digital/libRETS | cdf8d74c446c7f0ca4dc35ac64220b356f69d73f | [
"ICU"
] | 69 | 2015-02-27T14:49:47.000Z | 2022-02-10T17:51:13.000Z | /*
* Copyright (C) 2008 National Association of REALTORS(R)
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished
* to do so, provided that the above copyright notice(s) and this
* permission notice appear in all copies of the Software and that
* both the above copyright notice(s) and this permission notice
* appear in supporting documentation.
*/
#include "librets.h"
#include "Options.h"
#include <iostream>
#include <iomanip>
#include <boost/date_time.hpp>
#include "librets/str_stream.h"
using namespace librets;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::stringstream;
using std::setw;
using std::vector;
namespace po = boost::program_options;
int main(int argc, char * argv[])
{
try
{
string classTimeStamp;
SearchRequest::CountType count;
string countString;
int defaultLimit = SearchRequest::LIMIT_DEFAULT;
int defaultOffset = SearchRequest::OFFSET_NONE;
SearchRequest::FormatType format = SearchRequest::COMPACT_DECODED;
string keyField;
string lastModified;
vector<string> listingIds;
int limit;
RetsMetadata * metadata;
MetadataClass * metadataClass;
MetadataResource * metadataResource;
int offset;
bool printCount;
string query;
string resource;
string searchClass;
SearchRequestAPtr searchRequest;
string select;
bool standardNames = true;
int totalListings = 0;
string type;
Options options;
options.descriptions.add_options()
("resource,r", po::value<string>(&resource)
->default_value("Property"), "Search resource")
("class,C", po::value<string>(&searchClass)
->default_value("RES"), "Search class")
("timestamp,T", po::value<string>(&classTimeStamp)
->default_value(""), "Systemname of the Class TimeStamp field")
("lastmodified,L", po::value<string>(&lastModified)
->default_value(""), "RETS timestamp of the earliest date from which to select")
("select,s", po::value<string>(&select)
->default_value("ListingID,ListPrice,Beds,City"), "Search select")
("query,q", po::value<string>(&query)
->default_value("(ListPrice=300000-)"), "Search query")
("system-names,S", "Use system names, instead of standard names")
("type,t", po::value<string>(&type)
->default_value("Photo"), "Media Type")
("compact", "Use COMPACT instead of COMPACT-DECODED")
("limit,L", po::value<int>(&limit)
->default_value(defaultLimit), "Set the limit")
("offset,O", po::value<int>(&offset)
->default_value(defaultOffset), "Set the offset")
("count,n", po::value<string>(&countString)
->default_value("yes"),
"Set the count type: no, yes or count-only)")
;
if (!options.ParseCommandLine(argc, argv))
{
return 0;
}
if (options.count("system-names"))
{
standardNames = false;
}
if (options.count("compact"))
{
format = SearchRequest::COMPACT;
}
if (countString == "yes")
{
count = SearchRequest::RECORD_COUNT_AND_RESULTS;
printCount = true;
}
else if (countString == "no")
{
count = SearchRequest::NO_RECORD_COUNT;
printCount = false;
}
else if (countString == "count-only")
{
count = SearchRequest::RECORD_COUNT_ONLY;
printCount = true;
}
else
{
count = SearchRequest::RECORD_COUNT_AND_RESULTS;
printCount = true;
}
RetsSessionPtr session = options.RetsLogin();
if (!session)
{
cout << "Login failed\n";
return -1;
}
/*
* Find the keyfield for the resource.
*/
metadata = session->GetMetadata();
metadataResource = metadata->GetResource(resource);
if (metadataResource == NULL)
{
cout << "Invalid resource: " << resource << std::endl;
session->Logout();
return -1;
}
keyField = metadataResource->GetKeyField();
/*
* Find the timetsamp field if it is known (RETS 1.7 and later). If
* not known, the user must provide it.
*/
metadataClass = metadata->GetClass(resource, searchClass);
if (metadataClass == NULL)
{
cout << "Invalid resource:class: "
<< resource
<< ":"
<< searchClass
<< std::endl;
session->Logout();
return -1;
}
if (classTimeStamp.length() == 0)
classTimeStamp = metadataClass->GetStringAttribute("ClassTimeStamp");
if (classTimeStamp.length() == 0)
{
cout << "Class "
<< resource
<< ":"
<< searchClass
<< " has no ClassTimeStamp specified in the metadata. "
<< std::endl
<< "Please manually provide one using the --timestamp switch."
<< std::endl;
session->Logout();
return -1;
}
/*
* See if the last modified timestamp has been provided. If not, take the
* current time less 24 hours.
*/
if (lastModified.length() == 0)
{
stringstream ss;
boost::gregorian::date_facet *output_facet = new boost::gregorian::date_facet("%Y-%m-%d");
ss.imbue(std::locale(std::locale::classic(), output_facet));
boost::gregorian::date d(boost::gregorian::day_clock::local_day());
d -= boost::gregorian::days(1);
ss << d;
lastModified = ss.str();
}
/*
* OK - let's find all listings that have changed since the lastModified date
*/
/*
* Construct the query.
*/
searchRequest = session->CreateSearchRequest(
resource, searchClass,
str_stream() << "("
<< classTimeStamp
<< "="
<< lastModified
<< "+)");
searchRequest->SetSelect(keyField);
/*
* Must use system names for this search.
*/
searchRequest->SetStandardNames(false);
searchRequest->SetLimit(SearchRequest::LIMIT_DEFAULT);
searchRequest->SetOffset(SearchRequest::OFFSET_NONE);
searchRequest->SetCountType(SearchRequest::RECORD_COUNT_AND_RESULTS);
searchRequest->SetFormatType(SearchRequest::COMPACT);
SearchResultSetAPtr results = session->Search(searchRequest.get());
if (printCount)
{
cout << "Matching record count: " << results->GetCount() << endl;
}
/*
* For all listings found, fetch the full listing detail and then the
* associated Photos.
*/
while (results->HasNext())
{
totalListings++;
listingIds.push_back(results->GetString(keyField));
/*
* Create a new search to fetch all the detail for the listing.
*/
SearchRequestAPtr listingRequest = session->CreateSearchRequest(
resource,
searchClass,
str_stream() << "("
<< keyField
<< "="
<< results->GetString(keyField)
<< ")");
listingRequest->SetStandardNames(false);
listingRequest->SetLimit(SearchRequest::LIMIT_DEFAULT);
listingRequest->SetOffset(SearchRequest::OFFSET_NONE);
listingRequest->SetCountType(SearchRequest::NO_RECORD_COUNT);
listingRequest->SetFormatType(SearchRequest::COMPACT);
SearchResultSetAPtr listingResult = session->Search(listingRequest.get());
StringVector columns = listingResult->GetColumns();
while (listingResult->HasNext())
{
/*
* Show the listing detail.
*/
for (StringVector::iterator i = columns.begin(); i != columns.end(); i++)
{
string column = *i;
cout << setw(15) << column << ": "
<< setw(0) << listingResult->GetString(column) << endl;
}
}
/*
* Now set up to fetch the objects associated with this listing.
*/
GetObjectRequest getObjectRequest(resource, type);
getObjectRequest.AddAllObjects(results->GetString(keyField));
GetObjectResponseAPtr getObjectResponse = session->GetObject(&getObjectRequest);
ObjectDescriptor * objectDescriptor;
while ((objectDescriptor = getObjectResponse->NextObject()))
{
/*
* Report the object details.
*/
string objectKey = objectDescriptor->GetObjectKey();
int objectId = objectDescriptor->GetObjectId();
string contentType = objectDescriptor->GetContentType();
string description = objectDescriptor->GetDescription();
int replyCode = objectDescriptor->GetRetsReplyCode();
string replyText = objectDescriptor->GetRetsReplyText();
cout << "Object "
<< objectKey
<< ":"
<< objectId;
if (!description.empty())
cout << ", description: "
<< description;
cout << endl;
if (replyCode != 0)
cout << "***: "
<< replyCode
<< ": "
<< replyText
<< endl;
}
cout << endl;
}
cout << "Total Listings Retrieved: " << totalListings << endl;
cout << "Listing IDs:" << endl;
for (vector<string>::iterator i = listingIds.begin(); i != listingIds.end(); i++)
cout << *i << endl;
session->Logout();
}
catch (RetsException & e)
{
e.PrintFullReport(cerr);
}
catch (std::exception & e)
{
cerr << e.what() << endl;
}
}
| 38.589905 | 107 | 0.482792 | [
"object",
"vector"
] |
c3961afa1ae60d48e9595cbeda4a3edab1b1d707 | 829 | hpp | C++ | Paramedic.hpp | aimanyounises1/wargame-bb | 48ec4de52f83558d94d8a5193f39f4ec1877ccbd | [
"MIT"
] | null | null | null | Paramedic.hpp | aimanyounises1/wargame-bb | 48ec4de52f83558d94d8a5193f39f4ec1877ccbd | [
"MIT"
] | null | null | null | Paramedic.hpp | aimanyounises1/wargame-bb | 48ec4de52f83558d94d8a5193f39f4ec1877ccbd | [
"MIT"
] | null | null | null |
#pragma once
#include "Soldier.hpp"
#include <iostream>
class Paramedic: public Soldier {
public:
Paramedic(int t) : Soldier(100,50,t,3,false){}
~Paramedic(){}
virtual void attack(std::vector<std::vector<Soldier*>> &board, std::pair<int,int> source) override {
int check = board[source.first][source.second]->team;
for(int i = source.first-1;i<=source.first+1;i++){
for(int j = source.second-1;j<=source.second+1;j++){
if(i>=0 && i<board.size() && j>=0 && j<board[i].size()) {
if (board[i][j]!=nullptr && i != source.first && j != source.second && board[i][j]->team == check)
board[i][j]->HP = this->resetlife();
}
}
}
}
int resetlife() override{
this->HP = 100;
return this->HP;
}
}; | 31.884615 | 114 | 0.536791 | [
"vector"
] |
c39adfefa4a4694a1f6671cb3cc6e5a8f2884460 | 3,774 | cpp | C++ | src/r_cmb_table.cpp | USDAForestService/FIESTAutils | 5d3e74289c5645ec08f0d3e08cfff699ab0bc767 | [
"MIT"
] | 4 | 2022-01-13T21:35:26.000Z | 2022-02-02T23:50:04.000Z | src/r_cmb_table.cpp | USDAForestService/FIESTAutils | 5d3e74289c5645ec08f0d3e08cfff699ab0bc767 | [
"MIT"
] | 1 | 2022-01-24T21:59:49.000Z | 2022-03-01T20:32:03.000Z | src/r_cmb_table.cpp | USDAForestService/FIESTAutils | 5d3e74289c5645ec08f0d3e08cfff699ab0bc767 | [
"MIT"
] | null | null | null | // Hash table class for counting unique integer combinations
// Mainly for raster combine
// Chris Toney, christoney at fs.fed.us
#include <Rcpp.h>
// [[Rcpp::plugins(cpp11)]]
#include <string>
#include <unordered_map>
#include <vector>
struct cmbKey {
Rcpp::IntegerVector cmb;
bool operator==(const cmbKey &other) const {
for (int i = 0; i < cmb.size(); ++i) {
if (cmb[i] != other.cmb[i]) return false;
}
return true;
}
};
struct cmbData {
unsigned long ID;
unsigned long long count = 0;
};
struct cmbHasher {
// Boost hash_combine method
std::size_t operator()(cmbKey const& vec) const {
std::size_t seed = 0;
for (int i=0; i < vec.cmb.size(); ++i) {
seed ^= vec.cmb[i] + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
class CmbTable {
unsigned int nKeyLen;
Rcpp::CharacterVector cvVarNames;
unsigned long nLastCmbID;
std::unordered_map<cmbKey, cmbData, cmbHasher> cmb_map;
public:
CmbTable(unsigned int keyLen, Rcpp::CharacterVector varNames):
nKeyLen(keyLen), cvVarNames(varNames), nLastCmbID(0) {}
unsigned long update(Rcpp::IntegerVector ivKey, unsigned long nIncr) {
// Increment count for existing key
// or insert new key with count = nIncr
if (nIncr == 0) return 0;
cmbKey key;
key.cmb = ivKey;
cmbData& cmbdat = cmb_map[key];
if (cmbdat.count != 0) {
cmbdat.count += nIncr;
}
else {
cmbdat.count = nIncr;
cmbdat.ID = ++nLastCmbID;
}
return cmbdat.ID;
}
Rcpp::IntegerVector updateFromMatrix(const Rcpp::IntegerMatrix& imKeys, int nIncr) {
// int combinations (keys) are in columns of a matrix (nKeyLen = nrow)
// This is much faster than using apply update on the matrix from R
// Increment count for existing key,
// else insert new key with count = nIncr
// Return a vector of cmb IDs for the columns of the input matrix
R_xlen_t ncol = imKeys.ncol();
Rcpp::IntegerVector out(ncol);
for (R_xlen_t k=0; k!=ncol; ++k) {
out[k] = update(imKeys.column(k), nIncr);
}
return out;
}
Rcpp::DataFrame asDataFrame() {
// Return the table as a data frame.
// Set up the data in a named list, then create the dataframe from
// the list.
Rcpp::IntegerVector ivCmbID(cmb_map.size());
Rcpp::NumericVector dvCmbCount(cmb_map.size());
//Rcpp::IntegerVector aVec[nKeyLen]; //array of data vectors
std::vector<Rcpp::IntegerVector> aVec(nKeyLen);
cmbKey key;
cmbData cmbdat;
// set table data in vectors
for(int n=0; n < nKeyLen; ++n) {
aVec[n] = Rcpp::IntegerVector(cmb_map.size());
}
unsigned long this_idx = 0;
for(auto iter = cmb_map.begin(); iter != cmb_map.end(); ++iter) {
key = iter->first;
cmbdat = iter->second;
ivCmbID[this_idx] = cmbdat.ID;
// numeric vector to preserve count as long long int
dvCmbCount[this_idx] = cmbdat.count;
for(int var=0; var < nKeyLen; ++var) {
aVec[var][this_idx] = key.cmb[var];
}
++this_idx;
}
// make the data frame
Rcpp::List lOut = Rcpp::List::create(Rcpp::Named("cmbid") = ivCmbID,
Rcpp::Named("count") = dvCmbCount);
for(int n=0; n < nKeyLen; ++n) {
lOut.push_back(aVec[n], Rcpp::String(cvVarNames[n]));
}
Rcpp::DataFrame dfOut(lOut);
return dfOut;
}
};
RCPP_EXPOSED_CLASS(CmbTable)
RCPP_MODULE(mod_cmb_table) {
Rcpp::class_<CmbTable>("CmbTable")
.constructor<unsigned int, Rcpp::CharacterVector>("Sets length of the combination vector and variable names")
.method("update", &CmbTable::update, "Increment by nIncr if key exists, else insert with count = nIncr")
.method("updateFromMatrix", &CmbTable::updateFromMatrix, "Increment by nIncr if key exists, else insert with count = nIncr")
.method("asDataFrame", &CmbTable::asDataFrame, "Returns a dataframe containing the cmb table")
;
}
| 26.765957 | 125 | 0.671966 | [
"vector"
] |
c3a4df3d6c6cfc40b1773361c0f59ae7b15093b5 | 5,641 | cpp | C++ | llvm/lib/IR/GlobalPtrAuthInfo.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 605 | 2019-10-18T01:15:54.000Z | 2022-03-31T14:31:04.000Z | llvm/lib/IR/GlobalPtrAuthInfo.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,180 | 2019-10-18T01:21:21.000Z | 2022-03-31T23:25:41.000Z | llvm/lib/IR/GlobalPtrAuthInfo.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 275 | 2019-10-18T05:27:22.000Z | 2022-03-30T09:04:21.000Z | //===- GlobalPtrAuthInfo.cpp - Analysis tools for ptrauth globals ---------===//
//
// 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 "llvm/IR/GlobalPtrAuthInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
using namespace llvm;
Expected<GlobalPtrAuthInfo> GlobalPtrAuthInfo::tryAnalyze(const Value *V) {
auto Invalid = [](const Twine &Reason) {
return make_error<StringError>(Reason, inconvertibleErrorCode());
};
auto &Ctx = V->getContext();
V = V->stripPointerCasts();
auto *GV = dyn_cast<GlobalVariable>(V);
if (!GV)
return Invalid("value isn't a global");
if (GV->getSection() != "llvm.ptrauth")
return Invalid("global isn't in section \"llvm.ptrauth\"");
if (!GV->hasInitializer())
return Invalid("global doesn't have an initializer");
auto *Init = GV->getInitializer();
auto *Ty = dyn_cast<StructType>(GV->getInitializer()->getType());
if (!Ty)
return Invalid("global isn't a struct");
auto *I64Ty = Type::getInt64Ty(Ctx);
auto *I32Ty = Type::getInt32Ty(Ctx);
auto *P0I8Ty = Type::getInt8PtrTy(Ctx);
// Check that the struct matches its expected shape:
// { i8*, i32, i64, i64 }
if (!Ty->isLayoutIdentical(
StructType::get(Ctx, {P0I8Ty, I32Ty, I64Ty, I64Ty})))
return Invalid("global doesn't have type '{ i8*, i32, i64, i64 }'");
auto *Key = dyn_cast<ConstantInt>(Init->getOperand(1));
if (!Key)
return Invalid("key isn't a constant integer");
auto *AddrDiscriminator = Init->getOperand(2);
if (!isa<ConstantInt>(AddrDiscriminator) &&
!isa<ConstantExpr>(AddrDiscriminator))
return Invalid("address discriminator isn't a constant integer or expr");
auto *Discriminator = dyn_cast<ConstantInt>(Init->getOperand(3));
if (!Discriminator)
return Invalid("discriminator isn't a constant integer");
return GlobalPtrAuthInfo(GV);
}
Optional<GlobalPtrAuthInfo> GlobalPtrAuthInfo::analyze(const Value *V) {
if (auto PAIOrErr = tryAnalyze(V)) {
return *PAIOrErr;
} else {
consumeError(PAIOrErr.takeError());
return None;
}
}
static bool areEquivalentAddrDiscriminators(const Value *V1, const Value *V2,
const DataLayout &DL) {
APInt V1Off(DL.getPointerSizeInBits(), 0);
APInt V2Off(DL.getPointerSizeInBits(), 0);
if (auto *V1Cast = dyn_cast<PtrToIntOperator>(V1))
V1 = V1Cast->getPointerOperand();
if (auto *V2Cast = dyn_cast<PtrToIntOperator>(V2))
V2 = V2Cast->getPointerOperand();
auto *V1Base = V1->stripAndAccumulateInBoundsConstantOffsets(DL, V1Off);
auto *V2Base = V2->stripAndAccumulateInBoundsConstantOffsets(DL, V2Off);
return V1Base == V2Base && V1Off == V2Off;
}
bool GlobalPtrAuthInfo::isCompatibleWith(const Value *Key,
const Value *Discriminator,
const DataLayout &DL) const {
// If the keys are different, there's no chance for this to be compatible.
if (Key != getKey())
return false;
// If the discriminators are the same, this is compatible iff there is no
// address discriminator.
if (Discriminator == getDiscriminator())
return getAddrDiscriminator()->isNullValue();
// If we dynamically blend the discriminator with the address discriminator,
// this is compatible.
if (auto *DiscBlend = dyn_cast<IntrinsicInst>(Discriminator)) {
if (DiscBlend->getIntrinsicID() == Intrinsic::ptrauth_blend &&
DiscBlend->getOperand(1) == getDiscriminator() &&
areEquivalentAddrDiscriminators(DiscBlend->getOperand(0),
getAddrDiscriminator(), DL))
return true;
}
// If we don't have a non-address discriminator, we don't need a blend in
// the first place: accept the address discriminator as the discriminator.
if (getDiscriminator()->isNullValue() &&
areEquivalentAddrDiscriminators(getAddrDiscriminator(), Discriminator,
DL))
return true;
// Otherwise, we don't know.
return false;
}
Constant *GlobalPtrAuthInfo::createWithSameSchema(Module &M,
Constant *Pointer) const {
return create(M, Pointer, const_cast<ConstantInt*>(getKey()),
const_cast<Constant*>(getAddrDiscriminator()),
const_cast<ConstantInt*>(getDiscriminator()));
}
Constant *GlobalPtrAuthInfo::create(Module &M, Constant *Pointer,
ConstantInt *Key,
Constant *AddrDiscriminator,
ConstantInt *Discriminator) {
auto CastPointer =
ConstantExpr::getBitCast(Pointer, Type::getInt8PtrTy(M.getContext()));
auto Init = ConstantStruct::getAnon({CastPointer, Key, AddrDiscriminator,
Discriminator}, /*packed*/ false);
// TODO: look for an existing global with the right setup?
auto GV = new GlobalVariable(M, Init->getType(), /*constant*/ true,
GlobalVariable::PrivateLinkage, Init);
GV->setSection("llvm.ptrauth");
auto Result = ConstantExpr::getBitCast(GV, Pointer->getType());
assert(analyze(Result).hasValue() && "invalid ptrauth constant");
return Result;
}
| 36.869281 | 80 | 0.643857 | [
"shape"
] |
c3a7167324b8b35f46b6bfceeb3c7f0301e3d75c | 6,287 | cpp | C++ | src/donation_analysis_cpp/src/Record.cpp | cyang019/retrieve_data | 740f3ed828bbb21ecbaeff287a4e010138d22cef | [
"MIT"
] | null | null | null | src/donation_analysis_cpp/src/Record.cpp | cyang019/retrieve_data | 740f3ed828bbb21ecbaeff287a4e010138d22cef | [
"MIT"
] | null | null | null | src/donation_analysis_cpp/src/Record.cpp | cyang019/retrieve_data | 740f3ed828bbb21ecbaeff287a4e010138d22cef | [
"MIT"
] | null | null | null | #include "Record.h"
#include "TrackerDate.h" // inherit from TrackerInterface
#include "TrackerZip.h" // inherit from TrackerInterface
#include <cstdint> // int64_t
#include <cstring> // strtok
#include <iostream> // endl
#include <map>
#include <memory> // unique_ptr
#include <sstream> // stringstream
#include <string>
#include <tuple> // std::tie
#include <unordered_map>
#include <utility> // make_pair
using ::std::int64_t;
using ::std::map;
using ::std::make_pair;
using ::std::make_unique;
using ::std::string;
using ::std::strtok;
using ::std::to_string;
using ::std::tuple;
using ::std::unordered_map;
namespace donation_analysis {
/// constructors
Record::Record() : m_id_zip_records(), m_id_date_records()
{}
Record::Record(Record &&rhs) noexcept
: m_id_zip_records(std::move(rhs.m_id_zip_records)),
m_id_date_records(std::move(rhs.m_id_date_records))
{}
Record& Record::operator=(Record &&rhs) noexcept
{
m_id_zip_records = std::move(rhs.m_id_zip_records);
m_id_date_records = std::move(rhs.m_id_date_records);
return *this;
}
Record::~Record() {}
/** store a single entry if valid, output a string for medianvals_by_zip.
* \param t_s is the input line
* \return a pipe separated record to output to medianvals_by_zip
*/
std::string Record::parse_single_entry(const string &t_s)
{
string cmte_id, zipcode, date, other_id;
int64_t amt;
std::tie(cmte_id, zipcode, date, amt, other_id) =
m_extract_info_from_line(t_s);
string output_line = "";
/// if not from individual, skip entry
if(!other_id.empty()) return output_line;
/// if no cmte_id, skip entry
if(cmte_id.empty()) return output_line;
/// if no amount value, skip entry
if(amt < 0) return output_line;
/// if date is valid, store value to calculate median
if(checkDate(date)){
if(m_id_date_records.find(cmte_id) == m_id_date_records.end()){
m_id_date_records.emplace(
make_pair(cmte_id, make_unique<TrackerDate>())
);
}
m_id_date_records[cmte_id]->add(date, amt);
}
/// if zip is valid, store value and return running median
if(checkZipcode(zipcode)){
//if(m_id_zip_records.find(cmte_id) == m_id_zip_records.end()){
/// add 1st zipcode recipient
m_id_zip_records.emplace(
make_pair(cmte_id, make_unique<TrackerZip>())
);
//}
/// add zipcode element
m_id_zip_records[cmte_id]->add(zipcode, amt);
int64_t median, total_amt;
size_t cnt;
/// get median, count, and total transaction amount
std::tie(zipcode, median, cnt, total_amt) =
m_id_zip_records[cmte_id]->getData();
output_line += cmte_id + "|" + zipcode + "|"
+ to_string(median) + "|" + to_string(cnt) + "|"
+ to_string(total_amt);
}
return output_line;
}
/** calculate and export medianvals_by_date to an ostream object.
* \param t_os is the output stream binded with a opened file for write.
*/
void Record::calc_and_export_medianvals_by_date(std::ostream &t_os)
{
string date;
int64_t median, total_amt;
size_t cnt;
for(auto &kv : m_id_date_records){
const string cmte_id = kv.first;
(kv.second)->resetGetter();
std::tie(date, median, cnt, total_amt) = (kv.second)->getData();
/// past last element when getting all empty entries.
while(true){
if((date == "") && (median == 0) && (cnt == 0) && (total_amt == 0)) break;
const string out_str =
cmte_id + "|" + date + "|"
+ to_string(median) + "|" + to_string(cnt) + "|"
+ to_string(total_amt);
///< out_str format: cmte_id|date|median|cnt|total_amt
t_os << out_str << std::endl;
std::tie(date, median, cnt, total_amt) = (kv.second)->getData();
}
}
}
/** Get cmte_id, zipcode, date, amount from a pipe deliminated line
* \param t_s is the input line.
* \return a tuple of above mentioned data.
*/
tuple<string, string, string, int64_t, string>
Record::m_extract_info_from_line(const string &t_s)
{
std::string delim = "|"; ///< fields are pipe deliminated.
string cmte_id, zipcode, date, other_id, strAmt;
std::stringstream sAmt;
int64_t amt = 0;
std::string token;
size_t token_cnt = 0; ///< index of token
size_t pos = 0; ///< token position in the string
size_t found = 0; ///< pipe position
while((found = t_s.find(delim,pos)) != string::npos){
++token_cnt;
token = t_s.substr(pos,found - pos);
pos = found+1; ///< look ahead the found pipe character
switch(token_cnt){
case 1: cmte_id = token; ///< CMTE_ID
break;
case 11: zipcode = token; break; ///< ZIPCODE
case 14: date = token; break; ///< TRANSACTION_DT
case 15: strAmt = token; ///< TRANSACTION_AMT
if(!checkAmt(token)) amt = -1;
else { /// convert char* to int
sAmt << token;
sAmt >> amt;
}
break;
case 16: other_id = token; break; ///< OTHER_ID
default: break;
}
}
/// When there are exactly 16 fields, cannot find last pipe.
if(other_id.empty() && token_cnt == 15){
if(pos == t_s.size()) other_id = "";
else
other_id = t_s.substr(pos);
}
if(zipcode.length() > 5) zipcode = zipcode.substr(0,5);
return make_tuple(cmte_id, zipcode, date, amt, other_id);
}
} // namespace donation_analysis
| 36.132184 | 90 | 0.549229 | [
"object"
] |
ce79b6f1eadbb6eaca2f40448d38c091c0a8529d | 3,115 | cpp | C++ | src/anchor.cpp | jherrero/enredo | c017761241c0f51afb8a0e1820ba54016816cb14 | [
"BSD-3-Clause"
] | 9 | 2016-04-08T14:18:20.000Z | 2021-06-18T06:19:48.000Z | src/anchor.cpp | jherrero/enredo | c017761241c0f51afb8a0e1820ba54016816cb14 | [
"BSD-3-Clause"
] | null | null | null | src/anchor.cpp | jherrero/enredo | c017761241c0f51afb8a0e1820ba54016816cb14 | [
"BSD-3-Clause"
] | null | null | null | #include "anchor.h"
Anchor::Anchor(string this_id)
{
id = this_id;
num = 1;
}
Anchor::~Anchor()
{
}
/*!
\fn Anchor::get_direct_Link(Anchor *other_anchor)
This function looks for the Link in the set of existing ones.
If it does not exist yet, it will create it.
@param Anchor the other Anchor object
@return a pointer to the Link object between this and the other Anchor
*/
Link* Anchor::get_direct_Link(Anchor *other_anchor)
{
for (std::list<Link*>::iterator it = links.begin(); it != links.end(); it++) {
if ((*it)->anchor_list.size() != 2) {
continue;
}
std::list<Anchor*>::iterator anchor_it = (*it)->anchor_list.begin();
Anchor *anchor1 = (*anchor_it);
anchor_it++;
Anchor *anchor2 = (*anchor_it);
if (anchor1->id == this->id) {
if (anchor2 == other_anchor) {
return *it;
}
} else if (anchor1 == other_anchor) {
return *it;
}
}
// other_anchor was not found => create a new Link
Link* new_link = new Link(other_anchor, this);
if (new_link) {
this->add_Link(new_link);
if (other_anchor != this) {
other_anchor->add_Link(new_link);
}
return new_link;
}
cerr << "Cannot add a new Anchor" << endl;
return NULL;
}
/*!
\fn Graph::minimize_anchor(Anchor* this_anchor)
*/
uint Anchor::minimize(bool debug)
{
uint count = 0;
bool merge_event;
do {
merge_event = false;
for (std::list<Link*>::iterator p_link1 = this->links.begin(); p_link1 != this->links.end() and !merge_event; p_link1++) {
short strand1;
if ((*p_link1)->anchor_list.front() == (*p_link1)->anchor_list.back()) {
strand1 = 0;
} else if ((*p_link1)->anchor_list.back() == this) {
strand1 = 1;
} else if ((*p_link1)->anchor_list.front() == this) {
strand1 = -1;
}
for (std::list<Link*>::iterator p_link2 = this->links.begin(); p_link2 != p_link1 and !merge_event; p_link2++) {
if ((*p_link2)->tags.size() != (*p_link1)->tags.size()) {
continue;
}
short strand2;
if ((*p_link2)->anchor_list.front() == (*p_link2)->anchor_list.back()) {
strand2 = 0;
} else if ((*p_link2)->anchor_list.back() == this) {
strand2 = -1;
} else if ((*p_link2)->anchor_list.front() == this) {
strand2 = 1;
}
if ((*p_link1)->try_to_concatenate_with(*p_link2, strand1, strand2)) {
if (debug) {
cout << "Concatenated link: " << endl;
(*p_link1)->print();
}
merge_event = true;
count++;
}
}
}
} while (merge_event);
return count;
}
/*!
\fn Anchor::add_Link(Link *link)
Add a new Link at the end of the Anchor.links list
*/
void Anchor::add_Link(Link *link)
{
this->links.push_back(link);
}
/*!
\fn Anchor::print(ostream &out)
*/
void Anchor::print(ostream &out)
{
out << "Anchor " << this->id << endl;
for (std::list<Link*>::iterator p_link_it = this->links.begin(); p_link_it != this->links.end(); p_link_it++) {
(*p_link_it)->print(out);
}
}
| 25.958333 | 126 | 0.574639 | [
"object"
] |
ce7edc8a412c36b88b078d91207b749d1c6a46fb | 1,992 | cpp | C++ | code/MikoEngine/Renderer/Resource/CompositorNode/Pass/VrHiddenAreaMesh/CompositorInstancePassVrHiddenAreaMesh.cpp | warzes/MikoEngine | 1199f59a71ab3dfcbea5d02238639db55eded0d4 | [
"MIT"
] | 5 | 2020-08-04T17:57:01.000Z | 2021-02-07T12:19:02.000Z | code/MikoEngine/Renderer/Resource/CompositorNode/Pass/VrHiddenAreaMesh/CompositorInstancePassVrHiddenAreaMesh.cpp | warzes/MikoEngine | 1199f59a71ab3dfcbea5d02238639db55eded0d4 | [
"MIT"
] | null | null | null | code/MikoEngine/Renderer/Resource/CompositorNode/Pass/VrHiddenAreaMesh/CompositorInstancePassVrHiddenAreaMesh.cpp | warzes/MikoEngine | 1199f59a71ab3dfcbea5d02238639db55eded0d4 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Renderer/Resource/CompositorNode/Pass/VrHiddenAreaMesh/CompositorInstancePassVrHiddenAreaMesh.h"
#include "Renderer/Resource/CompositorNode/Pass/VrHiddenAreaMesh/CompositorResourcePassVrHiddenAreaMesh.h"
#include "Renderer/Resource/CompositorNode/CompositorNodeInstance.h"
#include "Renderer/Resource/CompositorWorkspace/CompositorContextData.h"
#include "Renderer/Resource/CompositorWorkspace/CompositorWorkspaceInstance.h"
#include "Renderer/Core/IProfiler.h"
#include "Renderer/IRenderer.h"
#include "Renderer/Context.h"
namespace Renderer
{
//[-------------------------------------------------------]
//[ Protected virtual Renderer::ICompositorInstancePass methods ]
//[-------------------------------------------------------]
void CompositorInstancePassVrHiddenAreaMesh::onFillCommandBuffer([[maybe_unused]] const Rhi::IRenderTarget* renderTarget, [[maybe_unused]] const CompositorContextData& compositorContextData, [[maybe_unused]] Rhi::CommandBuffer& commandBuffer)
{
// Sanity check
SE_ASSERT(nullptr != renderTarget, "The VR hidden area mesh compositor instance pass needs a valid render target");
SE_ASSERT(false, "OpenVR support is disabled");
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
CompositorInstancePassVrHiddenAreaMesh::CompositorInstancePassVrHiddenAreaMesh(const CompositorResourcePassVrHiddenAreaMesh& compositorResourcePassVrHiddenAreaMesh, const CompositorNodeInstance& compositorNodeInstance) :
ICompositorInstancePass(compositorResourcePassVrHiddenAreaMesh, compositorNodeInstance)
{
}
CompositorInstancePassVrHiddenAreaMesh::~CompositorInstancePassVrHiddenAreaMesh()
{
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
| 46.325581 | 243 | 0.64759 | [
"mesh",
"render"
] |
ce819ffa45982e4c53fabdfdabb54f755a10762b | 1,360 | cpp | C++ | LiBrother/LiBrotherServer/credentials_manager.cpp | sxtyzhangzk/LiBrother | 54e2982ffb246f90b1261df44f5d8de42de0999e | [
"MIT"
] | 6 | 2015-11-04T09:34:18.000Z | 2015-12-17T00:09:41.000Z | LiBrother/LiBrotherServer/credentials_manager.cpp | sxtyzhangzk/LiBrother | 54e2982ffb246f90b1261df44f5d8de42de0999e | [
"MIT"
] | 1 | 2015-11-19T08:44:39.000Z | 2015-11-27T20:59:25.000Z | LiBrother/LiBrotherServer/credentials_manager.cpp | sxtyzhangzk/LiBrother | 54e2982ffb246f90b1261df44f5d8de42de0999e | [
"MIT"
] | 2 | 2015-12-04T15:38:23.000Z | 2019-02-17T02:34:36.000Z | #include "credentials_manager.h"
#include <cstdio>
CCredentialsManager::CCredentialsManager(Botan::RandomNumberGenerator * rng) :
m_rng(rng)
{
}
void CCredentialsManager::loadCertificate(const std::string& strCert, const std::string& strKey, const std::string& strPassphrase)
{
TServerCert cert;
cert.pKey.reset(Botan::PKCS8::load_key(strKey, *m_rng, strPassphrase));
Botan::DataSource_Stream dsStream(strCert);
try
{
while (!dsStream.end_of_data())
cert.certChain.push_back(Botan::X509_Certificate(dsStream));
}
catch(std::exception& e)
{ }
m_vCerts.push_back(cert);
}
std::vector<Botan::X509_Certificate> CCredentialsManager::cert_chain(
const std::vector<std::string>& algos, const std::string& type, const std::string& hostname)
{
for (auto i = m_vCerts.begin(); i != m_vCerts.end(); ++i)
{
if (std::find(algos.begin(), algos.end(), i->pKey->algo_name()) == algos.end())
continue;
if(hostname != "" && !i->certChain[0].matches_dns_name(hostname))
continue;
return i->certChain;
}
return std::vector<Botan::X509_Certificate>();
}
Botan::Private_Key* CCredentialsManager::private_key_for(
const Botan::X509_Certificate& cert, const std::string& type, const std::string& context)
{
for (auto i = m_vCerts.begin(); i != m_vCerts.end(); ++i)
{
if (i->certChain[0] == cert)
return i->pKey.get();
}
return nullptr;
} | 28.333333 | 130 | 0.709559 | [
"vector"
] |
ce8a4f9f2ab0df495b93f74af03efc31a1e3d16b | 5,246 | cpp | C++ | UnitTests/Chapter1.cpp | JudsonSS/RayTracer | 33d5aea33c4a101970a463be212d50626494214f | [
"MIT"
] | 3 | 2022-01-11T09:02:23.000Z | 2022-02-27T16:32:56.000Z | UnitTests/Chapter1.cpp | JudsonSS/RayTracer | 33d5aea33c4a101970a463be212d50626494214f | [
"MIT"
] | null | null | null | UnitTests/Chapter1.cpp | JudsonSS/RayTracer | 33d5aea33c4a101970a463be212d50626494214f | [
"MIT"
] | 1 | 2022-01-11T09:02:28.000Z | 2022-01-11T09:02:28.000Z | /**********************************************************************************
// Chapter1 (Arquivo de Código Fonte)
//
// Criação: 27 Jun 2020
// Atualização: 17 Jul 2021
// Compilador: Clang++ 12.0.5 / GNU g++ 9.3.0
//
// Descrição: Define os testes de unidade criados no Capítulo 1, Tuplas,
// Pontos e Vetores, do livro "The Ray Tracer Challenge".
// Os testes utilizam o framework GoogleTest.
//
**********************************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include "Types.h"
#include "Tuple.h"
#include "Point.h"
#include "Vector.h"
using namespace RayTracer;
namespace Chapter1
{
TEST(Tuples, TupleEmpty)
{
Tuple t;
EXPECT_EQ(t.x, 0.0);
EXPECT_EQ(t.y, 0.0);
EXPECT_EQ(t.z, 0.0);
EXPECT_EQ(t.w, 0.0);
}
TEST(Tuples, TupleOne)
{
Tuple t{4.3, -4.2, 3.1, 1.0};
EXPECT_EQ(t.x, 4.3);
EXPECT_EQ(t.y, -4.2);
EXPECT_EQ(t.z, 3.1);
EXPECT_EQ(t.w, 1.0);
}
TEST(Tuples, TupleZero)
{
Tuple t{4.3, -4.2, 3.1, 0.0};
EXPECT_EQ(t.x, 4.3);
EXPECT_EQ(t.y, -4.2);
EXPECT_EQ(t.z, 3.1);
EXPECT_EQ(t.w, 0.0);
}
TEST(Tuples, PointOne)
{
Tuple t{4.3, -4.2, 3.1, 1.0};
Point p{4.3, -4.2, 3.1};
EXPECT_EQ(t.x, p.x);
EXPECT_EQ(t.y, p.y);
EXPECT_EQ(t.z, p.z);
EXPECT_EQ(t.w, p.w);
}
TEST(Tuples, VectorZero)
{
Tuple t{4.3, -4.2, 3.1, 0.0};
Vector v{4.3, -4.2, 3.1};
EXPECT_EQ(t.x, v.x);
EXPECT_EQ(t.y, v.y);
EXPECT_EQ(t.z, v.z);
EXPECT_EQ(t.w, v.w);
}
TEST(Tuples, TupleEquality)
{
Tuple ta{4.3, -4.2, 3.1, 1.0};
Tuple tb{4.3, -4.2, 3.1, 0.0};
Tuple tc{4.3, -4.2, 3.1, 1.0};
Tuple td{2.0, 1.0, -4.5, 1.0};
EXPECT_FALSE(ta == tb);
EXPECT_FALSE(ta == td);
EXPECT_FALSE(tb == td);
EXPECT_TRUE(ta == tc);
}
TEST(Tuples, TupleIsPoint)
{
Tuple t{4.3, -4.2, 3.1, 1.0};
Point p{4.3, -4.2, 3.1};
Vector v{4.3, -4.2, 3.1};
EXPECT_TRUE(t == p);
EXPECT_FALSE(t == v);
}
TEST(Tuples, TupleIsVector)
{
Tuple t{4.3, -4.2, 3.1, 0.0};
Point p{4.3, -4.2, 3.1};
Vector v{4.3, -4.2, 3.1};
EXPECT_FALSE(t == p);
EXPECT_TRUE(t == v);
}
TEST(Tuples, TupleAdd)
{
Tuple t1{3.0, -2.0, 5.0, 1.0};
Tuple t2{-2.0, 3.0, 1.0, 0.0};
Tuple t{1.0, 1.0, 6.0, 1.0};
Tuple add = t1 + t2;
EXPECT_TRUE(t == add);
}
TEST(Tuples, PointSubtract)
{
Point p1{3.0, 2.0, 1.0};
Point p2{5.0, 6.0, 7.0};
Vector v{-2.0, -4.0, -6.0};
EXPECT_TRUE(v == p1 - p2);
}
TEST(Tuples, PointVectorSubtract)
{
Point p{3.0, 2.0, 1.0};
Vector v{5.0, 6.0, 7.0};
Point q{-2.0, -4.0, -6.0};
EXPECT_TRUE(q == p - v);
}
TEST(Tuples, VectorVectorSubtract)
{
Vector v1{3.0, 2.0, 1.0};
Vector v2{5.0, 6.0, 7.0};
Vector r{-2.0, -4.0, -6.0};
EXPECT_TRUE(r == v1 - v2);
}
TEST(Tuples, TupleNegation)
{
Tuple t{1.0, -2.0, 3.0, -4.0};
Tuple n{-1.0, 2.0, -3.0, 4.0};
Vector v{5.0, 6.0, 7.0};
Vector i{-5.0, -6.0, -7.0};
EXPECT_TRUE(-t == n);
EXPECT_TRUE(-v == i);
}
TEST(Tuples, ScalarMultiplication)
{
Tuple t{1.0, -2.0, 3.0, -4.0};
Tuple m{3.5, -7.0, 10.5, -14.0};
EXPECT_TRUE(t * 3.5 == m);
EXPECT_TRUE(3.5 * t == m);
}
TEST(Tuples, ScalarDivision)
{
Tuple t{1.0, -2.0, 3.0, -4.0};
Tuple d{0.5, -1.0, 1.5, -2.0};
EXPECT_TRUE(t / 2.0 == d);
}
TEST(Vectors, Magnitude)
{
Vector v1{1.0, 0.0, 0.0};
Vector v2{0.0, 1.0, 0.0};
Vector v3{0.0, 0.0, 1.0};
Vector v4{1.0, 2.0, 3.0};
Vector v5{-1.0, -2.0, -3.0};
EXPECT_TRUE(Equal(v1.Magnitude(), 1.0));
EXPECT_TRUE(Equal(v2.Magnitude(), 1.0));
EXPECT_TRUE(Equal(v3.Magnitude(), 1.0));
EXPECT_TRUE(Equal(v4.Magnitude(), sqrt(14.0)));
EXPECT_TRUE(Equal(v5.Magnitude(), sqrt(14.0)));
}
TEST(Vectors, Normalization)
{
Vector v1{4.0, 0.0, 0.0};
Vector v2{1.0, 2.0, 3.0};
EXPECT_TRUE(v1.Normalized() == Vector(1.0, 0.0, 0.0));
EXPECT_TRUE(v2.Normalized() == Vector(1.0 / sqrt(14.0), 2.0 / sqrt(14.0), 3.0 / sqrt(14.0)));
EXPECT_TRUE(Equal(v1.Normalized().Magnitude(), 1.0));
EXPECT_TRUE(Equal(v2.Normalized().Magnitude(), 1.0));
}
TEST(Vectors, DotProduct)
{
Vector v1{1.0, 2.0, 3.0};
Vector v2{2.0, 3.0, 4.0};
EXPECT_TRUE(Equal(v1.Dot(v2), 20.0));
}
TEST(Vectors, CrossProduct)
{
Vector v1{1.0, 2.0, 3.0};
Vector v2{2.0, 3.0, 4.0};
EXPECT_TRUE(v1.Cross(v2) == Vector(-1.0, 2.0, -1.0));
EXPECT_TRUE(v2.Cross(v1) == Vector(1.0, -2.0, 1.0));
}
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 23.212389 | 101 | 0.463591 | [
"vector"
] |
ce8fb3ca19f538a2c3ebc08ecf81d94e8ffd6153 | 22,951 | cpp | C++ | maku/render/d3d9_hooker.cpp | shileiyu/maku | be07aa6f804c387aafbd79cdf952bd6a93c18771 | [
"MIT"
] | 10 | 2015-04-09T01:43:28.000Z | 2021-03-29T15:59:01.000Z | maku/render/d3d9_hooker.cpp | shileiyu/maku | be07aa6f804c387aafbd79cdf952bd6a93c18771 | [
"MIT"
] | null | null | null | maku/render/d3d9_hooker.cpp | shileiyu/maku | be07aa6f804c387aafbd79cdf952bd6a93c18771 | [
"MIT"
] | 1 | 2020-07-02T03:52:56.000Z | 2020-07-02T03:52:56.000Z | //without this macro that will lead to confilcit with winsock2 header
//detour rely on windows header
#include "d3d9_hooker.h"
#include "detours\detours.h"
#include "detours\detours_ext.h"
#include "render_context.h"
#include "utils.h"
#include "input_hooker.h"
#include "d3d9_canvas.h"
#include "d3d9_common.h"
namespace maku
{
namespace render
{
namespace d3d9hooker
{
typedef LazyMap<IDirect3DDevice9*, D3D9Canvas*> Device92Canvas;
Device92Canvas device9_canvas;
ncore::SpinLock locker;
//original function address
Direct3DCreate9_T TDirect3DCreate9 = 0;
Direct3DCreate9Ex_T TDirect3DCreate9Ex = 0;
CreateDevice_T TCreateDevice = 0;//IDirect3D9中的CreateDevice
CreateDevice_T TCreateDeviceFromEx = 0;//IDirect3D9Ex中的CreateDevice
CreateDeviceEx_T TCreateDeviceEx = NULL;
Present_T TPresent = 0;
PresentEx_T TPresentEx = NULL;
Release_T TRelease = NULL;
Reset_T TReset = NULL;
ResetEx_T TResetEx = NULL;
GetSwapChain_T TGetSwapChain = 0;
SwapChainPresent_T TSwapChainPresent = 0;
CreateAdditionalSwapChain_T TCreateAdditionalSwapChain = 0;
//detour function declare
IDirect3D9 * WINAPI FDirect3DCreate9(UINT SDKVersion);
HRESULT WINAPI FDirect3DCreate9Ex(UINT SDKVersion, IDirect3D9Ex ** ptr);
ULONG WINAPI FRelease(IUnknown * self);
HRESULT WINAPI FReset(
IDirect3DDevice9 * self,
D3DPRESENT_PARAMETERS * pPresentationParameters);
HRESULT WINAPI FResetEx(
IDirect3DDevice9Ex * self,
D3DPRESENT_PARAMETERS *pPresentationParameters,
D3DDISPLAYMODEEX *pFullscreenDisplayMode
);
HRESULT WINAPI FCreateDevice(
IDirect3D9 * self,
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS * pParams,
IDirect3DDevice9 ** ppDeviceIntf);
HRESULT WINAPI FCreateDeviceEx(
IDirect3D9Ex * self,
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS* pPresentationParameters,
D3DDISPLAYMODEEX* pFullscreenDisplayMode,
IDirect3DDevice9Ex** ppReturnedDeviceInterface
);
HRESULT WINAPI FCreateDeviceFromEx(
IDirect3D9Ex * self,
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS* pPresentationParameters,
IDirect3DDevice9** ppReturnedDeviceInterface);
HRESULT WINAPI FGetSwapChain(
IDirect3DDevice9 * self,
UINT iSwapChain,
IDirect3DSwapChain9 ** pSwapChain);
HRESULT WINAPI FCreateAdditionalSwapChain(
IDirect3DDevice9 * self,
D3DPRESENT_PARAMETERS * pPresentationParameters,
IDirect3DSwapChain9 ** pSwapChain);
HRESULT WINAPI FPresent(
IDirect3DDevice9 * self,
CONST RECT * pSourceRect,
CONST RECT * pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion);
HRESULT WINAPI FPresentEx(
IDirect3DDevice9Ex * self,
const RECT *pSourceRect,
const RECT *pDestRect,
HWND hDestWindowOverride,
const RGNDATA *pDirtyRegion,
DWORD dwFlags
);
HRESULT WINAPI FSwapChainPresent(
IDirect3DSwapChain9 * self,
RECT * pSourceRect,
CONST RECT * pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion,
DWORD dwFlags);
void OnPresenting(
IDirect3DDevice9 * device,
CONST RECT * pSourceRect,
CONST RECT * pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion);
void OnSwapChainPresenting(
IDirect3DSwapChain9 * self,
CONST RECT * pSourceRect,
CONST RECT * pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion);
void InsertDevice(IDirect3DDevice9 * device);
void DeleteDevice(IDirect3DDevice9 * device);
D3D9Canvas * GetCanvasByDevice(IDirect3DDevice9 * device);
//////////////////////////////////////////////////////////////////////////
void DetourPresent(IDirect3DDevice9 * i7e) //挂钩Present函数
{
//Present
if(IsVFDetoured(i7e, kIdxPresent))
return;
if(GetVFAddress(i7e, kIdxPresent, TPresent))
DetourAttach(&(PVOID&)TPresent, FPresent);
}
void DetourPresentEx(IDirect3DDevice9Ex * i7e)
{
if(IsVFDetoured(i7e, kIdxPresentEx))
return;
if(GetVFAddress(i7e, kIdxPresentEx, TPresentEx))
DetourAttach(&(PVOID&)TPresentEx, FPresentEx);
}
void DetourResetEx(IDirect3DDevice9Ex * i7e)
{
if(IsVFDetoured(i7e, kIdxResetEx))
return;
if(GetVFAddress(i7e, kIdxResetEx, TResetEx))
DetourAttach(&(PVOID&)TResetEx, FResetEx);
}
void DetourRelease(IDirect3DDevice9 * i7e) //挂钩Release函数
{
//Release
if(IsVFDetoured(i7e, kIdxRelease))
return;
if(GetVFAddress(i7e, kIdxRelease, TRelease))
DetourAttach((void**)&TRelease, FRelease);
}
void DetourReset(IDirect3DDevice9 * i7e) //挂钩Reset函数
{
if(IsVFDetoured(i7e, kIdxReset))
return;
if(GetVFAddress(i7e, kIdxReset, TReset))
DetourAttach((void**)&TReset, FReset);
}
void DetourGetSwapChain(IDirect3DDevice9 * i7e)
{
//GetSwapChain
if(IsVFDetoured(i7e, kIdxGetSwapChain))
return;
if(GetVFAddress(i7e, kIdxGetSwapChain, TGetSwapChain))
DetourAttach((void**)&TGetSwapChain, FGetSwapChain);
}
void DetourCreateAdditionalSwapChain(IDirect3DDevice9 * i7e)
{
if(IsVFDetoured(i7e, kIdxCreateAdditionalSwapChain))
return;
if(GetVFAddress(i7e, kIdxCreateAdditionalSwapChain,
TCreateAdditionalSwapChain))
DetourAttach((void**)&TCreateAdditionalSwapChain,
FCreateAdditionalSwapChain);
}
void DetourSwapChainPresent(IDirect3DSwapChain9 * i7e)
{
if(IsVFDetoured(i7e, kIdxSwapChainPresent))
return;
if(GetVFAddress(i7e, kIdxSwapChainPresent, TSwapChainPresent))
DetourAttach((void**)&TSwapChainPresent, FSwapChainPresent);
}
/*********************************************
FDirect3DCreate9
Hook IDirect3D9::CreateDevice
**********************************************/
//Implement
IDirect3D9 * WINAPI FDirect3DCreate9(UINT SDKVersion)
{
auto i7e = TDirect3DCreate9(SDKVersion);
if(i7e)
{
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
if(!IsVFDetoured(i7e, kIdxCreateDevice))
{
//Detach hook before Attach it again.
if((CreateDevice_T)GetVFAddress(i7e, kIdxCreateDevice, TCreateDevice))
DetourAttach((void**)&TCreateDevice, FCreateDevice);
}
DetourTransactionCommit();
}
return i7e;
}
/*********************************************
FDirect3DCreate9Ex
Hook IDirect3D9Ex::CreateDeviceEx
**********************************************/
HRESULT WINAPI FDirect3DCreate9Ex(UINT SDKVersion, IDirect3D9Ex** ptr)
{
HRESULT hr = TDirect3DCreate9Ex(SDKVersion, ptr);
if (ptr)
{
auto i7e = *ptr;
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
if(!IsVFDetoured(i7e, kIdxCreateDeviceEx))
{
//Detach hook before Attach it again.
if(GetVFAddress(i7e, kIdxCreateDeviceEx, TCreateDeviceEx))
DetourAttach((void**)&TCreateDeviceEx, FCreateDeviceEx);
}
if(!IsVFDetoured(i7e, kIdxCreateDevice))
{
if(GetVFAddress(i7e, kIdxCreateDevice, TCreateDeviceFromEx))
DetourAttach((void**)&TCreateDeviceFromEx,
FCreateDeviceFromEx);
}
DetourTransactionCommit();
}
return hr;
}
/*********************************************
FCreateDevice
Hook IDirect3DDevice9::Release
IDirect3DDevice9::Reset
IDirect3DDevice9::Present
IDirect3DDevice9::GetSwapChain
IDirect3DDevice9::CreateAdditionalSwapChain
创建与Device对应的Canvas
**********************************************/
HRESULT WINAPI FCreateDevice(IDirect3D9 * self,
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS* pParams,
IDirect3DDevice9** ppDeviceIntf)
{
if(TCreateDevice)
{
IDirect3DDevice9 * i7e = 0;
auto hr = TCreateDevice(self, Adapter, DeviceType, hFocusWindow,
BehaviorFlags, pParams, ppDeviceIntf);
if(ppDeviceIntf)
i7e = *ppDeviceIntf;
if(hr == S_OK && i7e)
{
InsertDevice(i7e);
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
DetourRelease(i7e);
DetourReset(i7e);
DetourPresent(i7e);
DetourGetSwapChain(i7e);
DetourCreateAdditionalSwapChain(i7e);
DetourTransactionCommit();
}
return hr;
}
else
{
return S_FALSE;
}
}
/*********************************************
FCreateDeviceEx
Hook IDirect3DDevice9Ex::Release
IDirect3DDevice9Ex::Reset
IDirect3DDevice9Ex::Present
IDirect3DDevice9Ex::ResetEx
IDirect3DDevice9Ex::PresentEx
IDirect3DDevice9Ex::GetSwapChain
IDirect3DDevice9Ex::CreateAdditionalSwapChain
创建与Device对应的Canvas
**********************************************/
HRESULT WINAPI FCreateDeviceEx(
IDirect3D9Ex * self,
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS* pPresentationParameters,
D3DDISPLAYMODEEX* pFullscreenDisplayMode,
IDirect3DDevice9Ex** ppReturnedDeviceInterface
)
{
if (TCreateDeviceEx)
{
HRESULT hr = TCreateDeviceEx(self, Adapter, DeviceType, hFocusWindow,
BehaviorFlags, pPresentationParameters, pFullscreenDisplayMode,
ppReturnedDeviceInterface);
IDirect3DDevice9Ex * i7e = *ppReturnedDeviceInterface;
if (SUCCEEDED(hr) && i7e)
{
InsertDevice(i7e);
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
DetourRelease(i7e);
DetourReset(i7e);
DetourPresent(i7e);
DetourResetEx(i7e);
DetourPresentEx(i7e);
DetourGetSwapChain(i7e);
DetourCreateAdditionalSwapChain(i7e);
DetourTransactionCommit();
}
return hr;
}
else
{
return S_FALSE;
}
}
HRESULT WINAPI FCreateDeviceFromEx(
IDirect3D9Ex * self,
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS* pPresentationParameters,
IDirect3DDevice9** ppReturnedDeviceInterface)
{
if(TCreateDeviceFromEx)
{
IDirect3DDevice9 * i7e = 0;
auto hr = TCreateDeviceFromEx(self, Adapter, DeviceType, hFocusWindow,
BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface);
if(ppReturnedDeviceInterface)
i7e = *ppReturnedDeviceInterface;
if(hr == S_OK && i7e)
{
InsertDevice(i7e);
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
DetourRelease(i7e);
DetourReset(i7e);
DetourPresent(i7e);
DetourGetSwapChain(i7e);
DetourCreateAdditionalSwapChain(i7e);
DetourTransactionCommit();
}
return hr;
}
else
{
return S_FALSE;
}
}
void GetDestRect(HWND hwnd, CONST RECT * pDestRect,
bool windowed, RECT & des_rect)
{
if (NULL == pDestRect)
{
if(windowed)
GetClientRect(hwnd, &des_rect);
else
GetWindowRect(hwnd, &des_rect);
}
else
{
des_rect = *pDestRect;
}
}
void OnCanvasPresenting(IDirect3DDevice9 * device,
IDirect3DSurface9 * target,
RECT & source, RECT & dest,
bool windowed, HWND game_hwnd)
{
HWND cur_hwnd = InputHooker::GetCurrentHWND();
if (game_hwnd != cur_hwnd && !IsChild(cur_hwnd, game_hwnd))
return;
RenderContext::Get()->UpdateStatus(source.right - source.left,
source.bottom - source.top);
if(RenderContext::Get()->IsPresent())
{
D3D9Canvas * canvas = GetCanvasByDevice(device);
if(canvas)
{
InputHooker::SetWindowed(windowed);
InputHooker::SetTransRect(dest, source);
canvas->UpdateRenderTarget(target, source);
canvas->SaveStatus();
RenderContext::Get()->Draw(canvas);
canvas->RestoreStatus();
}
}
}
void OnPresenting(IDirect3DDevice9 * device, CONST RECT * pSourceRect,
CONST RECT * pDestRect, HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion)
{
D3DDEVICE_CREATION_PARAMETERS dcp;
HRESULT hr = device->GetCreationParameters(&dcp);
if(FAILED(hr))
return;
//set window handle
HWND game_hwnd = dcp.hFocusWindow;
if(hDestWindowOverride)
game_hwnd = hDestWindowOverride;
IDirect3DSurface9 * target = 0;
device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &target);
if(target == 0)
return;
target->Release();
LPDIRECT3DSWAPCHAIN9 swap_chain = 0;
hr = device->GetSwapChain(0, &swap_chain);
if(FAILED(hr))
return;
swap_chain->Release();
D3DPRESENT_PARAMETERS desc;
hr = swap_chain->GetPresentParameters(&desc);
if(FAILED(hr))
return;
//little_inferno dcp.hFocusWindow 和 hDestWindowOverride 都为0
if(game_hwnd == 0)
game_hwnd = desc.hDeviceWindow;
RECT source = {0, 0, desc.BackBufferWidth, desc.BackBufferHeight};
//若sourcerect有值,则求sourcerect和backbuffer的交集矩形
if (pSourceRect != NULL)
{
RECT tmp_source = source;
IntersectRect(&source, &tmp_source, pSourceRect);
}
bool windowed = desc.Windowed ? true : false;
RECT dest = {0};
GetDestRect(game_hwnd, pDestRect, windowed, dest);
OnCanvasPresenting(device, target, source, dest, windowed, game_hwnd);
}
void OnSwapChainPresenting(
IDirect3DSwapChain9 * self,
CONST RECT * pSourceRect,
CONST RECT * pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion)
{
D3DPRESENT_PARAMETERS param;
auto hr = self->GetPresentParameters(¶m);
if(FAILED(hr))
return;
HWND game_hwnd = param.hDeviceWindow;
if(hDestWindowOverride)
game_hwnd = hDestWindowOverride;
IDirect3DDevice9 * device = 0;
self->GetDevice(&device);
if(!device)
return;
device->Release();
IDirect3DSurface9 * target = 0;
self->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &target);
if(target == 0)
return;
target->Release();
RECT source = {0, 0, param.BackBufferWidth, param.BackBufferHeight};
if(pSourceRect)
{
RECT tmp_source = source;
IntersectRect(&source, &tmp_source, pSourceRect);
}
bool windowed = param.Windowed ? true : false;
RECT dest = {0};
GetDestRect(game_hwnd, pDestRect, windowed, dest);
OnCanvasPresenting(device, target, source, dest, windowed, game_hwnd);
}
/*********************************************
FReset
在device Reset前 释放纹理 保证device Reset成功
**********************************************/
HRESULT WINAPI FReset(IDirect3DDevice9 * self,
D3DPRESENT_PARAMETERS * pPresentationParameters)
{
HRESULT hr = S_FALSE;
D3D9Canvas* d3d9_canvas = GetCanvasByDevice(self);
if (d3d9_canvas)
DeleteDevice(self);
if(TReset)
{
hr = TReset(self, pPresentationParameters);
if (S_OK == hr)
InsertDevice(self);
}
return hr;
}
//ResetEx
HRESULT WINAPI FResetEx(
IDirect3DDevice9Ex * self,
D3DPRESENT_PARAMETERS *pPresentationParameters,
D3DDISPLAYMODEEX *pFullscreenDisplayMode
)
{
HRESULT hr =S_FALSE;
D3D9Canvas* d3d9_canvas = GetCanvasByDevice(self);
if (d3d9_canvas)
DeleteDevice(self);
if (TResetEx)
{
hr = TResetEx(self, pPresentationParameters,
pFullscreenDisplayMode);
if(S_OK == hr)
InsertDevice(self);
}
return hr;
}
/*********************************************
FRelease
Release的对象是Device时 Device与Canvas的引用计数
相等时 删除Canvas
**********************************************/
ULONG WINAPI FRelease(IUnknown * self)
{
ULONG ret = 0;
IDirect3DDevice9* device = NULL;
self->QueryInterface(__uuidof(IDirect3DDevice9), (void**)&device);
if (device)
{
ret = TRelease(device); // 还原计数
ret = TRelease(self);
D3D9Canvas* d3d9_canvas = GetCanvasByDevice(device);
if (d3d9_canvas)
{
uint32_t count = d3d9_canvas->GetCountRef();
if (count == ret)
{
DeleteDevice(device);
ret = 0;
}
}
}
else
ret = TRelease(self);
return ret;
}
/*********************************************
FGetSwapChain
Hook IDirect3DSwapChain9::Present
**********************************************/
HRESULT WINAPI FGetSwapChain(IDirect3DDevice9 * self,
UINT iSwapChain,
IDirect3DSwapChain9 ** pSwapChain)
{
IDirect3DSwapChain9 * i7e = 0;
if(TGetSwapChain)
{
HRESULT hr = S_FALSE;
hr = TGetSwapChain(self, iSwapChain, pSwapChain);
if(pSwapChain)
i7e = *pSwapChain;
if(hr == S_OK && i7e)
{
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
DetourSwapChainPresent(i7e);
DetourTransactionCommit();
}
return hr;
}
return S_FALSE;
}
void InsertDevice(IDirect3DDevice9 * device)
{
D3D9Canvas * d3d9_canvas = new D3D9Canvas(device);
locker.Acquire();
device9_canvas[device] = d3d9_canvas;
locker.Release();
}
void DeleteDevice(IDirect3DDevice9 * device)
{
D3D9Canvas * d3d9_canvas = NULL;
locker.Acquire();
if(device9_canvas.Has(device))
{
d3d9_canvas = device9_canvas[device];
device9_canvas.Remove(device);
}
locker.Release();
if(d3d9_canvas)
delete d3d9_canvas;
}
D3D9Canvas* GetCanvasByDevice(IDirect3DDevice9 * device)
{
D3D9Canvas * canvas = NULL;
locker.Acquire();
if(device9_canvas.Has(device))
canvas = device9_canvas[device];
locker.Release();
return canvas;
}
/*********************************************
FCreateAdditionalSwapChain
Hook IDirect3DSwapChain9::Present
**********************************************/
HRESULT WINAPI FCreateAdditionalSwapChain(IDirect3DDevice9 * self,
D3DPRESENT_PARAMETERS* pPresentationParameters,
IDirect3DSwapChain9 ** pSwapChain)
{
IDirect3DSwapChain9 * i7e = 0;
if(TCreateAdditionalSwapChain)
{
HRESULT hr = S_FALSE;
hr = TCreateAdditionalSwapChain(self, pPresentationParameters,
pSwapChain);
if(pSwapChain)
i7e = *pSwapChain;
if( hr == S_OK && i7e)
{
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
DetourSwapChainPresent(i7e);
DetourTransactionCommit();
}
return hr;
}
return S_FALSE;
}
/*********************************************
FPresent
调用自己的绘制例程
**********************************************/
HRESULT WINAPI FPresent(IDirect3DDevice9 * self,
CONST RECT * pSourceRect,
CONST RECT * pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA * pDirtyRegion)
{
if(TPresent)
{
HRESULT hr = S_FALSE;
OnPresenting(self, pSourceRect, pDestRect,
hDestWindowOverride, pDirtyRegion);
hr = TPresent(self, pSourceRect, pDestRect, hDestWindowOverride,
pDirtyRegion);
return hr;
}
return S_FALSE;
}
//PresentEx
/*********************************************
FPresentEx
调用自己的绘制例程
**********************************************/
HRESULT WINAPI FPresentEx(
IDirect3DDevice9Ex * self,
const RECT *pSourceRect,
const RECT *pDestRect,
HWND hDestWindowOverride,
const RGNDATA *pDirtyRegion,
DWORD dwFlags
)
{
HRESULT hr = S_FALSE;
OnPresenting(self, pSourceRect, pDestRect, hDestWindowOverride,
pDirtyRegion);
hr = TPresentEx(self, pSourceRect, pDestRect,
hDestWindowOverride, pDirtyRegion, dwFlags);
return hr;
}
/*********************************************
FSwapChainPresent
调用自己的绘制例程
**********************************************/
HRESULT WINAPI FSwapChainPresent(IDirect3DSwapChain9 * self,
RECT* pSourceRect,
CONST RECT* pDestRect,
HWND hDestWindowOverride,
CONST RGNDATA* pDirtyRegion,
DWORD dwFlags)
{
HRESULT hr = S_FALSE;
if(TSwapChainPresent)
{
OnSwapChainPresenting(self, pSourceRect, pDestRect,
hDestWindowOverride, pDirtyRegion);
hr = TSwapChainPresent(self, pSourceRect, pDestRect,
hDestWindowOverride, pDirtyRegion, dwFlags);
}
return hr;
}
}
/*/////////////////////////////////////////////////////////////////////////////
//D3D9Hooker
/////////////////////////////////////////////////////////////////////////////*/
ncore::SpinLock D3D9Hooker::locker_;
void D3D9Hooker::Hook()
{
using namespace d3d9hooker;
wchar_t d3d9_path[MAX_PATH] = {0};
if( 0 == ::GetSystemDirectory(d3d9_path, sizeof(d3d9_path)) )
return;
wcscat_s(d3d9_path, L"\\d3d9.dll");
void * module = ::GetModuleHandle(d3d9_path);
if(module == 0)
return;
//see also: kernel_hooker.cpp
if(!IsModuleDetoured(module))
{
if(!locker_.TryAcquire())
return;
if(!IsModuleDetoured(module)) //防止多线程重复载入
{
FARPROC proc = 0;
HMODULE mod = (HMODULE)module;
proc = GetProcAddress(mod, "Direct3DCreate9");
TDirect3DCreate9 = (Direct3DCreate9_T)proc;
proc = GetProcAddress(mod, "Direct3DCreate9Ex");
TDirect3DCreate9Ex = (Direct3DCreate9Ex_T)proc;
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
if(TDirect3DCreate9)
DetourAttach(&(PVOID&)TDirect3DCreate9, FDirect3DCreate9);
//early version d3d9.dll does not include this iterface.
if(TDirect3DCreate9Ex)
DetourAttach(&(PVOID&)TDirect3DCreate9Ex, FDirect3DCreate9Ex);
//if every thing is ok. mark this module detoured.
if(!DetourTransactionCommit())
MarkModuleDetoured(module);
}
locker_.Release();
}
}
}
} | 27.954933 | 82 | 0.610605 | [
"render"
] |
cea18cabf39ebe3658c650982bdaf76eff747e9c | 2,833 | hpp | C++ | my_vulkan/descriptor_set.hpp | pixelwise/my_vulkan | f1c139ed8f95380186905d77cb8e81008f48bc95 | [
"CC0-1.0"
] | null | null | null | my_vulkan/descriptor_set.hpp | pixelwise/my_vulkan | f1c139ed8f95380186905d77cb8e81008f48bc95 | [
"CC0-1.0"
] | 3 | 2019-02-25T10:13:57.000Z | 2020-11-11T14:46:14.000Z | my_vulkan/descriptor_set.hpp | pixelwise/my_vulkan | f1c139ed8f95380186905d77cb8e81008f48bc95 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include <vulkan/vulkan.h>
#include <vector>
namespace my_vulkan
{
struct descriptor_set_t
{
descriptor_set_t(
VkDevice device,
VkDescriptorPool pool,
VkDescriptorSetLayout layout
);
descriptor_set_t(const descriptor_set_t&) = delete;
descriptor_set_t(descriptor_set_t&& other) noexcept;
descriptor_set_t& operator=(const descriptor_set_t&) = delete;
descriptor_set_t& operator=(descriptor_set_t&& other) noexcept;
~descriptor_set_t();
struct image_info_t{
VkImageView view;
VkImageLayout layout;
};
/*
VK_DESCRIPTOR_TYPE_SAMPLER
*/
void update_sampler_write(
uint32_t binding,
std::vector<VkSampler> samplers,
uint32_t array_offset = 0
);
/*
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
*/
void update_combined_image_sampler_write(
uint32_t binding,
std::vector<VkDescriptorImageInfo> infos,
uint32_t array_offset = 0
);
/*
VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE
VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT
*/
void update_image_write(
uint32_t binding,
VkDescriptorType type,
std::vector<image_info_t> image_infos,
uint32_t array_offset = 0
);
/*
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC
*/
void update_buffer_write(
uint32_t binding,
VkDescriptorType type,
std::vector<VkDescriptorBufferInfo> buffer_infos,
uint32_t array_offset = 0
);
/*
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER
VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER
*/
void update_texel_write(
uint32_t binding,
VkDescriptorType type,
std::vector<VkBufferView> buffer_views,
uint32_t array_offset = 0
);
void update_uniform_block_write(
uint32_t binding,
uint32_t offset,
uint32_t size
);
void update_copy_to(
VkDescriptorSet target,
uint32_t source_binding,
uint32_t source_array_offset,
uint32_t target_binding,
uint32_t target_array_offset,
uint32_t count
);
VkDescriptorSet get();
private:
void cleanup();
VkDevice _device;
VkDescriptorPool _descriptor_pool;
VkDescriptorSet _descriptor_set;
};
}
| 30.462366 | 71 | 0.594776 | [
"vector"
] |
ceb016730e39241a90414b9cca0fb901760c0bcc | 658 | cpp | C++ | acmicpc/1202.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/1202.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/1202.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> que;
vector<pair<int, int>> val;
vector<int> bag;
int n, k, w, p, b, idx = 0;
long long ans = 0;
cin >> n >> k;
for (int i=0; i<n; ++i) {
cin >> w >> p;
val.push_back({w, p});
}
for (int i=0; i<k; ++i) {
cin >> b;
bag.push_back(b);
}
sort(bag.begin(), bag.end());
sort(val.begin(), val.end());
for (int i=0; i<k; ++i) {
while (bag[i] >= val[idx].first && idx < n)
que.push(val[idx++].second);
if (!que.empty()) {
ans += que.top();
que.pop();
}
}
cout << ans << '\n';
return 0;
}
| 15.302326 | 45 | 0.528875 | [
"vector"
] |
ceb35eb73a3df8d5312c4894de9f92f2000e2fad | 20,209 | cpp | C++ | src/Core/Resource/ResourceLibrary.cpp | heroesiiifan/FreeHeroes | d9b396b527918cdf863fd2310bcf261e213bf553 | [
"MIT"
] | 17 | 2020-08-13T03:23:27.000Z | 2022-02-04T00:17:53.000Z | src/Core/Resource/ResourceLibrary.cpp | heroesiiifan/FreeHeroes | d9b396b527918cdf863fd2310bcf261e213bf553 | [
"MIT"
] | 2 | 2021-09-05T21:00:31.000Z | 2021-09-12T07:46:53.000Z | src/Core/Resource/ResourceLibrary.cpp | heroesiiifan/FreeHeroes | d9b396b527918cdf863fd2310bcf261e213bf553 | [
"MIT"
] | 2 | 2021-09-08T10:37:34.000Z | 2021-09-09T00:35:44.000Z | /*
* Copyright (C) 2020 Smirnov Vladimir / mapron1@gmail.com
* SPDX-License-Identifier: MIT
* See LICENSE file for details.
*/
#include "ResourceLibrary.hpp"
#include "StringUtils.hpp"
#include "Profiler.hpp"
#include "Logger.hpp"
#include <fstream>
#include <iostream>
#include <set>
#include <list>
#include <cassert>
namespace FreeHeroes::Core {
namespace {
const std::string extension1 = ".txt";
const std::string extension2 = ".fhindex";
const std::string fullSuffix = extension2 + extension1;
const std::string typeDatabase = "database";
const std::string typeTranslation = "translation";
enum class ParseMode
{
Undefined,
Media,
Database,
Translation
};
std::vector<std::string> getStringsFromViews(const std::vector<std::string_view>& arr)
{
std::vector<std::string> result;
result.reserve(arr.size());
for (auto& s : arr)
result.push_back(std::string{ s });
return result;
}
const std::map<ResourceMedia::Type, std::string> mediaTypeMapping{
{ ResourceMedia::Type::Sprite, "sprites" },
{ ResourceMedia::Type::Sound, "sounds" },
{ ResourceMedia::Type::Music, "music" },
{ ResourceMedia::Type::Video, "video" },
{ ResourceMedia::Type::Other, "other" },
};
class Graph {
std::map<std::string, ResourceLibrary::DepList> nodes;
std::map<std::string, bool> visited;
std::map<std::string, bool> onStack;
std::vector<std::string> sortResult;
void dfs(const std::string& node, bool optional)
{
if (nodes.count(node) == 0) {
if (optional)
return;
throw std::runtime_error("Invalid dependency found:" + node);
}
visited[node] = true;
onStack[node] = true;
for (const ResourceLibrary::Dep& neighbour : nodes[node]) {
if (visited[neighbour.id] && onStack[neighbour.id])
throw std::runtime_error("Loop detected in resource dependencies");
if (!visited[neighbour.id])
dfs(neighbour.id, neighbour.require == ResourceLibrary::DepsRequire::Soft);
}
onStack[node] = false;
sortResult.push_back(node);
}
public:
Graph() = default;
void add(std::string id, ResourceLibrary::DepList deps)
{
nodes[std::move(id)] = std::move(deps);
}
void sort()
{
for (auto& nodeP : nodes) {
if (!visited[nodeP.first])
dfs(nodeP.first, false);
}
}
const std::vector<std::string>& getSortResult() const { return sortResult; }
};
class FastCsvTable {
const char* begin;
const char* end;
const char* curr;
public:
FastCsvTable(const char* begin, size_t length)
{
this->begin = begin;
this->curr = begin;
this->end = begin + length;
}
bool scanLine()
{
if (curr >= end)
return false;
const char* peek = curr;
size_t tabs = 0;
while (peek < end) {
if (*peek == '\t')
tabs++;
if (*peek == '\r' || *peek == '\n')
break;
peek++;
}
const char* i = curr;
const char* lineEnd = peek;
line = std::string_view(curr, peek - curr);
if (*peek == '\r')
++peek;
if (*peek == '\n')
++peek;
curr = peek;
row.resize(tabs + 1);
size_t index = 0;
const char* prevI = i;
while (i < lineEnd) {
if (*i == '\t') {
row[index] = i == prevI ? std::string_view() : std::string_view(prevI, i - prevI);
prevI = i + 1;
index++;
}
i++;
}
row[index] = i == prevI ? std::string_view() : std::string_view(prevI, i - prevI);
return true;
}
std::vector<std::string_view> row;
std::string_view line;
};
}
ResourceLibrary::ResourceLibrary(std::string id)
: m_id(id)
{
}
ResourceLibrary::ResourceLibraryPathList ResourceLibrary::searchIndexInFolderRecursive(const std_path& folder)
{
ResourceLibraryPathList result;
if (!std_fs::exists(folder))
return result;
std::list<std_path> children;
for (const auto& it : std_fs::directory_iterator(folder)) {
if (!it.is_regular_file()) {
if (it.is_directory())
children.push_back(it.path());
continue;
}
auto f = it.path().filename();
auto ext1 = f.extension();
if (ext1 != extension1)
continue;
auto f2 = f.stem();
if (f2.extension() != extension2)
continue;
std::string id = path2string(f2.stem());
auto root = it.path().parent_path();
ResourceLibrary tmp(id);
tmp.setIndexFolder(root);
if (tmp.loadIndex(true)) {
result.records.push_back(ResourceLibraryPathList::Record{ root, tmp.m_id, tmp.m_dependencies });
} else {
std::cerr << "Warning: failed to load index from:" << path2string(root) << "/" << id << "\n";
}
}
if (result.records.empty()) {
for (const std_path& path : children) {
auto subRecords = searchIndexInFolderRecursive(path);
for (const auto& rec : subRecords.records)
result.records.push_back(rec);
}
}
return result;
}
std::shared_ptr<ResourceLibrary> ResourceLibrary::makeMergedLibrary(const ResourceLibraryPathList& pathList)
{
ProfilerScope scope("makeMergedLibrary");
auto result = std::make_shared<ResourceLibrary>();
{
ProfilerScope scopeEx("start");
for (const auto& rec : pathList.records) {
ResourceLibrary tmp(rec.id);
tmp.setIndexFolder(rec.path);
Logger(Logger::Info) << "Loading resource index:" << path2string(rec.path / rec.id);
if (!tmp.loadIndex())
throw std::runtime_error("Failed to load index:" + path2string(rec.path / rec.id));
result->mergeWith(tmp);
}
}
{
ProfilerScope scopeEx("end");
Graph g;
{
ProfilerScope scopeEx("g.sort");
for (const auto& dbPair : result->m_databases) {
DepList depList;
if (!dbPair.second.baseId.empty())
depList.push_back(Dep{ std::string{ dbPair.second.baseId } });
g.add(std::string{ dbPair.first }, depList);
}
g.sort();
}
for (const auto& dbId : g.getSortResult()) {
ResourceDatabase& db = result->m_databases[dbId];
if (!db.baseId.empty()) {
ResourceDatabase& depDb = result->m_databases[db.baseId];
for (auto& f : depDb.filesFullPathsWithDeps) {
db.filesFullPathsWithDeps.push_back(f);
}
}
for (auto& f : db.filesFullPaths) {
db.filesFullPathsWithDeps.push_back(f);
}
}
}
return result;
}
void ResourceLibrary::setIndexFolder(const std_path& folder)
{
m_indexFolder = folder;
m_mainStorage.m_rootDir = path2string(m_indexFolder) + "/";
}
void ResourceLibrary::addDep(std::string dep, ResourceLibrary::DepsRequire require)
{
m_dependencies.push_back({ dep, require });
}
bool ResourceLibrary::loadIndex(bool onlyMeta)
{
ProfilerScope scope("loadIndex");
// using txt format is 10 times faster in debug mode as json/cbor/etc.
// For release mode it is unnoticeable, but I'd like to have fast startup times in debug - event +0.5s is frustrating.
// also, i think it's a bit more readable and editable that json.
if (m_id.empty())
return false;
std::ifstream ifs(m_indexFolder / (m_id + fullSuffix), std::ios_base::in | std::ios_base::binary);
if (!ifs)
return false;
ifs.seekg(0, std::ios::end);
m_mainStorage.m_buffer.resize(ifs.tellg());
ifs.seekg(0, std::ios::beg);
ifs.read(m_mainStorage.m_buffer.data(), m_mainStorage.m_buffer.size());
FastCsvTable csvTable(m_mainStorage.m_buffer.data(), m_mainStorage.m_buffer.size());
m_dependencies.clear();
{
while (csvTable.scanLine()) {
if (csvTable.line.empty() || csvTable.line == "$")
break;
//tokens = splitLine(line, '\t', true);
Dep dep;
dep.id = csvTable.row[0];
if (csvTable.row[1] == std::string_view("soft"))
dep.require = DepsRequire::Soft;
m_dependencies.push_back(dep);
}
}
if (onlyMeta)
return true; // @todo: we still reading whole file in the memory
IdMappingMedia* currentMapping = nullptr;
IdMappingTrans* currentLocMapping = nullptr;
ResourceMedia::Type currentType = ResourceMedia::Type::None;
ParseMode parseMode = ParseMode::Undefined;
while (csvTable.scanLine()) {
if (csvTable.line.empty())
break;
const bool isHeader = !csvTable.row[0].empty();
if (isHeader) {
const std::string_view& typeName = csvTable.row[0];
parseMode = ParseMode::Undefined;
if (typeName == typeDatabase) {
parseMode = ParseMode::Database;
} else if (typeName == typeTranslation) {
parseMode = ParseMode::Translation;
std::string_view localeId{ csvTable.row[1] };
std::string_view contextId{ csvTable.row[2] };
currentLocMapping = &m_translations[localeId][contextId];
}
auto it = std::find_if(mediaTypeMapping.cbegin(), mediaTypeMapping.cend(), [&typeName](const auto& pair) { return pair.second == typeName; });
if (it != mediaTypeMapping.cend()) {
currentType = it->first;
currentMapping = &m_media[it->first];
parseMode = ParseMode::Media;
}
continue;
}
if (parseMode == ParseMode::Undefined)
throw std::runtime_error("Encountered undefined section in the index file");
//tokens.erase(tokens.begin());
const std::string_view id{ csvTable.row[1] };
//tokens.erase(tokens.begin());
if (parseMode == ParseMode::Media) {
ResourceMedia& res = (*currentMapping)[id];
res.type = currentType;
res.id = id;
res.subdir = ensureTrailingSlashOrEmpty(csvTable.row[2]);
res.mainFilename = csvTable.row[3];
res.root = m_mainStorage.m_rootDir;
} else if (parseMode == ParseMode::Translation) {
auto& values = (*currentLocMapping)[id].values;
for (size_t i = 2; i < csvTable.row.size(); i++) {
values.push_back(csvTable.row[i]);
}
} else if (parseMode == ParseMode::Database) {
ResourceDatabase& res = m_databases[id];
res.id = id;
res.baseId = csvTable.row[2];
res.subdir = ensureTrailingSlashOrEmpty(csvTable.row[3]);
res.root = m_mainStorage.m_rootDir;
for (size_t i = 4; i < csvTable.row.size(); i++) {
res.files.push_back(csvTable.row[i]);
}
for (auto& f : res.files)
res.filesFullPaths.push_back(std::string{ res.root } + std::string{ res.subdir } + std::string{ f });
}
}
return true;
}
bool ResourceLibrary::saveIndex()
{
if (m_id.empty())
return false;
std::ofstream ofs(m_indexFolder / (m_id + fullSuffix), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
if (!ofs)
return false;
for (auto& dep : m_dependencies) {
ofs << dep.id << '\t';
ofs << (dep.require == DepsRequire::Hard ? "hard" : "soft") << '\t';
//ofs << (dep.merge == DepsMerge::Extend ? "extend" : (dep.merge == DepsMerge::Append ? "append" : "replace")) << '\t';
ofs << "\n";
}
ofs << "\n";
const std::string replaceStart = path2string(m_indexFolder);
for (const auto& pair1 : m_media) {
const ResourceMedia::Type type = pair1.first;
const std::string& name = mediaTypeMapping.at(type);
ofs << name << "\n";
for (const auto& pair2 : pair1.second) {
const ResourceMedia& desc = pair2.second;
ofs << '\t' << desc.id << '\t' << desc.subdir << '\t' << desc.mainFilename << "\n";
}
}
for (const auto& pair1 : m_translations) {
const auto& localeId = pair1.first;
for (const auto& pair2 : pair1.second) {
const auto& contextId = pair2.first;
ofs << typeTranslation << '\t' << localeId << '\t' << contextId << "\n";
for (const auto& pair3 : pair2.second) {
ofs << '\t' << pair3.first;
for (auto& val : pair3.second.values)
ofs << '\t' << val;
ofs << "\n";
}
}
}
if (!m_databases.empty()) {
ofs << typeDatabase << "\n";
}
for (const auto& pair1 : m_databases) {
const ResourceDatabase& desc = pair1.second;
ofs << '\t' << desc.id << '\t' << desc.baseId << '\t' << desc.subdir;
for (auto& f : desc.files) {
ofs << '\t' << f;
}
ofs << "\n";
}
return true;
}
bool ResourceLibrary::mediaExists(ResourceMedia::Type type, const std::string& id) const noexcept
{
auto itType = m_media.find(type);
if (itType == m_media.cend())
return false;
auto& idMapping = itType->second;
auto it = idMapping.find(id);
if (it == idMapping.cend())
return false;
const auto& desc = it->second;
std::error_code ec;
return std_fs::exists(std_path(desc.getFullPath()), ec);
}
const ResourceMedia& ResourceLibrary::getMedia(ResourceMedia::Type type, const std::string& id) const
{
if (!m_media.at(type).contains(id))
Logger(Logger::Err) << "Invalid id=" << id;
return m_media.at(type).at(id);
}
void ResourceLibrary::registerResource(ResourceMedia desc)
{
ResourceMedia newRec{ desc.type, deepCopy(desc.id), deepCopy(desc.subdir, true), deepCopy(desc.mainFilename), m_mainStorage.m_rootDir };
m_media[desc.type][newRec.id] = newRec;
}
std::vector<std::string> ResourceLibrary::getTranslationContextChildren(const std::string& localeId, const std::string& contextId) const
{
auto it = m_translations.find(localeId);
if (it == m_translations.cend())
return {};
auto it2 = it->second.find(contextId);
if (it2 == it->second.cend())
return {};
std::vector<std::string> result;
result.reserve(it2->second.size());
for (auto& p : it2->second)
result.push_back(std::string{ p.first });
return result;
}
std::vector<std::string> ResourceLibrary::getTranslation(const std::string& localeId, const std::string& contextId, const std::string& id) const
{
auto it = m_translations.find(localeId);
if (it == m_translations.cend())
return {};
auto it2 = it->second.find(contextId);
if (it2 == it->second.cend())
return {};
auto it3 = it2->second.find(id);
if (it3 == it2->second.cend())
return {};
return getStringsFromViews(it3->second.values);
}
void ResourceLibrary::registerResource(ResourceTranslation desc)
{
ResourceTranslation newRec{ deepCopy(desc.localeId), deepCopy(desc.contextId), deepCopy(desc.id), deepCopy(desc.values) };
;
m_translations[newRec.localeId][newRec.contextId][newRec.id] = newRec;
}
std::vector<std::string> ResourceLibrary::getDatabaseIds() const
{
std::vector<std::string> result;
for (auto& p : m_databases)
result.push_back(std::string{ p.first });
return result;
}
const ResourceDatabase& ResourceLibrary::getDatabase(const std::string& id) const
{
if (!m_databases.contains(id))
Logger(Logger::Err) << "Invalid id=" << id;
return m_databases.at(id);
}
void ResourceLibrary::registerResource(ResourceDatabase desc)
{
ResourceDatabase newRec{ deepCopy(desc.id), deepCopy(desc.baseId), deepCopy(desc.subdir, true), deepCopy(desc.files), m_mainStorage.m_rootDir, {}, {} };
newRec.filesFullPaths.reserve(desc.files.size());
for (auto& f : newRec.files)
newRec.filesFullPaths.push_back(std::string{ newRec.root } + std::string{ newRec.subdir } + std::string{ f });
m_databases[newRec.id] = newRec;
}
void ResourceLibrary::mergeWith(ResourceLibrary& newData)
{
ProfilerScope scope("mergeWith");
m_storages.insert(m_storages.end(),
std::make_move_iterator(newData.m_storages.begin()),
std::make_move_iterator(newData.m_storages.end()));
newData.m_storages.erase(newData.m_storages.begin(), newData.m_storages.end());
{
ProfilerScope scope("media");
for (const auto& pair1 : newData.m_media) {
const ResourceMedia::Type type = pair1.first;
auto& idMapping = m_media[type];
for (const auto& pair2 : pair1.second) {
auto& resourceDesc = idMapping[pair2.first];
resourceDesc = pair2.second;
}
}
}
{
ProfilerScope scope("translations");
for (const auto& pair1 : newData.m_translations) {
const auto& key1 = pair1.first;
auto& mapping1 = m_translations[key1];
for (const auto& pair2 : pair1.second) {
const auto& key2 = pair2.first;
auto& mapping2 = mapping1[key2];
for (const auto& pair3 : pair2.second) {
const auto& key3 = pair3.first;
ResourceTranslation& mapping3 = mapping2[key3];
const ResourceTranslation& value = pair3.second;
if (value.values.size() > 1 && value.values[0] == "+") {
if (mapping3.values.size() > 0)
mapping3.values.insert(mapping3.values.end(), value.values.cbegin() + 1, value.values.cend());
} else {
mapping3 = value;
}
}
}
}
}
for (const auto& db : newData.m_databases) {
m_databases[db.first] = db.second;
}
}
std::string_view ResourceLibrary::deepCopy(const std::string_view& data, bool ensureSlash)
{
const bool appendSlash = ensureSlash && !data.empty() && data[data.size() - 1] != '/';
return makeNewString(std::string{ data } + (appendSlash ? "/" : ""));
}
std::vector<std::string_view> ResourceLibrary::deepCopy(const std::vector<std::string_view>& data)
{
std::vector<std::string_view> result;
result.reserve(data.size());
for (auto& s : data)
result.push_back(deepCopy(s));
return result;
}
std::string_view ResourceLibrary::makeNewString(std::string data)
{
m_mainStorage.m_strStorage.push_back(std::move(data));
std::string& newRecord = m_mainStorage.m_strStorage.back();
return std::string_view(newRecord.data(), newRecord.size());
}
std::string_view ResourceLibrary::ensureTrailingSlashOrEmpty(std::string_view path)
{
if (path.empty() || path[path.size() - 1] == '/')
return path;
return makeNewString(std::string{ path } + '/');
}
void ResourceLibrary::ResourceLibraryPathList::topoSort()
{
Graph g;
for (const auto& rec : records) {
g.add(rec.id, rec.deps);
}
g.sort();
std::vector<Record> recordsNew;
for (const auto& id : g.getSortResult()) {
auto it = std::find_if(records.cbegin(), records.cend(), [id](const auto& rec) { return rec.id == id; });
assert(it != records.cend());
recordsNew.push_back(*it);
}
this->records = recordsNew;
}
}
| 33.794314 | 156 | 0.568905 | [
"vector"
] |
ceb4fe8b491d3afd411e5bfc9c82ef8774eb317b | 17,584 | cpp | C++ | Contrib/at67/cpu.cpp | tbraun-de/gigatron-rom | a7cf71f4bce8e980a2f8ae409cc6c727c7b1e339 | [
"BSD-2-Clause"
] | null | null | null | Contrib/at67/cpu.cpp | tbraun-de/gigatron-rom | a7cf71f4bce8e980a2f8ae409cc6c727c7b1e339 | [
"BSD-2-Clause"
] | null | null | null | Contrib/at67/cpu.cpp | tbraun-de/gigatron-rom | a7cf71f4bce8e980a2f8ae409cc6c727c7b1e339 | [
"BSD-2-Clause"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fstream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include "memory.h"
#include "cpu.h"
#ifndef STAND_ALONE
#include <SDL.h>
#include "editor.h"
#include "timing.h"
#include "graphics.h"
#include "gigatron_0x1c.h"
#endif
#ifdef _WIN32
#include <Windows.h>
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
#endif
namespace Cpu
{
int _vCpuInstPerFrame = 0;
int _vCpuInstPerFrameMax = 0;
float _vCpuUtilisation = 0.0;
int64_t _clock = -2;
uint8_t _IN = 0xFF, _XOUT = 0x00;
uint8_t _ROM[ROM_SIZE][2], _RAM[RAM_SIZE];
std::vector<uint8_t> _scanlinesRom0;
std::vector<uint8_t> _scanlinesRom1;
std::vector<InternalGt1> _internalGt1s;
uint8_t* getPtrToROM(int& romSize) {romSize = sizeof(_ROM); return (uint8_t*)_ROM;}
void initialiseInternalGt1s(void)
{
InternalGt1 internalGt1Snake = {0xE39C, 0xFDB1, 0xFC89, 5};
_internalGt1s.push_back(internalGt1Snake);
InternalGt1 internalGt1Racer = {0xEA2C, 0xFDBB, 0xFC90, 5};
_internalGt1s.push_back(internalGt1Racer);
InternalGt1 internalGt1Mandelbrot = {0xF16E, 0xFDC5, 0xFC97, 10};
_internalGt1s.push_back(internalGt1Mandelbrot);
InternalGt1 internalGt1Pictures = {0xF655, 0xFDCF, 0xFCA3, 8};
_internalGt1s.push_back(internalGt1Pictures);
InternalGt1 internalGt1Credits = {0xF731, 0xFDD9, 0xFCAD, 7};
_internalGt1s.push_back(internalGt1Credits);
InternalGt1 internalGt1Loader = {0xF997, 0xFDE3, 0xFCB6, 6};
_internalGt1s.push_back(internalGt1Loader);
}
void patchSYS_Exec_88(void)
{
_ROM[0x00AD][ROM_INST] = 0x00;
_ROM[0x00AD][ROM_DATA] = 0x00;
_ROM[0x00AF][ROM_INST] = 0x00;
_ROM[0x00AF][ROM_DATA] = 0x67;
_ROM[0x00B5][ROM_INST] = 0xDC;
_ROM[0x00B5][ROM_DATA] = 0xCF;
_ROM[0x00B6][ROM_INST] = 0x80;
_ROM[0x00B6][ROM_DATA] = 0x23;
_ROM[0x00BB][ROM_INST] = 0x80;
_ROM[0x00BB][ROM_DATA] = 0x00;
}
void patchScanlineModeVideoB(void)
{
_ROM[0x01C2][ROM_INST] = 0x14;
_ROM[0x01C2][ROM_DATA] = 0x01;
_ROM[0x01C9][ROM_INST] = 0x01;
_ROM[0x01C9][ROM_DATA] = 0x09;
_ROM[0x01CA][ROM_INST] = 0x90;
_ROM[0x01CA][ROM_DATA] = 0x01;
_ROM[0x01CB][ROM_INST] = 0x01;
_ROM[0x01CB][ROM_DATA] = 0x0A;
_ROM[0x01CC][ROM_INST] = 0x8D;
_ROM[0x01CC][ROM_DATA] = 0x00;
_ROM[0x01CD][ROM_INST] = 0xC2;
_ROM[0x01CD][ROM_DATA] = 0x0A;
_ROM[0x01CE][ROM_INST] = 0x00;
_ROM[0x01CE][ROM_DATA] = 0xD4;
_ROM[0x01CF][ROM_INST] = 0xFC;
_ROM[0x01CF][ROM_DATA] = 0xFD;
_ROM[0x01D0][ROM_INST] = 0xC2;
_ROM[0x01D0][ROM_DATA] = 0x0C;
_ROM[0x01D1][ROM_INST] = 0x02;
_ROM[0x01D1][ROM_DATA] = 0x00;
_ROM[0x01D2][ROM_INST] = 0x02;
_ROM[0x01D2][ROM_DATA] = 0x00;
_ROM[0x01D3][ROM_INST] = 0x02;
_ROM[0x01D3][ROM_DATA] = 0x00;
}
void patchScanlineModeVideoC(void)
{
_ROM[0x01DA][ROM_INST] = 0xFC;
_ROM[0x01DA][ROM_DATA] = 0xFD;
_ROM[0x01DB][ROM_INST] = 0xC2;
_ROM[0x01DB][ROM_DATA] = 0x0C;
_ROM[0x01DC][ROM_INST] = 0x02;
_ROM[0x01DC][ROM_DATA] = 0x00;
_ROM[0x01DD][ROM_INST] = 0x02;
_ROM[0x01DD][ROM_DATA] = 0x00;
_ROM[0x01DE][ROM_INST] = 0x02;
_ROM[0x01DE][ROM_DATA] = 0x00;
}
void patchTitleIntoRom(const std::string& title)
{
int minLength = std::min(int(title.size()), MAX_TITLE_CHARS);
for(int i=0; i<minLength; i++) _ROM[ROM_TITLE_ADDRESS + i][ROM_DATA] = title[i];
for(int i=minLength; i<MAX_TITLE_CHARS; i++) _ROM[ROM_TITLE_ADDRESS + i][ROM_DATA] = ' ';
}
void patchSplitGt1IntoRom(const std::string& splitGt1path, const std::string& splitGt1name, uint16_t startAddress, InternalGt1Id gt1Id)
{
size_t filelength = 0;
char filebuffer[RAM_SIZE];
std::ifstream romfile_ti(splitGt1path + "_ti", std::ios::binary | std::ios::in);
if(!romfile_ti.is_open()) fprintf(stderr, "Cpu::patchSplitGt1IntoRom() : failed to open %s ROM file.\n", std::string(splitGt1path + "_ti").c_str());
romfile_ti.seekg (0, romfile_ti.end); filelength = romfile_ti.tellg(); romfile_ti.seekg (0, romfile_ti.beg);
romfile_ti.read(filebuffer, filelength);
if(romfile_ti.eof() || romfile_ti.bad() || romfile_ti.fail()) fprintf(stderr, "Cpu::patchSplitGt1IntoRom() : failed to read %s ROM file.\n", std::string(splitGt1path + "_ti").c_str());
for(int i=0; i<filelength; i++) _ROM[startAddress + i][ROM_INST] = filebuffer[i];
std::ifstream romfile_td(splitGt1path + "_td", std::ios::binary | std::ios::in);
if(!romfile_td.is_open()) fprintf(stderr, "Cpu::patchSplitGt1IntoRom() : failed to open %s ROM file.\n", std::string(splitGt1path + "_td").c_str());
romfile_td.seekg (0, romfile_td.end); filelength = romfile_td.tellg(); romfile_td.seekg (0, romfile_td.beg);
romfile_td.read(filebuffer, filelength);
if(romfile_td.eof() || romfile_td.bad() || romfile_td.fail()) fprintf(stderr, "Cpu::patchSplitGt1IntoRom() : failed to read %s ROM file.\n", std::string(splitGt1path + "_td").c_str());
for(int i=0; i<filelength; i++) _ROM[startAddress + i][ROM_DATA] = filebuffer[i];
// Replace internal gt1 menu option with split gt1
_ROM[_internalGt1s[gt1Id]._patch + 0][ROM_DATA] = startAddress & 0x00FF;
_ROM[_internalGt1s[gt1Id]._patch + 1][ROM_DATA] = (startAddress & 0xFF00) >>8;
// Replace internal gt1 menu option name with split gt1 name
int minLength = std::min(uint8_t(splitGt1name.size()), _internalGt1s[gt1Id]._length);
for(int i=0; i<minLength; i++) _ROM[_internalGt1s[gt1Id]._string + i][ROM_DATA] = splitGt1name[i];
for(int i=minLength; i<_internalGt1s[gt1Id]._length; i++) _ROM[_internalGt1s[gt1Id]._string + i][ROM_DATA] = ' ';
}
#ifndef STAND_ALONE
int64_t getClock(void) {return _clock;}
uint8_t getIN(void) {return _IN;}
uint8_t getXOUT(void) {return _XOUT;}
uint8_t getRAM(uint16_t address) {return _RAM[address & (RAM_SIZE-1)];}
uint8_t getROM(uint16_t address, int page) {return _ROM[address & (ROM_SIZE-1)][page & 0x01];}
uint16_t getRAM16(uint16_t address) {return _RAM[address & (RAM_SIZE-1)] | (_RAM[(address+1) & (RAM_SIZE-1)]<<8);}
uint16_t getROM16(uint16_t address, int page) {return _ROM[address & (ROM_SIZE-1)][page & 0x01] | (_ROM[(address+1) & (ROM_SIZE-1)][page & 0x01]<<8);}
float getvCpuUtilisation(void) {return _vCpuUtilisation;}
void setClock(int64_t clock) {_clock = clock;}
void setIN(uint8_t in) {_IN = in;}
void setXOUT(uint8_t xout) {_XOUT = xout;}
void setRAM(uint16_t address, uint8_t data)
{
// Constant "0" and "1" are stored here
if(address == 0x0000) return;
if(address == 0x0080) return;
_RAM[address & (RAM_SIZE-1)] = data;
}
void setROM(uint16_t base, uint16_t address, uint8_t data)
{
uint16_t offset = (address - base) / 2;
_ROM[base + offset][address & 0x01] = data;
}
void setRAM16(uint16_t address, uint16_t data)
{
// Constant "0" and "1" are stored here
if(address == 0x0000) return;
if(address == 0x0080) return;
_RAM[address & (RAM_SIZE-1)] = uint8_t(data & 0x00FF);
_RAM[(address+1) & (RAM_SIZE-1)] = uint8_t((data & 0xFF00)>>8);
}
void setROM16(uint16_t base, uint16_t address, uint16_t data)
{
uint16_t offset = (address - base) / 2;
_ROM[base + offset][address & 0x01] = uint8_t(data & 0x00FF);
_ROM[base + offset][(address+1) & 0x01] = uint8_t((data & 0xFF00)>>8);
}
void saveScanlineModes(void)
{
for(int i=0x01C2; i<=0x01DE; i++)
{
_scanlinesRom0.push_back(_ROM[i][ROM_INST]);
_scanlinesRom1.push_back(_ROM[i][ROM_DATA]);
}
}
void restoreScanlineModes(void)
{
for(int i=0x01C2; i<=0x01DE; i++)
{
_ROM[i][ROM_INST] = _scanlinesRom0[i - 0x01C2];
_ROM[i][ROM_DATA] = _scanlinesRom1[i - 0x01C2];
}
}
void setScanlineMode(ScanlineMode scanlineMode)
{
switch(scanlineMode)
{
case Normal: restoreScanlineModes(); break;
case VideoB: patchScanlineModeVideoB(); break;
case VideoC: patchScanlineModeVideoC(); break;
case VideoBC: patchScanlineModeVideoB(); patchScanlineModeVideoC(); break;
}
}
void garble(uint8_t* mem, int len)
{
for(int i=0; i<len; i++) mem[i] = rand();
}
void createRomHeader(const uint8_t* rom, const std::string& filename, const std::string& name, int length)
{
std::ofstream outfile(filename);
if(!outfile.is_open())
{
fprintf(stderr, "Graphics::createRomHeader() : failed to create '%s'\n", filename.c_str());
return;
}
outfile << "uint8_t " << name + "[] = \n";
outfile << "{\n";
outfile << " ";
int colCount = 0;
uint8_t* data = (uint8_t*)rom;
for(int i=0; i<length; i++)
{
outfile << "0x" << std::hex << std::setw(2) << std::setfill('0') << int(data[i]) << ", ";
if(++colCount == 12)
{
colCount = 0;
if(i < length-1) outfile << "\n ";
}
}
outfile << "\n};" << std::endl;
}
void loadDefaultRom(const uint8_t* rom)
{
uint8_t* srcRom = (uint8_t *)rom;
uint8_t* dstRom = (uint8_t *)_ROM;
for(int i=0; i<sizeof(_ROM); i++)
{
*dstRom++ = *srcRom++;
}
}
void initialise(State& S)
{
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if(!AllocConsole()) return;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
csbi.dwSize.Y = 1000;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csbi.dwSize);
}
if(!freopen("CONIN$", "w", stdin)) return;
if(!freopen("CONOUT$", "w", stderr)) return;
if (!freopen("CONOUT$", "w", stdout)) return;
setbuf(stdout, NULL);
#endif
// Memory
srand((unsigned int)time(NULL)); // Initialize with randomized data
garble((uint8_t*)_ROM, sizeof _ROM);
garble(_RAM, sizeof _RAM);
garble((uint8_t*)&S, sizeof S);
// Check for ROM file
std::string filenameRom = "test.rom";
std::ifstream romfile(filenameRom, std::ios::binary | std::ios::in);
if(!romfile.is_open())
{
loadDefaultRom(_gigatron_0x1c_rom);
}
else
{
// Load ROM file
romfile.read((char *)_ROM, sizeof(_ROM));
if(romfile.bad() || romfile.fail())
{
fprintf(stderr, "Cpu::initialise() : failed to read %s ROM file, using default ROM.\n", filenameRom.c_str());
loadDefaultRom(_gigatron_0x1c_rom);
}
#ifdef CREATE_ROM_HEADER
// Use this if you ever want to change the default ROM
createRomHeader((uint8_t *)_ROM, "gigatron_0x1c.h", "_gigatron_0x1c_rom", sizeof(_ROM));
#endif
}
saveScanlineModes();
//#define CUSTOM_ROM
#ifdef CUSTOM_ROM
initialiseInternalGt1s();
patchSYS_Exec_88();
#define CUSTOM_ROMV0
#ifdef CUSTOM_ROMV0
patchTitleIntoRom(" TTL micrcomputer AT67 v0");
patchSplitGt1IntoRom("./roms/starfield.rom", "Starfield", 0x0b00, MandelbrotGt1);
patchSplitGt1IntoRom("./roms/life.rom", "Life", 0x0f00, LoaderGt1);
patchSplitGt1IntoRom("./roms/lines.rom", "Lines", 0x1100, SnakeGt1);
patchSplitGt1IntoRom("./roms/gigatris.rom", "Gigatris", 0x1300, PicturesGt1);
patchSplitGt1IntoRom("./roms/tetris.rom", "Tetris", 0x3000, CreditsGt1);
patchSplitGt1IntoRom("./roms/miditest.rom", "Midi", 0x5800, RacerGt1);
#else
patchTitleIntoRom(" TTL micrcomputer AT67 v0");
patchSplitGt1IntoRom("./roms/midi64.rom", "Midi64", 0x0b00, PicturesGt1);
#endif
#endif
// SDL initialisation
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_EVENTS) < 0)
{
fprintf(stderr, "Cpu::initialise() : failed to initialise SDL.\n");
_EXIT_(EXIT_FAILURE);
}
}
State cycle(const State& S)
{
State T = S; // New state is old state unless something changes
T._IR = _ROM[S._PC][ROM_INST]; // Instruction Fetch
T._D = _ROM[S._PC][ROM_DATA];
int ins = S._IR >> 5; // Instruction
int mod = (S._IR >> 2) & 7; // Addressing mode (or condition)
int bus = S._IR&3; // Busmode
int W = (ins == 6); // Write instruction?
int J = (ins == 7); // Jump instruction?
uint8_t lo=S._D, hi=0, *to=NULL; // Mode Decoder
int incX=0;
if(!J)
{
switch (mod)
{
#define E(p) (W?0:p) // Disable _AC and _OUT loading during _RAM write
case 0: to=E(&T._AC); break;
case 1: to=E(&T._AC); lo=S._X; break;
case 2: to=E(&T._AC); hi=S._Y; break;
case 3: to=E(&T._AC); lo=S._X; hi=S._Y; break;
case 4: to= &T._X; break;
case 5: to= &T._Y; break;
case 6: to=E(&T._OUT); break;
case 7: to=E(&T._OUT); lo=S._X; hi=S._Y; incX=1; break;
}
}
uint16_t addr = (hi << 8) | lo;
int B = S._undef; // Data Bus
switch(bus)
{
case 0: B=S._D; break;
case 1: if (!W) B = _RAM[addr&(RAM_SIZE-1)]; break;
case 2: B=S._AC; break;
case 3: B=_IN; break;
}
if(W) _RAM[addr&(RAM_SIZE-1)] = B; // Random Access Memory
uint8_t ALU; // Arithmetic and Logic Unit
switch(ins)
{
case 0: ALU = B; break; // LD
case 1: ALU = S._AC & B; break; // ANDA
case 2: ALU = S._AC | B; break; // ORA
case 3: ALU = S._AC ^ B; break; // XORA
case 4: ALU = S._AC + B; break; // ADDA
case 5: ALU = S._AC - B; break; // SUBA
case 6: ALU = S._AC; break; // ST
case 7: ALU = -S._AC; break; // Bcc/JMP
}
if(to) *to = ALU; // Load value into register
if(incX) T._X = S._X + 1; // Increment _X
T._PC = S._PC + 1; // Next instruction
if(J)
{
if(mod != 0) // Conditional branch within page
{
int cond = (S._AC>>7) + 2*(S._AC==0);
if (mod & (1 << cond)) // 74153
T._PC = (S._PC & 0xff00) | B;
}
else
{
T._PC = (S._Y << 8) | B; // Unconditional far jump
}
}
return T;
}
void reset(bool coldBoot)
{
// Cold boot
if(coldBoot)
{
setRAM(BOOT_COUNT, 0x00);
setRAM(BOOT_CHECK, 0xA6); // TODO: don't hardcode the checksum, calculate it properly
}
Graphics::resetVTable();
Editor::setSingleStepWatchAddress(VIDEO_Y_ADDRESS);
setClock(CLOCK_RESET);
}
// Counts maximum and used vCPU instruction slots available per frame
void vCpuUsage(State& S)
{
if(S._PC == ROM_VCPU_DISPATCH)
{
uint16_t vPC = (getRAM(0x0017) <<8) |getRAM(0x0016);
if(vPC < Editor::getCpuUsageAddressA() || vPC > Editor::getCpuUsageAddressB()) _vCpuInstPerFrame++;
_vCpuInstPerFrameMax++;
static uint64_t prevFrameCounter = 0;
double frameTime = double(SDL_GetPerformanceCounter() - prevFrameCounter) / double(SDL_GetPerformanceFrequency());
if(frameTime > VSYNC_TIMING_60)
{
// TODO: this is a bit of a hack, but it's emulation only so...
// Check for magic cookie that defines a CpuUsageAddressA and CpuUsageAddressB sequence
uint16_t magicWord0 = (getRAM(0x7F99) <<8) | getRAM(0x7F98);
uint16_t magicWord1 = (getRAM(0x7F9B) <<8) | getRAM(0x7F9A);
uint16_t cpuUsageAddressA = (getRAM(0x7F9D) <<8) | getRAM(0x7F9C);
uint16_t cpuUsageAddressB = (getRAM(0x7F9F) <<8) | getRAM(0x7F9E);
if(magicWord0 == 0xDEAD && magicWord1 == 0xBEEF)
{
Editor::setCpuUsageAddressA(cpuUsageAddressA);
Editor::setCpuUsageAddressB(cpuUsageAddressB);
}
prevFrameCounter = SDL_GetPerformanceCounter();
_vCpuUtilisation = (_vCpuInstPerFrameMax) ? float(_vCpuInstPerFrame) / float(_vCpuInstPerFrameMax) : 0.0f;
_vCpuInstPerFrame = 0;
_vCpuInstPerFrameMax = 0;
}
}
}
#endif
}
| 35.027888 | 192 | 0.564718 | [
"vector"
] |
ceb9968c55e84709cd727e77cb9f26cd86fb1a06 | 87,745 | cpp | C++ | src/rpc/blockchain.cpp | yinchengtsinghua/BitCoinCppChinese | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | [
"MIT"
] | 13 | 2019-01-23T04:36:05.000Z | 2022-02-21T11:20:25.000Z | src/rpc/blockchain.cpp | yinchengtsinghua/BitCoinCppChinese | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | [
"MIT"
] | null | null | null | src/rpc/blockchain.cpp | yinchengtsinghua/BitCoinCppChinese | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | [
"MIT"
] | 3 | 2019-01-24T07:48:15.000Z | 2021-06-11T13:34:44.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2010 Satoshi Nakamoto
//版权所有(c)2009-2018比特币核心开发者
//根据MIT软件许可证分发,请参见随附的
//文件复制或http://www.opensource.org/licenses/mit-license.php。
#include <rpc/blockchain.h>
#include <amount.h>
#include <base58.h>
#include <chain.h>
#include <chainparams.h>
#include <checkpoints.h>
#include <coins.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <hash.h>
#include <index/txindex.h>
#include <key_io.h>
#include <policy/feerate.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/descriptor.h>
#include <streams.h>
#include <sync.h>
#include <txdb.h>
#include <txmempool.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <validation.h>
#include <validationinterface.h>
#include <versionbitsinfo.h>
#include <warnings.h>
#include <assert.h>
#include <stdint.h>
#include <univalue.h>
#include <boost/thread/thread.hpp> //boost::线程::中断
#include <memory>
#include <mutex>
#include <condition_variable>
struct CUpdatedBlock
{
uint256 hash;
int height;
};
static Mutex cs_blockchange;
static std::condition_variable cond_blockchange;
static CUpdatedBlock latestblock;
/*计算给定块索引的难度。
**/
double GetDifficulty(const CBlockIndex* blockindex)
{
assert(blockindex);
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
static int ComputeNextBlockAndDepth(const CBlockIndex* tip, const CBlockIndex* blockindex, const CBlockIndex*& next)
{
next = tip->GetAncestor(blockindex->nHeight + 1);
if (next && next->pprev == blockindex) {
return tip->nHeight - blockindex->nHeight + 1;
}
next = nullptr;
return blockindex == tip ? 1 : -1;
}
UniValue blockheaderToJSON(const CBlockIndex* tip, const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.pushKV("hash", blockindex->GetBlockHash().GetHex());
const CBlockIndex* pnext;
int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
result.pushKV("confirmations", confirmations);
result.pushKV("height", blockindex->nHeight);
result.pushKV("version", blockindex->nVersion);
result.pushKV("versionHex", strprintf("%08x", blockindex->nVersion));
result.pushKV("merkleroot", blockindex->hashMerkleRoot.GetHex());
result.pushKV("time", (int64_t)blockindex->nTime);
result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast());
result.pushKV("nonce", (uint64_t)blockindex->nNonce);
result.pushKV("bits", strprintf("%08x", blockindex->nBits));
result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex->nChainWork.GetHex());
result.pushKV("nTx", (uint64_t)blockindex->nTx);
if (blockindex->pprev)
result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex());
if (pnext)
result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* tip, const CBlockIndex* blockindex, bool txDetails)
{
UniValue result(UniValue::VOBJ);
result.pushKV("hash", blockindex->GetBlockHash().GetHex());
const CBlockIndex* pnext;
int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
result.pushKV("confirmations", confirmations);
result.pushKV("strippedsize", (int)::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS));
result.pushKV("size", (int)::GetSerializeSize(block, PROTOCOL_VERSION));
result.pushKV("weight", (int)::GetBlockWeight(block));
result.pushKV("height", blockindex->nHeight);
result.pushKV("version", block.nVersion);
result.pushKV("versionHex", strprintf("%08x", block.nVersion));
result.pushKV("merkleroot", block.hashMerkleRoot.GetHex());
UniValue txs(UniValue::VARR);
for(const auto& tx : block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());
txs.push_back(objTx);
}
else
txs.push_back(tx->GetHash().GetHex());
}
result.pushKV("tx", txs);
result.pushKV("time", block.GetBlockTime());
result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast());
result.pushKV("nonce", (uint64_t)block.nNonce);
result.pushKV("bits", strprintf("%08x", block.nBits));
result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex->nChainWork.GetHex());
result.pushKV("nTx", (uint64_t)blockindex->nTx);
if (blockindex->pprev)
result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex());
if (pnext)
result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
return result;
}
static UniValue getblockcount(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getblockcount",
"\nReturns the number of blocks in the longest blockchain.\n", {}}
.ToString() +
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n"
+ HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
);
LOCK(cs_main);
return chainActive.Height();
}
static UniValue getbestblockhash(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getbestblockhash",
"\nReturns the hash of the best (tip) block in the longest blockchain.\n", {}}
.ToString() +
"\nResult:\n"
"\"hex\" (string) the block hash, hex-encoded\n"
"\nExamples:\n"
+ HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
{
if(pindex) {
std::lock_guard<std::mutex> lock(cs_blockchange);
latestblock.hash = pindex->GetBlockHash();
latestblock.height = pindex->nHeight;
}
cond_blockchange.notify_all();
}
static UniValue waitfornewblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
RPCHelpMan{"waitfornewblock",
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n",
{
/*超时“,rpcarg::type::num,/*opt*/true,/*default_val*/”0“,”等待响应的时间(毫秒)。0表示没有超时。“,
}
toSTRIN()+
“\NESRES:\N”
“(JSON对象\n”
“\”哈希\“:(字符串)块哈希\n”
“高度\”:(int)块高度\n”
“}\n”
“\n实例:\n”
+helpExamplecli(“waitfornewblock”,“1000”)。
+HelpExampleRPC(“WaitForNewBlock”,“1000”)。
;
int超时=0;
如果(!)请求.params[0].isNull())
timeout=request.params[0].get_int();
CupdatedBlock块;
{
等待锁定(cs-blockchange,lock);
block=最新block;
如果(超时)
cond_blockchange.wait_for(lock,std::chrono::millises(timeout),[&block]返回latestblock.height!=block.height latestblock.hash!=block.hash!isrpcrunning();));
其他的
Cond_BlockChange.wait(锁定,[&block]返回latestblock.height!=block.height latestblock.hash!=block.hash!isrpcrunning();));
block=最新block;
}
单值ret(单值::vobj);
ret.pushkv(“hash”,block.hash.gethex());
ret.pushkv(“高度”,块高度);
返回RET;
}
静态单值WaitForBlock(const jsonrpcrequest&request)
{
if(request.fhelp request.params.size()<1 request.params.size()>2)
throw std::runtime_错误(
rpchelpman“等待阻止”,
\n等待特定的新块并返回有关它的有用信息。\n
\n在超时或退出时返回当前块。\n“,
{
“blockhash”,rpcarg::type::str_hex,/*opt*/ false, /* default_val */ "", "Block hash to wait for."},
/*超时“,rpcarg::type::num,/*opt*/true,/*default_val*/”0“,”等待响应的时间(毫秒)。0表示没有超时。“,
}
toSTRIN()+
“\NESRES:\N”
“(JSON对象\n”
“\”哈希\“:(字符串)块哈希\n”
“高度\”:(int)块高度\n”
“}\n”
“\n实例:\n”
+helpExamplecli(“waitForBlock”,“000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862”,“1000”)。
+帮助示例rpc(“WaitForBlock”,“000000000079F8EF3D2C688C2444EB7A4570B24C9ED7B4A8C619EB02596F8862”,“1000”)。
;
int超时=0;
uint256散列(parsehashv(request.params[0],“blockhash”));
如果(!)请求.params[1].isNull())
timeout=request.params[1].get_int();
CupdatedBlock块;
{
等待锁定(cs-blockchange,lock);
如果(超时)
cond_blockchange.wait_for(lock,std::chrono::millises(timeout),[&hash]返回latestblock.hash==hash!isrpcrunning();));
其他的
cond_blockchange.wait(lock,[&hash]返回latestblock.hash==hash!isrpcrunning();));
block=最新block;
}
单值ret(单值::vobj);
ret.pushkv(“hash”,block.hash.gethex());
ret.pushkv(“高度”,块高度);
返回RET;
}
静态单值WaitForBlockHeight(const jsonrpcrequest&request)
{
if(request.fhelp request.params.size()<1 request.params.size()>2)
throw std::runtime_错误(
rpchelpman“等待锁高度”,
\n等待(至少)块高度并返回高度和哈希值\n
“当前提示的内容。\n”
\n在超时或退出时返回当前块。\n“,
{
“高度”,rpcarg::type::num,/*opt*/ false, /* default_val */ "", "Block height to wait for."},
/*超时“,rpcarg::type::num,/*opt*/true,/*default_val*/”0“,”等待响应的时间(毫秒)。0表示没有超时。“,
}
toSTRIN()+
“\NESRES:\N”
“(JSON对象\n”
“\”哈希\“:(字符串)块哈希\n”
“高度\”:(int)块高度\n”
“}\n”
“\n实例:\n”
+helpexamplecli(“waitForBlockHeight”,“100”,“1000”)。
+helpExampleRPC(“waitForBlockHeight”,“100”,“1000”)。
;
int超时=0;
int height=request.params[0].get_int();
如果(!)请求.params[1].isNull())
timeout=request.params[1].get_int();
CupdatedBlock块;
{
等待锁定(cs-blockchange,lock);
如果(超时)
cond_blockchange.wait_for(lock,std::chrono::millises(timeout),[&height]return latestblock.height>=height!isrpcrunning();));
其他的
cond_blockchange.wait(lock,[&height]返回latestblock.height>=height!isrpcrunning();));
block=最新block;
}
单值ret(单值::vobj);
ret.pushkv(“hash”,block.hash.gethex());
ret.pushkv(“高度”,块高度);
返回RET;
}
静态单值同步与validationInterfaceQueue(const jsonrpcrequest&request)
{
if(request.fhelp request.params.size()>0)
throw std::runtime_错误(
rpchelpman“与validationInterfaceQueue同步”,
“\n等待验证接口队列在我们进入此函数时赶上那里的所有内容。\n”,
toSTRIN()+
“\n实例:\n”
+helpExamplecli(“与validationInterfaceQueue同步”,“”)
+helpExampleRpc(“与validationInterfaceQueue同步”,“”)
;
}
与validationInterfaceQueue()同步;
返回nullunivalue;
}
静态单值获取难度(const jsonrpcrequest&request)
{
如果(request.fhelp request.params.size()!= 0)
throw std::runtime_错误(
rpchelpman“获取难度”,
\n将工作难度的证明作为最小难度的倍数返回。\n“”
toSTRIN()+
“\NESRES:\N”
“N.n n n(数字)作为最小难度的倍数的工作难度证明。\n”
“\n实例:\n”
+helpExamplecli(“GetDifficulty”,“”)
+helpExampleRpc(“获取难度”,“)
;
锁(CSKEMAN);
返回getDifficulty(chainActive.tip());
}
静态Std::String EntryDescriptionString()
{
返回“大小”:n,(数字)BIP 141中定义的虚拟事务大小。这与证人事务的实际序列化大小不同,因为证人数据已折扣。\n“
“费用\”:n,(数字)以“+货币\单位+”表示的交易费用(已弃用)\n”
“\”ModifiedFee\“:n,(数字)用于挖掘优先级的费用增量交易费(已弃用)\n”
““时间”:n,(数字)本地时间事务自1970年1月1日格林威治标准时间以来以秒为单位输入池\n”
“高度”:n,(数字)当事务输入池时块高度\n”
““DescendantCount”:n,(数字)内存池中的后代事务数(包括此事务)\n”
““子体大小”:n,(数字)内存池子体(包括此子体)的虚拟事务大小\n”
“子代费用\”:n,(数字)修改了mempool子代(包括此子代)的费用(见上文)(已弃用)\n”
“AncestorCount”:n,(数字)内存池中的祖先事务数(包括此事务)\n”
“AncestorSize”:n,(数字)内存池中祖先的虚拟事务大小(包括此事务大小)\n”
“Ancestorfees”:n,(数字)修改了mempool祖先(包括此祖先)的费用(见上文)(已弃用)\n”
““wtxid”:哈希,(字符串)序列化事务的哈希,包括见证数据\n”
“费用\”:\n”
“基数”:n,(数字)以“+货币\单位+”表示的交易费\n”
“\”已修改\“:n,(数字)以“+货币\单位+”表示的用于挖掘优先级的费用增量的交易费用\n”
“祖先”:n,(数字)以“+货币\单位+”表示的mempool祖先(包括此祖先)的修改费用(见上文)。\n”
“\”子体\“:n,(数字)以“+货币\单位+”修改了mempool子体(包括此子体)的费用(见上文)。\n”
“}\n”
“依赖于”:[(数组)未确认的事务,用作此事务的输入\n”
“\”transaction id\“,(string)父事务id\n”
“……”\n
“\”Spentby\“:[(数组)未确认的事务支出此事务的输出\n”
“transaction id\”,(string)子事务id \n”
“……”\n
“\”bip125 replacement\”:true false,(布尔值)由于bip125(替换为费用)是否可以替换此事务\n”;
}
静态void entryTojson(univalue&info,const ctxmempoolEntry&e)需要唯一的锁(::mempool.cs)
{
断言锁定(mempool.cs);
单值费用(单值::VOBJ);
fees.pushkv(“基础”,valuefromamount(e.getfee());
fees.pushkv(“已修改”,valuefromamount(e.getModifiedFee());
fees.pushkv(“祖先”,valuefromamount(e.getmodfeeswith祖先());
fees.pushkv(“后代”,valueFromAmount(e.GetModFeesWithDescendants());
信息:pushkv(“费用”,费用);
info.pushkv(“大小”,(int)e.gettxsize());
info.pushkv(“费用”,valuefromamount(e.getfee());
info.pushkv(“modifiedfee”,valuefromamount(e.getmodifiedfee());
info.pushkv(“时间”,e.gettime());
info.pushkv(“高度”,(int)e.getheight());
info.pushkv(“DescendantCount”,e.getCountWithDescendants());
info.pushkv(“DescendantSize”,e.getSizeWithDescendants());
info.pushkv(“DescendantFees”,e.getModFeesWithDescendants());
info.pushkv(“AncestorCount”,e.getCountWithOrights());
info.pushkv(“ancestorsize”,e.getsizewith祖先());
info.pushkv(“ancestorfees”,e.getmodfeeswith祖先());
info.pushkv(“wtxid”,mempool.vtxhash[e.vtxhashesidx].first.toString());
const ctransaction&tx=e.gettx();
std::set<std::string>setdepends;
用于(const ctxin和txin:tx.vin)
{
if(mempool.exists(txin.prevout.hash))。
setDepends.insert(txin.prevout.hash.toString());
}
单值依赖(单值::varr);
for(const std::string&dep:setdepends)
{
视情况而定。向后推(DEP);
}
信息:pushkv(“取决于”,取决于);
花费的单值(单值::varr);
const ctxmempool::txter&it=mempool.maptx.find(tx.gethash());
const ctxmempool::setentries&setchildren=mempool.getmempoolchildren(it);
对于(ctxmempool::txter childiter:setchildren)
speed.push_back(childiter->gettx().gethash().toString());
}
信息:pushkv(“spentby”,已用);
//添加选择加入RBF状态
bool rbfstatus=假;
rbftTransactionState rbfstate=isrbfoptin(tx,mempool);
if(rbfstate==rbftTransactionState::Unknown)
throw jsonrpcerror(rpc_misc_error,“transaction is not in mempool”);
else if(rbfstate==rbfttransactionstate::replacement_bip125)
rbfstatus=真;
}
信息pushkv(“bip125可替换”,rbfstatus);
}
单值mempooltokson(bool fverbose)
{
如果(FVBBOSE)
{
锁(mempool.cs);
单值o(单值::vobj);
用于(const ctxmempool entry&e:mempool.maptx)
{
const uint256&hash=e.gettx().gethash();
单值信息(univalue::vobj);
EntryTojson(信息,E);
o.pushkv(hash.toString(),信息);
}
返回O;
}
其他的
{
std::vector<uint256>vtxid;
mempool.queryhashes(vtxid);
单值A(单值::varr);
for(const uint256&hash:vtxid)
a.向后推(hash.toString());
返回A;
}
}
静态单值getrawmupool(const-jsonrpcrequest&request)
{
if(request.fhelp request.params.size()>1)
throw std::runtime_错误(
rpchelpman“getrawmempool”,
\n将内存池中的所有事务ID作为字符串事务ID的JSON数组返回。\n
\nhint:使用getmempoolentry从mempool中提取特定事务。\n“,
{
“verbose”,rpcarg::type::bool,/*opt*/ true, /* default_val */ "false", "True for a json object, false for array of transaction ids"},
}}
.ToString() +
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
);
bool fVerbose = false;
if (!request.params[0].isNull())
fVerbose = request.params[0].get_bool();
return mempoolToJSON(fVerbose);
}
static UniValue getmempoolancestors(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
RPCHelpMan{"getmempoolancestors",
"\nIf txid is in the mempool, returns all in-mempool ancestors.\n",
{
/*xid“,rpcarg::type::str_hex,/*opt*/false,/*default_val*/”,“事务ID(必须在mempool中)”,
“verbose”,rpcarg::type::bool,/*opt*/ true, /* default_val */ "false", "True for a json object, false for array of transaction ids"},
}}
.ToString() +
"\nResult (for verbose = false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolancestors", "\"mytxid\"")
+ HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
);
}
bool fVerbose = false;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setAncestors;
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
if (!fVerbose) {
UniValue o(UniValue::VARR);
for (CTxMemPool::txiter ancestorIt : setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter ancestorIt : setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.pushKV(_hash.ToString(), info);
}
return o;
}
}
static UniValue getmempooldescendants(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
RPCHelpMan{"getmempooldescendants",
"\nIf txid is in the mempool, returns all in-mempool descendants.\n",
{
/*xid“,rpcarg::type::str_hex,/*opt*/false,/*default_val*/”,“事务ID(必须在mempool中)”,
“verbose”,rpcarg::type::bool,/*opt*/ true, /* default_val */ "false", "True for a json object, false for array of transaction ids"},
}}
.ToString() +
"\nResult (for verbose = false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempooldescendants", "\"mytxid\"")
+ HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
);
}
bool fVerbose = false;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setDescendants;
mempool.CalculateDescendants(it, setDescendants);
//ctxmempool::calculateDescendants将包括给定的Tx
setDescendants.erase(it);
if (!fVerbose) {
UniValue o(UniValue::VARR);
for (CTxMemPool::txiter descendantIt : setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter descendantIt : setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.pushKV(_hash.ToString(), info);
}
return o;
}
}
static UniValue getmempoolentry(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
RPCHelpMan{"getmempoolentry",
"\nReturns mempool data for given transaction\n",
{
/*xid“,rpcarg::type::str_hex,/*opt*/false,/*default_val*/”,“事务ID(必须在mempool中)”,
}
toSTRIN()+
“\NESRES:\N”
“(JSON对象\n”
+EntryDescriptionString())
+“}\n”
“\n实例:\n”
+helpexamplecli(“getmempoolentry”,“mytxid\”)
+helpExampleRpc(“getmempoolentry”,“MyTxID\”)
;
}
uint256 hash=parsehashv(request.params[0],“参数1”);
锁(mempool.cs);
ctxmempool::txter it=mempool.maptx.find(哈希);
if(it==mempool.maptx.end())
throw jsonrpcerror(rpc_invalid_address_or_key,“transaction not in mempool”);
}
const ctxmempoolEntry&E=*IT;
单值信息(univalue::vobj);
EntryTojson(信息,E);
返回信息;
}
静态单值getblockhash(const jsonrpcrequest&request)
{
如果(request.fhelp request.params.size()!= 1)
throw std::runtime_错误(
rpchelpman“getblockhash”,
\n返回所提供高度的最佳区块链中区块的哈希值。\n“,
{
“高度”,rpcarg::type::num,/*opt*/ false, /* default_val */ "", "The height index"},
}}
.ToString() +
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = request.params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
static UniValue getblockheader(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"getblockheader",
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n",
{
/*lockhash“,rpcarg::type::str_hex,/*opt*/false,/*默认值_val*/”“,“块哈希”,
“verbose”,rpcarg::type::bool,/*opt*/ true, /* default_val */ "true", "true for a json object, false for the hex-encoded data"},
}}
.ToString() +
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"nTx\" : n, (numeric) The number of transactions in the block.\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
uint256 hash(ParseHashV(request.params[0], "hash"));
bool fVerbose = true;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
const CBlockIndex* pblockindex;
const CBlockIndex* tip;
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);
tip = chainActive.Tip();
}
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(tip, pblockindex);
}
static CBlock GetBlockChecked(const CBlockIndex* pblockindex)
{
CBlock block;
if (IsBlockPruned(pblockindex)) {
throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
}
if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
//在磁盘上找不到块。这可能是因为我们有街区
//头在索引中,但没有块(例如
//非白名单节点向我们发送一个未请求的长有效链
//块,我们将头添加到索引中,但不接受
//块)。
throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
}
return block;
}
static UniValue getblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"getblock",
"\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbosity is 1, returns an Object with information about block <hash>.\n"
"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n",
{
/*lockhash“,rpcarg::type::str_hex,/*opt*/false,/*默认值_val*/”“,“块哈希”,
“冗长”,rpcarg::type::num,/*opt*/ true, /* default_val */ "1", "0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data"},
}}
.ToString() +
"\nResult (for verbosity = 0):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nResult (for verbosity = 1):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
" \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"nTx\" : n, (numeric) The number of transactions in the block.\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbosity = 2):\n"
"{\n"
" ..., Same output as verbosity = 1.\n"
" \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
" ,...\n"
" ],\n"
" ,... Same output as verbosity = 1.\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
int verbosity = 1;
if (!request.params[1].isNull()) {
if(request.params[1].isNum())
verbosity = request.params[1].get_int();
else
verbosity = request.params[1].get_bool() ? 1 : 0;
}
const CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
const CBlock block = GetBlockChecked(pblockindex);
if (verbosity <= 0)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, chainActive.Tip(), pblockindex, verbosity >= 2);
}
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64_t nTransactions;
uint64_t nTransactionOutputs;
uint64_t nBogoSize;
uint256 hashSerialized;
uint64_t nDiskSize;
CAmount nTotalAmount;
CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {}
};
static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
ss << hash;
ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u);
stats.nTransactions++;
for (const auto& output : outputs) {
ss << VARINT(output.first + 1);
ss << output.second.out.scriptPubKey;
ss << VARINT(output.second.out.nValue, VarIntMode::NONNEGATIVE_SIGNED);
stats.nTransactionOutputs++;
stats.nTotalAmount += output.second.out.nValue;
/*ts.nbogosize+=32/*txid*/+4/*vout index*/+4/*height+coinbase*/+8/*amount*/+
2/*scriptpubkey长度*/ + output.second.out.scriptPubKey.size() /* scriptPubKey */;
}
ss << VARINT(0u);
}
//!计算未占用事务输出集的统计信息
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
{
std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
assert(pcursor);
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight;
}
ss << stats.hashBlock;
uint256 prevkey;
std::map<uint32_t, Coin> outputs;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
COutPoint key;
Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, ss, prevkey, outputs);
outputs.clear();
}
prevkey = key.hash;
outputs[key.n] = std::move(coin);
} else {
return error("%s: unable to read value", __func__);
}
pcursor->Next();
}
if (!outputs.empty()) {
ApplyStats(stats, ss, prevkey, outputs);
}
stats.hashSerialized = ss.GetHash();
stats.nDiskSize = view->EstimateSize();
return true;
}
static UniValue pruneblockchain(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"pruneblockchain", "",
{
/*八“,rpcarg::type::num,/*opt*/false,/*default_val*/”,“要修剪到的块高度。可以设置为离散高度,也可以设置为Unix时间戳\n“
“删除块时间至少比提供的时间戳早2小时的块。”,
}
toSTRIN()+
“\NESRES:\N”
“N(数字)最后一个修剪块的高度。\n”
“\n实例:\n”
+helpExamplecli(“pruneblockchain”,“1000”)。
+helpexamplerpc(“pruneblockchain”,“1000”);
如果(!)FPRONMODED
throw jsonrpcerror(rpc_misc_error,“无法修剪块,因为节点未处于修剪模式。”);
锁(CSKEMAN);
int heightparam=request.params[0].get_int();
如果(高度参数<0)
throw jsonrpcerror(rpc_无效的_参数,“负块高度”);
//超过10亿的高度值太高,无法作为块高度,并且
//太低,无法作为块时间(对应于2001年9月的时间戳)。
如果(高度参数>100000000)
//添加一个2小时的缓冲区以包含可能具有旧时间戳的块
cblockindex*pindex=chainactive.findearliestatleast(heightparam-timestamp_window);
如果(!)pQueD){
throw jsonrpcerror(rpc_invalid_参数,“找不到至少具有指定时间戳的块。”);
}
heightparam=pindex->nheight;
}
无符号整型高度=(无符号整型)高度参数;
unsigned int chainheight=(unsigned int)chainactive.height();
if(chainheight<params().pruneafterheight())
throw jsonrpcerror(rpc_misc_error,“区块链太短,无法修剪”);
否则,如果(高度>链高度)
throw jsonrpcerror(rpc_invalid_参数,“区块链短于尝试的修剪高度”);
否则,如果(高度>链高-最小_块_到保持)
logprint(bclog::rpc,“尝试修剪靠近尖端的块。保留最小块数。\n”)。
高度=链高-最小\块\保持;
}
pruneblockfiles手动(高度);
返回uint64_t(高度);
}
静态单值gettxoutsetinfo(const jsonrpcrequest&request)
{
如果(request.fhelp request.params.size()!= 0)
throw std::runtime_错误(
rpchelpman“gettxoutsetinfo”,
\n返回有关未暂停事务输出集的统计信息。\n
“注意,此呼叫可能需要一些时间。\n”,
{}
toSTRIN()+
“\NESRES:\N”
“{n”
““高度”:n,(数字)当前块高度(索引)\n”
““bestblock\”:“hex\”,(string)链顶端的块哈希\n”
““事务”:n,(数字)具有未暂停输出的事务数\n”
““txouts”:n,(数字)未暂停的事务输出数\n”
““bogosize”:n,(数字)utxo集大小的无意义度量值\n”
“哈希\已序列化\u 2\”:\“哈希\”,(string)已序列化的哈希\n”
“磁盘大小”:n,(数字)磁盘上链状态的估计大小\n”
“总金额”:x.x x x(数字)总金额\n”
“}\n”
“\n实例:\n”
+helpexamplecli(“gettxoutsetinfo”,“”)
+helpExampleRPC(“gettXoutSetInfo”,“”)
;
单值ret(单值::vobj);
CCoinstats统计;
flushstatetodisk();
if(getutxostats(pcoinsdbview.get(),stats))
ret.pushkv(“高度”,(int64_t)stats.nheight);
ret.pushkv(“bestblock”,stats.hashblock.gethex());
ret.pushkv(“事务”,(int64_t)stats.ntransactions);
ret.pushkv(“txouts”,(int64_t)stats.ntransactionoutputs);
ret.pushkv(“bogosize”,(int64_t)stats.nbogosize);
ret.pushkv(“hash_serialized_2”,stats.hash serialized.gethex());
ret.pushkv(“磁盘大小”,stats.ndisksize);
ret.pushkv(“总金额”,valuefromamount(stats.ntotalamount));
}否则{
throw jsonrpcerror(rpc_internal_error,“Unable to read utxo set”);
}
返回RET;
}
单值gettxout(const-jsonrpcrequest&request)
{
if(request.fhelp request.params.size()<2 request.params.size()>3)
throw std::runtime_错误(
rpchelpman“gettxout”,
“\n返回有关未暂停事务输出的详细信息。\n”,
{
“txid”,rpcarg::type::str,/*opt*/ false, /* default_val */ "", "The transaction id"},
/*“,rpcarg::type::num,/*opt*/false,/*默认值/”“,vout编号”,
“include_mempool”,rpcarg::type::bool,/*opt*/ true, /* default_val */ "true", "Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear."},
}}
.ToString() +
"\nResult:\n"
"{\n"
" \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of bitcoin addresses\n"
" \"address\" (string) bitcoin address\n"
" ,...\n"
" ]\n"
" },\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
uint256 hash(ParseHashV(request.params[0], "txid"));
int n = request.params[1].get_int();
COutPoint out(hash, n);
bool fMempool = true;
if (!request.params[2].isNull())
fMempool = request.params[2].get_bool();
Coin coin;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip.get(), mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
return NullUniValue;
}
} else {
if (!pcoinsTip->GetCoin(out, coin)) {
return NullUniValue;
}
}
const CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock());
ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.pushKV("confirmations", 0);
} else {
ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1));
}
ret.pushKV("value", ValueFromAmount(coin.out.nValue));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
ret.pushKV("scriptPubKey", o);
ret.pushKV("coinbase", (bool)coin.fCoinBase);
return ret;
}
static UniValue verifychain(const JSONRPCRequest& request)
{
int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"verifychain",
"\nVerifies blockchain database.\n",
{
/*hecklevel“,rpcarg::type::num,/*opt*/true,/*default_val*/strprintf(”%d,range=0-4“,nchecklevel),“块验证的彻底性。”,
“nblocks”,rpcarg::type::num,/*opt*/ true, /* default_val */ strprintf("%d, 0=all", nCheckDepth), "The number of blocks to check."},
}}
.ToString() +
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
+ HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
);
LOCK(cs_main);
if (!request.params[0].isNull())
nCheckLevel = request.params[0].get_int();
if (!request.params[1].isNull())
nCheckDepth = request.params[1].get_int();
return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth);
}
/*具有更好反馈的问题优先级的实现*/
static UniValue SoftForkMajorityDesc(int version, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
bool activated = false;
switch(version)
{
case 2:
activated = pindex->nHeight >= consensusParams.BIP34Height;
break;
case 3:
activated = pindex->nHeight >= consensusParams.BIP66Height;
break;
case 4:
activated = pindex->nHeight >= consensusParams.BIP65Height;
break;
}
rv.pushKV("status", activated);
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
rv.pushKV("id", name);
rv.pushKV("version", version);
rv.pushKV("reject", SoftForkMajorityDesc(version, pindex, consensusParams));
return rv;
}
static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
UniValue rv(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case ThresholdState::DEFINED: rv.pushKV("status", "defined"); break;
case ThresholdState::STARTED: rv.pushKV("status", "started"); break;
case ThresholdState::LOCKED_IN: rv.pushKV("status", "locked_in"); break;
case ThresholdState::ACTIVE: rv.pushKV("status", "active"); break;
case ThresholdState::FAILED: rv.pushKV("status", "failed"); break;
}
if (ThresholdState::STARTED == thresholdState)
{
rv.pushKV("bit", consensusParams.vDeployments[id].bit);
}
rv.pushKV("startTime", consensusParams.vDeployments[id].nStartTime);
rv.pushKV("timeout", consensusParams.vDeployments[id].nTimeout);
rv.pushKV("since", VersionBitsTipStateSinceHeight(consensusParams, id));
if (ThresholdState::STARTED == thresholdState)
{
UniValue statsUV(UniValue::VOBJ);
BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
statsUV.pushKV("period", statsStruct.period);
statsUV.pushKV("threshold", statsStruct.threshold);
statsUV.pushKV("elapsed", statsStruct.elapsed);
statsUV.pushKV("count", statsStruct.count);
statsUV.pushKV("possible", statsStruct.possible);
rv.pushKV("statistics", statsUV);
}
return rv;
}
static void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
//超时值为0的部署被隐藏。
//超时值为0可确保永远不会激活SoftFork。
//这在合并SoftFork代码而不指定部署计划时使用。
if (consensusParams.vDeployments[id].nTimeout > 0)
bip9_softforks.pushKV(VersionBitsDeploymentInfo[id].name, BIP9SoftForkDesc(consensusParams, id));
}
UniValue getblockchaininfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getblockchaininfo",
"Returns an object containing various state info regarding blockchain processing.\n", {}}
.ToString() +
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n"
" \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
" \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n"
" \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n"
" \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" },\n"
" }, ...\n"
" ],\n"
" \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
" \"xxxx\" : { (string) name of the softfork\n"
" \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
" \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
" \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
" \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
" \"since\": xx, (numeric) height of the first block to which the status applies\n"
" \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n"
" \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n"
" \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n"
" \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n"
" \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n"
" \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n"
" }\n"
" }\n"
" }\n"
" \"warnings\" : \"...\", (string) any network and blockchain warnings.\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
);
LOCK(cs_main);
const CBlockIndex* tip = chainActive.Tip();
UniValue obj(UniValue::VOBJ);
obj.pushKV("chain", Params().NetworkIDString());
obj.pushKV("blocks", (int)chainActive.Height());
obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1);
obj.pushKV("bestblockhash", tip->GetBlockHash().GetHex());
obj.pushKV("difficulty", (double)GetDifficulty(tip));
obj.pushKV("mediantime", (int64_t)tip->GetMedianTimePast());
obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), tip));
obj.pushKV("initialblockdownload", IsInitialBlockDownload());
obj.pushKV("chainwork", tip->nChainWork.GetHex());
obj.pushKV("size_on_disk", CalculateCurrentUsage());
obj.pushKV("pruned", fPruneMode);
if (fPruneMode) {
const CBlockIndex* block = tip;
assert(block);
while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
block = block->pprev;
}
obj.pushKV("pruneheight", block->nHeight);
//如果为0,则执行将绕过整个if块。
bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1);
obj.pushKV("automatic_pruning", automatic_pruning);
if (automatic_pruning) {
obj.pushKV("prune_target_size", nPruneTarget);
}
}
const Consensus::Params& consensusParams = Params().GetConsensus();
UniValue softforks(UniValue::VARR);
UniValue bip9_softforks(UniValue::VOBJ);
softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
for (int pos = Consensus::DEPLOYMENT_CSV; pos != Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++pos) {
BIP9SoftForkDescPushBack(bip9_softforks, consensusParams, static_cast<Consensus::DeploymentPos>(pos));
}
obj.pushKV("softforks", softforks);
obj.pushKV("bip9_softforks", bip9_softforks);
obj.pushKV("warnings", GetWarnings("statusbar"));
return obj;
}
/*用于对getchaintips头排序的比较函数。*/
struct CompareBlocksByHeight
{
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/*确保高度相同的不相等块不会比较
相等。使用指针本身进行区分。*/
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
static UniValue getchaintips(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getchaintips",
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n",
{}}
.ToString() +
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
);
LOCK(cs_main);
/*
*想法:链提示的集合是chainactive.tip,加上孤立块,它们没有其他孤立的构建。
*算法:
*-通过一次mapblockindex,选择孤立块,并存储一组孤立块的pprev指针。
*-遍历孤立块。如果块没有被另一个孤立对象指向,则它是一个链尖。
*-添加chainactive.tip()。
**/
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
std::set<const CBlockIndex*> setOrphans;
std::set<const CBlockIndex*> setPrevs;
for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
{
if (!chainActive.Contains(item.second)) {
setOrphans.insert(item.second);
setPrevs.insert(item.second->pprev);
}
}
for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
{
if (setPrevs.erase(*it) == 0) {
setTips.insert(*it);
}
}
//始终报告当前活动的提示。
setTips.insert(chainActive.Tip());
/*构造输出数组。*/
UniValue res(UniValue::VARR);
for (const CBlockIndex* block : setTips)
{
UniValue obj(UniValue::VOBJ);
obj.pushKV("height", block->nHeight);
obj.pushKV("hash", block->phashBlock->GetHex());
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
obj.pushKV("branchlen", branchLen);
std::string status;
if (chainActive.Contains(block)) {
//此块是当前活动链的一部分。
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
//此块或其祖先之一无效。
status = "invalid";
} else if (!block->HaveTxsDownloaded()) {
//无法连接此块,因为缺少它或它的某个父级的完整块数据。
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
//此块已完全验证,但不再是活动链的一部分。它可能曾经是活动块,但被重新组织了。
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
//此块的头有效,但尚未验证。它可能从来不是大多数工作链的一部分。
status = "valid-headers";
} else {
//没有线索。
status = "unknown";
}
obj.pushKV("status", status);
res.push_back(obj);
}
return res;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.pushKV("size", (int64_t) mempool.size());
ret.pushKV("bytes", (int64_t) mempool.GetTotalTxSize());
ret.pushKV("usage", (int64_t) mempool.DynamicMemoryUsage());
size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.pushKV("maxmempool", (int64_t) maxmempool);
ret.pushKV("mempoolminfee", ValueFromAmount(std::max(mempool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK()));
ret.pushKV("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()));
return ret;
}
static UniValue getmempoolinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getmempoolinfo",
"\nReturns details on the active state of the TX memory pool.\n", {}}
.ToString() +
"\nResult:\n"
"{\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
" \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n"
" \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
);
return mempoolInfoToJSON();
}
static UniValue preciousblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"preciousblock",
"\nTreats a block as if it were received before others with the same work.\n"
"\nA later preciousblock call can override the effect of an earlier one.\n"
"\nThe effects of preciousblock are not retained across restarts.\n",
{
/*lockhash“,rpcarg::type::str_hex,/*opt*/false,/*default_val*/”“,“要标记为贵重”的块的哈希,
}
toSTRIN()+
“\NESRES:\N”
“\n实例:\n”
+helpExamplecli(“preciousBlock”,“blockhash\”)
+helpexamplerpc(“preciousBlock”,“blockhash\”)
;
uint256散列(parsehashv(request.params[0],“blockhash”));
cblockindex*pblockindex;
{
锁(CSKEMAN);
pblockindex=lookupblockindex(哈希);
如果(!)P-阻断蛋白)
throw jsonrpcerror(rpc_invalid_address_or_key,“找不到块”);
}
}
cvalidationState状态;
preciousBlock(状态,params(),pblockIndex);
如果(!)state.isvalid())
throw jsonrpcerror(rpc_database_error,formatStateMessage(state));
}
返回nullunivalue;
}
静态单值无效块(const-jsonrpcrequest&request)
{
如果(request.fhelp request.params.size()!= 1)
throw std::runtime_错误(
rpchelpman“无效块”,
\n永久性地将块标记为无效,就像它违反了共识规则一样。\n“,
{
“blockhash”,rpcarg::type::str_hex,/*opt*/ false, /* default_val */ "", "the hash of the block to mark as invalid"},
}}
.ToString() +
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
CValidationState state;
{
LOCK(cs_main);
CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
InvalidateBlock(state, Params(), pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state, Params());
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue reconsiderblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"reconsiderblock",
"\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n",
{
/*lockhash“,rpcarg::type::str_hex,/*opt*/false,/*default_val*/”,“要重新考虑的块的哈希”,
}
toSTRIN()+
“\NESRES:\N”
“\n实例:\n”
+helpexamplecli(“重新考虑块”,“\”blockhash\”)
+helpexamplerpc(“重新考虑块”,“\”blockhash\”)
;
uint256散列(parsehashv(request.params[0],“blockhash”));
{
锁(CSKEMAN);
cBlockIndex*pbLockIndex=LookupBlockIndex(哈希);
如果(!)P-阻断蛋白)
throw jsonrpcerror(rpc_invalid_address_or_key,“找不到块”);
}
ResetBlockFailureFlags(pbLockIndex);
}
cvalidationState状态;
activateBestChain(状态,params());
如果(!)state.isvalid())
throw jsonrpcerror(rpc_database_error,formatStateMessage(state));
}
返回nullunivalue;
}
静态单值getchaintxstats(const jsonrpcrequest&request)
{
if(request.fhelp request.params.size()>2)
throw std::runtime_错误(
rpchelpman“getchaintxstats”,
\n计算链中事务总数和速率的统计信息。\n“,
{
“nblocks”,rpcarg::type::num,/*opt*/ true, /* default_val */ "one month", "Size of the window in number of blocks"},
/*lockhash“,rpcarg::type::str_hex,/*opt*/true,/*default_val*/”chain tip“,”结束窗口的块的哈希。”,
}
toSTRIN()+
“\NESRES:\N”
“{n”
“time”:xxxxx,(数字)窗口中最后一个块的时间戳,采用unix格式。\n”
““txcount”:xxxxx,(数字)到该点为止链中的事务总数。\n”
“window”window“最后一个”block“hash\”:\“…\”,(string)窗口中最后一个块的hash。\n”
“窗口\块\计数\”:xxxxx,(数字)窗口的大小(以块数计)。\n”
“\”window_tx_count\”:xxxxx,(数字)窗口中的事务数。仅当“窗口块计数”大于0时返回。\n
“\”窗口\间隔\“:XXXXX,(数字)窗口中的已用时间(以秒为单位)。仅当“窗口块计数”大于0时返回。\n
“\”txRate\“:x.x x,(数字)窗口中每秒事务的平均速率。仅当“窗口间隔”大于0时返回。\n
“}\n”
“\n实例:\n”
+helpExamplecli(“getchaintxstats”,“”)
+helpExampleRPC(“getchaintxstats”,“2016”)。
;
常量cblockindex*pindex;
int blockcount=30*24*60*60/params().getconsensus().npowTargetSpacking;//默认为1个月
if(request.params[1].isNull())
锁(CSKEMAN);
pindex=chainactive.tip();
}否则{
uint256散列(parsehashv(request.params[1],“blockhash”));
锁(CSKEMAN);
pindex=查找块索引(hash);
如果(!)pQueD){
throw jsonrpcerror(rpc_invalid_address_or_key,“找不到块”);
}
如果(!)chainactive.contains(pindex))
throw jsonrpcerror(rpc_invalid_参数,“block is not in main chain”);
}
}
断言(pCurnor)!= null pTr);
if(request.params[0].isNull())
blockcount=std::max(0,std::min(blockcount,pindex->nheight-1));
}否则{
blockCount=request.params[0].get_int();
if(blockcount<0(blockcount>0&&blockcount>=pindex->nheight))
throw jsonrpcerror(rpc_invalid_参数,“无效的块计数:应介于0和块的高度-1之间”);
}
}
const cblockindex*pindexpast=pindex->getancestor(pindex->nheight-blockcount);
int ntimediff=pindex->getmediantimepast()-pindexpast->getmediantimepast();
int ntxdiff=pindex->nchaintx-pindexpass->nchaintx;
单值ret(单值::vobj);
ret.pushkv(“时间”,(int64_t)pindex->ntime);
ret.pushkv(“txcount”,(int64_t)pindex->nchaintx);
ret.pushkv(“window_final_block_hash”,pindex->getblockhash().gethex());
ret.pushkv(“窗口块计数”,块计数);
如果(blockcount>0)
ret.pushkv(“window_tx_count”,ntxdiff);
ret.pushkv(“窗口间隔”,ntimediff);
如果(ntimediff>0)
ret.pushkv(“txtrate”,((双)ntxdiff)/ntimediff);
}
}
返回RET;
}
模板<typename t>
静态t calculateTruncatedMedian(std::vector<t>和scores)
{
size_t size=scores.size();
如果(尺寸=0)
返回0;
}
std::sort(scores.begin(),scores.end());
如果(大小%2==0)
返回(分数[size/2-1]+分数[size/2])/2;
}否则{
返回分数[尺寸/2];
}
}
void calculatePercentilesByweight(camount result[num搎getBlockStats_percentiles],std::vector<std::pair<camount,int64_t>>&scores,int64_t total_weight)
{
if(scores.empty())
返回;
}
std::sort(scores.begin(),scores.end());
//第10、25、50、75和90百分位重量单位。
常量双权重[num_GetBlockStats_Percentiles]=
总重量/10.0,总重量/4.0,总重量/2.0,(总重量*3.0)/4.0,(总重量*9.0)/10.0
};
Int64_t next_percentile_index=0;
Int64_t累计_权重=0;
for(const auto&element:分数)
累计_weight+=element.second;
while(next_percentile_index<num_getblockstats_percentiles&&cumulative_weight>=weights[next_percentile_index]);
结果[下一个百分位索引]=element.first;
+下一个_百分位数_指数;
}
}
//用最后一个值填充所有剩余的百分位数。
for(int64_t i=next_percentile_index;i<num_getblockstats_percentiles;i++)
结果[i]=scores.back().first;
}
}
模板<typename t>
静态内联bool sethaskeys(const std::set<t>&set)返回false;
模板<typename t,typename tk,typename…ARG>
静态内联bool sethaskeys(const std::set<t>&set,const tk&key,const args&…ARGS)
{
返回(set.count(key)!=0)sethaskeys(set,args…);
}
//outpoint(utxo索引需要)+nheight+fcoinbase
静态constexpr size_t per_utxo_开销=sizeof(coutpoint)+sizeof(uint32_t)+sizeof(bool);
静态单值getblockstats(const jsonrpcrequest&request)
{
if(request.fhelp request.params.size()<1 request.params.size()>4)
throw std::runtime_错误(
rpchelpman“getblockstats”,
\n计算给定窗口的每个块的统计信息。所有金额均以Satoshis为单位。\n“
“修剪对某些高度不起作用。\n”
“如果没有utxo-size_inc的-txindex、*费用或*feerate状态,它将无法工作。\n”,
{
“hash_or_height”,rpcarg::type::num,/*opt*/ false, /* default_val */ "", "The block hash or height of the target block", "", {"", "string or numeric"}},
/*tats“,rpcarg::type::arr,/*opt*/true,/*default_val*/”all values“,”要绘制的值(请参见下面的结果)”,
{
“高度”,rpcarg::type::str,/*opt*/ true, /* default_val */ "", "Selected statistic"},
/*输入法“,rpcarg::type::str,/*opt*/true,/*默认值“/”,“所选统计”,
}
“统计”}
}
toSTRIN()+
“\NESRES:\N”
“(JSON对象\n”
“avgfee\”:xxxxx,(数字)块中的平均费用\n”
“avgfeerate\”:xxxxx,(数字)平均频率(以每虚拟字节的Satoshis为单位)\n”
“avgtxsize\”:xxxxx,(数字)平均事务大小\n”
“\”block hash\“:xxxxx,(string)块哈希(检查潜在的重新排序)。\n”
“feerate percentiles”:[(数字数组)feerates at the 10th、25th、50th、75th和90th percentile weight unity(in satoshis per virtual byte)\n”
“第10个百分点值”,(数字)第10个百分点值\n”
“25%”,(数字)25%”,
“第50个百分点值”“,(数字)第50个百分点值\n”
“第75个百分点值”“,(数字)第75个百分点值\n”
“第90个百分点值”“,(数字)第90个百分点值\n”
“”
““高度”:XXXXX,(数字)块的高度\n”
“\”ins\“:xxxxx,(数字)输入数(不包括coinbase)\n”
“maxfee”:xxxxx,(数字)块中的最大费用\n”
“maxfeerate”:xxxxx,(数字)最大feerate(以每个虚拟字节的Satoshis为单位)\n”
“\”maxtxsize\“:xxxxx,(数字)最大事务大小\n”
“median fee”:xxxxx,(数字)块中截断的中间费用\n”
““median time\”:xxxxx,(数字)过去的块中位数时间\n”
“mediantxsize”:xxxxx,(数字)截断的中间事务大小\n”
“minfee”:xxxxx,(数字)块中的最低费用\n”
“minfeerate\”:xxxxx,(数字)最小feerate(以每个虚拟字节的Satoshis为单位)\n”
“mintxsize\”:xxxxx,(数字)最小事务大小\n”
““Outs”:XXXXX,(数字)输出数\n”
““补贴”:XXXXX,(数字)块补贴\n”
““swtotal”大小“:xxxxx,(数字)所有segwit事务的总大小\n”
“swtotal_weight”:xxxxx,(数字)所有segwit事务的总重量除以segwit比例因子(4)\n”
““SWTXS\”:xxxxx,(数字)segwit事务数\n”
““时间”:XXXXX,(数字)块时间\n”
“\”合计\“:XXXXX,(数字)所有输出的总金额(不包括CoinBase,因此奖励[即补贴+总费用])\n”
“总计大小”:XXXXX,(数字)所有非CoinBase交易的总计大小\n”
“总权重”:XXXXX,(数字)所有非CoinBase交易的总权重除以Segwit比例因子(4)\n”
“\”total fee\“:xxxxx,(数字)总费用\n”
““txs\”:xxxxx,(数字)事务数(不包括coinbase)\n”
““utxo增加”:xxxxx,(数字)未暂停输出数量的增加/减少\n”
“utxo-size_inc”:xxxxx,(数字)utxo索引的大小增加/减少(不折扣opu-return和类似的值)\n”
“}\n”
“\n实例:\n”
+helpExamplecli(“getblockstats”,“1000'[\”minfeerate\“,\”avgfeerate\“]”)
+helpExampleRpc(“getBlockstats”,“1000'[\”minfeerate\“,\”avgfeerate\“]”)
;
}
锁(CSKEMAN);
cblockindex*索引;
if(request.params[0].isnum())
const int height=request.params[0].get_int();
const int current_tip=chainactive.height();
如果(高度<0)
throw jsonrpcerror(rpc_无效的_参数,strprintf(“目标块高度%d为负”,高度));
}
如果(高度>当前_尖)
throw jsonrpcerror(rpc_无效的_参数,strprintf(“当前提示%d之后的目标块高度%d”,高度,当前_提示));
}
pindex=链激活[高度];
}否则{
const uint256 hash(parsehashv(request.params[0],“hash_or_height”));
pindex=查找块索引(hash);
如果(!)pQueD){
throw jsonrpcerror(rpc_invalid_address_or_key,“找不到块”);
}
如果(!)chainactive.contains(pindex))
throw jsonrpcerror(rpc_invalid_参数,strprintf(“block is not in chain%s”,params().networkidstring());
}
}
断言(pCurnor)!= null pTr);
std::set<std::string>stats;
如果(!)request.params[1].isNull())
const univalue stats_univalue=request.params[1].get_array();
for(unsigned int i=0;i<stats_univalue.size();i++)
const std::string stat=stats_univalue[i].get_str();
stats.插入(stat);
}
}
const cblock block=getblockchecked(pindex);
const bool do_all=stats.size()==0;//如果未选择任何内容,则计算所有内容(默认)
const bool do_mediantxsize=全部stats.count(“mediantxsize”)!=0;
const bool do_medianfee=全部stats.count(“medianfee”)!=0;
const bool do feerate_percentiles=所有stats.count(“feerate_percentiles”)!=0;
const bool loop_inputs=do_all_do_medianfee_do_erate_u percentiles_
sethaskeys(stats,“utxo-size_inc”,“totalfee”,“avgfee”,“avgfeerate”,“minfee”,“maxfee”,“minfeerate”,“maxfeerate”);
const bool loop_outputs=do_all_loop_inputs_stats.count(“total_out”);
const bool do_calculate_size=do_mediantxsize_
sethaskeys(stats,“total_size”,“avgtxsize”,“mintxsize”,“maxtxsize”,“swtotal_size”);
const bool do_calculate_weight=do_all_sethaskeys(stats,“totalou weight”,“avgfeerate”,“swtotalou weight”,“avgfeerate”,“feerateou percentiles”,“minfeerate”,“maxfeerate”);
const bool do_calculate_sw=do_all_sethaskeys(stats,“swtxs”,“swtotal_size”,“swtotal_weight”);
如果(循环输入&!GX-TXEXT){
throw jsonrpcerror(rpc_invalid_参数,“所选的一个或多个状态需要-txindex enabled”);
}
camount maxfee=0;
camount maxfeerate=0;
camount minfee=最高奖金;
camount minfeerate=最高金额;
camount total_out=0;
camount totalfee=0;
Int64输入=0;
Int64_t maxtxsize=0;
int64_t mintxsize=max_block_serialized_size;
Int64输出=0;
int64_t swtotal_size=0;
Int64总重量=0;
Int64_t SWTXS=0;
Int64总尺寸=0;
Int64总重量=0;
int64_t utxo_size_inc=0;
std::vector<camount>fee_array;
std::vector<std::pair<camount,int64_t>>feerate_array;
std::vector<int64_t>txsize_array;
用于(const auto&tx:block.vtx)
输出+=tx->vout.size();
camount tx_total_out=0;
如果(回路输出)
for(const ctxout&out:tx->vout)
tx_total_out+=out.n值;
utxo_size_inc+=getSerializeSize(out,协议_版本)+每_utxo_开销;
}
}
if(tx->iscoinBase())
继续;
}
input s+=tx->vin.size();//不计算coinbase的假输入
total_out+=tx_total_out;//不计算coinbase奖励
Int64_t tx_尺寸=0;
如果(do_calculate_size)
tx_size=tx->gettotalize();
如果(do mediantxsize)
tx size_array.push_back(tx_size);
}
max tx size=std::max(max tx size,tx_大小);
min tx size=std::min(min tx size,tx_大小);
总尺寸+=Tx尺寸;
}
Int64_t权重=0;
如果(do_calculate_weight)
权重=GetTransactionWeight(*Tx);
总重量+=重量;
}
if(do_calculate_sw&&tx->hasWitness())
+SWTXs;
swtotal_size+=tx_大小;
SWtotal_weight+=重量;
}
if(回路输入)
camount tx_total_in=0;
用于(const ctxin&in:tx->vin)
ctransactionref-tx-in;
uint256哈希块;
如果(!)getTransaction(in.prevout.hash,tx_in,params().getconsensus(),hashblock,false))
throw jsonrpcerror(rpc_internal_error,std::string(“意外的内部错误(Tx索引似乎已损坏)”);
}
ctxout prevoutput=tx_in->vout[in.prevout.n];
tx_total_in+=上一个输出值;
utxo-size_inc-=getserializesize(prevoutput,protocol_version)+每个utxo_开销;
}
camount txfee=tx_total_in-tx_total_out;
断言(moneyrange(txfee));
如果(do-medianfee)
fee_array.push_back(txfee);
}
maxfee=std::max(maxfee,txfee);
minfee=std::min(minfee,txfee);
总费用+=txfee;
//新feerate使用satoshis per virtual byte而不是per serialized byte
camount feerate=重量?(txfee*见证人×比例系数)/重量:0;
如果(做百分比)
feerate_array.emplace_back(std::make_pair(feerate,weight));
}
max feerate=std::max(max feerate,feerate);
min feerate=std::min(min feerate,feerate);
}
}
camount feerate_percentiles[num_getblockstats_percentiles]=0_
计算百分比重量(feerate_percentiles,feerate_array,total_weight);
单值函数(univavalue::varr);
for(int64_t i=0;i<num_getblockstats_percentiles;i++)
feerates.push_back(feerate_percentiles[i]);
}
univalue ret_all(univalue::vobj);
ret_all.pushkv(“avgfee”,(block.vtx.size()>1)?totalfee/(block.vtx.size()-1):0);
ret_all.pushkv(“avgfeereate”,总重量?(totalfee*witness_scale_factor)/total_weight:0);//单位:Sat/vByte
ret_all.pushkv(“avgtxsize”,(block.vtx.size()>1)?总尺寸/(block.vtx.size()-1):0);
ret_all.pushkv(“blockhash”,pindex->getblockhash().gethex());
ret_all.pushkv(“feerate_percentiles”,feerates_res);
ret_all.pushkv(“高度”,(int64_t)pindex->nheight);
ret_all.pushkv(“ins”,输入);
ret_all.pushkv(“maxfee”,maxfee);
ret_all.pushkv(“maxfeerate”,maxfeerate);
ret_all.pushkv(“maxtxsize”,maxtxsize);
ret_all.pushkv(“medianfee”,calculated truncatedmedian(fee_array));
ret_all.pushkv(“mediantime”,pindex->getmediantimepast());
ret_all.pushkv(“mediantxsize”,calculatetruncatedmedian(txsize_array));
ret_all.pushkv(“minfee”,(minfee==max_money)?0:明费);
ret-all.pushkv(“minfeerate”,(minfeerate==max\u money)?0:分钟);
ret_all.pushkv(“mintxsize”,mintxsize==max_block_serialized_size??0:MimtxSead;
ret_all.pushkv(“输出”,输出);
ret_all.pushkv(“补贴”,getBlock补贴(pindex->nheight,params().getconsensus());
ret_all.pushkv(“swtotal_size”,swtotal_size);
ret_all.pushkv(“swtotal_weight”,swtotal_weight);
ret_all.pushkv(“SWTXS”,SWTXS);
ret_all.pushkv(“时间”,pindex->getBlockTime());
ret_all.pushkv(“total_out”,total_out);
ret_all.pushkv(“总尺寸”,总尺寸);
ret_all.pushkv(“总重量”,总重量);
ret_all.pushkv(“totalfee”,totalfee);
ret_all.pushkv(“txs”,(int64_t)block.vtx.size());
ret_all.pushkv(“utxo_increase”,输出-输入);
ret_all.pushkv(“utxo_size_inc”,utxo_size_inc);
如果(doyALL){
返回回复;
}
单值ret(单值::vobj);
for(const std::string&stat:stats)
const univalue&value=ret_all[stat];
if(value.isNull())
throw jsonrpcerror(rpc_invalid_参数,strprintf(“invalid selected statistic%s”,stat));
}
ret.pushkv(stat,value);
}
返回RET;
}
静态单值savemempool(const jsonrpcrequest&request)
{
如果(request.fhelp request.params.size()!= 0){
throw std::runtime_错误(
rpchelpman“保存内存池”,
\n将内存池复制到磁盘。在上一个转储完全加载之前,它将失败。\n“”
toSTRIN()+
“\n实例:\n”
+helpexamplecli(“savemempool”,“”)
+helpexamplerpc(“savemempool”,“”)
;
}
如果(!)g_是_mempool_loaded)
throw jsonrpcerror(rpc“misc”错误,“mempool尚未加载”);
}
如果(!)dumpmempool())
throw jsonrpcerror(rpc_misc_error,“Unable to dump mempool to disk”);
}
返回nullunivalue;
}
/ /!搜索给定的pubkey脚本集
bool findscriptpubkey(std::atomic<int>&scan_progress,const std::atomic<bool>&shouldaurt,int64_t&count,ccoinsviewcursor*cursor,const std::set<cscript>&pines,std::map<coutpoint,coin>out_results)
扫描进度=0;
计数=0;
while(cursor->valid())
关键点;
硬币硬币;
如果(!)光标->getkey(key)!cursor->getvalue(coin))返回false;
如果(++计数%8192==0)
boost::this_thread::interrupt_point();
如果(应该中止)
//允许通过abort引用中止扫描
返回错误;
}
}
如果(计数%256==0)
//每256项更新进度引用
uint32_t high=0x100**key.hash.begin()+*(key.hash.begin()+1);
扫描进度=(int)(高*100.0/65536.0+0.5);
}
if(pines.count(coin.out.scriptpubkey))
输出结果。安放(钥匙、硬币);
}
光标> NEXT();
}
扫描进度=100;
回归真实;
}
/**raii对象防止扫描txout集时出现并发问题*/
static std::mutex g_utxosetscan;
static std::atomic<int> g_scan_progress;
static std::atomic<bool> g_scan_in_progress;
static std::atomic<bool> g_should_abort_scan;
class CoinsViewScanReserver
{
private:
bool m_could_reserve;
public:
explicit CoinsViewScanReserver() : m_could_reserve(false) {}
bool reserve() {
assert (!m_could_reserve);
std::lock_guard<std::mutex> lock(g_utxosetscan);
if (g_scan_in_progress) {
return false;
}
g_scan_in_progress = true;
m_could_reserve = true;
return true;
}
~CoinsViewScanReserver() {
if (m_could_reserve) {
std::lock_guard<std::mutex> lock(g_utxosetscan);
g_scan_in_progress = false;
}
}
};
UniValue scantxoutset(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
RPCHelpMan{"scantxoutset",
"\nEXPERIMENTAL warning: this call may be removed or changed in future releases.\n"
"\nScans the unspent transaction output set for entries that match certain output descriptors.\n"
"Examples of output descriptors are:\n"
" addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n"
" raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
" combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
" pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
" sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
"\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
/*更多路径元素由\“/\”分隔,可选以\“/*\”(未硬化)或\“/*'\”或\“/*H\”(硬化)结尾,以指定所有\n
“未硬化或硬化的子密钥。\n”
在后一种情况下,如果与1000不同,则需要在下面指定一个范围。\n
“有关输出描述符的详细信息,请参阅doc/descriptors.md文件中的文档。\n”,
{
“action”,rpcarg::type::str,/*opt*/ false, /* default_val */ "", "The action to execute\n"
" \"start\" for starting a scan\n"
" \"abort\" for aborting the current scan (returns true when abort was successful)\n"
" \"status\" for progress report (in %) of the current scan"},
/*canObjects“,rpcarg::type::arr,/*opt*/false,/*default_val*/”“,“扫描对象数组\n”
“每个扫描对象都是字符串描述符或对象:”,
{
“描述符”,rpcarg::type::str,/*opt*/ true, /* default_val */ "", "An output descriptor"},
/*,rpcarg::type::obj,/*opt*/true,/*default_val*/”“,“带有输出描述符和元数据的对象”,
{
“desc”,rpcarg::type::str,/*opt*/ false, /* default_val */ "", "An output descriptor"},
/*ange“,rpcarg::type::num,/*opt*/true,/*default_val*/”1000“,最多可浏览哪个子索引hd链”,
}
}
}
“[扫描对象…]”,
}
toSTRIN()+
“\NESRES:\N”
“{n”
“未使用的”:[\n”
“{n”
“txid\”:“transaction id\”,(string)事务ID \n”
“vout”:n,(数字)vout值\n”
“scriptpubkey\”:\“script\”,(string)脚本键\n”
“desc\”:“descriptor\”,(string)匹配的scriptpubkey的专用描述符\n”
“amount”:x.x x x,(数字)未用输出的以“+货币单位+”表示的总金额\n”
“高度”:n,(数字)未暂停事务输出的高度\n”
“}\n”
“,……”
“\”总金额\“:x.x x x,(数字)以“+货币\单位+”表示的所有未使用输出的总金额\n”
“\n”
;
rpctypecheck(request.params,univalue::vstr,univalue::varr);
单值结果(单值::vobj);
if(request.params[0].get_str()=“状态”)
coinsviewscanreserver reserver;
if(reserver.reserve())
//没有正在进行的扫描
返回nullunivalue;
}
结果.pushkv(“进度”,g_scan_progress);
返回结果;
else if(request.params[0].get_str()==“abort”)
coinsviewscanreserver reserver;
if(reserver.reserve())
//可以保留,这意味着没有运行扫描
返回错误;
}
//设置abort标志
G_应_中止_扫描=真;
回归真实;
else if(request.params[0].get_str()==“开始”)
coinsviewscanreserver reserver;
如果(!)reserver.reserve())
throw jsonrpcerror(rpc_invalid_参数,“scan already in progress,use action \”abort \“or \”status \“”);
}
std::set<cscript>针;
std::map<cscript,std::string>描述符;
camount total_in=0;
//循环扫描对象
for(const univalue&scanObject:request.params[1].get_array().getValues())
std::字符串描述字符串;
int范围=1000;
if(scanObject.isstr())
desc_str=scanObject.get_str();
else if(scanObject.isObject())
uni value desc_uni=查找值(scanObject,“desc”);
if(desc_uni.isnull())throw jsonrpcerror(rpc_invalid_参数,“需要在扫描对象中提供描述符”);
desc_str=desc_uni.get_str();
uni value range_uni=find_value(scanObject,“range”);
如果(!)范围“uni.isNull())”
range=range_uni.get_int();
if(range<0_range>1000000)throw jsonrpcerror(rpc_invalid_parameter,“range out of range”);
}
}否则{
throw jsonrpcerror(rpc_invalid_参数,“扫描对象必须是字符串或对象”);
}
FlatsigningProvider提供程序;
auto desc=解析(desc_str,provider);
如果(!)DESC){
throw jsonrpcerror(rpc_invalid_address_or_key,strprintf(“无效描述符'%s'”,desc_str));
}
如果(!)desc->isrange())范围=0;
对于(int i=0;i<=range;++i)
std::vector<cscript>脚本;
如果(!)desc->expand(i,provider,scripts,provider))
throw jsonrpcerror(rpc_invalid_address_or_key,strprintf(“没有私钥,无法派生脚本:”%s“,desc_str));
}
用于(const auto&script:scripts)
std::string推理=inferDescriptor(script,provider)->toString();
针。安放(脚本);
descriptors.emplace(std::move(脚本),std::move(推断));
}
}
}
//扫描未暂停的事务输出集的输入
未使用的单值(单值::varr);
std::vector<ctxout>input_Txos;
std::map<coutpoint,coin>coins;
G_应_中止_扫描=假;
G_scan_progress=0;
Int64计数=0;
std::unique_ptr<ccoinsviewcursor>pcursor;
{
锁(CSKEMAN);
flushstatetodisk();
pcursor=std::unique_ptr<ccoinsViewCursor>(pcoinsDBView->Cursor());
断言(pcursor);
}
bool res=findscriptpubkey(g_scan_progress,g_应中止_scan,count,pcursor.get(),针,硬币);
结果.pushkv(“成功”,res);
结果.pushkv(“搜索项”,计数);
用于(const auto&it:硬币)
const coutpoint&outpoint=it.first;
const coin&coin=it.second;
const ctxout&txo=coin.out;
输入txos.push-back(txo);
总_in+=txo.n值;
未使用的单值(单值::vobj);
unpent.pushkv(“txid”,outpoint.hash.gethex());
未使用的pushkv(“vout”,(int32_t)outpoint.n);
unpent.pushkv(“scriptpubkey”,hexstr(txo.scriptpubkey.begin(),txo.scriptpubkey.end());
unspent.pushkv(“desc”,描述符[txo.scriptpubkey]);
未使用的pushkv(“金额”,valuefromamount(txo.nvalue));
未使用的pushkv(“高度”,(int32-t)coin.nheight);
松开。向后推(未松开);
}
结果.pushkv(“未使用”,未使用);
result.pushkv(“总金额”,valuefromamount(总金额));
}否则{
throw jsonrpcerror(rpc_invalid_参数,“无效命令”);
}
返回结果;
}
//关闭clang格式
静态const crpccommand命令[]
//类别名称actor(function)argnames
///————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
“区块链”,“获取区块链信息”,&getblockchaininfo,,
“区块链”,“getchaintxstats”,&getchaintxstats,“nblocks”,“blockhash”,
“区块链”,“GetBlockStats”,&GetBlockStats,“hash_or_height”,“stats”,
“区块链”,“GetBestBlockHash”,&GetBestBlockHash,,
“区块链”,“GetBlockCount”,&GetBlockCount,,
“区块链”,“GetBlock”,&GetBlock,“BlockHash”,“详细详细”,
“区块链”,“GetBlockHash”,&GetBlockHash,“高度”,
“区块链”,“GetBlockHeader”,&GetBlockHeader,“BlockHash”,“详细”,
“区块链”,“getchaintips”,&getchaintips,,
“区块链”、“获取难度”&获取难度,,
“区块链”,“GetMemPooolancestors”,&GetMemPooolancestors,“txid”,“详细”,
“区块链”,“getmempooldescendants”,&getmempooldescendants,“txid”,“verbose”,
“区块链”,“getmempoolentry”,&getmempoolentry,“txid”,
“区块链”,“getmempoolinfo”,&getmempoolinfo,,
“区块链”,“getrawmupool”,&getrawmupool,“详细”,
“区块链”,“getXout”,&getXout,“txid”,“n”,“include,
“区块链”,“getXoutsetInfo”,&getXoutsetInfo,,
“区块链”,“pruneblockchain”,&pruneblockchain,“height”,
“区块链”,“存储内存池”,&savemempool,,
“区块链”、“verifychain”、&verifychain、“checklevel”、“nblocks”,
“区块链”,“PreciousBlock”,&PreciousBlock,“BlockHash”,
“区块链”、“scantStartet”、&scantStartet、“操作”、“scanObjects”,
/*未在帮助中显示*/
{ "hidden", "invalidateblock", &invalidateblock, {"blockhash"} },
{ "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} },
{ "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} },
{ "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} },
{ "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} },
{ "hidden", "syncwithvalidationinterfacequeue", &syncwithvalidationinterfacequeue, {} },
};
//CLAN格式
void RegisterBlockchainRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| 37.72356 | 203 | 0.579201 | [
"object",
"vector"
] |
cebca0be7ee44b3446cde7348fb071361be60eae | 2,066 | cpp | C++ | src/SharedLibrary/IntegrationTests/SharedLibrary_StandardScaleWrapper_IntegrationTest.cpp | Bhaskers-Blu-Org2/FeaturizersLibrary | 229ae38ea233bfb02a6ff92ec3a67c1751c58005 | [
"MIT"
] | 15 | 2019-12-14T07:54:18.000Z | 2021-03-14T14:53:28.000Z | src/SharedLibrary/IntegrationTests/SharedLibrary_SSWFeaturizer_IntegrationTest.cpp | Lisiczka27/FeaturizersLibrary | dc7b42abd39589af0668c896666affb4abe8a622 | [
"MIT"
] | 30 | 2019-12-03T20:58:56.000Z | 2020-04-21T23:34:39.000Z | src/SharedLibrary/IntegrationTests/SharedLibrary_SSWFeaturizer_IntegrationTest.cpp | Lisiczka27/FeaturizersLibrary | dc7b42abd39589af0668c896666affb4abe8a622 | [
"MIT"
] | 13 | 2020-01-23T00:18:47.000Z | 2021-10-04T17:46:45.000Z | // ----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
// ----------------------------------------------------------------------
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "GeneratedCode/SharedLibraryTests_StandardScaleWrapperFeaturizer.h"
TEST_CASE("int8_t_with_mean_with_std") {
StandardScaleWrapperFeaturizer_int8_Test(
std::vector<std::int8_t>{
0,
0,
1,
1
},
std::vector<std::int8_t>{
2
},
[](std::vector<std::double_t> const &args) {
return args[0] == 3.0;
},
true,
true
);
}
TEST_CASE("double_t_without_mean_with_std") {
StandardScaleWrapperFeaturizer_double_Test(
std::vector<std::double_t>{
0.0,
0.0,
1.0,
1.0
},
std::vector<std::double_t>{
2.0
},
[](std::vector<std::double_t> const &args) {
return args[0] == 4.0;
},
false,
true
);
}
TEST_CASE("double_t_with_mean_without_std") {
StandardScaleWrapperFeaturizer_double_Test(
std::vector<std::double_t>{
0.0,
0.0,
1.0,
1.0
},
std::vector<std::double_t>{
2.0
},
[](std::vector<std::double_t> const &args) {
return args[0] == 1.5;
},
true,
false
);
}
TEST_CASE("double_t_without_mean_without_std") {
StandardScaleWrapperFeaturizer_double_Test(
std::vector<std::double_t>{
0.0,
0.0,
1.0,
1.0
},
std::vector<std::double_t>{
2.0
},
[](std::vector<std::double_t> const &args) {
return args[0] == 2.0;
},
false,
false
);
}
| 24.305882 | 77 | 0.433688 | [
"vector"
] |
cec12be762a35d24ebb923c0ecad9053d3064d2f | 1,983 | cpp | C++ | cpp/0238_product_of_array_except_self.cpp | willheryanto/leetcode | 234c54d0d666f2a9db8928f898e1dbff97ebbb10 | [
"MIT"
] | null | null | null | cpp/0238_product_of_array_except_self.cpp | willheryanto/leetcode | 234c54d0d666f2a9db8928f898e1dbff97ebbb10 | [
"MIT"
] | null | null | null | cpp/0238_product_of_array_except_self.cpp | willheryanto/leetcode | 234c54d0d666f2a9db8928f898e1dbff97ebbb10 | [
"MIT"
] | null | null | null | // Source : https://leetcode.com/problems/product-of-array-except-self/
// Author : willheryanto
// Date : 2021-12-08
/*******************************************************************************
*
* Given an integer array `nums`, return an array `answer` such that
* `answer[i]` is equal to the product of all the elements of `nums` except
* `nums[i]`.
*
* The product of any prefix or suffix of `nums` is guaranteed to fit in a
* 32-bit integer.
*
* You must write an algorithm that runs in `O(n)` time and without using the
* division operation.
*
*
* Example 1:
* Input: nums = [1,2,3,4]
* Output: [24,12,8,6]
* Example 2:
* Input: nums = [-1,1,0,-3,3]
* Output: [0,0,9,0,0]
*
*
* Constraints:
*
*
* - `2 <= nums.length <= 105`
* - `-30 <= nums[i] <= 30`
* - The product of any prefix or suffix of `nums` is guaranteed to
* fit in a 32-bit integer.
*
*
*
* Follow up: Can you solve the problem in `O(1) `extra space complexity? (The
* output array does not count as extra space for space complexity analysis.)
*
*******************************************************************************/
#include <my/libs.h>
class Solution {
public:
vector<int> productExceptSelf(vector<int> &nums) {
vector<int> res;
int n = nums.size();
int p = 1;
for (int i = 0; i < n; i++) {
res.push_back(p);
p *= nums[i];
}
p = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= p;
p *= nums[i];
}
return res;
}
};
void solve() {
int n;
read(n);
vector<int> nums(n);
read(nums);
Solution s;
auto ans = s.productExceptSelf(nums);
EACH(a, ans)
cout << a << " ";
cout << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tc = 1;
cin >> tc;
for (int t = 1; t <= tc; t++) {
cout << "Case #" << t << ": ";
solve();
}
}
| 22.534091 | 81 | 0.486636 | [
"vector"
] |
cecaee925424623e6a90c885ef8b4e0041af4325 | 17,785 | cpp | C++ | MPEC/functions.cpp | foolish3/DDCM | b3c52e19600faefc8ec853f0d2bd18f2293e2897 | [
"MIT"
] | 4 | 2018-10-29T04:59:03.000Z | 2020-05-04T03:26:32.000Z | MPEC/functions.cpp | foolish3/DDCM | b3c52e19600faefc8ec853f0d2bd18f2293e2897 | [
"MIT"
] | null | null | null | MPEC/functions.cpp | foolish3/DDCM | b3c52e19600faefc8ec853f0d2bd18f2293e2897 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "tools.h"
//#include "global.h"
#include "extern.h"
#include "functions.h"
#include "nfpIteration.h"
#include "mpec.h"
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
//#include "knitro.h"
void printOutputMPEC
(
const int &nnzJ,
const double * const x,
double * const obj,
double * const objGrad,
struct USERSTRUCT *us
)
{
double toc;
FILE *outp;
toc = gettimeofday_sec();
outp = fopen("outputMPEC.txt","a");
fprintf(outp, "%6d %6d ",us->mcID, us->seed);
for (int k=0; k<n_theta; k++)
fprintf(outp, "%20.14f ",x[k]);
fprintf(outp, "%16.5f %14.2f\n",*obj,toc-us->tic);
fclose(outp);
}
void printOutput
(
char *filenameEstim,
int &mcID,
int &seed,
int &nStatus,
double &obj,
double &toc,
double *x,
struct USERSTRUCT &us
)
{
int k;
FILE * outp_stat;
outp_stat = fopen(filenameEstim, "a");
fprintf(outp_stat, "%6d %6d %6d ", mcID,seed,nStatus);
for (k=0; k<n_theta2; k++)
fprintf(outp_stat, "%12.6f %12.6f ", x[k], us.par.sd2[k]);
for (k=0; k<n_theta1; k++)
fprintf(outp_stat, "%12.6f %12.6f ", x[n_theta2+k], us.par.sd1[k]);
fprintf(outp_stat, "%14.5f %8d %8d %8d %8d %12lld %14.4f\n", obj,us.diag.iters,
us.diag.FC_evals,us.diag.GA_evals,us.diag.H_evals,
us.diag.bellmanIter,toc-us.tic);
fclose(outp_stat);
printf("MC experiment %d seed %d complete. Total time elapsed: %f\n",
mcID, seed, toc-us.tic);
}
void initializeMu
(
//=======================================================
adouble **expMu,
double *nu,
struct PAR_AD &par_ad,
struct VAR &var
//=======================================================
)
{
int j, k, t, id;
adouble mu;
for (t=0; t<n_period; t++){
for (j=0; j<n_product; j++){
id = idx[t][j];
mu = 0;
for (k=0; k<n_theta2; k++)
mu += par_ad.theta2[k] * nu[k] * var.X[id][rcID[k]];
expMu[t][j] = exp(mu);
}
}
}
void initializeMu
(
//=======================================================
double ***expMu,
struct PAR &par,
struct RND &rnd,
struct VAR &var
//=======================================================
)
{
int i, j, k, t, id;
double mu;
for (i=0; i<n_person; i++){
for (t=0; t<n_period; t++){
for (j=0; j<n_product; j++){
id = idx[t][j];
mu = 0;
for (k=0; k<n_theta2; k++)
mu += par.theta2[k] * rnd.nu[i][k] * var.X[id][rcID[k]];
expMu[i][t][j] = exp(mu);
}
}
}
}
void initialize
(
int &mcID,
int &seed,
double *xInitial,
double *paramSeed,
struct USERSTRUCT &us
)
{
int i, j, k, n, t, s0;
us.mcID = mcID;
us.seed = seed;
computeMatrices(us.var.invPHI, us.var.XZPHIZXZ, us.var.X, us.var.Z, us.var.Z_t);
for (k=0; k<n_theta2; k++){
xInitial[k] = paramSeed[k];
us.par.theta2[k] = paramSeed[k];
}
/*
par.theta2[0] = 0.5;
par.theta2[1] = 0.5;
par.theta2[2] = 0.25;
par.theta1[0] = 6.0;
par.theta1[1] = 1.0;
par.theta1[2] = 1.0;
par.theta1[3] = 0.5;
par.theta1[4] = 2.0;
xInitial[0] = 0.5;
xInitial[1] = 0.5;
xInitial[2] = 0.25;
xInitial[3] = 6.0;
xInitial[4] = 1.0;
xInitial[5] = 1.0;
xInitial[6] = 0.5;
xInitial[7] = 2.0;
*/
matvecmul(us.var.X, us.par.theta1, us.var.Xtheta1, n_obs, n_theta1); // X*theta1
for (t=0; t<n_period; t++){
for (j=0; j<n_product; j++){
us.fxp.expDeltaIn[idx[t][j]] = us.dat.ms[t][j] / us.dat.ms0[t];
//fxp.expDeltaOut[idx[t][j]] = exp(var.Xtheta1[idx[t][j]] + dat.xi[t][j]);
}
}
for (i=0; i<n_person; i++){
for (s0=0; s0<n_grid; s0++){
us.fxp.valuefunIn[i][s0] = 0;
//fxp.valuefunOut[i][s0] = dat.valfun[i][s0];
}
}
us.var.tol_blp = 1e-3;
us.var.tol_bellman = 1e-5;
us.diag.lipschitz = 0;
us.diag.lipschitzIter = 1;
us.diag.blpIter = 0;
us.diag.bellmanIter = 0;
nfpBLP(us.fxp,us.dat,us.par,us.rnd,us.var,us.diag,us.incv,us.pred);
logVector(us.fxp.expDeltaOut, us.fxp.delta, n_obs);
matvecmul(us.var.XZPHIZXZ, us.fxp.delta, us.par.theta1, n_theta1, n_obs);
matvecmul(us.var.X, us.par.theta1, us.var.Xtheta1, n_obs, n_theta1);
k = n_theta2;
for (i=0; i<n_theta1; i++){
xInitial[k] = us.par.theta1[i];
k++;
}
/*
for (t=0; t<n_period; t++){
for (j=0; j<n_product; j++){
par.xi[idx[t][j]] = dat.xi[t][j];
}
} */
for (n=0; n<n_obs; n++){
us.par.xi[n] = us.fxp.delta[n] - us.var.Xtheta1[n];
xInitial[k] = us.par.xi[n];
k++;
}
for (i=0; i<n_person; i++){
for (s0=0; s0<n_grid; s0++){
xInitial[k] = us.fxp.valuefunOut[i][s0];
k++;
}
}
matvecmul(us.var.Z_t, us.par.xi, us.par.g, n_inst, n_obs);
for (i=0; i<n_inst; i++){
xInitial[k] = us.par.g[i];
k++;
}
}
void computeMatrices
(
//=======================================================
double **invPHI,
double **XZPHIZXZ,
double **X,
double **Z,
double **Z_t
//=======================================================
)
{
int i, j;
double
**X_t,
**PHI,
**XZ,
**ZX,
**XZPHI,
**XZPHIZ,
**XZPHIZX,
**XZPHIZXinv;
X_t = dmatrix(n_theta1, n_obs);
PHI = dmatrix(n_inst, n_inst);
XZ = dmatrix(n_theta1, n_inst);
ZX = dmatrix(n_inst, n_theta1);
XZPHI = dmatrix(n_theta1, n_inst);
XZPHIZ = dmatrix(n_theta1, n_obs);
XZPHIZX = dmatrix(n_theta1, n_theta1);
XZPHIZXinv = dmatrix(n_theta1, n_theta1);
gsl_matrix
*gsl_invPHI = gsl_matrix_alloc(n_inst, n_inst),
*gsl_XZPHIZXinv = gsl_matrix_alloc(n_theta1, n_theta1);
// Compute 1st-stage GMM weight matrix
transpose(Z, Z_t, n_obs, n_inst);
matmul(Z_t, Z, PHI, n_inst, n_obs, n_inst); // PHI = Z'Z
for (i=0; i<n_inst; i++){
for (j=0; j<n_inst; j++){
gsl_matrix_set (gsl_invPHI, i, j, PHI[i][j]);
}
}
gsl_linalg_cholesky_decomp(gsl_invPHI);
gsl_linalg_cholesky_invert(gsl_invPHI);
for (i=0; i<n_inst; i++){
for (j=0; j<n_inst; j++){
invPHI[i][j] = gsl_matrix_get (gsl_invPHI, i, j);
}
}
transpose(X, X_t, n_obs, n_theta1);
matmul(X_t, Z, XZ, n_theta1, n_obs, n_inst); // XZ = X_t*Z = X'Z
transpose(XZ, ZX, n_theta1, n_inst); // ZX = (XZ)' = Z'X
matmul(XZ, invPHI, XZPHI, n_theta1, n_inst, n_inst); // XZPHI = (X'Z)inv(Z'Z)
matmul(XZPHI, ZX, XZPHIZX, n_theta1, n_inst, n_theta1); // XZPHIZX = (X'Z)inv(Z'Z)(Z'X)
for (i=0; i<n_theta1; i++){
for (j=0; j<n_theta1; j++){
gsl_matrix_set (gsl_XZPHIZXinv, i, j, XZPHIZX[i][j]);
}
}
gsl_linalg_cholesky_decomp(gsl_XZPHIZXinv);
gsl_linalg_cholesky_invert(gsl_XZPHIZXinv);
for (i=0; i<n_theta1; i++){
for (j=0; j<n_theta1; j++){
XZPHIZXinv[i][j] = gsl_matrix_get (gsl_XZPHIZXinv, i, j);
}
}
matmul(XZPHI, Z_t, XZPHIZ, n_theta1, n_inst, n_obs); // XZPHIZ = (X'Z)inv(Z'Z)Z'
// XZPHIZXZ = inv((X'Z)inv(Z'Z)(Z'X))(X'Z)inv(Z'Z)Z'
matmul(XZPHIZXinv, XZPHIZ, XZPHIZXZ, n_theta1, n_theta1, n_obs);
gsl_matrix_free (gsl_invPHI);
gsl_matrix_free (gsl_XZPHIZXinv);
free_dmatrix(X_t);
free_dmatrix(PHI);
free_dmatrix(XZ);
free_dmatrix(ZX);
free_dmatrix(XZPHI);
free_dmatrix(XZPHIZ);
free_dmatrix(XZPHIZX);
free_dmatrix(XZPHIZXinv);
}
void readData
(
int &mcID,
FILE* inpData,
FILE* inpRand,
char* filenameValfun,
struct DAT &dat,
struct RND &rnd,
struct VAR &var
)
{
int i, j, k, t, s0, id, imc, itime, iproduct, status;
for (t=0; t<n_period; t++){
for (j=0; j<n_product; j++){
id = idx[t][j];
status = fscanf(inpData, "%d %d %d ", &imc, &itime, &iproduct);
status = fscanf(inpData, "%lf %lf %lf ", &dat.ms[t][j], &dat.ms0[t], &dat.xi[t][j]);
for (k=0; k<n_theta1; k++)
status = fscanf(inpData, "%lf ", &var.X[id][k]);
for (k=0; k<n_inst; k++)
status = fscanf(inpData, "%lf ", &var.Z[id][k]);
if (imc>n_mc || itime>n_period || iproduct>n_product || imc!=mcID+1){
error("Dimensions of data and estimation model do not match.");
}
}
}
FILE* inpVfun = fopen(filenameValfun,"r");
for (i=0; i<n_person; i++){
for (k=0; k<n_theta2; k++)
status = fscanf(inpRand, "%lf ", &rnd.nu[i][k]);
for (s0=0; s0<n_grid; s0++)
status = fscanf(inpVfun, "%lf ", &dat.valfun[i][s0]);
}
fclose(inpVfun);
}
void readSeed
(
double ***paramSeed,
char* filenameSeed
)
{
int i, k, s;
FILE* inpSeed;
inpSeed = fopen(filenameSeed,"r");
for (i=0; i<n_mc; i++){
for (s=0; s<n_seed; s++){
for (k=0; k<n_theta2; k++){
fscanf(inpSeed, "%lf ", ¶mSeed[i][s][k]);
}
}
}
fclose(inpSeed);
}
void initializeKnitro
(
int &m,
int &n,
int &nnzJ,
int &nnzH,
int *cType,
double *xInitial,
double *xLoBnds,
double *xUpBnds,
double *cLoBnds,
double *cUpBnds,
double *paramBound,
struct USERSTRUCT &us
)
{
int i,j,k;
for (i=0; i<n_theta2; i++){
xLoBnds[i] = 0.0;
xUpBnds[i] = paramBound[i];
}
for (i=n_theta2; i<n; i++){
xLoBnds[i] = -KTR_INFBOUND;
xUpBnds[i] = KTR_INFBOUND;
}
for (j=0; j<m; j++){
cType[j] = KTR_CONTYPE_GENERAL;
cLoBnds[j] = 0.0;
cUpBnds[j] = 0.0;
}
for (j=n_obs+dimValfun; j<m; j++){
cType[j] = KTR_CONTYPE_LINEAR;
}
us.tagJacobian = 0; // index of Adolc tape for Jacobian
us.tagHessian = 1; // index of Adolc tape for Hessian
us.optionsJac[0] = 0;
us.optionsJac[1] = 0;
us.optionsJac[2] = 0;
us.optionsJac[3] = 0;
nnzJ = NULL;
us.nnzHconst = NULL;
double *constraint = dvector(dimConst);
us.tic = gettimeofday_sec();
// Generate permanent tapes
tapeJacobian(constraint, xInitial, us);
free_dvector(constraint);
// Detect sparsity patterns
sparse_jac(us.tagJacobian, dimConst, dimOptim,0, xInitial, &nnzJ,
&us.jacIndexCons, &us.jacIndexVars, &us.jac, us.optionsJac);
//printf("Constraint Jacobian sparsity pattern detected.\n");
us.jacIndexVarsInt = ivector(nnzJ);
us.jacIndexConsInt = ivector(nnzJ);
// Copy Adolc jacobian index to KNITRO
for (k=0; k<nnzJ; k++){
us.jacIndexConsInt[k] = us.jacIndexCons[k];
us.jacIndexVarsInt[k] = us.jacIndexVars[k];
}
// UPPER TRIANGULAR Hessian sparsity
k = 0;
for (i=0; i<n_theta+n_obs+dimValfun; i++){
for (j=i; j<n_theta+n_obs+dimValfun; j++){
us.hessIndexRows[k] = i;
us.hessIndexCols[k] = j;
k++;
}
}
us.nnzHconst = k;
for (i=n_theta+n_obs+dimValfun; i<dimOptim; i++){
for (j=i; j<dimOptim; j++){
us.hessIndexRows[k] = i;
us.hessIndexCols[k] = j;
k++;
}
}
nnzH = k;
}
void allocateKnitro
(
int &m,
int &n,
//int &nnzJ,
int &nnzH,
int **cType,
double **xLoBnds,
double **xUpBnds,
double **xInitial,
double **x,
double **cLoBnds,
double **cUpBnds,
double **lambda,
struct USERSTRUCT &us
)
{
*xLoBnds = dvector(n);
*xUpBnds = dvector(n);
*xInitial = dvector(n);
*x = dvector(n);
*cType = ivector(m);
*cLoBnds = dvector(m);
*cUpBnds = dvector(m);
*lambda = dvector(m+n);
allocateActiveMemory(us.par_ad, us.fxp_ad, us.var_ad, us.incv_ad, us.pred_ad);
us.c_ad = advector(dimConst);
us.xcopy = dvector(dimOptim);
us.jac = NULL;
us.hessConstraint = dmatrix(dimOptim, dimOptim);
us.jacIndexCons = NULL;
us.jacIndexVars = NULL;
us.hessIndexRows = ivector(nnzH);
us.hessIndexCols = ivector(nnzH);
}
void freeKnitro
(
int **cType,
double **xLoBnds,
double **xUpBnds,
double **xInitial,
double **x,
double **cLoBnds,
double **cUpBnds,
double **lambda,
struct USERSTRUCT &us
)
{
free_dvector(*xLoBnds);
free_dvector(*xUpBnds);
free_dvector(*xInitial);
free_dvector(*x);
free_ivector(*cType);
free_dvector(*cLoBnds);
free_dvector(*cUpBnds);
free_dvector(*lambda);
releaseActiveMemory(us.par_ad, us.fxp_ad, us.var_ad, us.incv_ad, us.pred_ad);
free_advector(us.c_ad);
free_dvector(us.xcopy);
free(us.jac);
free_dmatrix(us.hessConstraint);
free(us.jacIndexVars);
free(us.jacIndexCons);
free_ivector(us.hessIndexRows);
free_ivector(us.hessIndexCols);
free_ivector(us.jacIndexVarsInt);
free_ivector(us.jacIndexConsInt);
}
void allocateMemory
(
struct DAT &dat,
struct FXP &fxp,
struct PAR &par,
struct RND &rnd,
struct VAR &var,
struct INCV &incv,
struct PRED &pred
)
{
par.theta1 = dvector(n_theta1);
par.theta2 = dvector(n_theta2);
par.sd1 = dvector(n_theta1);
par.sd2 = dvector(n_theta2);
par.xi = dvector(n_obs);
par.valfun = dmatrix(n_person, n_grid);
par.g = dvector(n_inst);
dat.ms = dmatrix(n_period, n_product);
dat.ms0 = dvector(n_period);
dat.xi = dmatrix(n_period, n_product);
dat.delta = dvector(n_obs);
dat.valfun = dmatrix(n_person, n_grid);
fxp.delta = dvector(n_obs);
fxp.expDeltaIn = dvector(n_obs);
fxp.expDeltaOut = dvector(n_obs);
fxp.valuefunIn = dmatrix(n_person, n_grid);
fxp.valuefunOut = dmatrix(n_person, n_grid);
fxp.expMu = darray3d(n_person, n_period, n_product);
rnd.nu = dmatrix(n_person, n_theta2);
idx = imatrix(n_period, n_product);
var.X = dmatrix(n_obs, n_theta1);
var.Z = dmatrix(n_obs, n_inst);
var.Z_t = dmatrix(n_inst, n_obs);
var.invPHI = dmatrix(n_inst, n_inst);
var.XZPHIZXZ = dmatrix(n_theta1, n_obs);
var.num = dmatrix(n_period, n_product+1);
var.value0 = dvector (n_period);
var.Xtheta1 = dvector(n_obs);
var.e = dvector(n_obs);
var.Ze = dvector(n_inst);
var.PHIZe = dvector(n_inst);
var.weightMat = dmatrix(n_grid, n_grid);
incv.w = dvector(n_period);
incv.wGrid = dvector(n_grid);
incv.lambda = dvector(2);
incv.y = dvector(n_period-1);
incv.wy = dvector(2);
incv.wlambda = dvector(n_period-1);
incv.w_lag = dmatrix(n_period-1, 2);
incv.w_lag_t = dmatrix(2, n_period-1);
incv.ww = dmatrix(2, 2);
incv.ww_inv = dmatrix(2, 2);
pred.ms = dmatrix(n_period, n_product);
pred.survivalRate = dvector(n_period);
}
void allocateActiveMemory
(
struct PAR_AD &par_ad,
struct FXP_AD &fxp_ad,
struct VAR_AD &var_ad,
struct INCV_AD &incv_ad,
struct PRED_AD &pred_ad
)
{
par_ad.theta1 = advector(n_theta1);
par_ad.theta2 = advector(n_theta2);
par_ad.xi = advector(n_obs);
par_ad.valfun = admatrix(n_person, n_grid);
par_ad.g = advector(n_inst);
fxp_ad.expDeltaIn = advector(n_obs);
fxp_ad.expMu = admatrix(n_period, n_product);
fxp_ad.valuefunOut = admatrix(n_person, n_grid);
var_ad.num = admatrix(n_period, n_product+1);
var_ad.value0 = advector (n_period);
var_ad.Xtheta1 = advector(n_obs);
var_ad.e = advector(n_obs);
var_ad.Ze = advector(n_inst);
var_ad.PHIZe = advector(n_inst);
var_ad.weightMat = admatrix(n_grid, n_grid);
incv_ad.w = advector(n_period);
incv_ad.wGrid = advector(n_grid);
incv_ad.lambda = advector(2);
incv_ad.y = advector(n_period-1);
incv_ad.wy = advector(2);
incv_ad.wlambda = advector(n_period-1);
incv_ad.w_lag = admatrix(n_period-1, 2);
incv_ad.w_lag_t = admatrix(2, n_period-1);
incv_ad.ww = admatrix(2, 2);
incv_ad.ww_inv = admatrix(2, 2);
pred_ad.ms = admatrix(n_period, n_product);
pred_ad.survivalRate = advector(n_period);
}
void releaseMemory
(
struct DAT &dat,
struct FXP &fxp,
struct PAR &par,
struct RND &rnd,
struct VAR &var,
struct INCV &incv,
struct PRED &pred
)
{
free_dvector(par.theta1);
free_dvector(par.theta2);
free_dvector(par.sd1);
free_dvector(par.sd2);
free_dvector(par.xi);
free_dmatrix(par.valfun);
free_dvector(par.g);
free_dmatrix(dat.ms);
free_dvector(dat.ms0);
free_dmatrix(dat.xi);
free_dvector(dat.delta);
free_dmatrix(dat.valfun);
free_dvector(fxp.delta);
free_dvector(fxp.expDeltaIn);
free_dvector(fxp.expDeltaOut);
free_dmatrix(fxp.valuefunIn);
free_dmatrix(fxp.valuefunOut);
free_darray3d(fxp.expMu);
free_dmatrix(rnd.nu);
free_imatrix(idx);
free_dmatrix(var.X);
free_dmatrix(var.Z);
free_dmatrix(var.Z_t);
free_dmatrix(var.invPHI);
free_dmatrix(var.XZPHIZXZ);
free_dmatrix(var.num);
free_dvector(var.value0);
free_dvector(var.Xtheta1);
free_dvector(var.e);
free_dvector(var.Ze);
free_dvector(var.PHIZe);
free_dmatrix(var.weightMat);
free_dvector(incv.w);
free_dvector(incv.wGrid);
free_dvector(incv.lambda);
free_dvector(incv.y);
free_dvector(incv.wy);
free_dvector(incv.wlambda);
free_dmatrix(incv.w_lag);
free_dmatrix(incv.w_lag_t);
free_dmatrix(incv.ww);
free_dmatrix(incv.ww_inv);
free_dmatrix(pred.ms);
free_dvector(pred.survivalRate);
}
void releaseActiveMemory
(
struct PAR_AD &par_ad,
struct FXP_AD &fxp_ad,
struct VAR_AD &var_ad,
struct INCV_AD &incv_ad,
struct PRED_AD &pred_ad
)
{
free_advector(par_ad.theta1);
free_advector(par_ad.theta2);
free_advector(par_ad.xi);
free_admatrix(par_ad.valfun);
free_advector(par_ad.g);
free_advector(fxp_ad.expDeltaIn);
free_admatrix(fxp_ad.expMu);
free_admatrix(fxp_ad.valuefunOut);
free_admatrix(var_ad.num);
free_advector(var_ad.value0);
free_advector(var_ad.Xtheta1);
free_advector(var_ad.e);
free_advector(var_ad.Ze);
free_advector(var_ad.PHIZe);
free_admatrix(var_ad.weightMat);
free_advector(incv_ad.w);
free_advector(incv_ad.wGrid);
free_advector(incv_ad.lambda);
free_advector(incv_ad.y);
free_advector(incv_ad.wy);
free_advector(incv_ad.wlambda);
free_admatrix(incv_ad.w_lag);
free_admatrix(incv_ad.w_lag_t);
free_admatrix(incv_ad.ww);
free_admatrix(incv_ad.ww_inv);
free_admatrix(pred_ad.ms);
free_advector(pred_ad.survivalRate);
} | 24.00135 | 90 | 0.607816 | [
"model"
] |
cecb72a65e1e7043ef778f5810c26a70a0c8ecd0 | 7,223 | cpp | C++ | dev/src/host_core/blockAllocator.cpp | FateForWindows/recompiler | a3f4ef5b0482c879826f97132eed9cd9273f8a59 | [
"MIT"
] | 1,473 | 2017-06-27T19:25:41.000Z | 2022-03-30T03:18:35.000Z | dev/src/host_core/blockAllocator.cpp | Grima04/recompiler | 29c71bc26092c45508866bd7e7a0bd8a6160a898 | [
"MIT"
] | 20 | 2017-07-27T22:21:24.000Z | 2021-05-13T15:23:00.000Z | dev/src/host_core/blockAllocator.cpp | Grima04/recompiler | 29c71bc26092c45508866bd7e7a0bd8a6160a898 | [
"MIT"
] | 113 | 2017-08-09T20:41:53.000Z | 2022-03-08T03:58:12.000Z | #include "build.h"
#include "blockAllocator.h"
//#pragma optimize("",off)
namespace utils
{
BlockAllocator::BlockAllocator()
: m_blockPool(NULL)
, m_numFreePages(0)
, m_freeBlocks(NULL)
{}
void BlockAllocator::Initialize(const uint32 numPages)
{
// create page tables
m_blockTable.resize(numPages*2 - 1);
m_pages.resize(numPages);
// create block pool
for (size_t i = 0; i<m_blockTable.size(); ++i)
{
BlockInfo* block = &m_blockTable[i];
block->m_firstPage = 0;
block->m_numPages = 0;
block->m_next = m_blockPool;
m_blockPool = block;
}
// reset
m_numFreePages = numPages;
// create first free page
m_freeBlocks = m_blockPool;
m_freeBlocks->m_firstPage = 0;
m_freeBlocks->m_numPages = numPages;
m_blockPool = m_blockPool->m_next;
m_freeBlocks->m_next = nullptr;
}
const bool BlockAllocator::IsAllocated(const uint32 firstPage, const uint32 numPages) const
{
const auto maxPage = m_pages.size();
for (uint32 i = 0; i < numPages; ++i)
{
auto pageIndex = firstPage + i;
if (pageIndex >= maxPage)
break;
const auto& info = m_pages[pageIndex];
if (info.IsAllocated())
return true;
}
return false;
}
const bool BlockAllocator::SetPageFlags(const uint32 page, const uint32 flags)
{
const auto maxPage = m_pages.size();
if (page >= maxPage)
return false;
auto& info = m_pages[page];
if (!info.IsAllocated())
return false;
info.m_flags = flags;
return true;
}
const bool BlockAllocator::GetPageFlags(const uint32 page, uint32& outFlags) const
{
const auto maxPage = m_pages.size();
if (page >= maxPage)
return false;
auto& info = m_pages[page];
if (!info.IsAllocated())
return false;
outFlags = info.m_flags;
return true;
}
const bool BlockAllocator::GetBasePage(const uint32 page, uint32& outBasePage) const
{
const auto maxPage = m_pages.size();
if (page >= maxPage)
return false;
auto& info = m_pages[page];
if (!info.IsAllocated())
return false;
outBasePage = info.m_basePage;
DEBUG_CHECK(m_pages[outBasePage].IsAllocated());
return true;
}
const bool BlockAllocator::GetNumAllocatedPages(const uint32 page, uint32& outNumAllocatedPages) const
{
const auto maxPage = m_pages.size();
if (page >= maxPage)
return false;
auto& info = m_pages[page];
if (!info.IsAllocated())
return false;
outNumAllocatedPages = info.m_numPages;
return true;
}
const uint32 BlockAllocator::GetTotalAllocatedPages() const
{
return (uint32)(m_pages.size() - m_numFreePages);
}
void BlockAllocator::GetAllocationBitMask(std::vector<bool>& outAllocatedPages) const
{
outAllocatedPages.resize(m_pages.size());
for (uint32 i = 0; i < m_pages.size(); ++i)
outAllocatedPages[i] = m_pages[i].IsAllocated();
}
const bool BlockAllocator::AllocateBlock(const uint32 numPages, const bool top, const uint32 initialFlags, uint32& outAllocatedFirstPage)
{
// to small to ever fit
if (numPages > m_numFreePages)
return false;
// find first fitting block
BlockInfo** prevFreeBlock = NULL;
BlockInfo* freeBlock = NULL;
{
BlockInfo** prevBlock = &m_freeBlocks;
BlockInfo* curBlock = m_freeBlocks;
while (curBlock != NULL)
{
if (curBlock->m_numPages >= numPages)
{
freeBlock = curBlock;
prevFreeBlock = prevBlock;
if (!top) break;
}
prevBlock = &curBlock->m_next;
curBlock = curBlock->m_next;
}
}
// nothing
if (!freeBlock)
return false;
// get the first allocated page
if (top)
outAllocatedFirstPage = freeBlock->m_firstPage + freeBlock->m_numPages - numPages;
else
outAllocatedFirstPage = freeBlock->m_firstPage;
// split block
const uint32 pagesLeft = freeBlock->m_numPages - numPages;
if (pagesLeft)
{
// adjust free block
if (top)
{
// free space is left at the beginning of the block
freeBlock->m_numPages -= numPages;
}
else
{
// free space is left at the end of the block
freeBlock->m_firstPage += numPages;
freeBlock->m_numPages -= numPages;
}
}
else
{
// unlink
DEBUG_CHECK(*prevFreeBlock == freeBlock);
*prevFreeBlock = freeBlock->m_next;
// add block to free pool
freeBlock->m_numPages = 0;
freeBlock->m_firstPage = 0;
freeBlock->m_next = m_blockPool;
m_blockPool = freeBlock;
}
// mark memory as allocated
for (uint32 i = 0; i < numPages; ++i)
{
const uint32 pageIndex = outAllocatedFirstPage + i;
auto& pageInfo = m_pages[pageIndex];
pageInfo.m_numPages = numPages;
pageInfo.m_basePage = outAllocatedFirstPage;
pageInfo.m_flags = initialFlags;
}
// allocated
m_numFreePages -= numPages;
return true;
}
const bool BlockAllocator::FreeBlock(const uint32 page)
{
const auto maxPage = m_pages.size();
if (page >= maxPage)
return false;
// check that the memory is allocated
const auto& pageInfo = m_pages[page];
if (!pageInfo.IsAllocated())
return false;
// get the range of pages to free
const auto firstPage = pageInfo.m_basePage;
const auto numPages = pageInfo.m_numPages;
// mark all pages as free
for (uint32 i = 0; i < numPages; ++i)
{
auto& pageInfo = m_pages[i];
pageInfo.m_flags = 0;
pageInfo.m_basePage = 0;
pageInfo.m_numPages = 0;
}
// allocate block
BlockInfo* freeBlock = m_blockPool;
DEBUG_CHECK(freeBlock != nullptr);
m_blockPool = freeBlock->m_next;
freeBlock->m_next = nullptr;
freeBlock->m_numPages = numPages;
freeBlock->m_firstPage = firstPage;
// page indices
const uint32 lastPageUsed = firstPage + numPages - 1;
const uint32 endPage = firstPage + numPages;
uint32 lastPageOfPrevBlock = 0;
// add into the free list
bool added = false;
BlockInfo** prevBlock = &m_freeBlocks;
BlockInfo* lastBlock = m_freeBlocks;
while (*prevBlock)
{
if (firstPage >= lastPageOfPrevBlock && lastPageUsed < (*prevBlock)->m_firstPage)
{
// link in list
freeBlock->m_next = *prevBlock;
*prevBlock = freeBlock;
added = true;
break;
}
lastPageOfPrevBlock = (*prevBlock)->m_firstPage + (*prevBlock)->m_numPages;
lastBlock = *prevBlock;
prevBlock = &(*prevBlock)->m_next;
}
// not added anywhere, add at the end
if (!added)
{
DEBUG_CHECK(lastBlock != nullptr);
DEBUG_CHECK(*prevBlock == nullptr);
DEBUG_CHECK(lastBlock != freeBlock);
DEBUG_CHECK(firstPage >= lastBlock->m_firstPage);
DEBUG_CHECK(lastBlock->m_next == nullptr);
lastBlock->m_next = freeBlock;
freeBlock->m_next = nullptr;
}
// update stats
m_numFreePages += numPages;
// merge free blocks that are close to each other
MergeFreeBlocks();
return true;
}
void BlockAllocator::MergeFreeBlocks()
{
BlockInfo* cur = m_freeBlocks;
while (cur)
{
BlockInfo* next = cur->m_next;
// try merge
if (next && (next->m_firstPage == (cur->m_firstPage + cur->m_numPages)))
{
// merge memory range
cur->m_numPages += next->m_numPages;
cur->m_next = next->m_next;
// return free block structure to pool
next->m_next = m_blockPool;
next->m_firstPage = 0;
next->m_numPages = 0;
m_blockPool = next;
continue;
}
// continue
cur = next;
}
}
} // utils | 22.713836 | 138 | 0.675204 | [
"vector"
] |
ced46144c7bd0a478088bd9d33672404d636ba4f | 2,897 | cpp | C++ | aws-cpp-sdk-greengrassv2/source/model/GetDeploymentResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-greengrassv2/source/model/GetDeploymentResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-greengrassv2/source/model/GetDeploymentResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/greengrassv2/model/GetDeploymentResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::GreengrassV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetDeploymentResult::GetDeploymentResult() :
m_deploymentStatus(DeploymentStatus::NOT_SET),
m_isLatestForTarget(false)
{
}
GetDeploymentResult::GetDeploymentResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_deploymentStatus(DeploymentStatus::NOT_SET),
m_isLatestForTarget(false)
{
*this = result;
}
GetDeploymentResult& GetDeploymentResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("targetArn"))
{
m_targetArn = jsonValue.GetString("targetArn");
}
if(jsonValue.ValueExists("revisionId"))
{
m_revisionId = jsonValue.GetString("revisionId");
}
if(jsonValue.ValueExists("deploymentId"))
{
m_deploymentId = jsonValue.GetString("deploymentId");
}
if(jsonValue.ValueExists("deploymentName"))
{
m_deploymentName = jsonValue.GetString("deploymentName");
}
if(jsonValue.ValueExists("deploymentStatus"))
{
m_deploymentStatus = DeploymentStatusMapper::GetDeploymentStatusForName(jsonValue.GetString("deploymentStatus"));
}
if(jsonValue.ValueExists("iotJobId"))
{
m_iotJobId = jsonValue.GetString("iotJobId");
}
if(jsonValue.ValueExists("iotJobArn"))
{
m_iotJobArn = jsonValue.GetString("iotJobArn");
}
if(jsonValue.ValueExists("components"))
{
Aws::Map<Aws::String, JsonView> componentsJsonMap = jsonValue.GetObject("components").GetAllObjects();
for(auto& componentsItem : componentsJsonMap)
{
m_components[componentsItem.first] = componentsItem.second.AsObject();
}
}
if(jsonValue.ValueExists("deploymentPolicies"))
{
m_deploymentPolicies = jsonValue.GetObject("deploymentPolicies");
}
if(jsonValue.ValueExists("iotJobConfiguration"))
{
m_iotJobConfiguration = jsonValue.GetObject("iotJobConfiguration");
}
if(jsonValue.ValueExists("creationTimestamp"))
{
m_creationTimestamp = jsonValue.GetDouble("creationTimestamp");
}
if(jsonValue.ValueExists("isLatestForTarget"))
{
m_isLatestForTarget = jsonValue.GetBool("isLatestForTarget");
}
if(jsonValue.ValueExists("tags"))
{
Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects();
for(auto& tagsItem : tagsJsonMap)
{
m_tags[tagsItem.first] = tagsItem.second.AsString();
}
}
return *this;
}
| 23.552846 | 117 | 0.728685 | [
"model"
] |
cedcef16c84d3918a2f8d5090837d70078f10d9d | 3,702 | cpp | C++ | RenderSystem/Cuda/rtCudaRenderSystem.cpp | CharlesCarley/Raytracer | 63f4926846195e45b3620aeea007094857a709d9 | [
"MIT"
] | null | null | null | RenderSystem/Cuda/rtCudaRenderSystem.cpp | CharlesCarley/Raytracer | 63f4926846195e45b3620aeea007094857a709d9 | [
"MIT"
] | null | null | null | RenderSystem/Cuda/rtCudaRenderSystem.cpp | CharlesCarley/Raytracer | 63f4926846195e45b3620aeea007094857a709d9 | [
"MIT"
] | null | null | null | /*
-------------------------------------------------------------------------------
Copyright (c) Charles Carley.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors 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 "RenderSystem/Cuda/rtCudaRenderSystem.h"
#include "RenderSystem/Cuda/rtCudaHostMath.h"
#include "RenderSystem/Cuda/rtCudaUtils.h"
#include "RenderSystem/rtCamera.h"
rtCudaRenderSystem::rtCudaRenderSystem() :
m_frameBuffer{nullptr, 0, 0, 0},
m_cudaTarget(nullptr)
{
}
rtCudaRenderSystem ::~rtCudaRenderSystem()
{
if (m_cudaTarget)
{
m_cudaTarget->pixels = nullptr;
rtCudaFreeTarget(m_cudaTarget);
}
rtCudaFreeFrameBuffer(&m_frameBuffer);
}
void rtCudaRenderSystem::initialize(rtScene* scene)
{
if (!m_dirty)
return;
if (!m_target)
{
printf("No target was specified.\n");
return;
}
if (m_cudaTarget)
{
m_cudaTarget->pixels = nullptr;
rtCudaFreeTarget(m_cudaTarget);
}
if (m_frameBuffer.memory != nullptr)
rtCudaFreeFrameBuffer(&m_frameBuffer);
const rtFrameBufferInfo& fbi = m_target->getFrameBufferInfo();
rtCudaAllocateFrameBuffer(&m_frameBuffer, fbi.maxSize, 512);
if (!m_frameBuffer.memory)
{
// cannot render
return;
}
m_cudaTarget = rtCudaAllocateTarget();
m_cudaTarget->dimensions = fbi.width * fbi.height;
m_cudaTarget->length = fbi.maxSize;
m_cudaTarget->width = fbi.width;
m_cudaTarget->height = fbi.height;
m_cudaTarget->pitch = fbi.pitch;
m_cudaTarget->pixels = (uint8_t*)m_frameBuffer.memory;
m_scene = scene;
if (!m_scene)
{
printf("Invalid supplied scene.\n");
return;
}
rtCameras& cameras = m_scene->getCameras();
if (cameras.empty())
{
printf("No cameras were found in the scene.\n");
return;
}
// Cache any persistent per frame variables before spiting into tiles.
// Any render method / sub method must be immutable.
m_camera = cameras.at(0);
rtSceneType* sc = m_scene->getPtr();
rtCameraType* ca = m_camera->getPtr();
updatePixelOffset();
ca->offset = {
m_iPixelOffset.x,
m_iPixelOffset.y,
m_iPixelOffset.z,
m_iPixelOffset.w,
};
sc->camera = ca;
sc->flags = m_mode;
m_dirty = false;
}
void rtCudaRenderSystem::render(rtScene* scene)
{
if (m_dirty)
initialize(scene);
if (m_dirty)
{
// cannot render
return;
}
SK_ASSERT(m_frameBuffer.memory);
SK_ASSERT(m_scene);
if (m_frameBuffer.memory)
{
m_scene->updateCaches();
rtCudaKernelMain(&m_frameBuffer, m_cudaTarget, m_scene->getPtr());
rtCudaSwapBuffers(m_target->getFrameBufferInfo().pixels, m_cudaTarget);
}
}
| 27.220588 | 79 | 0.633441 | [
"render"
] |
cedfae51f977265fc6312547ddef5cd5759e5faf | 198 | hpp | C++ | modules/python/src/Aquila/python/algorithm.hpp | dtmoodie/Acquilla | b395b7d1338221369f9b0b46c7abc20f7bc5e827 | [
"MIT"
] | null | null | null | modules/python/src/Aquila/python/algorithm.hpp | dtmoodie/Acquilla | b395b7d1338221369f9b0b46c7abc20f7bc5e827 | [
"MIT"
] | null | null | null | modules/python/src/Aquila/python/algorithm.hpp | dtmoodie/Acquilla | b395b7d1338221369f9b0b46c7abc20f7bc5e827 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
struct IObjectConstructor;
namespace aq
{
namespace python
{
void setupAlgorithmInterface();
void setupAlgorithmObjects(std::vector<IObjectConstructor*>& ctrs);
}
}
| 14.142857 | 67 | 0.787879 | [
"vector"
] |
ceec7683c65ddd34c26834d39625bc0176af7b49 | 4,522 | cpp | C++ | src/Ops/Select/SelectExtend.cpp | lsimic/AobaAPI | 5bb17a1055cd1621eebeb91844c2f8b4a3572cb8 | [
"MIT"
] | 9 | 2021-05-16T19:49:09.000Z | 2021-12-02T17:42:30.000Z | src/Ops/Select/SelectExtend.cpp | lsimic/AobaAPI | 5bb17a1055cd1621eebeb91844c2f8b4a3572cb8 | [
"MIT"
] | null | null | null | src/Ops/Select/SelectExtend.cpp | lsimic/AobaAPI | 5bb17a1055cd1621eebeb91844c2f8b4a3572cb8 | [
"MIT"
] | null | null | null | #include "AobaAPI/Ops/Select.hpp"
namespace Aoba {
namespace Ops {
const SelectResult SelectExtend(Core::Mesh* m, const std::vector<Core::Vert*>& verts,
const std::vector<Core::Edge*>& edges, const std::vector<Core::Face*>& faces, bool faceStep) {
// flags
const int32_t SELECTED_FACE = 1 << 0;
const int32_t SELECTED_VERT = 1 << 0;
const int32_t SELECTED_EDGE = 1 << 0;
std::vector<Core::Vert*> selectedVerts = std::vector<Core::Vert*>();
std::vector<Core::Edge*> selectedEdges = std::vector<Core::Edge*>();
std::vector<Core::Face*> selectedFaces = std::vector<Core::Face*>();
std::vector<Core::Vert*> newSelectedVerts = std::vector<Core::Vert*>();
std::vector<Core::Face*> adjecentFaces = std::vector<Core::Face*>();
// mark input verts as selected
for(Core::Vert* vert : verts) {
if(!(vert->flagsIntern & SELECTED_VERT)) {
vert->flagsIntern = SELECTED_VERT;
selectedVerts.push_back(vert);
}
}
// mark input edges and their verts as selected
for(Core::Edge* edge : edges) {
if(!(edge->flagsIntern & SELECTED_EDGE)) {
edge->flagsIntern = SELECTED_EDGE;
selectedEdges.push_back(edge);
for(Core::Vert* vert : edge->Verts()) {
if(!(vert->flagsIntern & SELECTED_VERT)) {
vert->flagsIntern = SELECTED_VERT;
selectedVerts.push_back(vert);
}
}
}
}
// mark input faces, their edges and verts as selected
for(Core::Face* face : faces) {
if(!(face->flagsIntern & SELECTED_FACE)) {
face->flagsIntern = SELECTED_FACE;
selectedFaces.push_back(face);
for(Core::Edge* edge : face->Edges()) {
edge->flagsIntern = SELECTED_EDGE;
selectedEdges.push_back(edge);
}
for(Core::Vert* vert : face->Verts()) {
if(!(vert->flagsIntern & SELECTED_VERT)) {
vert->flagsIntern = SELECTED_VERT;
selectedVerts.push_back(vert);
}
}
}
}
// step using edges
for(Core::Vert* vert : selectedVerts) {
for(Core::Edge* edge : vert->Edges()) {
if(!(edge->flagsIntern % SELECTED_EDGE)) {
edge->flagsIntern = SELECTED_EDGE;
selectedEdges.push_back(edge);
Core::Vert* other = edge->Other(vert);
if(!(other->flagsIntern & SELECTED_VERT)) {
other->flagsIntern = SELECTED_VERT;
newSelectedVerts.push_back(other);
}
}
}
for(Core::Face* face : vert->Faces()) {
if(!(face->flagsIntern % SELECTED_FACE)) {
adjecentFaces.push_back(face);
}
}
}
// concat new selected verts to selected verts
selectedVerts.insert(selectedVerts.end(), newSelectedVerts.begin(), newSelectedVerts.end());
// check adjecent faces
for(Core::Face* face : adjecentFaces) {
// if using face step, mark all edges and verts as selected
if(faceStep) {
for(Core::Edge* edge : face->Edges()) {
if(!(edge->flagsIntern & SELECTED_EDGE)) {
edge->flagsIntern = SELECTED_EDGE;
selectedEdges.push_back(edge);
}
}
for(Core::Vert* vert : face->Verts()) {
if(!(vert->flagsIntern & SELECTED_VERT)) {
vert->flagsIntern = SELECTED_VERT;
selectedVerts.push_back(vert);
}
}
} else {
bool selected = true;
for(Core::Edge* edge : face->Edges()) {
if(!(edge->flagsIntern & SELECTED_EDGE)) {
selected = false;
break;
}
}
if(selected) {
selectedFaces.push_back(face);
}
}
}
// clear flags, return
for(Core::Edge* edge : selectedEdges) {
edge->flagsIntern = 0;
}
for(Core::Face* face : selectedFaces) {
face->flagsIntern = 0;
}
for(Core::Vert* vert : selectedVerts) {
vert->flagsIntern = 0;
}
SelectResult result = SelectResult();
result.edges = selectedEdges;
result.verts = selectedVerts;
result.faces = selectedFaces;
return result;
}
} // namespace Ops
} // namespace Aoba | 34.257576 | 98 | 0.531844 | [
"mesh",
"vector"
] |
ceee9ac0898708fa754c16cba729ee85390824fe | 1,269 | cpp | C++ | src/audio/input.cpp | Dervish13/libmaolan | 4844ed1468c1938c0c3b64127a7dfd8a8fc6261f | [
"BSD-2-Clause"
] | null | null | null | src/audio/input.cpp | Dervish13/libmaolan | 4844ed1468c1938c0c3b64127a7dfd8a8fc6261f | [
"BSD-2-Clause"
] | null | null | null | src/audio/input.cpp | Dervish13/libmaolan | 4844ed1468c1938c0c3b64127a7dfd8a8fc6261f | [
"BSD-2-Clause"
] | null | null | null | #include <maolan/audio/input.h>
#include <maolan/config.h>
using namespace maolan::audio;
Input::Input() : IO(1, true)
{
_type = "Input";
connections.clear();
}
void Input::add(IO *to, size_t ch)
{
auto it = connections.emplace(connections.end());
it->target(to, ch);
}
void Input::fetch()
{
std::vector<Buffer> channels;
bool empty = true;
for (auto &connection : connections)
{
const auto element = connection.pull();
if (element != nullptr)
{
empty = false;
channels.push_back(element);
}
}
if (empty)
{
outputs[0] = nullptr;
}
else if (channels.size() == 1)
{
outputs[0] = channels[0];
}
else
{
const Buffer result = Buffer(new BufferData(Config::audioBufferSize));
for (size_t i = 0; i < Config::audioBufferSize; ++i)
{
float sum = 0;
for (auto channel : channels)
{
if (channel == nullptr)
{
continue;
}
if (channel->data[i] == 0.0)
{
continue;
}
sum += channel->data[i];
}
result->data[i] = sum;
}
outputs[0] = result;
}
}
size_t Input::channels() const { return outputs.size(); }
Buffer Input::pull() { return outputs[0]; }
void Input::process() {}
| 16.92 | 74 | 0.555556 | [
"vector"
] |
ceef775dc010281649206654a373b91decc84d7d | 2,617 | cpp | C++ | tst/operator_overloaded_class_test.cpp | liyinnbw/cpp_boilerplate | 868ebf7e8c6e2a7ffb0f1bf12643bd26ed6ed9cc | [
"MIT"
] | null | null | null | tst/operator_overloaded_class_test.cpp | liyinnbw/cpp_boilerplate | 868ebf7e8c6e2a7ffb0f1bf12643bd26ed6ed9cc | [
"MIT"
] | null | null | null | tst/operator_overloaded_class_test.cpp | liyinnbw/cpp_boilerplate | 868ebf7e8c6e2a7ffb0f1bf12643bd26ed6ed9cc | [
"MIT"
] | null | null | null | /*
Copyright: 2020 liyinnbw
author: liyinnbw
licence: MIT
*/
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
#include "gtest/gtest.h"
#include "operator_overload/operator_overloaded_class.h"
namespace cpp_boilerplate{
TEST(OperatorOverloadedClass, Comparators) {
OperatorOverloadedClass a(1,0);
OperatorOverloadedClass b(2,0);
OperatorOverloadedClass c(1,1);
OperatorOverloadedClass d(1,1);
EXPECT_EQ(c, d);
EXPECT_EQ(c == d, true);
EXPECT_EQ(c != d, false);
EXPECT_EQ(c <= d, true);
EXPECT_EQ(c >= d, true);
EXPECT_EQ(c < d, false);
EXPECT_EQ(c > d, false);
EXPECT_EQ(d == c, true);
EXPECT_EQ(d != c, false);
EXPECT_EQ(d <= c, true);
EXPECT_EQ(d >= c, true);
EXPECT_EQ(d < c, false);
EXPECT_EQ(d > c, false);
EXPECT_EQ(a == b, false);
EXPECT_EQ(a != b, true);
EXPECT_EQ(a <= b, true);
EXPECT_EQ(a >= b, false);
EXPECT_EQ(a < b, true);
EXPECT_EQ(a > b, false);
EXPECT_EQ(b == a, false);
EXPECT_EQ(b != a, true);
EXPECT_EQ(b <= a, false);
EXPECT_EQ(b >= a, true);
EXPECT_EQ(b < a, false);
EXPECT_EQ(b > a, true);
EXPECT_EQ(a == c, false);
EXPECT_EQ(a != c, true);
EXPECT_EQ(a <= c, true);
EXPECT_EQ(a >= c, false);
EXPECT_EQ(a < c, true);
EXPECT_EQ(a > c, false);
EXPECT_EQ(c == a, false);
EXPECT_EQ(c != a, true);
EXPECT_EQ(c <= a, false);
EXPECT_EQ(c >= a, true);
EXPECT_EQ(c < a, false);
EXPECT_EQ(c > a, true);
EXPECT_EQ(b == c, false);
EXPECT_EQ(b != c, true);
EXPECT_EQ(b <= c, false);
EXPECT_EQ(b >= c, true);
EXPECT_EQ(b < c, false);
EXPECT_EQ(b > c, true);
EXPECT_EQ(c == b, false);
EXPECT_EQ(c != b, true);
EXPECT_EQ(c <= b, true);
EXPECT_EQ(c >= b, false);
EXPECT_EQ(c < b, true);
EXPECT_EQ(c > b, false);
}
TEST(SimpleClass, Tuple) {
OperatorOverloadedClass a(1,0);
OperatorOverloadedClass b(2,0);
OperatorOverloadedClass c(1,1);
OperatorOverloadedClass d(1,1);
EXPECT_EQ(std::tie(a, c) < std::tie(a, b), true);
EXPECT_EQ(std::tie(b, a) < std::tie(b, c), true);
}
TEST(SimpleClass, Sort) {
std::vector<OperatorOverloadedClass> vec;
vec.emplace_back(1, 0);
vec.emplace_back(2, 0);
vec.emplace_back(1, 1);
vec.emplace_back(1, 1);
std::sort(vec.begin(), vec.end());
std::vector<OperatorOverloadedClass> vec_expected;
vec_expected.emplace_back(1, 0);
vec_expected.emplace_back(1, 1);
vec_expected.emplace_back(1, 1);
vec_expected.emplace_back(2, 0);
EXPECT_EQ(vec, vec_expected);
}
}
| 24.92381 | 56 | 0.60642 | [
"vector"
] |
ceefb4857c88eb45977994e9bf4cdffc7009e793 | 4,834 | cpp | C++ | src/xray/render/core/sources/res_rt.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/render/core/sources/res_rt.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/render/core/sources/res_rt.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 27.02.2009
// Author : Mykhailo Parfeniuk
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include <xray/render/core/device.h>
#include <xray/render/core/res_rt.h>
#include <xray/render/core/resource_manager.h>
namespace xray {
namespace render_dx10 {
u32 btw_lowest_bitmask( u32 x) {return x & ~( x-1);}
bool btw_is_pow2( u32 v) {return btw_lowest_bitmask( v) == v;}
res_rt::res_rt()
{
m_surface = NULL;
m_rt = NULL;
m_width = 0;
m_height = 0;
m_format = DXGI_FORMAT_UNKNOWN;
}
res_rt::~res_rt()
{
destroy();
}
void res_rt::_free() const
{
resource_manager::ref().release( const_cast<res_rt*>(this) );
}
void res_rt::create( LPCSTR name, u32 width, u32 height, DXGI_FORMAT format, enum_usage usage)
{
u32 sample_count = 1;
if( m_surface)
return;
R_ASSERT( device::ref().d3d_context() && name && name[0] && width && height);
m_order = timing::get_clocks();
// Check width-and-height of render target surface
if ( width > D3D_REQ_TEXTURE2D_U_OR_V_DIMENSION) return;
if ( height > D3D_REQ_TEXTURE2D_U_OR_V_DIMENSION) return;
// Select usage
if( usage == enum_usage_depth_stencil)
{
if ( DXGI_FORMAT_R24G8_TYPELESS != format
|| DXGI_FORMAT_D24_UNORM_S8_UINT != format
|| DXGI_FORMAT_D16_UNORM != format
// This is a hardware specific format need to check what formats can be used for modern hardware.
// || ( D3DFORMAT)MAKEFOURCC( 'D','F','2','4') != format
)
{
ASSERT(0, "The spedified format is not supported.");
return;
}
}
m_width = width;
m_height = height;
m_format = format;
m_usage = usage;
resource_manager::ref().evict(); // ??????
D3D_TEXTURE2D_DESC desc;
ZeroMemory( &desc, sizeof(desc) );
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = format;
desc.SampleDesc.Count = sample_count;
desc.Usage = D3D_USAGE_DEFAULT;
if( sample_count <= 1 )
desc.BindFlags = D3D_BIND_SHADER_RESOURCE | ((usage==enum_usage_depth_stencil) ? D3D_BIND_DEPTH_STENCIL : D3D_BIND_RENDER_TARGET);
else
{
desc.BindFlags = ((usage==enum_usage_depth_stencil) ? D3D_BIND_DEPTH_STENCIL : (D3D_BIND_SHADER_RESOURCE | D3D_BIND_RENDER_TARGET));
// if( RImplementation.o.dx10_msaa_opt )
// {
// desc.SampleDesc.Quality = UINT(D3D_STANDARD_MULTISAMPLE_PATTERN);
// }
}
#ifdef USE_DX11
if (HW.FeatureLevel>=D3D_FEATURE_LEVEL_11_0 && !bUseAsDepth && sample_count == 1 && useUAV )
desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
#endif
R_CHK( device::ref().d3d_device()->CreateTexture2D( &desc, NULL, &m_surface ) );
#ifdef DEBUG
LOG_INFO( "* created RT( %s), %dx%d", name, width, height);
#endif // DEBUG
if (usage == enum_usage_depth_stencil)
{
D3D_DEPTH_STENCIL_VIEW_DESC ViewDesc;
ZeroMemory( &ViewDesc, sizeof(ViewDesc) );
ViewDesc.Format = DXGI_FORMAT_UNKNOWN;
if( sample_count <= 1 )
{
ViewDesc.ViewDimension = D3D_DSV_DIMENSION_TEXTURE2D;
}
else
{
ViewDesc.ViewDimension = D3D_DSV_DIMENSION_TEXTURE2DMS;
ViewDesc.Texture2DMS.UnusedField_NothingToDefine = 0;
}
ViewDesc.Texture2D.MipSlice = 0;
switch (desc.Format)
{
case DXGI_FORMAT_R24G8_TYPELESS:
ViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
break;
case DXGI_FORMAT_R32_TYPELESS:
ViewDesc.Format = DXGI_FORMAT_D32_FLOAT;
break;
}
R_CHK( device::ref().d3d_device()->CreateDepthStencilView( m_surface, &ViewDesc, &m_zrt) );
}
else
R_CHK( device::ref().d3d_device()->CreateRenderTargetView( m_surface, 0, &m_rt ) );
#ifdef USE_DX11
if (HW.FeatureLevel>=D3D_FEATURE_LEVEL_11_0 && !bUseAsDepth && SampleCount == 1 && useUAV)
{
D3D11_UNORDERED_ACCESS_VIEW_DESC UAVDesc;
ZeroMemory( &UAVDesc, sizeof( D3D11_UNORDERED_ACCESS_VIEW_DESC ) );
UAVDesc.Format = dx10FMT;
UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
UAVDesc.Buffer.FirstElement = 0;
UAVDesc.Buffer.NumElements = dwWidth * dwHeight;
CHK_DX( HW.pDevice->CreateUnorderedAccessView( pSurface, &UAVDesc, &pUAView ) );
}
#endif
m_texture = resource_manager::ref().create_texture( name);
m_texture->set_hw_texture( m_surface);
}
void res_rt::destroy()
{
if ( m_texture.c_ptr())
{
m_texture->set_hw_texture( 0);
m_texture = NULL;
}
safe_release( m_rt);
log_ref_count( get_name(), m_surface);
safe_release( m_surface);
}
// void res_rt::reset_begin()
// {
// destroy();
// }
//
// void res_rt::reset_end()
// {
// create( get_name(), m_width, m_height, m_format, m_usage);
// }
}// namespace render
}// namespace xray
| 26.855556 | 135 | 0.659495 | [
"render"
] |
cef9b83f2aec0956ddbff731176c77013258e7b3 | 1,893 | cpp | C++ | src/game/skirmish/mapvalidator.cpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 3 | 2015-03-28T02:51:58.000Z | 2018-11-08T16:49:53.000Z | src/game/skirmish/mapvalidator.cpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 39 | 2015-05-18T08:29:16.000Z | 2020-07-18T21:17:44.000Z | src/game/skirmish/mapvalidator.cpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | null | null | null | #include "game/skirmish/mapvalidator.hpp"
#include <iostream>
#include "meta/metaclass.hpp"
#include "core/sid.hpp"
#include "engine/board.hpp"
#include "game/deploymentzone.hpp"
namespace qrw
{
MapValidator::MapValidator(Logger* logger)
: logger_(logger)
{
if(logger_ == nullptr)
logger_.reset(new Logger());
logger_->setPrefix("MapValidator");
}
MapValidator::~MapValidator()
{
}
bool MapValidator::validate(const std::vector<YAML::Node>& mapContent) const
{
if(mapContent.size() != 2)
{
logger_->logWarning("Map must contain exactly 2 yaml documents (description and content)");
return false;
}
if(!validateObjectsDocument(mapContent[1]))
return false;
return true;
}
bool MapValidator::validateObjectsDocument(const YAML::Node& objects) const
{
size_t boardCount = 0;
size_t deploymentZoneCount = 0;
for(auto& object : objects)
{
if(!object[MetaClass::TYPE_NAME_YAML_KEY])
{
logger_->logWarning("Object does not contain mandatory \"" + MetaClass::TYPE_NAME_YAML_KEY + "\" key");
return false;
}
SID type(object[MetaClass::TYPE_NAME_YAML_KEY].as<std::string>());
if(type == Board::typeName)
++boardCount;
else if(type == DeploymentZone::typeName)
++deploymentZoneCount;
else
{
logger_->logWarning("Object has invalid \"" + MetaClass::TYPE_NAME_YAML_KEY + "\": \"" + type.getStringId() + "\"");
return false;
}
}
if(boardCount != 1)
{
logger_->logWarning("Map must contain exactly one \"qrw::Board\"");
return false;
}
if(deploymentZoneCount < 2)
{
logger_->logWarning("Map must contain at least two \"qrw::DeploymentZone\"s");
return false;
}
return true;
}
} // namespace qrw
| 23.085366 | 128 | 0.614897 | [
"object",
"vector"
] |
cefac52ebc9f3709969c2d8174ca0fdcd174fb1f | 8,645 | hpp | C++ | src/Client/GUI2/Container.hpp | Marukyu/NecroEdit | 4b2380cc3417c6578476a213e05f4cbc846e5a77 | [
"MIT",
"Unlicense"
] | 13 | 2016-04-02T14:21:49.000Z | 2021-01-10T17:32:43.000Z | src/Client/GUI2/Container.hpp | Marukyu/NecroEdit | 4b2380cc3417c6578476a213e05f4cbc846e5a77 | [
"MIT",
"Unlicense"
] | 24 | 2016-04-02T12:08:39.000Z | 2021-01-27T01:21:58.000Z | src/Client/GUI2/Container.hpp | Marukyu/NecroEdit | 4b2380cc3417c6578476a213e05f4cbc846e5a77 | [
"MIT",
"Unlicense"
] | 6 | 2016-04-02T12:05:28.000Z | 2017-05-10T14:13:39.000Z | #ifndef GUI2_CONTAINER_HPP
#define GUI2_CONTAINER_HPP
#include "Client/GUI2/Widget.hpp"
#include "Client/GUI2/Internal/WidgetEvents.hpp"
#include <memory>
#include <unordered_map>
#include <iterator>
namespace gui2
{
class Interface;
/**
* a widget that can hold and manage other widgets.
*/
class Container : public Widget
{
struct WidgetInfo;
public:
/// factory function.
static Ptr<Container> make();
/// destructor.
~Container();
/// adds the specified widget to the container. overloaded by panels
/// for positioning parameters. calls onAdd().
void add(std::shared_ptr<Widget> widget);
/// removes the specified widget from the container. does nothing if
/// the widget is not within this container.
void remove(std::shared_ptr<Widget> widget);
/// returns true if the specified widget is within this container.
bool isContained(std::shared_ptr<const Widget> widget) const;
bool isContained(const Widget * widget) const;
/// sets/gets the currently focused widget. null pointer means no
/// focused widget.
void setFocusedWidget(std::shared_ptr<Widget> widget);
std::shared_ptr<Widget> getFocusedWidget() const;
/// checks if the specified widget or any of its focus-pass-through
/// parent widgets are focused.
bool isWidgetFocused(std::shared_ptr<const Widget> widget) const;
/// marks the specified widget's vertices for redrawing.
void invalidateWidgetVertices(std::shared_ptr<Widget> widget);
/// marks all widgets' vertices for redrawing.
void invalidateAllWidgetVertices();
/// sends the specified widget to the top/bottom of its z-position
/// group.
void sendWidgetToFront(std::shared_ptr<Widget> widget);
void sendWidgetToBack(std::shared_ptr<Widget> widget);
/// reinserts the widget to the correct z-position group.
void updateWidgetZPosition(std::shared_ptr<Widget> widget);
/// returns true if the widget supports returning its vertices as
/// consistently textured triangles, or false if the special render()
/// function should be called to draw the widget instead. (slower)
virtual bool isVertexRenderable() const;
/// returns the transformation this container applies to its widgets.
virtual sf::Transform getContainerTransform() const;
/// returns the inner bounding box for widget positioning.
virtual sf::FloatRect getContainerBoundingBox() const;
/// returns the inner bounding box for restricting widget rendering.
virtual sf::FloatRect getContainerClipBox() const;
/// returns true if this container clips widgets.
virtual bool isClippingWidgets() const;
/// returns true if this container manages widget focus.
virtual bool isManagingFocus() const;
/// automatically makes the specified observer monitor all current
/// and future widgets in this container.
void addWidgetObserver(Observer * observer);
/// un-observes all widgets from the specified observer. must be
/// called before the specified observer object is destroyed.
void removeWidgetObserver(Observer * observer);
/// returns true if the specified observer is already auto-monitoring
/// this container's widgets.
bool isWidgetObserver(Observer * observer) const;
/// possible notification types for observers.
enum NotifyMessagesContainer
{
NotifyContainerBox = NotifyCount,
NotifyContainerTransform,
NotifyCountContainer
};
/// iterator over widgets.
class Iterator
{
public:
typedef std::random_access_iterator_tag iterator_category;
typedef std::shared_ptr<Widget> value_type;
typedef std::ptrdiff_t difference_type;
typedef std::shared_ptr<Widget> * pointer;
typedef std::shared_ptr<Widget> & reference;
inline bool operator==(const Iterator & i2) const
{ return myIt != i2.myIt; }
inline bool operator!=(const Iterator & i2) const
{ return myIt != i2.myIt; }
inline const Iterator & operator++()
{ ++myIt; return *this;}
inline Iterator operator++(int)
{ Iterator old(myIt++); return old;}
inline const Iterator & operator--()
{ --myIt; return *this;}
inline Iterator operator--(int)
{ Iterator old(myIt--); return old;}
inline void operator+=(difference_type b)
{ myIt += b; }
inline void operator-=(difference_type b)
{ myIt -= b; }
inline Iterator operator+(difference_type b)
{ return Iterator(myIt + b); }
inline Iterator operator-(difference_type b)
{ return Iterator(myIt - b); }
inline difference_type operator-(const Iterator & i2) const
{ return myIt - i2.myIt; }
inline value_type operator*() const
{ return myIt->widget; }
inline value_type operator->() const
{ return myIt->widget; }
private:
inline Iterator(std::vector<WidgetInfo>::const_iterator it) :
myIt(it)
{}
std::vector<WidgetInfo>::const_iterator myIt;
friend class Container;
};
inline Iterator begin() const
{
return Iterator(myWidgets.begin());
}
inline Iterator end() const
{
return Iterator(myWidgets.end());
}
protected:
/// initializes the container. must be called by subclass init() if overridden.
virtual void init();
/// adds a widget to the container without invoking onAdd(). returns true if
/// widget was added successfully, false otherwise.
bool doAdd(std::shared_ptr<Widget> widget);
// called when the application's fonts are updated.
virtual void onUpdateFonts();
// called whenever the container's parent is changed.
virtual void onParent(std::shared_ptr<Container> oldParent);
// called on resize, updates all widget vertices and notifies for container
// box change.
virtual void onResize();
private:
// invoked when add() is called.
virtual void onAdd(std::shared_ptr<Widget> widget);
// invoked when remove() is called.
virtual void onRemove(std::shared_ptr<Widget> widget);
// overridable processing function. called by onProcess() after processing
// this container's widgets, but before updating their vertices.
virtual void onProcessContainer(WidgetEvents & events);
// renders the container. TODO: description and stuff.
virtual void onDraw(sf::RenderTarget & target, sf::RenderStates states) const;
// adds vertices to the container's vertex cache with untransformed vertices.
// prepend/append determine whether the vertices will be inserted before or
// after the vertices of the contained widgets.
// do NOT call clearVertices() within these functions.
virtual void onUpdateVertexCachePrepend();
virtual void onUpdateVertexCacheAppend();
// builds a vertex cache for this container's vertex-renderable widgets.
void onUpdateVertexCache();
// prevents unnecessary vertex cache updates on mouse actions.
virtual void onMouseOver();
virtual void onMouseAway();
virtual void onMouseDown(sf::Vector2f pos, Input button);
virtual void onMouseUp(sf::Vector2f pos, Input button);
// processes this widget. subclasses should override onProcessContainer().
void onProcess(const WidgetEvents & events);
// called by getParentInterface() on unparented widgets.
// returns the parent interface for root containers.
virtual std::shared_ptr<Interface> onGetParentInterface() const;
// returns the parent interface's font.
//virtual std::shared_ptr<const btx::Font> onGetFont(int index) const;
// constructs a container linked to an interface.
void setParentInterface(std::shared_ptr<Interface> interface);
// moves the widget at the specified index to the destination index,
// updating the vertex cache and widget index map correctly.
void moveWidget(std::size_t sourcePos, std::size_t destPos);
void debug() const;
struct WidgetInfo
{
WidgetInfo(std::shared_ptr<Widget> widget) :
widget(widget),
cachedVertexCount(0),
verticesInvalid(true)
{}
std::shared_ptr<Widget> widget;
std::size_t cachedVertexCount;
bool verticesInvalid;
};
// a vector holding this container's widgets.
std::vector<WidgetInfo> myWidgets;
// maps each widget pointer to its index in the widget vector.
std::map<std::weak_ptr<const Widget>, std::size_t, std::owner_less<std::weak_ptr<const Widget> > > myWidgetIndexMap;
// true if all widgets in this container are vertex-renderable.
bool myIsVertexRenderable;
// true if all widgets' vertices are invalid.
bool myAllVerticesInvalid;
// number of vertices before/after the widget vertices.
std::size_t myVertexCountPrepend, myVertexCountAppend;
// a pointer to this container's parent interface.
std::weak_ptr<Interface> myParentInterface;
// a pointer to the currently focused widget.
std::weak_ptr<Widget> myFocusedWidget;
// a list of pointers to current widget observers.
std::set<Observer*> myWidgetObservers;
friend class Interface;
friend class Application;
};
} // namespace gui2
#endif
| 30.121951 | 117 | 0.748525 | [
"render",
"object",
"vector",
"transform"
] |
cefaf98eaf1b993695dd9305d8094837f31d47ce | 17,704 | cpp | C++ | lib/Query.cpp | renjipanicker/noql | 355b4b04de412328d3879891c47dfdbab0fb33df | [
"MIT"
] | 6 | 2020-03-10T01:32:54.000Z | 2020-04-09T13:52:28.000Z | lib/Query.cpp | renjipanicker/noql | 355b4b04de412328d3879891c47dfdbab0fb33df | [
"MIT"
] | null | null | null | lib/Query.cpp | renjipanicker/noql | 355b4b04de412328d3879891c47dfdbab0fb33df | [
"MIT"
] | null | null | null | #include "pch.hpp"
#include "noql/Query.hpp"
#include "ExprEval.hpp"
#include "Logger.hpp"
namespace {
struct EnvBlock {
std::map<std::string, ::noq::Value> vlist;
inline void str(std::ostream& os) const {
os << "{";
std::string sep;
for(auto& v : vlist) {
os << sep << v.first << ":" << v.second;
sep = ",";
}
os << "}";
}
inline friend std::ostream& operator<<(std::ostream& os, const EnvBlock& c) {
c.str(os);
return os;
}
};
struct ExprEngine {
const noq::Value& exprList_;
const EnvBlock& env_;
std::vector<noq::Value> stack_;
inline ExprEngine(const noq::Value& exprList, const EnvBlock& env) : exprList_(exprList), env_(env) {}
inline noq::Value doOp(const std::string& op, const noq::Value& lhs, const noq::Value& rhs) {
if(op == "+") return (lhs + rhs);
if(op == "-") return (lhs - rhs);
if(op == "*") return (lhs * rhs);
if(op == "/") return (lhs / rhs);
if(op == "%") return (lhs % rhs);
if(op == "<") return (lhs < rhs);
if(op == ">") return (lhs > rhs);
if(op == "<=") return (lhs <= rhs);
if(op == ">=") return (lhs >= rhs);
if(op == "==") return (lhs == rhs);
if(op == "!=") return (lhs != rhs);
throw noq::Exception("unknown operator:" + op);
}
inline noq::Value process() {
for(auto& exprx : exprList_.getArray()){
noq::Logger().trace("exprx:{0}", exprx);
auto& expr = exprx.getObject();
auto xit = expr.find("type");
auto xite = expr.end();
if(xit == xite) {
continue;
}
auto type = (noq::ExprType)xit->second.getInteger();
switch(type){
case noq::ExprType::Operator1:
assert(false);
break;
case noq::ExprType::Operator2:
if((xit = expr.find("op")) != xite){
auto& op = xit->second.getString();
auto rhs = stack_.back();
stack_.pop_back();
auto lhs = stack_.back();
stack_.pop_back();
auto val = doOp(op, lhs, rhs);
stack_.push_back(val);
}
break;
case noq::ExprType::VariableRef:
if((xit = expr.find("ref")) != xite){
auto& vref = xit->second.getString();
auto vit = env_.vlist.find(vref);
if(vit == env_.vlist.end()){
stack_.push_back(noq::Value());
break;
}
auto val = vit->second;
stack_.push_back(val);
}
break;
case noq::ExprType::Value:
if((xit = expr.find("val")) != xite){
auto& val = xit->second;
stack_.push_back(val);
}
break;
default:
break;
}
for(auto& s : stack_){
noq::Logger().trace("-si:{0}", s);
}
}
noq::Value val = stack_.back();
return val;
}
};
struct QueryEngine {
const noq::Query& query_;
const noq::Connection& conn_;
struct HeadStackItem {
const noq::Rule* rule;
inline void addResult(const noq::Function& res) {
for(auto& r : resl_){
if(r.compare(res) == 0){
return;
}
}
resl_.push_back(res);
}
inline auto& resl() const {
return resl_;
}
inline HeadStackItem(std::vector<noq::Function>& s) : rule(nullptr), resl_(s) {}
private:
std::vector<noq::Function>& resl_;
};
std::vector<std::unique_ptr<HeadStackItem>> headStack_;
struct StackGuard {
inline StackGuard(std::vector<std::unique_ptr<HeadStackItem>>& stack, std::vector<noq::Function>& resl) : stack_(stack) {
stack_.push_back(std::make_unique<HeadStackItem>(resl));
}
inline ~StackGuard() {
stack_.pop_back();
}
inline auto& resl() {
return stack_.back()->resl();
}
private:
std::vector<std::unique_ptr<HeadStackItem>>& stack_;
};
struct RuleGuard {
inline RuleGuard(std::vector<std::unique_ptr<HeadStackItem>>& stack, const noq::Rule& rule) : stack_(stack) {
assert(stack_.size() > 0);
assert(stack_.back()->rule == nullptr);
stack_.back()->rule = &rule;
}
inline ~RuleGuard(){
assert(stack_.size() > 0);
stack_.back()->rule = nullptr;
}
private:
std::vector<std::unique_ptr<HeadStackItem>>& stack_;
};
inline bool isRecursive(const noq::Rule& rule) const {
for(auto& si : headStack_) {
if(si->rule == &rule){
return true;
}
}
return false;
}
inline auto convertValToArray(const noq::Value& val) const {
std::vector<noq::Value> valList;
if(val.isArray()){
auto& arr = val.getArray();
for(auto& v : arr){
valList.push_back(v);
}
}else{
valList.push_back(val);
}
return valList;
}
inline EnvBlock scatter(const noq::Function& from, const noq::Function& to, const EnvBlock& senv) const {
assert(from.arity() == to.arity());
EnvBlock env = senv;
auto fit = from.parameterList().begin();
auto fite = from.parameterList().end();
auto tit = to.parameterList().begin();
auto tite = to.parameterList().end();
while((fit != fite) && (tit != tite)){
if((fit->type() == noq::Parameter::Type::Value) && (tit->type() == noq::Parameter::Type::Variable)){
env.vlist.emplace(tit->value().getString(), fit->value());
}
++fit;
++tit;
}
noq::Logger().trace("{0}:scatter:env:{1}", headStack_.size(), env);
return env;
}
inline noq::Function gather(const noq::Function& from, const EnvBlock& env, const noq::Function::Type& type) const {
auto fit = from.parameterList().begin();
auto fite = from.parameterList().end();
std::vector<noq::Parameter> parameterList;
noq::Logger().trace("{0}:gather:env:{1}", headStack_.size(), env);
while(fit != fite){
decltype(EnvBlock::vlist)::const_iterator eit;
if((fit->type() == noq::Parameter::Type::Variable) && ((eit = env.vlist.find(fit->value().getString())) != env.vlist.end())){
parameterList.push_back(noq::Parameter(noq::Parameter::Type::Value, noq::ReferenceType::Any, eit->second));
}else{
parameterList.push_back(*fit);
}
++fit;
}
noq::Function to(type, from.ns(), from.name(), parameterList);
noq::Logger().trace("{0}:gather:to:{1}", headStack_.size(), to);
return to;
}
struct CacheItem {
std::vector<noq::Function> flist;
};
std::map<noq::Function, std::unique_ptr<CacheItem>> cache_;
inline const auto& processQuery(const noq::Function& qry) {
auto cit = cache_.find(qry);
if(cit == cache_.end()){
cache_[qry] = std::make_unique<CacheItem>();
cit = cache_.find(qry);
StackGuard sg(headStack_, cit->second->flist);
processHead(qry);
}
assert(cit != cache_.end());
return cit->second->flist;
}
void processBody(const std::vector<noq::Function>::const_iterator& it, const EnvBlock& env) {
auto& part = *it;
noq::Logger().trace("{0}:processBody:part[{1}], env:[{2}]", headStack_.size(), part, env);
if(part.type() == noq::Function::Type::EndRule){
auto res = gather(part, env, noq::Function::Type::Regular);
noq::Logger().trace("{0}:endBody[{1}]:[{2}]", headStack_.size(), res, env);
headStack_.back()->addResult(res);
return;
}
if((part.type() == noq::Function::Type::Assign) || (part.type() == noq::Function::Type::Logical)) {
noq::Logger().trace("{0}:ExprEval:qry:[{1}]", headStack_.size(), part.parameterList().at(0).value());
ExprEngine ee(part.parameterList().at(0).value(), env);
auto res = ee.process();
noq::Logger().trace("{0}:ExprEval:qry:[{1}], res:[{2}]", headStack_.size(), part.parameterList().at(0).value(), res);
if(res.isNull()){
return;
}
auto nenv = env;
if(part.type() == noq::Function::Type::Assign){
assert(part.parameterList().size() == 2);
auto& var = part.parameterList().at(1);
nenv.vlist[var.value().getString()] = res;
}else{
if((!res.isBoolean()) || (!res.getBoolean())){
return;
}
}
processBody((it+1), nenv);
return;
}
auto nqry = gather(part, env, part.type());
noq::Logger().trace("{0}:processBody:part[{1}], env:[{2}], nqry:[{3}]", headStack_.size(), part, env, nqry);
auto& nresl = processQuery(nqry);
for(auto& res : nresl){
EnvBlock nenv = scatter(res, part, env);
noq::Logger().trace("{0}:processBody:res[{1}], part:[{2}], nenv:[{3}]", headStack_.size(), res, part, nenv);
processBody((it+1), nenv);
}
}
void processHead(const noq::Function& qry) {
noq::Logger().info("{0}:processHead:part[{1}]", headStack_.size(), qry);
if(conn_.hasRuleList(qry.ns())){
auto& ruleList = conn_.ruleList(qry.ns());
for(auto& rule : ruleList){
noq::Logger().trace("{0}:processHead:check:rule:[{1}]", headStack_.size(), rule);
assert(rule.head().type() == noq::Function::Type::BeginRule);
if(rule.head().name() != qry.name()){
noq::Logger().trace("{0}:processHead:skip(name mismatch):[{1}]", headStack_.size(), rule);
continue;
}
if(rule.head().arity() != qry.arity()){
noq::Logger().trace("{0}:processHead:skip(arity mismatch):[{1}]", headStack_.size(), rule);
continue;
}
if(isRecursive(rule)){
noq::Logger().trace("{0}:processHead:skip(recursive):[{1}]", headStack_.size(), rule);
continue;
}
noq::Logger().info("{0}:processHead:execute:[{1}]", headStack_.size(), rule);
EnvBlock nenv = scatter(qry, rule.head(), EnvBlock());
RuleGuard rg(headStack_, rule);
processBody(rule.body().begin(), nenv);
}
}
if(qry.arity() == 1) {
noq::Logger().trace("{0}:processHead:native-call-1:[{1}]", headStack_.size(), qry);
auto& key = qry.name();
auto& p0 = qry.parameterList().at(0);
// KeyVal == ValVal or KeyVal == ValVar
auto valList = conn_.queryValueByKey(key);
noq::Logger().trace("{0}:processHead:native-call-1:[{1}], valList:[{2}] (ValValVal or ValValVar)", headStack_.size(), qry, valList.size());
for(auto& vali : valList){
auto avalList = convertValToArray(vali);
for(auto& val : avalList){
std::vector<noq::Parameter> parameterList;
parameterList.push_back(noq::Parameter(noq::Parameter::Type::Value, noq::ReferenceType::Any, val));
auto fn = noq::Function(qry.type(), qry.ns(), qry.name(), parameterList);
noq::Logger().trace("{0}:processHead:native-call-1:qry:[{1}], res:[{2}], fn:[{3}] *********", headStack_.size(), qry, val, fn);
headStack_.back()->addResult(fn);
}
}
noq::Logger().trace("{0}:processHead:native-call-1-done:qry:[{1}], resl:[{2}]", headStack_.size(), qry, headStack_.back()->resl().size());
}else if(qry.arity() == 2) {
noq::Logger().trace("{0}:processHead:native-call:[{1}]", headStack_.size(), qry);
auto& key = qry.name();
auto& p0 = qry.parameterList().at(0);
auto& p1 = qry.parameterList().at(1);
if(p0.type() == noq::Parameter::Type::Value) {
// ObjKeyVal == ValValVal or ObjKeyVal == ValValVar
auto valList = conn_.queryValueByObjectKey(p0.value(), key);
noq::Logger().trace("{0}:processHead:native-call:[{1}], valList:[{2}] (ValValVal or ValValVar)", headStack_.size(), qry, valList.size());
for(auto& vali : valList){
auto avalList = convertValToArray(vali);
for(auto& val : avalList){
std::vector<noq::Parameter> parameterList;
parameterList.push_back(p0);
parameterList.push_back(noq::Parameter(noq::Parameter::Type::Value, noq::ReferenceType::Any, val));
auto fn = noq::Function(qry.type(), qry.ns(), qry.name(), parameterList);
noq::Logger().trace("{0}:processHead:native-call1:qry:[{1}], res:[{2}], fn:[{3}] *********", headStack_.size(), qry, val, fn);
headStack_.back()->addResult(fn);
}
}
}else if(p1.type() == noq::Parameter::Type::Value) {
// ObjKeyVal == VarValVal
auto valList = conn_.queryObjectByKeyValue(key, p1.value());
noq::Logger().trace("{0}:processHead:native-call:[{1}], valList:[{2}] (VarValVal)", headStack_.size(), qry, valList.size());
for(auto& vali : valList){
auto avalList = convertValToArray(vali);
for(auto& val : avalList){
std::vector<noq::Parameter> parameterList;
parameterList.push_back(noq::Parameter(noq::Parameter::Type::Value, noq::ReferenceType::Any, val));
parameterList.push_back(p1);
auto res = noq::Function(qry.type(), qry.ns(), qry.name(), parameterList);
noq::Logger().trace("{0}:processHead:native-call2:qry:[{1}], res:[{2}], fn:[{3}] ***********", headStack_.size(), qry, val, res);
headStack_.back()->addResult(res);
}
}
}
noq::Logger().trace("{0}:processHead:native-call-done:qry:[{1}], resl:[{2}]", headStack_.size(), qry, headStack_.back()->resl().size());
}
}
void process(const noq::Function& qry, std::vector<noq::Function>& resl) {
QueryEngine::StackGuard sg(headStack_, resl);
return processHead(qry);
}
inline QueryEngine(const noq::Query& query, const noq::Connection& conn) : query_(query), conn_(conn) {}
};
}
inline void noq::Query::setQuery(const noq::Function& query) {
query_ = std::make_unique<Function>(query);
parameterList_ = query_->parameterList();
for(size_t i = 0; i < parameterList_.size(); ++i){
auto& parameter = parameterList_.at(i);
if(parameter.type() == noq::Parameter::Type::Variable){
variableMap_[parameter.value().getString()] = i;
}
}
}
void noq::Query::compile(const std::string& str) {
Module module;
module.loadString(str);
auto& qry = module.getQuery();
setQuery(qry);
}
void noq::Query::exec(const noq::Connection& conn) {
assert(query_);
resl_.clear();
auto nquery = Function(query_->type(), query_->ns(), query_->name(), parameterList_);
QueryEngine qe(*this, conn);
qe.process(nquery, resl_);
}
void noq::Query::exec(const std::string& str, const noq::Connection& conn) {
compile(str);
exec(conn);
}
void noq::Query::exec(const noq::Function& qry, const noq::Connection& conn) {
setQuery(qry);
exec(conn);
}
| 42.557692 | 157 | 0.46916 | [
"vector"
] |
cefd79eedc9c426cc218ac0639e42ffe6c11d23d | 11,348 | cpp | C++ | code/engine.vc2008/xrRender/xrRender/ModelPool.cpp | porames25/xray-oxygen | 1f3f46a7a1ffc2be1de04a1ec665862127894ef7 | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrRender/xrRender/ModelPool.cpp | porames25/xray-oxygen | 1f3f46a7a1ffc2be1de04a1ec665862127894ef7 | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrRender/xrRender/ModelPool.cpp | porames25/xray-oxygen | 1f3f46a7a1ffc2be1de04a1ec665862127894ef7 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#pragma hdrstop
#include "ModelPool.h"
#include "../../xrEngine/IGame_Persistent.h"
#include "../../xrEngine/fmesh.h"
#include "fhierrarhyvisual.h"
#include "SkeletonAnimated.h"
#include "fvisual.h"
#include "fprogressive.h"
#include "fskinned.h"
#include "flod.h"
#include "ftreevisual.h"
#include "ParticleGroup.h"
#include "ParticleEffect.h"
dxRender_Visual* CModelPool::Instance_Create(u32 type)
{
dxRender_Visual *V = NULL;
// Check types
switch (type) {
case MT_NORMAL: // our base visual
V = xr_new<Fvisual> ();
break;
case MT_HIERRARHY:
V = xr_new<FHierrarhyVisual> ();
break;
case MT_PROGRESSIVE: // dynamic-resolution visual
V = xr_new<FProgressive> ();
break;
case MT_SKELETON_ANIM:
V = xr_new<CKinematicsAnimated> ();
break;
case MT_SKELETON_RIGID:
V = xr_new<CKinematics> ();
break;
case MT_SKELETON_GEOMDEF_PM:
V = xr_new<CSkeletonX_PM> ();
break;
case MT_SKELETON_GEOMDEF_ST:
V = xr_new<CSkeletonX_ST> ();
break;
case MT_PARTICLE_EFFECT:
V = xr_new<PS::CParticleEffect> ();
break;
case MT_PARTICLE_GROUP:
V = xr_new<PS::CParticleGroup> ();
break;
#ifndef _EDITOR
case MT_LOD:
V = xr_new<FLOD> ();
break;
case MT_TREE_ST:
V = xr_new<FTreeVisual_ST> ();
break;
case MT_TREE_PM:
V = xr_new<FTreeVisual_PM> ();
break;
#endif
default:
FATAL ("Unknown visual type");
break;
}
R_ASSERT (V);
V->Type = type;
return V;
}
dxRender_Visual* CModelPool::Instance_Duplicate (dxRender_Visual* V)
{
R_ASSERT(V);
dxRender_Visual* N = Instance_Create(V->Type);
N->Copy (V);
N->Spawn ();
// inc ref counter
for (xr_vector<ModelDef>::iterator I=Models.begin(); I!=Models.end(); I++)
if (I->model==V)
{
I->refs++;
break;
}
return N;
}
dxRender_Visual* CModelPool::TryLoadObject(const char* N)
{
return nullptr;
}
dxRender_Visual* CModelPool::TryLoadOgf(const char* N)
{
string_path fn;
string_path name;
// Add default ext if no ext at all
if (!strext(N))
strconcat(sizeof(name), name, N, ".ogf");
else
strcpy_s(name, sizeof(name), N);
// Load data from MESHES or LEVEL
if (!FS.exist(N)) {
if (!FS.exist(fn, "$level$", name) && !FS.exist(fn, "$game_meshes$", name))
return nullptr;
}
else
strcpy_s(fn, N);
// Actual loading
#ifdef DEBUG
if (bLogging) Msg("- Uncached model loading: %s", fn);
#endif // DEBUG
IReader* data = FS.r_open(fn);
ogf_header H;
data->r_chunk_safe(OGF_HEADER, &H, sizeof(H));
dxRender_Visual* V = Instance_Create(H.type);
V->Load(N, data, 0);
FS.r_close(data);
return V;
}
dxRender_Visual* CModelPool::Instance_Load (const char* N, BOOL allow_register)
{
dxRender_Visual* V = TryLoadOgf(N);
if (!V)
Debug.fatal(DEBUG_INFO, "Can't find model file '%s'.", N);
g_pGamePersistent->RegisterModel(V);
// Registration
if (allow_register) Instance_Register(N, V);
return V;
}
dxRender_Visual* CModelPool::Instance_Load(LPCSTR name, IReader* data, BOOL allow_register)
{
dxRender_Visual *V;
ogf_header H;
data->r_chunk_safe (OGF_HEADER,&H,sizeof(H));
V = Instance_Create (H.type);
V->Load (name,data,0);
// Registration
if (allow_register) Instance_Register(name,V);
return V;
}
void CModelPool::Instance_Register(LPCSTR N, dxRender_Visual* V)
{
// Registration
ModelDef M;
M.name = N;
M.model = V;
Models.push_back (M);
}
void CModelPool::Destroy()
{
// Pool
Pool.clear ();
// Registry
while(!Registry.empty()){
REGISTRY_IT it = Registry.begin();
dxRender_Visual* V=(dxRender_Visual*)it->first;
#ifdef DEBUG
Msg ("ModelPool: Destroy object: '%s'",*V->dbg_name);
#endif
DeleteInternal (V,TRUE);
}
// Base/Reference
xr_vector<ModelDef>::iterator I = Models.begin();
xr_vector<ModelDef>::iterator E = Models.end();
for (; I!=E; I++)
{
I->model->Release();
xr_delete(I->model);
}
Models.clear();
// cleanup motions container
g_pMotionsContainer->clean(false);
}
CModelPool::CModelPool()
{
bLogging = TRUE;
bForceDiscard = FALSE;
bAllowChildrenDuplicate = TRUE;
g_pMotionsContainer = xr_new<motions_container>();
}
CModelPool::~CModelPool()
{
Destroy ();
xr_delete (g_pMotionsContainer);
}
dxRender_Visual* CModelPool::Instance_Find(LPCSTR N)
{
dxRender_Visual* Model=nullptr;
xr_vector<ModelDef>::iterator I;
for (I=Models.begin(); I!=Models.end(); I++)
if (I->name[0]&&(0==xr_strcmp(*I->name,N)))
{
Model = I->model;
break;
}
return Model;
}
dxRender_Visual* CModelPool::Create(const char* name, IReader* data)
{
string_path low_name;
xr_strcpy(low_name, name); strlwr(low_name);
if (strext(low_name)) *strext(low_name) = 0;
// 0. Search POOL
POOL_IT it = Pool.find(low_name);
if (it != Pool.end())
{
// 1. Instance found
dxRender_Visual* Model = it->second;
Model->Spawn();
mtPeref.Enter();
Pool.erase(it);
mtPeref.Leave();
return Model;
}
else
{
// 1. Search for already loaded model (reference, base model)
dxRender_Visual* Base = Instance_Find(low_name);
mtPeref.Enter();
if (!Base)
{
// 2. If not found
bAllowChildrenDuplicate = FALSE;
if (data) Base = Instance_Load(low_name, data, TRUE);
else Base = Instance_Load(low_name, TRUE);
bAllowChildrenDuplicate = TRUE;
}
// 3. If found - return (cloned) reference
dxRender_Visual* Model = Instance_Duplicate(Base);
Registry.insert(std::make_pair(Model, low_name));
mtPeref.Leave();
return Model;
}
}
dxRender_Visual* CModelPool::CreateChild(LPCSTR name, IReader* data)
{
string256 low_name; VERIFY (xr_strlen(name)<256);
xr_strcpy(low_name,name); strlwr (low_name);
if (strext(low_name)) *strext (low_name) = 0;
// 1. Search for already loaded model
dxRender_Visual* Base = Instance_Find(low_name);
if(0==Base)
{
if (data) Base = Instance_Load (low_name,data,FALSE);
else Base = Instance_Load (low_name,FALSE);
}
dxRender_Visual* Model = bAllowChildrenDuplicate?Instance_Duplicate(Base):Base;
return Model;
}
extern BOOL ENGINE_API g_bRendering;
void CModelPool::DeleteInternal (dxRender_Visual* &V, BOOL bDiscard)
{
VERIFY (!g_bRendering);
if (!V) return;
V->Depart ();
if (bDiscard||bForceDiscard){
Discard (V, TRUE);
}else{
//
REGISTRY_IT it = Registry.find (V);
if (it!=Registry.end())
{
// Registry entry found - move it to pool
Pool.insert (std::make_pair(it->second,V));
} else {
// Registry entry not-found - just special type of visual / particles / etc.
xr_delete (V);
}
}
V = NULL;
}
void CModelPool::Delete (dxRender_Visual* &V, BOOL bDiscard)
{
if (NULL==V) return;
if (g_bRendering){
VERIFY (!bDiscard);
ModelsToDelete.push_back(V);
} else {
DeleteInternal (V,bDiscard);
}
V = NULL;
}
void CModelPool::DeleteQueue ()
{
for (u32 it=0; it<ModelsToDelete.size(); it++)
DeleteInternal(ModelsToDelete[it]);
ModelsToDelete.clear ();
}
void CModelPool::Discard (dxRender_Visual* &V, BOOL b_complete)
{
//
REGISTRY_IT it = Registry.find (V);
if (it!=Registry.end())
{
// Pool - OK
// Base
const shared_str& name = it->second;
xr_vector<ModelDef>::iterator I = Models.begin();
xr_vector<ModelDef>::iterator I_e = Models.end();
for (; I!=I_e; ++I)
{
if (I->name==name)
{
if(b_complete || strchr(*name,'#'))
{
VERIFY(I->refs>0);
I->refs--;
if (0==I->refs)
{
bForceDiscard = TRUE;
I->model->Release ();
xr_delete (I->model);
Models.erase (I);
bForceDiscard = FALSE;
}
break;
}else{
if(I->refs>0)
I->refs--;
break;
}
}
}
// Registry
xr_delete (V);
Registry.erase (it);
} else {
// Registry entry not-found - just special type of visual / particles / etc.
xr_delete (V);
}
V = nullptr;
}
void CModelPool::Prefetch()
{
Logging(FALSE);
// prefetch visuals
string256 section;
strconcat(sizeof(section), section, "prefetch_visuals_", g_pGamePersistent->m_game_params.m_game_type);
CInifile::Sect& sect = pSettings->r_section(section);
for (const CInifile::Item &it : sect.Data)
{
dxRender_Visual* V = Create(it.first.c_str());
}
Logging(TRUE);
}
void CModelPool::ClearPool( BOOL b_complete)
{
POOL_IT _I = Pool.begin();
POOL_IT _E = Pool.end();
for (;_I!=_E;_I++) {
Discard (_I->second, b_complete) ;
}
Pool.clear ();
}
dxRender_Visual* CModelPool::CreatePE (PS::CPEDef* source)
{
PS::CParticleEffect* V = (PS::CParticleEffect*)Instance_Create(MT_PARTICLE_EFFECT);
V->Compile (source);
return V;
}
dxRender_Visual* CModelPool::CreatePG (PS::CPGDef* source)
{
PS::CParticleGroup* V = (PS::CParticleGroup*)Instance_Create(MT_PARTICLE_GROUP);
V->Compile (source);
return V;
}
void CModelPool::dump()
{
Log ("--- model pool --- begin:");
u32 sz = 0;
u32 k = 0;
for (xr_vector<ModelDef>::iterator I=Models.begin(); I!=Models.end(); I++) {
CKinematics* K = PCKinematics(I->model);
if (K){
u32 cur = K->mem_usage (false);
sz += cur;
Msg("#%3d: [%3d/%5d Kb] - %s",k++,I->refs,cur/1024,I->name.c_str());
}
}
Msg ("--- models: %d, mem usage: %d Kb ",k,sz/1024);
sz = 0;
k = 0;
int free_cnt = 0;
for (REGISTRY_IT it=Registry.begin(); it!=Registry.end(); it++)
{
CKinematics* K = PCKinematics((dxRender_Visual*)it->first);
VERIFY (K);
if (K){
u32 cur = K->mem_usage (true);
sz += cur;
bool b_free = (Pool.find(it->second)!=Pool.end() );
if(b_free) ++free_cnt;
Msg("#%3d: [%s] [%5d Kb] - %s",k++, (b_free)?"free":"used", cur/1024,it->second.c_str());
}
}
Msg ("--- instances: %d, free %d, mem usage: %d Kb ",k, free_cnt, sz/1024);
Log ("--- model pool --- end.");
}
void CModelPool::memory_stats ( u32& vb_mem_video, u32& vb_mem_system, u32& ib_mem_video, u32& ib_mem_system )
{
vb_mem_video = 0;
vb_mem_system = 0;
ib_mem_video = 0;
ib_mem_system = 0;
xr_vector<ModelDef>::iterator it = Models.begin();
xr_vector<ModelDef>::const_iterator en = Models.end();
for(; it != en; ++it )
{
dxRender_Visual* ptr = it->model;
Fvisual* vis_ptr = dynamic_cast<Fvisual*> (ptr);
if( vis_ptr == nullptr)
continue;
#ifndef USE_DX11
D3DINDEXBUFFER_DESC IB_desc;
D3DVERTEXBUFFER_DESC VB_desc;
vis_ptr->m_fast->p_rm_Indices->GetDesc( &IB_desc );
D3DPOOL IB_Pool = IB_desc.Pool;
unsigned int IB_Size = IB_desc.Size;
if( IB_Pool == D3DPOOL_DEFAULT ||
IB_Pool == D3DPOOL_MANAGED )
ib_mem_video += IB_Size;
if( IB_Pool == D3DPOOL_MANAGED ||
IB_Pool == D3DPOOL_SCRATCH )
ib_mem_system += IB_Size;
vis_ptr->m_fast->p_rm_Vertices->GetDesc( &VB_desc );
D3DPOOL VB_Pool = VB_desc.Pool;
unsigned int VB_Size = VB_desc.Size;
if( VB_Pool == D3DPOOL_DEFAULT ||
VB_Pool == D3DPOOL_MANAGED)
vb_mem_video += VB_Size;
if( VB_desc.Pool == D3DPOOL_MANAGED ||
VB_desc.Pool == D3DPOOL_SCRATCH )
vb_mem_system += VB_Size;
#else
D3D_BUFFER_DESC IB_desc;
D3D_BUFFER_DESC VB_desc;
vis_ptr->m_fast->p_rm_Indices->GetDesc( &IB_desc );
ib_mem_video += IB_desc.ByteWidth;
ib_mem_system += IB_desc.ByteWidth;
vis_ptr->m_fast->p_rm_Vertices->GetDesc( &VB_desc );
vb_mem_video += IB_desc.ByteWidth;
vb_mem_system += IB_desc.ByteWidth;
#endif
}
} | 22.294695 | 111 | 0.650599 | [
"object",
"model",
"3d"
] |
30041dc12b8bcb14d2dfd729201eb025d83c7fed | 7,903 | hpp | C++ | src/Node.hpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | 2 | 2019-05-14T08:14:15.000Z | 2021-01-19T13:28:38.000Z | src/Node.hpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | null | null | null | src/Node.hpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | null | null | null | #ifndef __M3G_NODE_HPP__
#define __M3G_NODE_HPP__
#include "m3g/Transformable.hpp"
#include "m3g/m3ginternal.hpp"
#include <iosfwd>
namespace m3g {
class Transform;
class Matrix;
/**
* @~English An abstract base class for all scene graph nodes.
* @~Japanese シーングラフのノードを表す抽象クラス.
*/
class Node : public Transformable
{
/**
* @~English Structure of aliment property, for inner use.
* @~Japanese アライメントを保持する内部使用の構造体.
*/
struct Alignment {
Alignment (int t, Node* r) : target(t), reference(r) {};
int target;
Node* reference;
};
public:
/**
* @~English Specifies for the setAlignment method that no alignment should be done for the specified axis.
* @~Japanese setAlignment()関数で指定された軸に対するアライメントがない事を示す定数.
*/
static const int NONE = 144;
/**
* @~English Specifies the origin of the reference node as an orientation reference for the setAlighnment method.
* @~Japanese setAlignment()関数でアライメントがリファレンスノードの原点である事を示す定数.
*/
static const int ORIGIN = 145;
/**
* @~English Specifies the X axis of the reference node as an orientation reference for the setAlignement method.
* @~Japanese setAlignment()関数でアライメントがリファレンスノードのX軸である事を示す定数.
*/
static const int X_AXIS = 146;
/**
* @~English Specifieds the Y axis of the reference node as an orientation reference for the setAlignment mehotd.
* @~Japanese setAlignment()関数でアライメントがリファレンスノードのY軸である事を示す定数.
*/
static const int Y_AXIS = 147;
/**
* @~English Specifieds the Z axis of the reference node as an orientation reference for the setAlignment mehotd.
* @~Japanese setAlignment()関数でアライメントがリファレンスノードのZ軸である事を示す定数.
*/
static const int Z_AXIS = 148;
/**
* @~English Construct a new Node object.
* @~Japanese Nodeオブジェクトを作成するコンストラクタ.
*/
Node ();
/**
* @~English Destruct this object.
* @~Japanese このオブジェクトを削除するデストラクタ.
*/
virtual ~Node ();
/**
* @~English Creates a duplicate of this Object3D.
* @~Japanese このオブジェクトの複製の作成.
*/
Node* duplicate () const;
/**
* @~English Applies alignments to this Node and its descendants.
* @~Japanese このノードと子孫ノードにアライメントを適応する.
*/
void align (const Node* reference);
/**
* @~English Returns the alignment reference node for the given axis.
* @~Japanese 指定された軸にアライメントされた参照ノードを返す.
*/
Node* getAlignmentReference (int axis) const;
/**
* @~English Returns tthe alignment target for the given axis.
* @~Japanese 指定された軸に対するアライメントターゲットを返す.
*/
int getAlignmentTarget (int axis) const;
/**
* @~English Retrieves the alpha factor of this Node.
* @~Japanese このノードのα値の取得.
*/
float getAlphaFactor () const;
/**
* @~English Retrieves the alpha factor of this Node and all ancestors, not in M3G.
* @~Japanese このノードと先祖のα値を全て乗算した値の取得, M3G非標準.
*/
float getGlobalAlphaFactor () const;
/**
* @~English Retrieves the transformation matrix from this to target, not in M3G.
* @~Japanese このノードから指定のノードまでの変換行列を返すM3G非標準の関数.
*/
Matrix getGlobalPose (const Node* target) const;
/**
* @~English Returns the scene graph parent of this node.
* @~Japanese このノードの親ノードの取得.
*/
Node* getParent () const;
/**
* @~English Returns the top scene graph parent of this node.
* @~Japanese このノードの一番上の親ノードの取得.
*/
Node* getGlobalParent () const;
/**
* @~English Retrieves the scope of this Node.
* @~Japanese このノードのスコープの取得.
*/
int getScope () const;
/**
* @~English Gets the composite transfformation from this node to the given node.
* @~Japanese このノードから指定されたノードへの座標変換の取得.
*/
bool getTransformTo (const Node* target, Transform* transform) const;
/**
* @~English Retrieves the all ascendant picking enable flag of this Node, not in M3G.
* @~Japanese このノードの先祖まで遡ったピッキング可能フラグを返す, M3G非標準.
*/
bool isGlobalPickingEnabled () const;
/**
* @~English Retrieves the all ascendant rendering enable flag of this Node, Not in M3G.
* @~Japanese このノードの先祖まで遡ったレンダリング可能フラグを返す, M3G非標準.
*/
bool isGlobalRenderingEnabled () const;
/**
* @~English Retrieves the picking enable flag of this Node.
* @~Japanese このノードのピッキング可能フラグを返す.
*/
bool isPickingEnabled () const;
/**
* @~English Retrieves the rendering neble flag of this Node.
* @~Japanese このノードのレンダリング可能フラグを返す.
*/
bool isRenderingEnabled () const;
/**
* @~English Sets this node to align with the given other nodes(s), or disables alignment.
* @~Japanese このノードを指定されたノードに整列させる。もしくはアライメントを無効にする.
*/
void setAlignment (Node* z_ref, int z_target, Node* y_ref, int y_target);
/**
* @~English Sets the alpha factor for this Node.
* @~Japanese このノードのノードαを設定.
*/
void setAlphaFactor (float alpha);
/**
* @~English Sets the picking enable flag of this Node.
* @~Japanese このノードのピッキング可能フラグの設定.
*/
void setPickingEnable (bool enable);
/**
* @~English Sets the rendering enable flag of this Node.
* @~Japanese このノードのレンダリング可能フラグの設定.
*/
void setRenderingEnable (bool enable);
/**
* @~English Sets the scope of this node.
* @~Japanese このノードのスコープを設定する.
*/
void setScope (int scope);
/**
* @~English Print out information of this object.
* @~Japanese このNodeクラスの情報を表示する。デバッグ用.
*/
virtual std::ostream& print (std::ostream& out) const;
/**
* @~English Sets parent of this node, not in M3G.
* @~Japanese このノードの親ノードを設定するM3G非標準の関数.
*/
void setParent (Node* node);
/**
* @~English Retrieve duplicated node from this node, for inner use.
* @~Japanese このノードから複製されたNodeを取得する内部仕様の関数.
*/
Node* getDuplicatedNode () const;
protected:
/**
* @~English
* @~Japanese
*/
virtual void addAnimationTrack_xxx (AnimationTrack* animation_track, bool accepted);
/**
* @~English Implement align().
* @~Japanese アライメントを実行するalign()関数の実装.
* @param[in] reference 実行時にアライメント対象を指定する時のノード.
*/
virtual void align_xxx (const Node* reference);
/**
* @~English
* @~Japanese
*/
virtual int animate_xxx (int world_time);
/**
* @~English
* @~Japanese
*/
virtual Node* duplicate_xxx (Object3D* obj) const;
/**
* @~English
* @~Japanese
*/
virtual void render_xxx (RenderState& state) const;
private:
Node (const Node& node);
Node& operator= (const Node& node);
private:
Node* parent;
bool rendering_enable;
bool picking_enable;
float alpha_factor;
int scope;
Alignment z_alignment;
Alignment y_alignment;
Node* duplicated;
};
} // namespace m3g {
std::ostream& operator<< (std::ostream& out, const m3g::Node& n);
#endif
| 28.738182 | 122 | 0.563963 | [
"object",
"transform"
] |
300bd2aab837be114e3db900c4564fc46d43b90c | 18,807 | cc | C++ | build/build/void/makepkg/astroid/src/astroid/src/chunk.cc | scobiehague/dotfiles | b5819fb09be3d0b1ed43ef1a56d6f196609ec47b | [
"MIT"
] | 117 | 2015-02-14T14:35:49.000Z | 2022-03-02T01:46:23.000Z | build/build/void/makepkg/astroid/src/astroid/src/chunk.cc | scobiehague/dotfiles | b5819fb09be3d0b1ed43ef1a56d6f196609ec47b | [
"MIT"
] | 4 | 2019-03-28T23:51:42.000Z | 2022-02-23T08:45:25.000Z | build/build/void/makepkg/astroid/src/astroid/src/chunk.cc | scobiehague/dotfiles | b5819fb09be3d0b1ed43ef1a56d6f196609ec47b | [
"MIT"
] | 23 | 2015-11-28T01:49:27.000Z | 2021-12-13T16:17:54.000Z | # include <vector>
# include <iostream>
# include <atomic>
# include <fstream>
# include <boost/filesystem.hpp>
# include <glib.h>
# include <gmime/gmime.h>
# include "utils/gmime/gmime-filter-html-bq.h"
# include "astroid.hh"
# include "message_thread.hh"
# include "chunk.hh"
# include "log.hh"
# include "utils/utils.hh"
# include "utils/ustring_utils.hh"
# include "utils/vector_utils.hh"
# include "config.hh"
# include "crypto.hh"
namespace Astroid {
std::atomic<uint> Chunk::nextid (0);
Chunk::Chunk (GMimeObject * mp) : mime_object (mp) {
using std::endl;
id = nextid++;
if (mp == NULL) {
log << error << "chunk (" << id << "): got NULL mime_object." << endl;
throw std::logic_error ("chunk: got NULL mime_object");
}
content_type = g_mime_object_get_content_type (mime_object);
if (content_type) {
log << debug << "chunk (" << id << "): content-type: " << g_mime_content_type_to_string (content_type) << endl;
} else {
log << warn << "chunk (" << id << "): content-type not specified, could be mime-message." << endl;
}
if (GMIME_IS_PART (mime_object)) {
// has no sub-parts
std::string disposition = g_mime_object_get_disposition(mime_object) ? : std::string();
viewable = !(disposition == "attachment");
const char * cid = g_mime_part_get_content_id ((GMimePart *) mime_object);
if (cid != NULL) {
content_id = ustring(cid);
log << debug << "chunk: part, id: " << content_id << endl;
}
if (content_type != NULL) {
if (viewable) {
/* check if we can show this type */
viewable = false;
for (auto &m : viewable_types) {
if (g_mime_content_type_is_type (content_type,
g_mime_content_type_get_media_type (m.second),
g_mime_content_type_get_media_subtype (m.second))) {
viewable = true;
break;
}
}
}
} else {
viewable = false;
}
attachment = !viewable;
if (g_mime_content_type_is_type (content_type,
g_mime_content_type_get_media_type (preferred_type),
g_mime_content_type_get_media_subtype (preferred_type)))
{
log << debug << "chunk: preferred." << endl;
preferred = true;
}
log << debug << "chunk: is part (viewable: " << viewable << ", attachment: " << attachment << ") " << endl;
} else if GMIME_IS_MESSAGE_PART (mime_object) {
log << debug << "chunk: message part" << endl;
/* contains a GMimeMessage with a potential substructure */
GMimeMessage * msg = g_mime_message_part_get_message ((GMimeMessagePart *) mime_object);
kids.push_back (refptr<Chunk>(new Chunk((GMimeObject *) msg)));
} else if GMIME_IS_MESSAGE_PARTIAL (mime_object) {
log << debug << "chunk: partial" << endl;
GMimeMessage * msg = g_mime_message_partial_reconstruct_message (
(GMimeMessagePartial **) &mime_object,
g_mime_message_partial_get_total ((GMimeMessagePartial *) mime_object)
);
kids.push_back (refptr<Chunk>(new Chunk((GMimeObject *) msg)));
} else if GMIME_IS_MULTIPART (mime_object) {
log << debug << "chunk: multi part" << endl;
int total = g_mime_multipart_get_count ((GMimeMultipart *) mime_object);
if (GMIME_IS_MULTIPART_ENCRYPTED (mime_object)) {
log << warn << "chunk: is encrypted." << endl;
isencrypted = true;
if (total != 2) {
log << error << "chunk: encrypted message with not exactly 2 parts." << endl;
return;
}
const char *protocol = g_mime_content_type_get_parameter (content_type, "protocol");
Crypto cr (protocol);
if (cr.ready) {
GMimeObject * k = cr.decrypt_and_verify (mime_object);
if (k != NULL) {
auto c = refptr<Chunk>(new Chunk(k));
c->isencrypted = true;
kids.push_back (c);
}
}
/*
} else if (GMIME_IS_MULTIPART_SIGNED (mime_object)) {
log << warn << "chunk: is signed." << endl;
issigned = true;
*/
} else {
bool alternative = (g_mime_content_type_is_type (content_type, "multipart", "alternative"));
log << debug << "chunk: alternative: " << alternative << endl;
for (int i = 0; i < total; i++) {
GMimeObject * mo = g_mime_multipart_get_part (
(GMimeMultipart *) mime_object,
i);
kids.push_back (refptr<Chunk>(new Chunk(mo)));
}
if (alternative) {
for_each (
kids.begin(),
kids.end(),
[&] (refptr<Chunk> c) {
for_each (
kids.begin(),
kids.end(),
[&] (refptr<Chunk> cc) {
if (c != cc) {
log << debug << "chunk: multipart: added sibling" << endl;
c->siblings.push_back (cc);
}
}
);
if (g_mime_content_type_is_type (c->content_type,
g_mime_content_type_get_media_type (preferred_type),
g_mime_content_type_get_media_subtype (preferred_type)))
{
log << debug << "chunk: multipart: preferred." << endl;
c->preferred = true;
}
}
);
}
}
log << debug << "chunk: multi part end" << endl;
} else if GMIME_IS_MESSAGE (mime_object) {
log << debug << "chunk: mime message" << endl;
mime_message = true;
}
// TODO: check for inline PGP encryption, also its unsafe:
// https://dkg.fifthhorseman.net/notes/inline-pgp-harmful/
}
ustring Chunk::viewable_text (bool html = true) {
using std::endl;
GMimeStream * content_stream = NULL;
if (GMIME_IS_PART(mime_object)) {
log << debug << "chunk: body: part" << endl;
if (g_mime_content_type_is_type (content_type, "text", "plain")) {
log << debug << "chunk: plain text (out html: " << html << ")" << endl;
GMimeDataWrapper * content = g_mime_part_get_content_object (
(GMimePart *) mime_object);
const char * charset = g_mime_object_get_content_type_parameter(GMIME_OBJECT(mime_object), "charset");
GMimeStream * stream = g_mime_data_wrapper_get_stream (content);
GMimeStream * filter_stream = g_mime_stream_filter_new (stream);
/* convert to html */
guint32 cite_color = 0x1e1e1e;
/* other filters:
*
* GMIME_FILTER_HTML_PRE ||
*/
guint32 html_filter_flags = GMIME_FILTER_HTML_CONVERT_NL |
GMIME_FILTER_HTML_CONVERT_SPACES |
GMIME_FILTER_HTML_CONVERT_URLS |
GMIME_FILTER_HTML_CONVERT_ADDRESSES |
GMIME_FILTER_HTML_BQ_BLOCKQUOTE_CITATION ;
/* convert encoding */
GMimeContentEncoding enc = g_mime_data_wrapper_get_encoding (content);
if (enc) {
log << debug << "enc: " << g_mime_content_encoding_to_string(enc) << endl;
}
GMimeFilter * filter = g_mime_filter_basic_new(enc, false);
g_mime_stream_filter_add(GMIME_STREAM_FILTER(filter_stream), filter);
g_object_unref(filter);
if (charset)
{
log << debug << "charset: " << charset << endl;
if (std::string(charset) == "utf-8") {
charset = "UTF-8";
}
GMimeFilter * filter = g_mime_filter_charset_new(charset, "UTF-8");
g_mime_stream_filter_add(GMIME_STREAM_FILTER(filter_stream), filter);
g_object_unref(filter);
} else {
log << warn << "charset: not defined." << endl;
}
if (html) {
GMimeFilter * html_filter;
html_filter = g_mime_filter_html_bq_new (html_filter_flags, cite_color);
g_mime_stream_filter_add (GMIME_STREAM_FILTER(filter_stream),
html_filter);
g_object_unref (html_filter);
} else {
/* CRLF to LF */
GMimeFilter * crlf_filter = g_mime_filter_crlf_new (false, false);
g_mime_stream_filter_add (GMIME_STREAM_FILTER (filter_stream),
crlf_filter);
g_object_unref (crlf_filter);
}
g_mime_stream_reset (stream);
content_stream = filter_stream;
} else if (g_mime_content_type_is_type (content_type, "text", "html")) {
log << debug << "chunk: html text" << endl;
GMimeDataWrapper * content = g_mime_part_get_content_object (
(GMimePart *) mime_object);
const char * charset = g_mime_object_get_content_type_parameter(GMIME_OBJECT(mime_object), "charset");
GMimeStream * stream = g_mime_data_wrapper_get_stream (content);
GMimeStream * filter_stream = g_mime_stream_filter_new (stream);
/* convert encoding */
GMimeContentEncoding enc = g_mime_data_wrapper_get_encoding (content);
if (enc) {
log << debug << "enc: " << g_mime_content_encoding_to_string(enc) << endl;
}
GMimeFilter * filter = g_mime_filter_basic_new(enc, false);
g_mime_stream_filter_add(GMIME_STREAM_FILTER(filter_stream), filter);
g_object_unref(filter);
if (charset)
{
log << debug << "charset: " << charset << endl;
if (std::string(charset) == "utf-8") {
charset = "UTF-8";
}
GMimeFilter * filter = g_mime_filter_charset_new(charset, "UTF-8");
g_mime_stream_filter_add(GMIME_STREAM_FILTER(filter_stream), filter);
g_object_unref(filter);
} else {
log << warn << "charset: not defined" << endl;
}
g_mime_stream_reset (stream);
content_stream = filter_stream;
}
}
if (content_stream != NULL) {
char buffer[4097];
ssize_t prevn = 1;
ssize_t n;
std::stringstream sstr;
while ((n = g_mime_stream_read (content_stream, buffer, 4096), n) >= 0)
{
buffer[n] = 0;
sstr << buffer;
if (n == 0 && prevn == 0) {
break;
}
prevn = n;
}
g_object_unref (content_stream);
ustring b;
try {
b = sstr.str();
} catch (Glib::ConvertError &ex) {
log << error << "could not convert chunk to utf-8, contents: " << sstr.str() << endl;
throw ex;
}
return b;
} else {
return ustring ("Error: Non-viewable part!");
log << error << "chunk: tried to display non-viewable part." << endl;
//throw runtime_error ("chunk: tried to display non-viewable part.");
}
}
ustring Chunk::get_filename () {
if (_fname.size () > 0) {
return _fname;
}
if (GMIME_IS_PART (mime_object)) {
const char * s = g_mime_part_get_filename (GMIME_PART(mime_object));
if (s != NULL) {
ustring fname (s);
_fname = fname;
return fname;
}
} else if (GMIME_IS_MESSAGE (mime_object)) {
const char * s = g_mime_message_get_subject (GMIME_MESSAGE (mime_object));
if (s != NULL) {
ustring fname (s);
_fname = fname + ".eml";
return fname;
}
}
// no filename specified
return ustring ("");
}
size_t Chunk::get_file_size () {
time_t t0 = clock ();
// https://github.com/skx/lumail/blob/master/util/attachments.c
refptr<Glib::ByteArray> cnt = contents ();
size_t sz = cnt->size ();
log << info << "chunk: file size: " << sz << " (time used to calculate: " << ( (clock () - t0) * 1000.0 / CLOCKS_PER_SEC ) << " ms.)" << std::endl;
return sz;
}
refptr<Glib::ByteArray> Chunk::contents () {
time_t t0 = clock ();
// https://github.com/skx/lumail/blob/master/util/attachments.c
GMimeStream * mem = g_mime_stream_mem_new ();
if (GMIME_IS_PART (mime_object)) {
GMimeDataWrapper * content = g_mime_part_get_content_object (GMIME_PART (mime_object));
g_mime_data_wrapper_write_to_stream (content, mem);
} else {
g_mime_object_write_to_stream (mime_object, mem);
g_mime_stream_flush (mem);
}
GByteArray * res = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (mem));
auto data = Glib::ByteArray::create ();
if (res != NULL) {
data->append (res->data, res->len);
}
g_object_unref (mem);
log << info << "chunk: contents: loaded " << data->size () << " bytes in " << ( (clock () - t0) * 1000.0 / CLOCKS_PER_SEC ) << " ms." << std::endl;
return data;
}
bool Chunk::save_to (std::string filename, bool overwrite) {
/* saves chunk to file name, if filename is dir, own name */
using std::endl;
using bfs::path;
path to (filename.c_str());
if (is_directory (to)) {
ustring fname = Utils::safe_fname (get_filename ());
if (fname.size () == 0) {
if (content_id != "") {
fname = ustring::compose ("astroid-attachment-%1", content_id);
} else {
/* make up a name */
path new_to;
do {
fname = ustring::compose ("astroid-attachment-%1", UstringUtils::random_alphanumeric (5));
new_to = to / path(fname.c_str ());
} while (exists (new_to));
}
}
to /= path (fname.c_str ());
}
log << info << "chunk: saving to: " << to << endl;
if (exists (to)) {
if (!overwrite) {
log << error << "chunk: save: file already exists! not writing." << endl;
return false;
} else {
log << warn << "chunk: save: file already exists: overwriting." << endl;
}
}
if (!exists(to.parent_path ()) || !is_directory (to.parent_path())) {
log << error << "chunk: save: parent path does not exist or is not a directory." << endl;
return false;
}
std::ofstream f (to.c_str (), std::ofstream::binary);
auto data = contents ();
f.write (reinterpret_cast<char*>(data->get_data ()), data->size ());
f.close ();
return true;
}
refptr<Chunk> Chunk::get_by_id (int _id, bool check_siblings) {
if (check_siblings) {
for (auto c : siblings) {
if (c->id == _id) {
return c;
} else {
auto kc = c->get_by_id (_id, false);
if (kc) return kc;
}
}
}
for (auto c : kids) {
if (c->id == _id) {
return c;
} else {
auto kc = c->get_by_id (_id, true);
if (kc) return kc;
}
}
return refptr<Chunk>();
}
void Chunk::open () {
using bfs::path;
log << info << "chunk: " << get_filename () << ", opening.." << std::endl;
path tf = astroid->standard_paths().cache_dir;
ustring tmp_fname = ustring::compose("%1-%2", UstringUtils::random_alphanumeric (10), Utils::safe_fname(get_filename ()));
tf /= path (tmp_fname.c_str());
log << debug << "chunk: saving to tmp path: " << tf.c_str() << std::endl;
save_to (tf.c_str());
ustring tf_p (tf.c_str());
Glib::Threads::Thread::create (
sigc::bind (
sigc::mem_fun (this, &Chunk::do_open),
tf_p ));
}
void Chunk::do_open (ustring tf) {
using std::endl;
ustring external_cmd = astroid->config().get<std::string> ("attachment.external_open_cmd");
std::vector<std::string> args = { external_cmd.c_str(), tf.c_str () };
log << debug << "chunk: spawning: " << args[0] << ", " << args[1] << endl;
std::string stdout;
std::string stderr;
int exitcode;
try {
Glib::spawn_sync ("",
args,
Glib::SPAWN_DEFAULT | Glib::SPAWN_SEARCH_PATH,
sigc::slot <void> (),
&stdout,
&stderr,
&exitcode
);
} catch (Glib::SpawnError &ex) {
log << error << "chunk: exception while opening attachment: " << ex.what () << endl;
log << info << "chunk: deleting tmp file: " << tf << endl;
unlink (tf.c_str());
}
ustring ustdout = ustring(stdout);
for (ustring &l : VectorUtils::split_and_trim (ustdout, ustring("\n"))) {
log << debug << l << endl;
}
ustring ustderr = ustring(stderr);
for (ustring &l : VectorUtils::split_and_trim (ustderr, ustring("\n"))) {
log << debug << l << endl;
}
if (exitcode != 0) {
log << error << "chunk: chunk script exited with code: " << exitcode << endl;
}
log << info << "chunk: deleting tmp file: " << tf << endl;
unlink (tf.c_str());
}
bool Chunk::any_kids_viewable () {
if (viewable) return true;
for (auto &k : kids) {
if (k->any_kids_viewable ()) return true;
}
return false;
}
bool Chunk::any_kids_viewable_and_preferred () {
if (viewable && preferred) return true;
for (auto &k : kids) {
if (k->any_kids_viewable_and_preferred ()) return true;
}
return false;
}
ustring Chunk::get_content_type () {
return ustring (g_mime_content_type_to_string (content_type));
}
void Chunk::save () {
using std::endl;
log << info << "chunk: " << get_filename () << ", saving.." << endl;
Gtk::FileChooserDialog dialog ("Save attachment to folder..",
Gtk::FILE_CHOOSER_ACTION_SAVE);
dialog.add_button ("_Cancel", Gtk::RESPONSE_CANCEL);
dialog.add_button ("_Select", Gtk::RESPONSE_OK);
dialog.set_do_overwrite_confirmation (true);
dialog.set_current_name (Utils::safe_fname (get_filename ()));
int result = dialog.run ();
switch (result) {
case (Gtk::RESPONSE_OK):
{
std::string fname = dialog.get_filename ();
log << info << "chunk: saving attachment to: " << fname << endl;
/* the dialog asks whether to overwrite or not */
save_to (fname, true);
break;
}
default:
{
log << debug << "chunk: save: cancelled." << endl;
}
}
}
refptr<Message> Chunk::get_mime_message () {
if (!mime_message) {
log << error << "chunk: this is not a mime message." << std::endl;
throw std::runtime_error ("chunk: not a mime message");
}
refptr<Message> m = refptr<Message> ( new Message (GMIME_MESSAGE(mime_object)) );
return m;
}
Chunk::~Chunk () {
// these should not be unreffed.
// g_object_unref (mime_object);
// g_object_unref (content_type);
}
}
| 29.385938 | 151 | 0.561387 | [
"vector"
] |
300c1ed22ae1dcd7c6905a28003ce228742ce83b | 2,147 | cpp | C++ | src/Stop.cpp | xxAtrain223/EmbGenParser | c6debf74579349c152170f1d4316525a29985960 | [
"MIT"
] | null | null | null | src/Stop.cpp | xxAtrain223/EmbGenParser | c6debf74579349c152170f1d4316525a29985960 | [
"MIT"
] | null | null | null | src/Stop.cpp | xxAtrain223/EmbGenParser | c6debf74579349c152170f1d4316525a29985960 | [
"MIT"
] | null | null | null | #include "EmbGen/Parser/Stop.hpp"
#include "EmbGen/Parser/Exceptions.hpp"
#include <tinyxml2.h>
namespace emb
{
namespace gen
{
namespace parser
{
Stop::Stop(const tinyxml2::XMLElement* xml) :
XmlElement(xml)
{
try
{
m_command = getAttribute("command")->Value();
}
catch (AttributeException)
{
m_command = "";
}
std::vector<const tinyxml2::XMLElement*> code = getElements("code");
if (code.size() == 1)
{
m_code = std::make_shared<Code>(code.at(0));
}
else if (code.size() == 0)
{
m_code = nullptr;
}
else
{
throw ElementException("Too many Code elements for Stop on line " + std::to_string(getLineNum()));
}
if (m_command == "" && m_code == nullptr)
{
throw ParserException("Neither command nor code are defined for Stop on line " + std::to_string(getLineNum()));
}
if (m_command != "" && m_code != nullptr)
{
throw ParserException("Both command and code are defined for Stop on line " + std::to_string(getLineNum()));
}
if (!isAttributesEmpty())
{
throw AttributeException("Extra attributes for Stop on line " + std::to_string(getLineNum()));
}
if (!isElementsEmpty())
{
throw ElementException("Extra elements for Stop on line " + std::to_string(getLineNum()));
}
}
std::string Stop::getCommand() const
{
return m_command;
}
std::shared_ptr<Code> Stop::getCode() const
{
return m_code;
}
}
}
} | 31.115942 | 131 | 0.424313 | [
"vector"
] |
30100b2ff29e8421019198f269b973c5709028dd | 3,234 | hpp | C++ | YRoots/include/IntervalChecking/IntervalBounder.hpp | erikhparkinson/YRoots | 7907a7245ac37b38a06bc5cc94ad26c7cf5e5905 | [
"CNRI-Python"
] | null | null | null | YRoots/include/IntervalChecking/IntervalBounder.hpp | erikhparkinson/YRoots | 7907a7245ac37b38a06bc5cc94ad26c7cf5e5905 | [
"CNRI-Python"
] | null | null | null | YRoots/include/IntervalChecking/IntervalBounder.hpp | erikhparkinson/YRoots | 7907a7245ac37b38a06bc5cc94ad26c7cf5e5905 | [
"CNRI-Python"
] | null | null | null | //
// IntervalBounder.h
// YRoots
//
// Created by Erik Hales Parkinson on 8/14/21.
// Copyright © 2021 Erik Hales Parkinson. All rights reserved.
//
#ifndef IntervalBounder_h
#define IntervalBounder_h
#include "Approximation/ChebyshevApproximation.hpp"
#include "Utilities/Timer.hpp"
#include "Utilities/utilities.hpp"
#include <Eigen/Dense>
#include "IntervalChecking/BoundingIntervalUtilities.hpp"
template <int Rank>
class IntervalBounder {
public:
IntervalBounder(size_t _rank);
double computeBoundingInterval(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, const std::vector<bool>& _allowedToReduceDim);
const Interval& getBoundingInterval() {
return m_boundingInterval;
}
protected:
double updateBoundingIntervalLinearErrorSolve(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, const std::vector<bool>& _allowedToReduceDim);
double updateBoundingIntervalLipshitzSolve(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, const std::vector<bool>& _allowedToReduceDim);
void preconditionPolynomials(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations);
double computeLipshitzConstant(const Eigen::VectorXd& poly, size_t dim);
void chebValReduce(const Eigen::VectorXd& poly, Eigen::VectorXd& result, size_t dim, double value);
double getLiphsitzBoundIncreaseND(const Eigen::VectorXd& poly, double error, double lipshitzConstant, const Interval& boundingInterval, size_t dim);
double getExtremeAbsVal(const Eigen::VectorXd& poly, const Interval& boundingInterval, size_t dim);
protected:
size_t m_rank;
Interval m_boundingInterval;
//For Bounding Intervals
typename EigenTypes<Rank>::Matrix m_linearTerms;
typename EigenTypes<Rank>::Vector m_constantTerms;
typename EigenTypes<Rank>::Vector m_errorTerms;
typename EigenTypes<Rank>::Vector m_errorTermsOfLinear;
typename EigenTypes<Rank>::MatrixPowerColumns m_rightHandSideOfLinearSystemErrors;
typename Eigen::ColPivHouseholderQR<typename EigenTypes<Rank>::Matrix> m_linearTermsQR;
typename EigenTypes<Rank>::MatrixPowerColumns m_linearSystemWithErrorResult;
typename EigenTypes<Rank>::Matrix m_linearTermsInverse;
//The Preconditioned Polynomials
size_t m_preconditionPolysDegree;
typename EigenTypes<Rank>::Vector m_preconditionedErrors;
Eigen::MatrixXd m_preconditionedPolys;
//For Timing
static size_t m_timerLinearErrorSolveIndex;
static size_t m_timerPreconditionPolysIndex;
static size_t m_timerLipshitzSolveIndex;
static size_t m_timerChebValReduceIndex;
Timer& m_timer = Timer::getInstance();
};
template<int Rank>
size_t IntervalBounder<Rank>::m_timerLinearErrorSolveIndex = -1;
template<int Rank>
size_t IntervalBounder<Rank>::m_timerPreconditionPolysIndex = -1;
template<int Rank>
size_t IntervalBounder<Rank>::m_timerLipshitzSolveIndex = -1;
template<int Rank>
size_t IntervalBounder<Rank>::m_timerChebValReduceIndex = -1;
#include "IntervalBounder1D.ipp"
#include "IntervalBounderND.ipp"
#endif /* IntervalBounder_h */
| 40.936709 | 166 | 0.763142 | [
"vector"
] |
301a7f0c16b9118ef455d65b31bb7e4bb81e4ca9 | 1,914 | cpp | C++ | Graph/MINIMUM_SPANNING_TREE_kruskalAlgo(hackerearth).cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | 1 | 2021-07-20T06:08:26.000Z | 2021-07-20T06:08:26.000Z | Graph/MINIMUM_SPANNING_TREE_kruskalAlgo(hackerearth).cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | Graph/MINIMUM_SPANNING_TREE_kruskalAlgo(hackerearth).cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | // QUARANTINE DAYS..;)
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define test long long int tt;cin>>tt;while(tt--)
#define rep(i,a,b) for(long long int i=a;i<b;i++)
#define rev(i,a,b) for(long long int i=b-1;i>=a;i--)
#define reep(i,a,b) for(long long int i=a;i<=b;i++)
#define ll long long int
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MOD 1000000007
#define PI acos(-1.0)
#define assign(x,val) memset(x,val,sizeof(x))
#define prec(val, dig) fixed << setprecision(dig) << val
#define vec(vct) vector < ll > vct
#define vecpi(vct) vector < pair < ll, ll > > vct
#define pi pair < ll , ll >
#define lower(str) transform(str.begin(), str.end(), str.begin(), ::tolower);
#define upper(str) transform(str.begin(), str.end(), str.begin(), ::toupper);
#define mk(arr,n,type) type *arr=new type[n];
const int maxm = 2e6 + 10;
void fast() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
/**********====================########################=================***********/
struct edge {
int a; int b; int w;
};
edge ar[100001];
int par[10001]; //parents
bool comp(edge a, edge b)
{
if (a.w < b.w)
return true;
return false;
}
int find(int a)
{
if (par[a] == -1)
return a;
return par[a] = find(par[a]);
}
void merge(int a , int b) {
par[a] = b;
}
int32_t main()
{
fast();
int n, m, a, b, w;
cin >> n >> m;
for (int i = 0; i <= n; i++) par[i] = -1;
for (int i = 0; i < m; i++)
{
cin >> ar[i].a >> ar[i].b >> ar[i].w;
}
int sum = 0;
sort(ar, ar + m, comp);
for (int i = 0; i < m; i++)
{
a = find(ar[i].b);
b = find(ar[i].a);
if (a != b)
{
sum += ar[i].w;
merge(a, b);
}
}
cout << sum;
return 0;
} | 21.505618 | 84 | 0.53396 | [
"vector",
"transform"
] |
301bbed067bc89d189e160e8b9c38e37169034ee | 14,122 | cc | C++ | rdci/src/RdciGroupSubSystem.cc | RadeonOpenCompute/rdc | bb11a0abf5bea0ca8ad3d17bd687379c45149ed9 | [
"MIT"
] | 2 | 2020-09-10T02:04:00.000Z | 2020-12-03T10:55:38.000Z | rdci/src/RdciGroupSubSystem.cc | RadeonOpenCompute/rdc | bb11a0abf5bea0ca8ad3d17bd687379c45149ed9 | [
"MIT"
] | 2 | 2022-03-29T00:32:43.000Z | 2022-03-31T18:09:36.000Z | rdci/src/RdciGroupSubSystem.cc | RadeonOpenCompute/rdc | bb11a0abf5bea0ca8ad3d17bd687379c45149ed9 | [
"MIT"
] | 2 | 2020-09-15T08:05:43.000Z | 2021-09-02T03:06:41.000Z | /*
Copyright (c) 2020 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice 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 "RdciGroupSubSystem.h"
#include <getopt.h>
#include <unistd.h>
#include "common/rdc_utils.h"
#include "rdc_lib/rdc_common.h"
#include "rdc/rdc.h"
#include "rdc_lib/RdcException.h"
namespace amd {
namespace rdc {
RdciGroupSubSystem::RdciGroupSubSystem():
group_ops_(GROUP_UNKNOWN)
, is_group_set_(false) {
}
void RdciGroupSubSystem::parse_cmd_opts(int argc, char ** argv) {
const int HOST_OPTIONS = 1000;
const int JSON_OPTIONS = 1001;
const struct option long_options[] = {
{"host", required_argument, nullptr, HOST_OPTIONS },
{"help", optional_argument, nullptr, 'h' },
{"unauth", optional_argument, nullptr, 'u' },
{"list", optional_argument, nullptr, 'l' },
{"group", required_argument, nullptr, 'g'},
{"create", required_argument, nullptr, 'c' },
{"add", required_argument, nullptr, 'a' },
{"info", optional_argument, nullptr, 'i' },
{"delete", required_argument, nullptr, 'd' },
{"json", optional_argument, nullptr, JSON_OPTIONS },
{ nullptr, 0 , nullptr, 0 }
};
int option_index = 0;
int opt = 0;
while ((opt = getopt_long(argc, argv, "hluic:g:a:d:",
long_options, &option_index)) != -1) {
switch (opt) {
case HOST_OPTIONS:
ip_port_ = optarg;
break;
case JSON_OPTIONS:
set_json_output(true);
break;
case 'h':
group_ops_ = GROUP_HELP;
return;
case 'u':
use_auth_ = false;
break;
case 'l':
group_ops_ = GROUP_LIST;
break;
case 'g':
if (!IsNumber(optarg)) {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"The group id needs to be a number");
}
group_id_ = std::stoi(optarg);
is_group_set_ = true;
break;
case 'c':
group_ops_ = GROUP_CREATE;
group_name_ = optarg;
break;
case 'a':
// Create may add GPUs as well.
if (group_ops_ != GROUP_CREATE) {
group_ops_ = GROUP_ADD_GPUS;
}
gpu_ids_ = optarg;
break;
case 'i':
group_ops_ = GROUP_INFO;
break;
case 'd':
group_ops_ = GROUP_DELETE;
if (!IsNumber(optarg)) {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"The group id needs to be a number");
}
group_id_ = std::stoi(optarg);
is_group_set_ = true;
break;
default:
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"Unknown command line options");
}
}
if (group_ops_ == GROUP_UNKNOWN) {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"Must specify a valid operations");
}
}
void RdciGroupSubSystem::show_help() const {
if (is_json_output()) return;
std::cout << " group -- Used to create and maintain groups of GPUs.\n\n";
std::cout << "Usage\n";
std::cout << " rdci group [--host <IP/FQDN>:port] [--json] [-u] -l\n";
std::cout << " rdci group [--host <IP/FQDN>:port] [--json] [-u]"
<< " -c <groupName> [-a <entityId>]\n";
std::cout << " rdci group [--host <IP/FQDN>:port] [--json] [-u]"
<< " -g <groupId> [-a <entityId>]\n";
std::cout << " rdci group [--host <IP/FQDN>:port] [--json] [-u] "
<< "-g <groupId> [-i]\n";
std::cout << " rdci group [--host <IP/FQDN>:port] [--json] [-u] "
<< "-d <groupId>\n";
std::cout << "\nFlags:\n";
show_common_usage();
std::cout << " --json "
<< "Output using json.\n";
std::cout << " -l --list "
<< "List the groups that currently exist for a host.\n";
std::cout << " -g --group groupId "
<< "The GPU group to query on the specified host.\n";
std::cout << " -c --create groupName "
<< "Create a group on the remote host.\n";
std::cout << " -a --add gpuIndexes "
<< "Comma-separated list of the GPU indexes to add to the group.\n";
std::cout << " -i --info "
<< "Display the information for the specified group Id\n";
std::cout << " -d --delete groupId "
<< "Delete a group on the remote host.\n";
}
void RdciGroupSubSystem::process() {
rdc_status_t result = RDC_ST_OK;
std::vector<std::string> gpu_ids;
rdc_group_info_t group_info;
uint32_t count = 0;
std::string json_group_ids = "\"gpu_groups\": [";
switch (group_ops_) {
case GROUP_HELP:
show_help();
break;
case GROUP_CREATE:
if (group_name_ == "") {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"Must specify the group name when create a group");
}
rdc_gpu_group_t group_id;
result = rdc_group_gpu_create(rdc_handle_, RDC_GROUP_EMPTY,
group_name_.c_str(), &group_id);
if (result != RDC_ST_OK) {
throw RdcException(result, "Fail to create group "
+ group_name_);
}
gpu_ids = split_string(gpu_ids_, ',');
for (uint32_t i = 0; i < gpu_ids.size(); i++) {
if (!IsNumber(gpu_ids[i])) {
throw RdcException(RDC_ST_BAD_PARAMETER,
"The GPU Id "+gpu_ids[i]+" needs to be a number");
}
result = rdc_group_gpu_add(rdc_handle_,
group_id, std::stoi(gpu_ids[i]));
if (result != RDC_ST_OK) {
throw RdcException(result, "Fail to add GPU "
+ gpu_ids[i] + " to the group");
}
}
if (result == RDC_ST_OK) {
if (is_json_output()) {
std::cout << "\"group_id\": \"" << group_id
<<"\", \"status\": \"ok\"";
} else {
std::cout << "Successfully created group with a group ID "
<< group_id << std::endl;
}
return;
}
break;
case GROUP_DELETE:
if (!is_group_set_) {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"Need to specify the group id to delete a group");
}
result = rdc_group_gpu_destroy(rdc_handle_, group_id_);
if (result == RDC_ST_OK) {
if (is_json_output()) {
std::cout << "\"group_id\": \"" << group_id_
<<"\", \"status\": \"ok\"";
} else {
std::cout << "Successfully deleted the group "
<< group_id_ << std::endl;
}
return;
}
break;
case GROUP_LIST:
rdc_gpu_group_t group_id_list[RDC_MAX_NUM_GROUPS];
result = rdc_group_get_all_ids(rdc_handle_, group_id_list, &count);
if ( result != RDC_ST_OK) break;
if (!is_json_output()) {
std::cout << count << " group found.\n";
std::cout << "GroupID\t" << "GroupName\t" << "GPUIndex\n";
}
for (uint32_t i = 0; i < count; i++) {
result = rdc_group_gpu_get_info(rdc_handle_,
group_id_list[i], &group_info);
if (result != RDC_ST_OK) {
throw RdcException(RDC_ST_BAD_PARAMETER,
"Fail to get information for group "
+ std::to_string(group_id_list[i]));
}
if (!is_json_output()) {
std::cout << group_id_list[i] << "\t"
<< group_info.group_name << "\t\t";
} else {
json_group_ids += "{\"group_id\": \"";
json_group_ids += std::to_string(group_id_list[i]);
json_group_ids += "\", \"group_name\": \"";
json_group_ids += group_info.group_name;
json_group_ids += "\", \"gpu_indexes\": [";
}
for (uint32_t j = 0; j < group_info.count; j++) {
if (!is_json_output()) {
std::cout << group_info.entity_ids[j];
} else {
json_group_ids +=
std::to_string(group_info.entity_ids[j]);
}
if (j < group_info.count -1) {
if (!is_json_output()) {
std::cout << ",";
} else {
json_group_ids += ",";
}
}
}
if (!is_json_output()) {
std::cout << std::endl;
} else {
json_group_ids += "]}";
if (i != count -1) {
json_group_ids += ",";
}
}
}
if (is_json_output()) {
json_group_ids += "], \"status\": \"ok\"";
std::cout << json_group_ids;
}
break;
case GROUP_ADD_GPUS:
if (!is_group_set_) {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"Need to specify the group id to add a group");
}
gpu_ids = split_string(gpu_ids_, ',');
for (uint32_t i = 0; i < gpu_ids.size(); i++) {
if (!IsNumber(gpu_ids[i])) {
throw RdcException(RDC_ST_BAD_PARAMETER,
"The GPU Id "+gpu_ids[i]+" needs to be a number");
}
result = rdc_group_gpu_add(rdc_handle_,
group_id_, std::stoi(gpu_ids[i]));
if (result != RDC_ST_OK) {
throw RdcException(result, "Fail to add GPU "
+ gpu_ids[i] + " to the group");
}
}
if (result == RDC_ST_OK) {
if (is_json_output()) {
std::cout << "\"group_id\": \"" << group_id_
<<"\", \"status\": \"ok\"";
} else {
std::cout << "Successfully added the GPU " << gpu_ids_
<< " to group "<< group_id_ << std::endl;
}
return;
}
break;
case GROUP_INFO:
if (!is_group_set_) {
show_help();
throw RdcException(RDC_ST_BAD_PARAMETER,
"Need to specify the group id to show group info");
}
result = rdc_group_gpu_get_info(rdc_handle_,
group_id_, &group_info);
if (result == RDC_ST_OK) {
if (is_json_output()) {
std::cout << "\"group_name\": \"" << group_info.group_name
<< "\", \"gpu_indexes\": [";
} else {
std::cout << "Group name: "
<< group_info.group_name << std::endl;
std::cout << "Gpu indexes: ";
}
for (uint32_t i = 0; i < group_info.count; i++) {
if (is_json_output()) {
std::cout << group_info.entity_ids[i];
if ( i != group_info.count-1 ) {
std::cout << ",";
}
} else {
std::cout << group_info.entity_ids[i] << " ";
}
}
if (is_json_output()) {
std::cout << "], \"status\": \"ok\"";
} else {
std::cout << std::endl;
}
return;
}
break;
default:
throw RdcException(RDC_ST_BAD_PARAMETER, "Unknown command");
}
if (result != RDC_ST_OK) {
throw RdcException(result, rdc_status_string(result));
}
}
} // namespace rdc
} // namespace amd
| 39.337047 | 79 | 0.461479 | [
"vector"
] |
3021d9bd8f18f85195b3894f8b8ed611e3ac17fd | 1,773 | hpp | C++ | algorithms/p677/677.hpp | baishuai/leetcode_go | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | [
"Apache-2.0"
] | 9 | 2017-06-05T15:10:35.000Z | 2021-06-08T03:10:46.000Z | algorithms/p677/677.hpp | baishuai/leetcode | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | [
"Apache-2.0"
] | 3 | 2017-07-12T14:08:39.000Z | 2017-10-11T03:08:15.000Z | algorithms/p677/677.hpp | baishuai/leetcode_go | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | [
"Apache-2.0"
] | 1 | 2017-07-21T03:51:51.000Z | 2017-07-21T03:51:51.000Z |
#ifndef LEETCODE_677_HPP
#define LEETCODE_677_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
struct TrieNode {
int val;
unordered_map<char, TrieNode *> children;
};
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
root = new TrieNode();
}
void insert(string key, int val) {
auto iter = root;
for (char c: key) {
if (iter->children.count(c) == 0 || iter->children[c] == nullptr) {
iter->children[c] = new TrieNode();
}
iter = iter->children[c];
}
iter->val = val;
}
int sum(string prefix) {
auto iter = root;
for (char c: prefix) {
if (iter->children.count(c) == 0 || iter->children[c] == nullptr) {
return 0;
}
iter = iter->children[c];
}
return sumTail(iter);
}
int sumTail(TrieNode *node) {
if (node == nullptr)
return 0;
int ans = node->val;
for (auto &p : node->children) {
ans += sumTail(p.second);
}
return ans;
}
void free(TrieNode *node) {
if (node == nullptr)
return;
for (auto &p : node->children) {
free(p.second);
}
delete node;
}
virtual ~MapSum() {
free(root);
}
private:
TrieNode *root;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
#endif //LEETCODE_677_HPP
| 20.37931 | 79 | 0.530175 | [
"object",
"vector"
] |
3025f8c2707afd63c297a5cc3afe09a06975b737 | 4,002 | cpp | C++ | prog-lab-I/poker.cpp | hsnavarro/CompIME | b4f285826d001b6f818d94636a6294782f1cedf2 | [
"MIT"
] | null | null | null | prog-lab-I/poker.cpp | hsnavarro/CompIME | b4f285826d001b6f818d94636a6294782f1cedf2 | [
"MIT"
] | null | null | null | prog-lab-I/poker.cpp | hsnavarro/CompIME | b4f285826d001b6f818d94636a6294782f1cedf2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
enum figura {DOIS, TRES, QUATRO, CINCO, SEIS, SETE, OITO,
NOVE, DEZ, VALETE, DAMA, REI, AS};
enum simbolo {OUROS, ESPADAS, COPAS, PAUS};
string figuras[13] = {" 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9",
"10", "VA", "DA", "RE", "AS"};
char simbolos[4] = {"O", "E", "C", "P"};
figura f;
struct Carta{
figura valor;
simbolo naipe;
Carta operator++(int){
Carta temp(*this);
if (valor != AS) valor = (figura)(valor + 1);
else{
valor = dois;
if (naipe == PAUS) naipe = OUROS;
else naipe = (simbolo)(naipe + 1);
}
return temp;
}
};
ostream& operator<<(ostream &os, const Carta &carta){
os << figuras[carta.valor] << simbolos[carta.naipe];
return os;
}
Carta proximaCarta(){
static Carta c = {DOIS,OUROS};
return c++;
}
template <class T>
void imprimir(vector<T> v){
for(auto x : v) cout << x << " ";
cout << endl;
}
bool conta_f(const Carta &c){
return c.valor == f;
}
int main(){
srand(time(NULL));
vector<Carta> baralho(52);
generate_n(baralho.begin(), 52, proximaCarta);
/*
cout << "Baralho:\n";
imprimir(baralho);
cout << endl;
*/
random_shuffle(baralho.begin(), baralho.end());
cout << "Baralho:\n";
imprimir(baralho);
cout << endl;
vector< vector<Carta> > maos(4);
vector<Carta> mesa;
vector< vector<Carta> >::iterator it;
vector<Carta>::iterator it2;
for (unsigned k=0;k<2;k++)
for (it = maos.begin();it!=maos.end();it++){
Carta c = *(baralho.rbegin());
baralho.pop_back();
it->push_back(c);
}
//joga fora
baralho.pop_back();
//monta flop
mesa.push_back(*(baralho.rbegin()));
baralho.pop_back();
mesa.push_back(*(baralho.rbegin()));
baralho.pop_back();
mesa.push_back(*(baralho.rbegin()));
baralho.pop_back();
//joga fora
baralho.pop_back();
//monta turn
mesa.push_back(*(baralho.rbegin()));
baralho.pop_back();
//joga fora
baralho.pop_back();
//monta river
mesa.push_back(*(baralho.rbegin()));
baralho.pop_back();
unsigned m = 1;
for (it = maos.begin();it!=maos.end();it++){
it->reserve(it->size()+distance(mesa.begin(),mesa.end()));
it->insert(it->end(), mesa.begin(), mesa.end());
cout << "Mao " << m++ << ": ";
imprimir(*it);
}
cout << "Mesa : ";
imprimir(mesa);
m = 1;
for (it = maos.begin();it!=maos.end();it++){
int nduplas = 0, ntrincas = 0, nquadras = 0;
for (f=dois;f<=as;f = (figura)(f+1)){
int conta = count_if(it->begin(), it->end(),
conta_f);
switch (conta){
case 2:
cout << "Mao " << m <<
" possui dupla de " <<
figuras[f] << endl;
nduplas++;
break;
case 3:
cout << "Mao " << m <<
" possui trinca de " <<
figuras[f] << endl;
ntrincas++;
break;
case 4:
cout << "Mao " << m <<
" possui quadra de " <<
figuras[f] << endl;
nquadras++;
break;
}
}
if (nquadras>0 && (nduplas>0 || ntrincas>0))
cout << "Mao " << m <<
" possui Full House" << endl;
else
if (ntrincas>0 && nduplas>0)
cout << "Mao " << m <<
" possui Full House" << endl;
else
if (ntrincas>1)
cout << "Mao " << m <<
" possui Full House" << endl;
m++;
}
/*
cout << "Baralho:\n";
imprimir(baralho);
cout << endl;
Carta c;
c.valor = valete;
c.naipe = ouros;
cout << c << endl;
*/
return 0;
}
| 24.552147 | 69 | 0.465267 | [
"vector"
] |
6f74e9d0bb0034fa8cc4d07d31de64f4cd9283a8 | 7,236 | hpp | C++ | include/URDriver/RTDeserialize.hpp | AliRoshanbin/URDriver-1 | 7ed462ff86e242de1e8d148a13a489340cbe6a3e | [
"MIT"
] | 3 | 2016-03-09T10:06:10.000Z | 2021-11-10T16:26:40.000Z | include/URDriver/RTDeserialize.hpp | AliRoshanbin/URDriver-1 | 7ed462ff86e242de1e8d148a13a489340cbe6a3e | [
"MIT"
] | null | null | null | include/URDriver/RTDeserialize.hpp | AliRoshanbin/URDriver-1 | 7ed462ff86e242de1e8d148a13a489340cbe6a3e | [
"MIT"
] | 4 | 2017-02-09T11:00:16.000Z | 2021-04-01T13:34:43.000Z | /*
* RTDeserialize.hpp
*
* Created on: Dec 9, 2015
* Author: apertuscus
*/
#include <sys/socket.h>
#include <arpa/inet.h>
#ifndef SRC_RTDESERIALIZE_HPP_
#define SRC_RTDESERIALIZE_HPP_
using namespace std;
#include "utils.hpp"
class RTdata
{
protected:
std::string type;
int size;
bool configured;
public:
RTdata(): type("UNSET"),
size(-1),configured(false){}
typedef boost::shared_ptr<RTdata> Ptr;
virtual ~RTdata(){}
/**
* @brief read the data structure from the data
* @param sockfd socket descriptor
* @return negative with an error (to be doumented in specific implementations)
* otherwise the bytes read
*/
virtual int readRTData(int)=0;
/** @name Getter functions
* These functions all returns false if they are not
* implemented in the derived class, or the size of vectors
* is wrong.
*/
///@{
///Getter function for time
virtual int getType(string &t)const{t=type; return -1;}
//! Getter function for expected size in byte of the struct given by the robot.
/**
* Useful for checking after calling RTdata#readRTData
*/
virtual int getNominalSize(int &t)const{t=size; return -1;}
///Getter function for time
virtual int getTime ( double&t)const {return -1;}
///Getter function for joint value
virtual int getQ_actual ( vector<double>&t)const {return -1;}
///Getter function for joint velocity value
virtual int getQdot_actual ( vector<double>&t)const {return -1;}
///@}
};
//!This class implements the protocol for controller form v5.4 and v5.9.
/**
* details here
*/
class RTdataV59:public RTdata
{
public:
RTdataV59(){size=1116;type="5.4 to 5.9";}
int getNominalSize ( int&t)const {t=sizeof(data);return 1;}
int getTime ( double&t)const {t=data.Time;return 1;}
int getQ_actual ( vector<double>&q)const
{if (copyvector(data.q_actual,q,6)) return 1; return 0;}
int getQdot_actual ( vector<double>&qd)const
{if (copyvector(data.qd_actual,qd,6)) return 1; return 0;}
/**
* Reads the data from the socket and fill in the internal data structure
* @param sockfd socket identifier
* @return number of bytes read
*/
int readRTData(const int sockfd)
{
int n = read(sockfd,&data,sizeof(data));
// std::cout << "sizeof(data):" <<std::endl;
// std::cout << sizeof(data) <<std::endl;
data.Message_Size=ntohl(data.Message_Size);
double * pointer=&data.Time;
for (int i=0;i<139;i++)
{
ntohd(pointer[i]);
}
return n;
};
private:
//!This struct follows the indication of sheet 43 of the specfication given by UR.
/**For more info, look to
* (../Client_InterfaceV3.14andV5.9.xlsx), page 43
*
*/
#pragma pack(1)
struct data_struct{
int Message_Size;
double Time;
double q_target[6],
qd_target [6],
qdd_target [6],
I_target [6],
M_target [6],
q_actual [6],
qd_actual [6],
I_actual [6],
I_control [6],
Tool_vector_actual [6],
TCP_speed_actual [6],
TCP_force [6],
Tool_vector_target [6],
TCP_speed_target[6] ;
double Digital_input_bits;
double Motor_temperatures[6];
double Controller_Timer ,
Test_value ,
Robot_Mode ;
double Joint_Modes[6];
double Safety_Mode ;
double UNUSED1[6] ;//6
double Tool_Accelerometer_values[3];//3
double UNUSED2 [6];//6
double Speed_scaling,
Linear_momentum_norm,
UNUSED3,
UNUSED4,
V_main ,
V_robot,
I_robot;
double V_actual[6],//6
Digital_outputs,
Program_state,
Elbow_position[3],
Elbow_velocity[3],
Safety_Status;
} ;
#pragma pack(0)
data_struct data;
};
//!This class implements the protocol for controller v3.0 and v3.1.
/**
* details here
*/
class RTdataV31:public RTdata
{
public:
RTdataV31(){size=1044;type="3.0 and 3.1";}
int getNominalSize ( int&t)const {t=sizeof(data);return 1;}
int getTime ( double&t)const {t=data.Time;return 1;}
int getQ_actual ( vector<double>&q)const
{if (copyvector(data.q_actual,q,6)) return 1; return 0;}
int getQdot_actual ( vector<double>&qd)const
{if (copyvector(data.qd_actual,qd,6)) return 1; return 0;}
/**
* Reads the data from the socket and fill in the internal data structure
* @param sockfd socket identifier
* @return number of bytes read
*/
int readRTData(const int sockfd)
{
int n = read(sockfd,&data,sizeof(data));
data.Message_Size=ntohl(data.Message_Size);
double * pointer=&data.Time;
for (int i=0;i<130;i++)
{
ntohd(pointer[i]);
}
return n;
};
private:
//!This struct follows the indication of sheet 16 of the specfication given by UR.
/**For more info, look to
* [Client_Interface.xlsx](../Client_Interface.xlsx), page 16
*
*/
#pragma pack(1)
struct data_struct{
int Message_Size;
double Time;
double q_target[6],
qd_target [6],
qdd_target [6],
I_target [6],
M_target [6],
q_actual [6],
qd_actual [6],
I_actual [6],
I_control [6],
Tool_vector_actual [6],
TCP_speed_actual [6],
TCP_force [6],
Tool_vector_target [6],
TCP_speed_target[6] ;
double Digital_input_bits;
double Motor_temperatures[6];
double Controller_Timer ,
Test_value ,
Robot_Mode ;
double Joint_Modes[6];
double Safety_Mode ;
double UNUSED1[6] ;//6
double Tool_Accelerometer_values[3];//3
double UNUSED2 [6];//6
double Speed_scaling,
Linear_momentum_norm,
UNUSED3,
UNUSED4,
V_main ,
V_robot,
I_robot;
double V_actual[6];//6
} ;
#pragma pack(0)
data_struct data;
};
//!This class implements the protocol for controller Pre-3.0.
/**
* details here
*/
class RTdataV18:public RTdata
{
public:
RTdataV18(){size=764;type="Pre-3.0";}
int getNominalSize ( int&t)const {t=sizeof(data);return 1;}
int getTime ( double&t)const {t=data.Time;return 1;}
int getQ_actual ( vector<double>&q)const
{if (copyvector(data.q_actual,q,6)) return 1; return 0;}
int getQdot_actual ( vector<double>&qd)const
{if (copyvector(data.qd_actual,qd,6)) return 1; return 0;}
/**
* Reads the data from the socket and fill in the internal data structure
* @param sockfd socket identifier
* @return number of bytes read
*/
int readRTData(const int sockfd)
{
int n = read(sockfd,&data,sizeof(data));
data.Message_Size=ntohl(data.Message_Size);
double * pointer=&data.Time;
for (int i=0;i<95;i++)
ntohd(pointer[i]);
return n;
};
private:
//!This struct follows the indication of sheet 16 of the specfication given by UR.
/**For more info, look to
* [Client_Interface.xlsx](../Client_Interface.xlsx), page 15
*
* note from the documentation:
* `` If it is experienced that less than 756 bytes
* are received, the protocol for the actual received
* bytes also follows the structure listed above, only
* not containing the entries at leading up the 756th byte. ''
*/
#pragma pack(1)
struct data_struct{
int Message_Size;
double Time;
double q_target[6],
qd_target [6],
qdd_target [6],
I_target [6],
M_target [6],
q_actual [6],
qd_actual [6],
I_actual [6],
Tool_Accelerometer_values [3],
UNUSED[15],
TCP_force [6],
Tool_vector [6],
TCP_speed [6] ;
double Digital_input_bits;
double Motor_temperatures[6];
double Controller_Timer ,
Test_value ,
Robot_Mode ;
double Joint_Modes[6];
} ;
#pragma pack(0)
data_struct data;
};
#endif /* SRC_RTDESERIALIZE_HPP_ */ | 22.060976 | 83 | 0.687258 | [
"vector"
] |
6f7820088d6d40038f5d124ae0b14c283d52bc6c | 856 | cpp | C++ | 7_longestNoReapeatingLength.cpp | Cheemion/Leetcode | e0fee06896b13b1efb11338c383dafd5d0dfed19 | [
"MIT"
] | null | null | null | 7_longestNoReapeatingLength.cpp | Cheemion/Leetcode | e0fee06896b13b1efb11338c383dafd5d0dfed19 | [
"MIT"
] | null | null | null | 7_longestNoReapeatingLength.cpp | Cheemion/Leetcode | e0fee06896b13b1efb11338c383dafd5d0dfed19 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<unordered_set>
using std::vector;
using std::unordered_set;
class Solution {
public:
/**
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
if(arr.size() < 2)
return arr.size();
int i = 0;
int j = 0;
int res = 0;
std::unordered_set<int> set;
while(j < arr.size()) {
if(set.find(arr[j]) != set.end()) { // include
set.erase(arr[i]);
i++;
} else {
set.insert(arr[j]);
j++;
}
res = std::max(res, j - i);
}
return res;
}
};
int main(){
Solution s;
vector<int> ints = {1, 2, 3, 4, 1, 2, 2};
std::cout << s.maxLength(ints) << std::endl;
return 0;
} | 22.526316 | 58 | 0.455607 | [
"vector"
] |
6f7a40a9feab6645c0b537036894f0e466ddd18e | 2,897 | cpp | C++ | day-20/part-2/ayoub.cpp | lypnol/adventofcode-2017 | 03ced3df3eb80e5c7965c4120e3932919067cb15 | [
"MIT"
] | 16 | 2017-12-02T11:56:25.000Z | 2018-02-10T15:09:23.000Z | day-20/part-2/ayoub.cpp | lypnol/adventofcode-2017 | 03ced3df3eb80e5c7965c4120e3932919067cb15 | [
"MIT"
] | 19 | 2017-12-01T07:54:22.000Z | 2017-12-19T17:41:02.000Z | day-20/part-2/ayoub.cpp | lypnol/adventofcode-2017 | 03ced3df3eb80e5c7965c4120e3932919067cb15 | [
"MIT"
] | 4 | 2017-12-04T23:58:12.000Z | 2018-02-01T08:53:16.000Z | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
typedef struct {
int64_t x, y, z;
} coord_t;
typedef struct {
coord_t p, v, a;
bool removed;
} kinetic_t;
void get_numbers(string line, vector<string>& match) {
string number = "";
for (size_t i = 0; i < line.size(); i++) {
if (line.at(i) == '-' || (line.at(i) >= '0' && line.at(i) <= '9')) {
number.append(1, line.at(i));
} else if (number.size()) {
match.push_back(number);
number.clear();
}
}
}
kinetic_t parse_line(string line) {
kinetic_t res;
vector<string> match;
get_numbers(line, match);
res.p.x = stoi(match[0]);
res.p.y = stoi(match[1]);
res.p.z = stoi(match[2]);
res.v.x = stoi(match[3]);
res.v.y = stoi(match[4]);
res.v.z = stoi(match[5]);
res.a.x = stoi(match[6]);
res.a.y = stoi(match[7]);
res.a.z = stoi(match[8]);
res.removed = false;
return res;
}
bool simulate(vector<kinetic_t>& particles) {
for (size_t i = 0; i < particles.size(); i++) {
if (particles[i].removed) continue;
particles[i].v.x += particles[i].a.x;
particles[i].v.y += particles[i].a.y;
particles[i].v.z += particles[i].a.z;
particles[i].p.x += particles[i].v.x;
particles[i].p.y += particles[i].v.y;
particles[i].p.z += particles[i].v.z;
}
bool collision = false;
for (size_t i = 0; i < particles.size(); i++) {
if (particles[i].removed) continue;
for (size_t j = i+1; j < particles.size(); j++) {
if (particles[j].removed) continue;
if (particles[i].p.x == particles[j].p.x &&
particles[i].p.y == particles[j].p.y &&
particles[i].p.z == particles[j].p.z) {
particles[i].removed = true;
particles[j].removed = true;
collision = true;
}
}
}
return collision;
}
size_t cout_left(vector<kinetic_t>& particles) {
size_t res = 0;
for (size_t i = 0; i < particles.size(); i++) {
if (!particles[i].removed) res++;
}
return res;
}
string run(string s) {
istringstream input(s);
string line;
vector<kinetic_t> particles;
while (getline(input, line, '\n')) {
if(line.size() == 0) continue;
particles.push_back(parse_line(line));
}
bool collision = false;
int64_t frames = 1000;
do {
collision = simulate(particles);
if (collision) frames = 1000;
else frames--;
} while(frames);
return to_string(cout_left(particles));
}
int main(int argc, char** argv) {
if (argc < 2) {
cout << "Missing one argument" << endl;
exit(1);
}
cout << run(string(argv[1])) << "\n";
return 0;
} | 23.942149 | 76 | 0.530204 | [
"vector"
] |
6f8002c6485e4f64ad12eb44a6a1093075445f70 | 7,443 | cc | C++ | opensfm/src/features/src/hahog.cc | ashishd/OpenSfM | f66e51df7200fac676d8487499ebaf40e3de3e88 | [
"BSD-2-Clause"
] | null | null | null | opensfm/src/features/src/hahog.cc | ashishd/OpenSfM | f66e51df7200fac676d8487499ebaf40e3de3e88 | [
"BSD-2-Clause"
] | null | null | null | opensfm/src/features/src/hahog.cc | ashishd/OpenSfM | f66e51df7200fac676d8487499ebaf40e3de3e88 | [
"BSD-2-Clause"
] | null | null | null | #include <features/hahog.h>
#include <iostream>
#include <vector>
extern "C" {
#include <time.h>
#include <vl/covdet.h>
#include <vl/sift.h>
}
namespace features {
// from VLFeat implementation of _vl_compare_scores
static int vlfeat_compare_scores(const void *a, const void *b) {
float fa = ((VlCovDetFeature *)a)->peakScore;
float fb = ((VlCovDetFeature *)b)->peakScore;
return (fb > fa) - (fb < fa);
}
// select 'target_num_features' for using feature's scores
vl_size select_best_features(VlCovDet *covdet, vl_size num_features,
vl_size target_num_features) {
if (num_features > target_num_features) {
qsort(vl_covdet_get_features(covdet), num_features, sizeof(VlCovDetFeature),
vlfeat_compare_scores);
return target_num_features;
} else {
return num_features;
}
}
// select 'target_num_features' that have a maximum score in their neighbhood.
// The neighborhood is computing using the feature's scale and
// 'non_extrema_suppression' as : neighborhood = non_extrema_suppression * scale
vl_size run_non_maxima_suppression(VlCovDet *covdet, vl_size num_features,
double non_extrema_suppression) {
vl_index i, j;
double tol = non_extrema_suppression;
VlCovDetFeature *features = (VlCovDetFeature *)vl_covdet_get_features(covdet);
for (i = 0; i < (signed)num_features; ++i) {
double x = features[i].frame.x;
double y = features[i].frame.y;
double sigma = features[i].frame.a11;
double score = features[i].peakScore;
for (j = 0; j < (signed)num_features; ++j) {
double dx_ = features[j].frame.x - x;
double dy_ = features[j].frame.y - y;
double sigma_ = features[j].frame.a11;
double score_ = features[j].peakScore;
if (score_ == 0) continue;
if (sigma < (1 + tol) * sigma_ && sigma_ < (1 + tol) * sigma &&
vl_abs_d(dx_) < tol * sigma && vl_abs_d(dy_) < tol * sigma &&
vl_abs_d(score) > vl_abs_d(score_)) {
features[j].peakScore = 0;
}
}
}
j = 0;
for (i = 0; i < (signed)num_features; ++i) {
VlCovDetFeature feature = features[i];
if (features[i].peakScore != 0) {
features[j++] = feature;
}
}
return j;
}
vl_size run_features_selection(VlCovDet *covdet, vl_size target_num_features) {
vl_size numFeaturesKept = vl_covdet_get_num_features(covdet);
// keep only 1.5 x targetNumFeatures for speeding-up duplicate detection
if (target_num_features != 0) {
const int to_keep = 3 * target_num_features / 2;
numFeaturesKept = select_best_features(covdet, numFeaturesKept, to_keep);
}
// Remove non-maxima-in-their-neighborhood features
const double nonMaximaSuppressionTol =
vl_covdet_get_non_extrema_suppression_threshold(covdet);
if (nonMaximaSuppressionTol > 0.) {
numFeaturesKept = run_non_maxima_suppression(covdet, numFeaturesKept,
nonMaximaSuppressionTol);
}
// Keep the N best
return select_best_features(covdet, numFeaturesKept, target_num_features);
}
std::vector<VlCovDetFeature> vlfeat_covdet_extract_orientations(
VlCovDet *covdet, vl_size num_features) {
VlCovDetFeature *features = (VlCovDetFeature *)vl_covdet_get_features(covdet);
std::vector<VlCovDetFeature> vecFeatures;
vecFeatures.reserve(num_features);
vl_index i, j;
for (i = 0; i < (signed)num_features; ++i) {
vl_size numOrientations;
VlCovDetFeature feature = features[i];
VlCovDetFeatureOrientation *orientations =
vl_covdet_extract_orientations_for_frame(covdet, &numOrientations,
feature.frame);
for (j = 0; j < (signed)numOrientations; ++j) {
double A[2 * 2] = {feature.frame.a11, feature.frame.a21,
feature.frame.a12, feature.frame.a22};
double r1 = cos(orientations[j].angle);
double r2 = sin(orientations[j].angle);
vecFeatures.emplace_back(features[i]);
VlCovDetFeature &oriented = vecFeatures.back();
oriented.orientationScore = orientations[j].score;
oriented.frame.a11 = +A[0] * r1 + A[2] * r2;
oriented.frame.a21 = +A[1] * r1 + A[3] * r2;
oriented.frame.a12 = -A[0] * r2 + A[2] * r1;
oriented.frame.a22 = -A[1] * r2 + A[3] * r1;
}
}
return vecFeatures;
}
py::tuple hahog(foundation::pyarray_f image, float peak_threshold,
float edge_threshold, int target_num_features) {
if (!image.size()) {
return py::none();
}
std::vector<float> points;
std::vector<float> desc;
vl_size numFeatures;
vl_size dimension = 128;
{
py::gil_scoped_release release;
// create a detector object
VlCovDet *covdet = vl_covdet_new(VL_COVDET_METHOD_HESSIAN);
// set various parameters (optional)
vl_covdet_set_first_octave(covdet, 0);
vl_covdet_set_peak_threshold(covdet, peak_threshold);
vl_covdet_set_edge_threshold(covdet, edge_threshold);
// process the image and run the detector
vl_covdet_put_image(covdet, image.data(), image.shape(1), image.shape(0));
vl_covdet_set_non_extrema_suppression_threshold(covdet, 0);
vl_covdet_detect(covdet, std::numeric_limits<vl_size>::max());
// select the best features to keep
numFeatures = run_features_selection(covdet, target_num_features);
// compute the orientation of the features (optional)
std::vector<VlCovDetFeature> vecFeatures =
vlfeat_covdet_extract_orientations(covdet, numFeatures);
numFeatures = vecFeatures.size();
// get feature descriptors
VlSiftFilt *sift = vl_sift_new(16, 16, 1, 3, 0);
vl_index i;
vl_index patchResolution = 15;
double patchRelativeExtent = 7.5;
double patchRelativeSmoothing = 1;
vl_size patchSide = 2 * patchResolution + 1;
double patchStep = (double)patchRelativeExtent / patchResolution;
points.resize(4 * numFeatures);
desc.resize(dimension * numFeatures);
std::vector<float> patch(patchSide * patchSide);
std::vector<float> patchXY(2 * patchSide * patchSide);
vl_sift_set_magnif(sift, 3.0);
for (i = 0; i < (signed)numFeatures; ++i) {
const VlFrameOrientedEllipse &frame = vecFeatures.at(i).frame;
float det = frame.a11 * frame.a22 - frame.a12 * frame.a21;
float size = sqrt(fabs(det));
float angle = atan2(frame.a21, frame.a11) * 180.0f / M_PI;
points[4 * i + 0] = frame.x;
points[4 * i + 1] = frame.y;
points[4 * i + 2] = size;
points[4 * i + 3] = angle;
vl_covdet_extract_patch_for_frame(covdet, &patch[0], patchResolution,
patchRelativeExtent,
patchRelativeSmoothing, frame);
vl_imgradient_polar_f(&patchXY[0], &patchXY[1], 2, 2 * patchSide,
&patch[0], patchSide, patchSide, patchSide);
vl_sift_calc_raw_descriptor(
sift, &patchXY[0], &desc[dimension * i], (int)patchSide,
(int)patchSide, (double)(patchSide - 1) / 2,
(double)(patchSide - 1) / 2,
(double)patchRelativeExtent / (3.0 * (4 + 1) / 2) / patchStep,
VL_PI / 2);
}
vl_sift_delete(sift);
vl_covdet_delete(covdet);
}
return py::make_tuple(
foundation::py_array_from_data(points.data(), numFeatures, 4),
foundation::py_array_from_data(desc.data(), numFeatures, dimension));
}
} // namespace features
| 36.307317 | 80 | 0.659277 | [
"object",
"shape",
"vector"
] |
6f858e24aceb3056dac6752e3e4028c2dca69cd2 | 16,558 | cpp | C++ | pywinrt/winsdk/src/py.Windows.System.Preview.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | 3 | 2022-02-14T14:53:08.000Z | 2022-03-29T20:48:54.000Z | pywinrt/winsdk/src/py.Windows.System.Preview.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | 4 | 2022-01-28T02:53:52.000Z | 2022-02-26T18:10:05.000Z | pywinrt/winsdk/src/py.Windows.System.Preview.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | null | null | null | // WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4
#include "pybase.h"
#include "py.Windows.System.Preview.h"
PyTypeObject* py::winrt_type<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs>::python_type;
namespace py::cpp::Windows::System::Preview
{
// ----- TwoPanelHingedDevicePosturePreview class --------------------
constexpr const char* const _type_name_TwoPanelHingedDevicePosturePreview = "TwoPanelHingedDevicePosturePreview";
static PyObject* _new_TwoPanelHingedDevicePosturePreview(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_TwoPanelHingedDevicePosturePreview);
return nullptr;
}
static void _dealloc_TwoPanelHingedDevicePosturePreview(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreview* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* TwoPanelHingedDevicePosturePreview_GetCurrentPostureAsync(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreview* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetCurrentPostureAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreview_GetDefaultAsync(PyObject* /*unused*/, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview::GetDefaultAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreview_add_PostureChanged(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreview* self, PyObject* arg) noexcept
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview, winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs>>(arg);
return py::convert(self->obj.PostureChanged(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreview_remove_PostureChanged(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreview* self, PyObject* arg) noexcept
{
try
{
auto param0 = py::convert_to<winrt::event_token>(arg);
self->obj.PostureChanged(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_TwoPanelHingedDevicePosturePreview(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_TwoPanelHingedDevicePosturePreview[] = {
{ "get_current_posture_async", reinterpret_cast<PyCFunction>(TwoPanelHingedDevicePosturePreview_GetCurrentPostureAsync), METH_VARARGS, nullptr },
{ "get_default_async", reinterpret_cast<PyCFunction>(TwoPanelHingedDevicePosturePreview_GetDefaultAsync), METH_VARARGS | METH_STATIC, nullptr },
{ "add_posture_changed", reinterpret_cast<PyCFunction>(TwoPanelHingedDevicePosturePreview_add_PostureChanged), METH_O, nullptr },
{ "remove_posture_changed", reinterpret_cast<PyCFunction>(TwoPanelHingedDevicePosturePreview_remove_PostureChanged), METH_O, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_TwoPanelHingedDevicePosturePreview), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_TwoPanelHingedDevicePosturePreview[] = {
{ }
};
static PyType_Slot _type_slots_TwoPanelHingedDevicePosturePreview[] =
{
{ Py_tp_new, _new_TwoPanelHingedDevicePosturePreview },
{ Py_tp_dealloc, _dealloc_TwoPanelHingedDevicePosturePreview },
{ Py_tp_methods, _methods_TwoPanelHingedDevicePosturePreview },
{ Py_tp_getset, _getset_TwoPanelHingedDevicePosturePreview },
{ },
};
static PyType_Spec _type_spec_TwoPanelHingedDevicePosturePreview =
{
"_winsdk_Windows_System_Preview.TwoPanelHingedDevicePosturePreview",
sizeof(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreview),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_TwoPanelHingedDevicePosturePreview
};
// ----- TwoPanelHingedDevicePosturePreviewReading class --------------------
constexpr const char* const _type_name_TwoPanelHingedDevicePosturePreviewReading = "TwoPanelHingedDevicePosturePreviewReading";
static PyObject* _new_TwoPanelHingedDevicePosturePreviewReading(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_TwoPanelHingedDevicePosturePreviewReading);
return nullptr;
}
static void _dealloc_TwoPanelHingedDevicePosturePreviewReading(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* TwoPanelHingedDevicePosturePreviewReading_get_HingeState(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.HingeState());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreviewReading_get_Panel1Id(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Panel1Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreviewReading_get_Panel1Orientation(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Panel1Orientation());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreviewReading_get_Panel2Id(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Panel2Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreviewReading_get_Panel2Orientation(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Panel2Orientation());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* TwoPanelHingedDevicePosturePreviewReading_get_Timestamp(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Timestamp());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_TwoPanelHingedDevicePosturePreviewReading(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_TwoPanelHingedDevicePosturePreviewReading[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_TwoPanelHingedDevicePosturePreviewReading), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_TwoPanelHingedDevicePosturePreviewReading[] = {
{ "hinge_state", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReading_get_HingeState), nullptr, nullptr, nullptr },
{ "panel1_id", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReading_get_Panel1Id), nullptr, nullptr, nullptr },
{ "panel1_orientation", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReading_get_Panel1Orientation), nullptr, nullptr, nullptr },
{ "panel2_id", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReading_get_Panel2Id), nullptr, nullptr, nullptr },
{ "panel2_orientation", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReading_get_Panel2Orientation), nullptr, nullptr, nullptr },
{ "timestamp", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReading_get_Timestamp), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_TwoPanelHingedDevicePosturePreviewReading[] =
{
{ Py_tp_new, _new_TwoPanelHingedDevicePosturePreviewReading },
{ Py_tp_dealloc, _dealloc_TwoPanelHingedDevicePosturePreviewReading },
{ Py_tp_methods, _methods_TwoPanelHingedDevicePosturePreviewReading },
{ Py_tp_getset, _getset_TwoPanelHingedDevicePosturePreviewReading },
{ },
};
static PyType_Spec _type_spec_TwoPanelHingedDevicePosturePreviewReading =
{
"_winsdk_Windows_System_Preview.TwoPanelHingedDevicePosturePreviewReading",
sizeof(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_TwoPanelHingedDevicePosturePreviewReading
};
// ----- TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs class --------------------
constexpr const char* const _type_name_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs = "TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs";
static PyObject* _new_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs);
return nullptr;
}
static void _dealloc_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs_get_Reading(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Reading());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs[] = {
{ "reading", reinterpret_cast<getter>(TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs_get_Reading), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs[] =
{
{ Py_tp_new, _new_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs },
{ Py_tp_dealloc, _dealloc_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs },
{ Py_tp_methods, _methods_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs },
{ Py_tp_getset, _getset_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs },
{ },
};
static PyType_Spec _type_spec_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs =
{
"_winsdk_Windows_System_Preview.TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs",
sizeof(py::wrapper::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs
};
// ----- Windows.System.Preview Initialization --------------------
static int module_exec(PyObject* module) noexcept
{
try
{
py::pyobj_handle bases { PyTuple_Pack(1, py::winrt_type<py::Object>::python_type) };
py::winrt_type<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview>::python_type = py::register_python_type(module, _type_name_TwoPanelHingedDevicePosturePreview, &_type_spec_TwoPanelHingedDevicePosturePreview, bases.get());
py::winrt_type<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading>::python_type = py::register_python_type(module, _type_name_TwoPanelHingedDevicePosturePreviewReading, &_type_spec_TwoPanelHingedDevicePosturePreviewReading, bases.get());
py::winrt_type<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs>::python_type = py::register_python_type(module, _type_name_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs, &_type_spec_TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs, bases.get());
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyModuleDef_Slot module_slots[] = {{Py_mod_exec, module_exec}, {}};
PyDoc_STRVAR(module_doc, "Windows.System.Preview");
static PyModuleDef module_def
= {PyModuleDef_HEAD_INIT,
"_winsdk_Windows_System_Preview",
module_doc,
0,
nullptr,
module_slots,
nullptr,
nullptr,
nullptr};
} // py::cpp::Windows::System::Preview
PyMODINIT_FUNC
PyInit__winsdk_Windows_System_Preview (void) noexcept
{
return PyModuleDef_Init(&py::cpp::Windows::System::Preview::module_def);
}
| 41.086849 | 321 | 0.685228 | [
"object"
] |
6f882a5197452c524c824180c9bc376037699f82 | 2,538 | cpp | C++ | API CPP/api-cpp-sugar-free-1.0/src/TestJson/test.cpp | Souto751/isft151-practicas-2 | 261dd50b50954207a652df4dc45e980db460e0f1 | [
"Apache-2.0"
] | null | null | null | API CPP/api-cpp-sugar-free-1.0/src/TestJson/test.cpp | Souto751/isft151-practicas-2 | 261dd50b50954207a652df4dc45e980db460e0f1 | [
"Apache-2.0"
] | null | null | null | API CPP/api-cpp-sugar-free-1.0/src/TestJson/test.cpp | Souto751/isft151-practicas-2 | 261dd50b50954207a652df4dc45e980db460e0f1 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2016 Gabriel Ferreira <gabrielinuz@gmail.com>. All rights reserved.
* This file is part of API-CPP-SET.
* Released under the GPL3 license
* https://opensource.org/licenses/GPL-3.0
**/
#include <string>
#include <iostream>
#include <fstream>
#include <vendors/nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON object
//~ nlohmann::json j =
//~ {
//~ {"pi", 3.141},
//~ {"happy", true},
//~ {"name", "Niels"},
//~ {"nothing", nullptr},
//~ {
//~ "answer", {
//~ {"everything", 42}
//~ }
//~ },
//~ {"list", {1, 0, 2}},
//~ {
//~ "object", {
//~ {"currency", "USD"},
//~ {"value", 42.99}
//~ }
//~ }
//~ };
// add new values
//~ j["new"]["key"]["value"] = {"another", "list"};
// count elements
//~ auto s = j.size();
//~ j["size"] = s;
// pretty print with indent of 4 spaces
//~ std::cout << std::setw(4) << j << '\n';
// deserialize from standard input
//~ nlohmann::json j;
//~ std::cin >> j;
// serialize to standard output
//~ std::cout << j;
// the setw manipulator was overloaded to set the indentation for pretty printing
//~ std::cout << std::setw(4) << j << std::endl;
// read a JSON file
std::ifstream i("./example.json");
json j;
i >> j;
std::cout << std::setw(4) << j << std::endl;
// write prettified JSON to another file
std::ofstream o("./pretty.json");
o << std::setw(4) << j << std::endl;
std::cout << "" << std::endl;
std::cout << "RESULT:" << std::endl;
std::cout << "\t\tTEST JSON FILE OK!!!!!" << std::endl;
std::cout << "" << std::endl;
std::cout << "" << std::endl;
std::cout << "" << std::endl;
std::cout << "STANDARD INPUT JSON:" << std::endl;
// deserialize from standard input
json j2;
try
{
std::cin >> j2;
std::cout << std::setw(4) << j2 << std::endl;
std::cout << "\t\tTEST JSON STANDARD INPUT OK!!!!!" << std::endl;
}
catch(json::exception& e)
{
std::cout << "\t\tTEST JSON STANDARD INPUT FAIL, INCORRECT FORMAT!!!!!" << std::endl;
// output exception information
std::cout << "message: " << e.what() << '\n'
<< "exception id: " << e.id << std::endl;
}
std::cout << "" << std::endl;
std::cout << "" << std::endl;
return 0;
} | 26.164948 | 93 | 0.475571 | [
"object"
] |
6f911616a1072d69aedf124dcd770540bc6ecb6d | 6,115 | cpp | C++ | src/vm.cpp | aimktech/chip8 | 40f278e2638eb95abb2f7b979a4d8bfa69d2400b | [
"Apache-2.0"
] | 3 | 2021-01-20T21:26:30.000Z | 2021-12-17T10:09:54.000Z | src/vm.cpp | aimktech/chip8 | 40f278e2638eb95abb2f7b979a4d8bfa69d2400b | [
"Apache-2.0"
] | null | null | null | src/vm.cpp | aimktech/chip8 | 40f278e2638eb95abb2f7b979a4d8bfa69d2400b | [
"Apache-2.0"
] | null | null | null | /*
* vm.cpp
* Chip8 Virtual Machine implementation
*/
// includes
#include <fstream>
#include <SDL2/SDL.h>
#include "vm.h"
#include "mmu.h"
#include "cpu.h"
#include "display.h"
#include "keyboard.h"
#include "romset.h"
#include "constants.h"
#include "except.h"
// Virtual Machine structure
struct VM::OpaqueData
{
std::unique_ptr<MMU> memory;
std::unique_ptr<CPU> cpu;
std::unique_ptr<Display> display;
std::unique_ptr<Keyboard> keyboard;
void create();
void destroy();
void initMemory();
void updateTimers();
};
// initialize structure
void VM::OpaqueData::create()
{
// create main memory management unit
memory = std::unique_ptr<MMU>(new (std::nothrow) MMU);
if( memory == nullptr )
throw VMError("Unable to allocate memory for the Memory Unit.");
// create display
display = std::unique_ptr<Display>(new (std::nothrow) Display(
memory.get(),
MemoryDefaultValue::SCREEN_WIDTH, MemoryDefaultValue::SCREEN_HEIGHT,
MemoryDefaultValue::SCREEN_XSCALE, MemoryDefaultValue::SCREEN_YSCALE));
if( display == nullptr )
throw VMError("Unable to allocate memory for the Display Unit.");
// create the keyboard
keyboard = std::unique_ptr<Keyboard>(new (std::nothrow) Keyboard(memory.get()));
if( keyboard == nullptr )
throw VMError("Unable to allocate memory for the Keyboard Unit.");
// create CPU
cpu = std::unique_ptr<CPU>(new (std::nothrow) CPU(memory.get()));
if( cpu == nullptr )
throw VMError("Unable to allocate memory for the CPU Unit.");
// init the memory
initMemory();
}
// de-initialize structure
void VM::OpaqueData::destroy()
{ }
// initialize VM memory
void VM::OpaqueData::initMemory()
{
// initialize the romset
memory->loadMemory(MemoryZone::ROM_BEGIN, sizeof(romset), &romset[0]);
}
// update timers
void VM::OpaqueData::updateTimers()
{
byte_t value{0};
// update sound timer
value = memory->readB(MemoryRegister::SOUND_TIMER);
if(value > 0) {
value--;
memory->writeB(MemoryRegister::SOUND_TIMER, value);
}
// update delay timer
value = memory->readB(MemoryRegister::DELAY_TIMER);
if(value > 0) {
value--;
memory->writeB(MemoryRegister::DELAY_TIMER, value);
}
}
// Constructor
VM::VM() :
data_(new (std::nothrow) OpaqueData)
{
if( data_ == nullptr ) {
throw VMError("Unable to allocate memory for VM structure.");
}
if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0 ) {
throw VMError("Unable to initialize SDL library.");
}
data_->create();
}
// desctructor
VM::~VM()
{
data_->destroy();
SDL_Quit();
}
// VM initialization
void VM::init()
{
// nothing to be done here
}
// VM mainloop
void VM::run()
{
bool quit = false;
SDL_Event e;
int fps = 60;
int framerate = 1000 / fps;
int lasttime = SDL_GetTicks();
int speed = 1;
bool isPaused = false;
while(!quit)
{
// treats all events
if( SDL_PollEvent(&e) != 0 ) {
if( e.type == SDL_QUIT )
quit = true;
else
{
if( e.type == SDL_KEYDOWN )
{
switch(e.key.keysym.sym)
{
case SDLK_ESCAPE: // Quit the emulator with ESC
quit = true;
break;
case SDLK_F3: // F3 to increase the emulator speed
speed += 1;
if( speed > 20 )
speed = 20;
break;
case SDLK_F2: // F2 to reset the speed to 1
speed = 1;
break;
case SDLK_F1: // F1 to decrease the emulator speed
speed -= 1;
if( speed <= 1 )
speed = 1;
break;
case SDLK_F10: // Reset the emulator
speed = 1;
data_->cpu->reset();
break;
case SDLK_p: // Pause/unpause the emulator
isPaused = !isPaused;
break;
default:
data_->keyboard->update(e);
}
}
if( e.type == SDL_KEYUP )
data_->keyboard->update(e);
}
}
if( !isPaused )
{
// update CPU
for(int i =0; i<speed; i++) {
data_->cpu->update();
}
}
// update display
data_->display->render();
if( !isPaused )
{
// update timers at 60fps
if( SDL_GetTicks() - lasttime >= framerate ) {
// update timers
data_->updateTimers();
// update time variable
lasttime = SDL_GetTicks();
}
}
}
}
// VM shutdown
void VM::shutdown()
{ }
/* Load a ROM inside the VM memory
* Args:
* filename: the path to the ROM
* Raises:
* VMError in case of issues
*/
void VM::loadRom(std::string filename)
{
std::ifstream romfile (filename, std::ios::in | std::ios::binary | std::ios::ate );
if( !romfile.is_open() ) {
throw VMError("Unable to load the ROM.");
}
// retrieve the size of the ROM
std::streampos size = romfile.tellg();
char* memblock = new char[size];
// read the file
romfile.seekg(0, std::ios::beg);
romfile.read(memblock, size);
romfile.close();
// load the code in memory
data_->memory->loadMemory(MemoryZone::CODE_BEGIN, size, reinterpret_cast<byte_t*>(memblock));
delete[] memblock;
}
| 25.268595 | 107 | 0.507114 | [
"render"
] |
6f9cc5040823252c18e25625681d71f5638bd123 | 3,127 | cpp | C++ | libraries/eth/libdevcore/Base58.cpp | BitethereumFoundation/Bitethereum-core | 34bc9883b20cba200436021115db5388bf5df84d | [
"MIT"
] | null | null | null | libraries/eth/libdevcore/Base58.cpp | BitethereumFoundation/Bitethereum-core | 34bc9883b20cba200436021115db5388bf5df84d | [
"MIT"
] | null | null | null | libraries/eth/libdevcore/Base58.cpp | BitethereumFoundation/Bitethereum-core | 34bc9883b20cba200436021115db5388bf5df84d | [
"MIT"
] | null | null | null | /*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Base58.cpp
* Adapted from code found on https://github.com/bitcoin/bitcoin/blob/master/src/base58.cpp
* Licenced under The MIT License.
* @author The Bitcoin core developers (original)
* @author Gav Wood <i@gavwood.com> (minor modifications and reformating)
* @date 2015
*/
#include "Base58.h"
using namespace std;
using namespace dev;
std::string dev::AlphabetIPFS("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
std::string dev::AlphabetFlickr("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
bytes dev::fromBase58(string const& _s, string const& _alphabet)
{
auto index = _s.begin();
// Skip and count leading '1's.
int zeroes = 0;
while (*index == _alphabet[0])
{
zeroes++;
index++;
}
// Allocate enough space in big-endian base256 representation.
// log(58) / log(256), rounded up.
bytes ret((_s.size() - zeroes) * 733 / 1000 + 1);
// Process the characters.
while (index != _s.end())
{
// Decode base58 character
size_t carry = _alphabet.find(*index);
if (carry == string::npos)
throw invalid_argument("Invalid character in base-58 string");
// Apply "ret = ret * 58 + ch".
for (auto it = ret.rbegin(); it != ret.rend(); it++)
{
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
index++;
}
// Skip leading zeroes.
while (!ret.front())
ret.erase(ret.begin());
// Re-insert zeroes.
for (int i = 0; i < zeroes; ++i)
ret.insert(ret.begin(), 0);
return ret;
}
string dev::toBase58(bytesConstRef _d, string const& _alphabet)
{
auto begin = _d.data();
auto end = _d.data() + _d.size();
// Skip & count leading zeroes.
int zeroes = 0;
for (; begin != end && !*begin; begin++, zeroes++) {}
// Allocate enough space in big-endian base58 representation.
// log(256) / log(58), rounded up.
std::vector<unsigned char> b58((end - begin) * 138 / 100 + 1);
// Process the bytes.
while (begin != end)
{
int carry = *begin;
// Apply "b58 = b58 * 256 + ch".
for (auto it = b58.rbegin(); it != b58.rend(); it++)
{
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(!carry);
begin++;
}
// Skip leading zeroes in base58 result.
auto it = b58.begin();
while (it != b58.end() && !*it)
it++;
// Translate the result into a string.
std::string ret;
ret.reserve(zeroes + (b58.end() - it));
ret.assign(zeroes, '1');
while (it != b58.end())
ret += _alphabet[*(it++)];
return ret;
}
| 26.058333 | 94 | 0.662936 | [
"vector"
] |
6fa7d617f5af4f7e9924b29c27f219e0d3a85819 | 3,434 | cc | C++ | peridot/bin/suggestion_engine/ranking_features/affinity_ranking_feature.cc | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | peridot/bin/suggestion_engine/ranking_features/affinity_ranking_feature.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | peridot/bin/suggestion_engine/ranking_features/affinity_ranking_feature.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "peridot/bin/suggestion_engine/ranking_features/affinity_ranking_feature.h"
#include <lib/fsl/types/type_converters.h>
#include <src/lib/fxl/logging.h>
#include <src/lib/fxl/strings/join_strings.h>
namespace modular {
namespace {
bool MatchesMod(const fuchsia::modular::ModuleAffinity& affinity,
const std::vector<std::string>& mod_path,
const std::string& affinity_story) {
// If the stories are not the same return early.
if (affinity.story_name != affinity_story) {
return false;
}
// Since module_paths are composed using the name of the parent view (note
// this is how it's working today, but not how it should be expected to work.
// Module names are opaque identifiers we shouldn't rely on for this kind of
// logic), we compare the one in focused with the affinity we are interested.
// Exmaple:
// - In focus: a/b/c
// - Affinity: a/b
// Since the name is the same up to a/b, then we have higher confidence.
// TODO(miguelfrde): rather than using this in a boolean fashion, return a
// meaningful confidence that represents this behavior and supports cases such
// as a/b/c vs a/d. For the case above it could be 0.66 and for the case of
// a/d 0.33.
for (uint32_t i = 0; i < mod_path.size(); i++) {
if (i >= affinity.module_name.size()) {
break;
}
if (mod_path.at(i) != affinity.module_name.at(i)) {
return false;
}
}
return true;
}
} // namespace
AffinityRankingFeature::AffinityRankingFeature() {}
AffinityRankingFeature::~AffinityRankingFeature() = default;
double AffinityRankingFeature::ComputeFeatureInternal(
const fuchsia::modular::UserInput& query,
const RankedSuggestion& suggestion) {
const auto& proposal = suggestion.prototype->proposal;
if (proposal.affinity.empty()) {
return kMaxConfidence;
}
for (const auto& context_value : *ContextValues()) {
const auto& affinity_story_id = context_value.meta.story->id;
for (const auto& affinity : proposal.affinity) {
if (affinity.is_story_affinity() &&
affinity_story_id == affinity.story_affinity().story_name) {
return kMaxConfidence;
}
if (affinity.is_module_affinity() &&
MatchesMod(affinity.module_affinity(), context_value.meta.mod->path,
affinity_story_id)) {
return kMaxConfidence;
}
}
}
return kMinConfidence;
}
fuchsia::modular::ContextSelectorPtr
AffinityRankingFeature::CreateContextSelectorInternal() {
// Get currently focused mod and in focused story.
auto selector = fuchsia::modular::ContextSelector::New();
selector->type = fuchsia::modular::ContextValueType::MODULE;
selector->meta = fuchsia::modular::ContextMetadata::New();
selector->meta->story = fuchsia::modular::StoryMetadata::New();
selector->meta->story->focused = fuchsia::modular::FocusedState::New();
selector->meta->story->focused->state =
fuchsia::modular::FocusedStateState::FOCUSED;
selector->meta->mod = fuchsia::modular::ModuleMetadata::New();
selector->meta->mod->focused = fuchsia::modular::FocusedState::New();
selector->meta->mod->focused->state =
fuchsia::modular::FocusedStateState::FOCUSED;
return selector;
}
} // namespace modular
| 36.147368 | 84 | 0.700349 | [
"vector"
] |
6fbcd0193735a9948bd2f13e6b88fa30f9a46b23 | 2,535 | cpp | C++ | src/hischeck/main.cpp | paps/Open-Trading | b62f85f391be9975a161713f87aeff0cae0a1e37 | [
"BSD-2-Clause"
] | 23 | 2015-07-24T15:45:36.000Z | 2021-11-23T15:35:33.000Z | src/hischeck/main.cpp | paps/Open-Trading | b62f85f391be9975a161713f87aeff0cae0a1e37 | [
"BSD-2-Clause"
] | null | null | null | src/hischeck/main.cpp | paps/Open-Trading | b62f85f391be9975a161713f87aeff0cae0a1e37 | [
"BSD-2-Clause"
] | 21 | 2015-07-12T16:42:01.000Z | 2020-08-23T22:56:50.000Z | // The Open Trading Project - open-trading.org
//
// Copyright (c) 2011 Martin Tapia - martin.tapia@open-trading.org
// 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.
//
// 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 <boost/cstdlib.hpp>
#include "Logger.hpp"
#include "tools/ToString.hpp"
#include "core/History.hpp"
#include "core/Bar.hpp"
int main(int ac, char** av)
{
Hischeck::Logger logger;
if (ac <= 1 || !av[1])
{
logger.Log("Usage: hischeck PATH_TO_CSV");
return boost::exit_failure;
}
Core::History history(logger, true);
if (!history.Load(av[1]))
{
logger.Log("Failed to load history.", Logger::Error);
return boost::exit_failure;
}
std::vector<Core::Bar> const& bars = history.GetBars();
logger.Log("Start: " + bars[0].TimeToString() + ".");
logger.Log("End: " + bars[bars.size() - 1].TimeToString() + ".");
logger.Log("Duration:");
time_t diff = bars[bars.size() - 1].time - bars[0].time;
logger.Log(" seconds: " + Tools::ToString(diff));
logger.Log(" minutes: " + Tools::ToString(diff / 60));
logger.Log(" hours: " + Tools::ToString(diff / (60 * 60)));
logger.Log(" days: " + Tools::ToString(diff / (60 * 60 * 24)));
return boost::exit_success;
}
| 39.609375 | 76 | 0.686391 | [
"vector"
] |
6fc4ba76d3509e98da30f0dd4a49619d1d7b24f9 | 2,052 | cpp | C++ | src/processor.cpp | VimalKumarS/System_monitor_udacity_cpp | 0161b1f3ccf840d6ad22a69809881b39f128c127 | [
"MIT"
] | null | null | null | src/processor.cpp | VimalKumarS/System_monitor_udacity_cpp | 0161b1f3ccf840d6ad22a69809881b39f128c127 | [
"MIT"
] | null | null | null | src/processor.cpp | VimalKumarS/System_monitor_udacity_cpp | 0161b1f3ccf840d6ad22a69809881b39f128c127 | [
"MIT"
] | null | null | null | #include "processor.h"
#include "linux_parser.h"
// TODO: Return the aggregate CPU utilization
float Processor::Utilization() {
std::vector<std::string> cpu_list = LinuxParser::CpuUtilization();
long user, nice, system, irq, softirq, steal, idle, iowait;
user = std::stol(cpu_list[LinuxParser::CPUStates::kUser_]);
nice = std::stol(cpu_list[LinuxParser::CPUStates::kNice_]);
system = std::stol(cpu_list[LinuxParser::CPUStates::kSystem_]);
irq = std::stol(cpu_list[LinuxParser::CPUStates::kIRQ_]);
softirq = std::stol(cpu_list[LinuxParser::CPUStates::kSoftIRQ_]);
steal = std::stol(cpu_list[LinuxParser::CPUStates::kSteal_]);
idle = std::stol(cpu_list[LinuxParser::CPUStates::kIdle_]);
iowait = std::stol(cpu_list[LinuxParser::CPUStates::kIOwait_]);
long PrevIdle = previdle + previowait;
long Idle = idle + iowait;
long PrevNonIdle =
prevuser + prevnice + prevsystem + previrq + prevsoftirq + prevsteal;
long NonIdle = user + nice + system + irq + softirq + steal;
long PrevTotal = PrevIdle + PrevNonIdle;
long Total = Idle + NonIdle;
long totald = Total - PrevTotal;
long idled = Idle - PrevIdle;
float CPU_Percentage = 1.0 *(totald - idled) / totald;
prevuser = user;
prevnice = nice;
prevsystem = system;
previrq = irq;
prevsoftirq = softirq;
prevsteal = steal;
previdle = idle;
previowait = iowait;
return CPU_Percentage;
}
//user nice system idle iowait irq softirq steal guest guest_nice
//cpu 74608 2520 24433 1117073 6176 4054 0 0 0 0
//
//PrevIdle = previdle + previowait
//Idle = idle + iowait
//
//PrevNonIdle = prevuser + prevnice + prevsystem + previrq + prevsoftirq + prevsteal
//NonIdle = user + nice + system + irq + softirq + steal
//
//PrevTotal = PrevIdle + PrevNonIdle
//Total = Idle + NonIdle
//
//# differentiate: actual value minus the previous one
//totald = Total - PrevTotal
//idled = Idle - PrevIdle
//
//CPU_Percentage = (totald - idled)/totald | 33.096774 | 84 | 0.668616 | [
"vector"
] |
6fc5572e82ed8aa23db41baa4118bb76ee6064be | 4,070 | hpp | C++ | src/abacus/metrics.hpp | steinwurf/abacus | 80eb3611a6a97472a4a686ce9ffb380767c8c200 | [
"BSD-3-Clause"
] | 1 | 2022-02-04T17:32:30.000Z | 2022-02-04T17:32:30.000Z | src/abacus/metrics.hpp | steinwurf/abacus | 80eb3611a6a97472a4a686ce9ffb380767c8c200 | [
"BSD-3-Clause"
] | 8 | 2021-11-08T12:37:15.000Z | 2022-01-25T12:14:01.000Z | src/abacus/metrics.hpp | steinwurf/abacus | 80eb3611a6a97472a4a686ce9ffb380767c8c200 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) Steinwurf ApS 2020.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <cassert>
#include <vector>
#include "metric.hpp"
#include "version.hpp"
#include "view.hpp"
namespace abacus
{
inline namespace STEINWURF_ABACUS_VERSION
{
/// This class preallocates memory at construction to hold a header, a title
/// of size max_name_bytes, max_metrics metrics, each having a name of size
/// max_name_bytes, with a metric value of 8 bytes (sizeof(uint64_t)).
///
/// The total preallocated memory is
/// header_size + max_name_bytes + max_metrics * (max_name_bytes + 8).
///
/// To save memory, take caution in choosing the max_metrics. If your
/// library only uses 10 counters, you should probably not choose
/// max_metrics = 64. You can update the max_metrics value as you go to
/// ensure optimal memory usage.
///
/// The header consists of 42 bits of 3 values:
/// 1. 16 bit denoting the max size of name
/// 2. 16 bit denoting the max number of counters
/// 3. 8 bit denoting the max size of values
class metrics
{
public:
/// Default constructor
/// @param max_metrics The maximum number of metrics this object will
/// contain. Must be a number that can fit in 2 bytes.
/// @param max_name_bytes The maximum length in bytes the title/names of the
/// counters will contain. Must be a number that can fit in 2 bytes.
/// @param title The title of the metrics object
metrics(std::size_t max_metrics, std::size_t max_name_bytes,
const std::string& title);
/// Destructor
~metrics();
/// @return the maximum number of metrics that was provided to the
/// constructor
auto max_metrics() const -> std::size_t;
/// @return the maximum number of bytes used for a metric name that was
/// provided to the constructor
auto max_name_bytes() const -> std::size_t;
/// Set the name of all the metrics contained within
/// @param title The title of the metrics object
void set_metrics_title(const std::string& title);
/// @param index The index of a counter. Must be less than max_metrics.
/// @return The name of a counter as a string
auto metric_name(std::size_t index) const -> std::string;
/// @param index The index of a counter. Must be less than max_metrics.
/// @return A specific count
auto metric_value(std::size_t index) const -> uint64_t;
/// @param index The index of the new counter. Must be less than
/// max_metrics.
/// @param name The name of the new counter. Must be less than
/// max_name_bytes bytes
/// @return The value of the counter
auto initialize_metric(std::size_t index, const std::string& name)
-> metric;
/// @param index The index of the new counter. Must be less than
/// max_metrics.
/// @return True if the counter has been initialized
auto is_metric_initialized(std::size_t index) const -> bool;
/// Copies the memory backing the counter storage to a data pointer
/// @param data The data pointer to copy the raw memory to
void copy_storage(uint8_t* data) const;
/// @return The size of the counter storage in bytes
auto storage_bytes() const -> std::size_t;
/// Reset all the counters
void reset_metrics();
/// Reset specific counter
/// @param index The index of the new counter. Must be less than
/// max_metrics.
void reset_metric(std::size_t index);
/// @return All counters in json format
auto to_json() const -> std::string;
private:
/// No copy
metrics(metrics&) = delete;
/// No copy assignment
metrics& operator=(metrics&) = delete;
/// No move
metrics(metrics&&) = delete;
/// No move assignment
metrics& operator=(metrics&&) = delete;
private:
/// The number of values
std::size_t m_max_metrics = 0;
/// The number of values
std::size_t m_max_name_bytes = 0;
/// The raw memory for the counters (both value and name)
uint8_t* m_data = nullptr;
};
}
}
| 31.796875 | 80 | 0.681572 | [
"object",
"vector"
] |
6fddcc353c2395a7effdafd5b8131a8826da1071 | 15,181 | cc | C++ | src/firmware/lib/fastboot/fastboot.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 2 | 2022-02-24T16:24:29.000Z | 2022-02-25T22:33:10.000Z | src/firmware/lib/fastboot/fastboot.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | src/firmware/lib/fastboot/fastboot.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fidl/fuchsia.paver/cpp/wire.h>
#include <lib/fastboot/fastboot.h>
#include <lib/fdio/directory.h>
#include <lib/fidl-async/cpp/bind.h>
#include <lib/service/llcpp/service.h>
#include <lib/syslog/global.h>
#include <zircon/status.h>
#include <optional>
#include <string_view>
#include <vector>
#include "src/lib/fxl/strings/split_string.h"
#include "src/lib/fxl/strings/string_printf.h"
namespace fastboot {
namespace {
constexpr char kFastbootLogTag[] = __FILE__;
constexpr char kOemPrefix[] = "oem ";
enum class ResponseType {
kOkay,
kInfo,
kFail,
kData,
};
zx::status<> SendResponse(ResponseType resp_type, const std::string& message, Transport* transport,
zx::status<> ret_status = zx::ok()) {
const char* type = nullptr;
if (resp_type == ResponseType::kOkay) {
type = "OKAY";
} else if (resp_type == ResponseType::kInfo) {
type = "INFO";
} else if (resp_type == ResponseType::kFail) {
type = "FAIL";
} else if (resp_type == ResponseType::kData) {
type = "DATA";
} else {
FX_LOGF(ERROR, kFastbootLogTag, "Invalid response type %d\n", static_cast<int>(resp_type));
return zx::error(ZX_ERR_INVALID_ARGS);
}
std::string resp = type + message;
if (zx::status<> ret = transport->Send(resp); ret.is_error()) {
FX_LOGF(ERROR, kFastbootLogTag, "Failed to write packet %d\n", ret.status_value());
return zx::error(ret.status_value());
}
return ret_status;
}
zx::status<> SendDataResponse(size_t data_size, Transport* transport) {
std::string message = fxl::StringPrintf("%08zx", data_size);
return SendResponse(ResponseType::kData, message, transport);
}
bool MatchCommand(const std::string_view cmd, std::string_view ref) {
if (cmd.compare(0, strlen(kOemPrefix), kOemPrefix) == 0) {
// TODO(217597389): Once we need to support "oem " commands, figure out
// how to do the command matching. For now return false whenever we see
// an oem command.
return false;
} else {
// find the first occurrence of ":". if there isn't, return value will be
// string::npos, which will lead to full string comparison.
size_t pos = cmd.find(":");
return cmd.compare(0, pos, ref, 0, ref.size()) == 0;
}
}
struct FlashPartitionInfo {
std::string_view partition;
std::optional<fuchsia_paver::wire::Configuration> configuration;
};
FlashPartitionInfo GetPartitionInfo(std::string_view partition_label) {
size_t len = partition_label.length();
if (len < 2) {
return {partition_label, std::nullopt};
}
FlashPartitionInfo ret;
ret.partition = partition_label.substr(0, len - 2);
std::string_view slot_suffix = partition_label.substr(len - 2, 2);
if (slot_suffix == "_a") {
ret.configuration = fuchsia_paver::wire::Configuration::kA;
} else if (slot_suffix == "_b") {
ret.configuration = fuchsia_paver::wire::Configuration::kB;
} else if (slot_suffix == "_r") {
ret.configuration = fuchsia_paver::wire::Configuration::kRecovery;
} else {
ret.partition = partition_label;
}
return ret;
}
} // namespace
const std::vector<Fastboot::CommandEntry>& Fastboot::GetCommandTable() {
// Using a static pointer and allocate with `new` so that the static instance
// never gets deleted.
static const std::vector<CommandEntry>* kCommandTable = new std::vector<CommandEntry>({
{
.name = "getvar",
.cmd = &Fastboot::GetVar,
},
{
.name = "download",
.cmd = &Fastboot::Download,
},
{
.name = "flash",
.cmd = &Fastboot::Flash,
},
{
.name = "set_active",
.cmd = &Fastboot::SetActive,
},
});
return *kCommandTable;
}
const Fastboot::VariableHashTable& Fastboot::GetVariableTable() {
// Using a static pointer and allocate with `new` so that the static instance
// never gets deleted.
static const VariableHashTable* kVariableTable = new VariableHashTable({
{"max-download-size", &Fastboot::GetVarMaxDownloadSize},
});
return *kVariableTable;
}
Fastboot::Fastboot(size_t max_download_size) : max_download_size_(max_download_size) {}
Fastboot::Fastboot(size_t max_download_size, fidl::ClientEnd<fuchsia_io::Directory> svc_root)
: max_download_size_(max_download_size), svc_root_(std::move(svc_root)) {}
zx::status<> Fastboot::ProcessPacket(Transport* transport) {
if (!transport->PeekPacketSize()) {
return zx::ok();
}
if (state_ == State::kCommand) {
std::string command(transport->PeekPacketSize(), '\0');
zx::status<size_t> ret = transport->ReceivePacket(command.data(), command.size());
if (!ret.is_ok()) {
return SendResponse(ResponseType::kFail, "Fail to read command", transport,
zx::error(ret.status_value()));
}
for (const CommandEntry& cmd : GetCommandTable()) {
if (MatchCommand(command, cmd.name)) {
return (this->*cmd.cmd)(command, transport);
}
}
return SendResponse(ResponseType::kFail, "Unsupported command", transport);
} else if (state_ == State::kDownload) {
size_t packet_size = transport->PeekPacketSize();
if (packet_size > remaining_download_) {
ClearDownload();
return SendResponse(ResponseType::kFail, "Unexpected amount of download", transport);
}
size_t total_size = download_vmo_mapper_.size();
size_t offset = total_size - remaining_download_;
uint8_t* start = static_cast<uint8_t*>(download_vmo_mapper_.start());
zx::status<size_t> ret = transport->ReceivePacket(start + offset, remaining_download_);
if (ret.is_error()) {
ClearDownload();
return SendResponse(ResponseType::kFail, "Failed to write to vmo", transport,
zx::error(ret.status_value()));
}
remaining_download_ -= ret.value();
if (remaining_download_ == 0) {
state_ = State::kCommand;
return SendResponse(ResponseType::kOkay, "", transport);
}
return zx::ok();
}
return zx::ok();
}
void Fastboot::ClearDownload() {
state_ = State::kCommand;
download_vmo_mapper_.Reset();
remaining_download_ = 0;
}
zx::status<> Fastboot::Download(const std::string& command, Transport* transport) {
ClearDownload();
std::vector<std::string_view> args =
fxl::SplitString(command, ":", fxl::kTrimWhitespace, fxl::kSplitWantNonEmpty);
if (args.size() < 2) {
return SendResponse(ResponseType::kFail, "Not enough argument", transport);
}
remaining_download_ = static_cast<size_t>(std::stoul(args[1].data(), nullptr, 16));
if (remaining_download_ == 0) {
return SendResponse(ResponseType::kFail, "Empty size download is not allowed", transport);
}
if (zx_status_t ret = download_vmo_mapper_.CreateAndMap(remaining_download_, "fastboot download");
ret != ZX_OK) {
ClearDownload();
return SendResponse(ResponseType::kFail, "Failed to create download vmo", transport,
zx::error(ZX_ERR_INTERNAL));
}
state_ = State::kDownload;
return SendDataResponse(remaining_download_, transport);
}
zx::status<> Fastboot::GetVar(const std::string& command, Transport* transport) {
std::vector<std::string_view> args =
fxl::SplitString(command, ":", fxl::kTrimWhitespace, fxl::kSplitWantNonEmpty);
if (args.size() < 2) {
return SendResponse(ResponseType::kFail, "Not enough arguments", transport);
}
const VariableHashTable& var_table = GetVariableTable();
const VariableHashTable::const_iterator find_res = var_table.find(args[1].data());
if (find_res == var_table.end()) {
return SendResponse(ResponseType::kFail, "Unknown variable", transport);
}
zx::status<std::string> var_ret = (this->*(find_res->second))(args, transport);
if (var_ret.is_error()) {
return SendResponse(ResponseType::kFail, "Fail to get variable", transport,
zx::error(var_ret.status_value()));
}
return SendResponse(ResponseType::kOkay, var_ret.value(), transport);
}
zx::status<std::string> Fastboot::GetVarMaxDownloadSize(const std::vector<std::string_view>&,
Transport*) {
return zx::ok(fxl::StringPrintf("0x%08zx", max_download_size_));
}
zx::status<fidl::WireSyncClient<fuchsia_paver::Paver>> Fastboot::ConnectToPaver() {
// If `svc_root_` is not set, use the system svc root.
if (!svc_root_) {
zx::channel request, service_root;
zx_status_t status = zx::channel::create(0, &request, &service_root);
if (status != ZX_OK) {
FX_LOGF(ERROR, kFastbootLogTag, "Failed to create channel %s", zx_status_get_string(status));
return zx::error(ZX_ERR_INTERNAL);
}
status = fdio_service_connect("/svc/.", request.release());
if (status != ZX_OK) {
FX_LOGF(ERROR, kFastbootLogTag, "Failed to connect to svc root %s",
zx_status_get_string(status));
return zx::error(ZX_ERR_INTERNAL);
}
svc_root_ = fidl::ClientEnd<fuchsia_io::Directory>(std::move(service_root));
}
// Connect to the paver
auto paver_svc = service::ConnectAt<fuchsia_paver::Paver>(svc_root_);
if (!paver_svc.is_ok()) {
FX_LOGF(ERROR, kFastbootLogTag, "Unable to open /svc/fuchsia.paver.Paver");
return zx::error(paver_svc.error_value());
}
return zx::ok(fidl::BindSyncClient(std::move(*paver_svc)));
}
zx::status<> Fastboot::WriteFirmware(fuchsia_paver::wire::Configuration config,
std::string_view firmware_type, Transport* transport,
fidl::WireSyncClient<fuchsia_paver::DataSink>& data_sink) {
fuchsia_mem::wire::Buffer buf;
buf.size = download_vmo_mapper_.size();
buf.vmo = download_vmo_mapper_.Release();
auto ret = data_sink->WriteFirmware(config, fidl::StringView::FromExternal(firmware_type),
std::move(buf));
if (ret.status() != ZX_OK) {
return SendResponse(ResponseType::kFail, "Failed to invoke paver bootloader write", transport,
zx::error(ret.status()));
}
if (ret->result.is_status() && ret->result.status() != ZX_OK) {
return SendResponse(ResponseType::kFail, "Failed to write bootloader", transport,
zx::error(ret->result.status()));
}
if (ret->result.is_unsupported() && ret->result.unsupported()) {
return SendResponse(ResponseType::kFail, "Firmware type is not supported", transport);
}
return SendResponse(ResponseType::kOkay, "", transport);
}
zx::status<> Fastboot::WriteAsset(fuchsia_paver::wire::Configuration config,
fuchsia_paver::wire::Asset asset, Transport* transport,
fidl::WireSyncClient<fuchsia_paver::DataSink>& data_sink) {
fuchsia_mem::wire::Buffer buf;
buf.size = download_vmo_mapper_.size();
buf.vmo = download_vmo_mapper_.Release();
auto ret = data_sink->WriteAsset(config, asset, std::move(buf));
zx_status_t status = ret.status() == ZX_OK ? ret.value().status : ret.status();
if (status != ZX_OK) {
return SendResponse(ResponseType::kFail, "Failed to flash asset", transport, zx::error(status));
}
return SendResponse(ResponseType::kOkay, "", transport);
}
zx::status<> Fastboot::Flash(const std::string& command, Transport* transport) {
std::vector<std::string_view> args =
fxl::SplitString(command, ":", fxl::kTrimWhitespace, fxl::kSplitWantNonEmpty);
if (args.size() < 2) {
return SendResponse(ResponseType::kFail, "Not enough arguments", transport);
}
auto paver_client_res = ConnectToPaver();
if (paver_client_res.is_error()) {
return SendResponse(ResponseType::kFail, "Failed to connect to paver", transport,
zx::error(paver_client_res.status_value()));
}
// Connect to the data sink
auto data_sink_endpoints = fidl::CreateEndpoints<fuchsia_paver::DataSink>();
if (data_sink_endpoints.is_error()) {
return SendResponse(ResponseType::kFail, "Unable to create data sink endpoint", transport,
zx::error(data_sink_endpoints.status_value()));
}
auto [data_sink_local, data_sink_remote] = std::move(*data_sink_endpoints);
paver_client_res.value()->FindDataSink(std::move(data_sink_remote));
auto data_sink = fidl::BindSyncClient(std::move(data_sink_local));
FlashPartitionInfo info = GetPartitionInfo(args[1]);
if (info.partition == "bootloader" && info.configuration) {
std::string_view firmware_type = args.size() == 3 ? args[2] : "";
return WriteFirmware(*info.configuration, firmware_type, transport, data_sink);
} else if (info.partition == "zircon" && info.configuration) {
return WriteAsset(*info.configuration, fuchsia_paver::wire::Asset::kKernel, transport,
data_sink);
} else if (info.partition == "vbmeta" && info.configuration) {
return WriteAsset(*info.configuration, fuchsia_paver::wire::Asset::kVerifiedBootMetadata,
transport, data_sink);
} else {
return SendResponse(ResponseType::kFail, "Unsupported partition", transport);
}
return zx::ok();
}
zx::status<> Fastboot::SetActive(const std::string& command, Transport* transport) {
std::vector<std::string_view> args =
fxl::SplitString(command, ":", fxl::kTrimWhitespace, fxl::kSplitWantNonEmpty);
if (args.size() < 2) {
return SendResponse(ResponseType::kFail, "Not enough arguments", transport);
}
auto paver_client_res = ConnectToPaver();
if (!paver_client_res.is_ok()) {
return SendResponse(ResponseType::kFail, "Failed to connect to paver", transport,
zx::error(paver_client_res.status_value()));
}
zx::status endpoints = fidl::CreateEndpoints<fuchsia_paver::BootManager>();
if (endpoints.is_error()) {
return SendResponse(ResponseType::kFail, "Failed to create zx channel", transport,
zx::error(endpoints.status_value()));
}
fidl::WireResult res = paver_client_res.value()->FindBootManager(std::move(endpoints->server));
if (!res.ok()) {
return SendResponse(ResponseType::kFail, "Failed to find boot manager", transport,
zx::error(endpoints.status_value()));
}
fidl::WireSyncClient<fuchsia_paver::BootManager> boot_manager =
fidl::BindSyncClient(std::move(endpoints->client));
fuchsia_paver::wire::Configuration config = fuchsia_paver::wire::Configuration::kB;
if (args[1] == "a") {
config = fuchsia_paver::wire::Configuration::kA;
} else if (args[1] != "b") {
return SendResponse(ResponseType::kFail, "Invalid slot", transport);
}
auto result = boot_manager->SetConfigurationActive(config);
zx_status_t status = result.ok() ? result->status : result.status();
if (status != ZX_OK) {
return SendResponse(
ResponseType::kFail,
"Failed to set configuration active: " + std::string(zx_status_get_string(status)),
transport, zx::error(status));
}
return SendResponse(ResponseType::kOkay, "", transport);
}
} // namespace fastboot
| 37.299754 | 100 | 0.671827 | [
"vector"
] |
6fe8022421d1e299e11bbd7fdffe5058e1b5d17b | 7,080 | hpp | C++ | thirdparty/moab/tools/refiner/EntityRefiner.hpp | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | thirdparty/moab/tools/refiner/EntityRefiner.hpp | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | thirdparty/moab/tools/refiner/EntityRefiner.hpp | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | /*
* MOAB, a Mesh-Oriented datABase, is a software component for creating,
* storing and accessing finite element mesh data.
*
* Copyright 2007 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
/** \class moab::EntityRefiner
*
* This is an abstract class that contains the method used for per-entity refinement.
* Subclasses must implement the pure virtual refine_entity() function and
* may implement the vertices_per_split() function.
* This class constructor requires a non-NULL pointer to a mesh so that, given an
* entity handle, it can look up vertex coordinates and tags to prepare arguments for
* the refine_entity() method.
*
* Although the MeshRefiner class may not initially support it, entity refiners
* are required to support some level of recursion.
* The maximum number of recursive calls allowed may be set with
* EntityRefiner::set_maximum_number_of_subdivisions().
* As a convenience, some of the framework for recursion is provided by the
* EntityRefiner class.
*
* Specifically, EntityRefiner stores a pair of heap arrays
* to hold edge midpoint vertex coordinates and tag values pre-allocated to the
* maximum recursion depth so that no repeated allocation and deallocation
* needs to take place during refinement.
* To use these heaps, subclasses should call reset_heap_pointers() upon entry to
* EntityRefiner::refine_entity().
* Then, when the edge size evaluator requires an edge to be split, subclasses
* should call heap_coord_storage() and heap_tag_storage() to obtain pointers as
* required.
*
* \author David Thompson
* \author Philippe Pebay
*
* \date 24 December 2007
*/
/**\class EntityRefinerOutputFunctor
*
* This is an abstract class used by EntityRefiner to output entities that are the product of refinement.
* The parenthesis operator is overloaded with two forms:
* one used for appending a vertex to an entity,
* the other used to finalize the creation of the entity by specifying its type.
*
* You are also responsible for implementing the map_vertex() function to map an input vertex handle
* into an output vertex handle (which may then be appended to an entity using the first form
* of the parenthesis operator above).
*
* \author David Thompson
* \author Philippe Pebay
*
* \date 26 December 2007
*/
#ifndef MOAB_ENTITY_REFINER_HPP
#define MOAB_ENTITY_REFINER_HPP
#include "moab/Types.hpp"
#include "moab/Compiler.hpp" // for MB_DLL_EXPORT
#include <vector>
namespace moab {
class Interface;
class EdgeSizeEvaluator;
class RefinerTagManager;
class EntityRefinerOutputFunctor
{
public:
virtual ~EntityRefinerOutputFunctor() { }
/// Map an input vertex to the output mesh. This should return the same value when given the same input across multiple calls.
virtual EntityHandle map_vertex( EntityHandle vhash, const double* vcoords, const void* vtags ) = 0;
/**\brief Create a new vertex along an edge.
*
* @param[in] h0 An edge endpoint handle on the output mesh.
* @param[in] h1 An edge endpoint handle on the output mesh.
* @param[in] vcoords The location of the midpoint in world coordinates.
* @param[in] vtags Field values at the midpoint.
* @retval A handle for the midpoint on the output mesh.
*/
EntityHandle operator () ( EntityHandle h0, EntityHandle h1, const double* vcoords, const void* vtags )
{
EntityHandle harr[2];
harr[0] = h0;
harr[1] = h1;
return (*this)( 2, harr, vcoords, vtags );
}
/**\brief Create a new vertex on a triangular face.
*
* @param[in] h0 A triangle corner handle on the output mesh.
* @param[in] h1 A triangle corner handle on the output mesh.
* @param[in] h2 A triangle corner handle on the output mesh.
* @param[in] vcoords The location of the mid-face point in world coordinates.
* @param[in] vtags Field values at the mid-face point.
* @retval A handle for the mid-face point on the output mesh.
*/
virtual EntityHandle operator () ( EntityHandle h0, EntityHandle h1, EntityHandle h2, const double* vcoords, const void* vtags )
{
EntityHandle harr[3];
harr[0] = h0;
harr[1] = h1;
harr[2] = h2;
return (*this)( 3, harr, vcoords, vtags );
}
/**\brief Create a new vertex along a \f$k\f$-facet.
*
* @param[in] nhash The number of corner vertices (i.e, \f$k\f$ ).
* @param[in] hash An array of corner handles on the output mesh.
* @param[in] vcoords The location of the new point in world coordinates.
* @param[in] vtags Field values at the new point.
* @retval A handle for the new point on the output mesh.
*/
virtual EntityHandle operator () ( int nhash, EntityHandle* hash, const double* vcoords, const void* vtags ) = 0;
/**\brief Append an output vertex to the list of vertices defining a new entity.
*
* @param[in] vhash A vertex of the output mesh.
*/
virtual void operator () ( EntityHandle vhash ) = 0;
/**\brief Create a new entity from all previously appended output vertices.
*
* This resets the list of appended vertices.
* @param[in] etyp The type of entity to create.
*/
virtual void operator () ( EntityType etyp ) = 0;
};
class EntityRefiner
{
public:
EntityRefiner();
virtual ~EntityRefiner();
virtual bool prepare( RefinerTagManager* tmgr, EntityRefinerOutputFunctor* ofunc );
virtual bool refine_entity( EntityType typ, EntityHandle ent ) = 0;
virtual unsigned long get_heap_size_bound( int max_recursions ) const = 0;
virtual bool set_edge_size_evaluator( EdgeSizeEvaluator* );
EdgeSizeEvaluator* get_edge_size_evaluator() { return this->edge_size_evaluator; }
virtual bool set_output_functor( EntityRefinerOutputFunctor* func_obj );
EntityRefinerOutputFunctor* get_output_functor() { return this->output_functor; }
virtual bool set_minimum_number_of_subdivisions( int mn );
int get_minimum_number_of_subdivisions() const { return this->minimum_number_of_subdivisions; }
virtual bool set_maximum_number_of_subdivisions( int mx );
int get_maximum_number_of_subdivisions() const { return this->maximum_number_of_subdivisions; }
protected:
Interface* mesh_in;
EdgeSizeEvaluator* edge_size_evaluator;
EntityRefinerOutputFunctor* output_functor;
int minimum_number_of_subdivisions;
int maximum_number_of_subdivisions;
std::vector<double> coord_heap;
std::vector<double>::iterator current_coord;
std::vector<char> tag_heap;
std::vector<char>::iterator current_tag;
void update_heap_size();
void reset_heap_pointers();
double* heap_coord_storage();
void* heap_tag_storage();
};
} // namespace moab
#endif // MOAB_ENTITY_REFINER_HPP
| 39.333333 | 130 | 0.73065 | [
"mesh",
"vector"
] |
6fedcf7d2ae74f4b578efb56c9ee29f60e9aa577 | 7,963 | cpp | C++ | samples/source/AML_SearchAndDeleteComponent.cpp | ThE-TiGeR/XMP-Toolkit | 064cde77086c1e13a8524f63c461b5cc650de15f | [
"BSD-3-Clause"
] | 13 | 2015-04-10T16:31:04.000Z | 2021-10-12T18:01:22.000Z | samples/source/AML_SearchAndDeleteComponent.cpp | ThE-TiGeR/XMP-Toolkit | 064cde77086c1e13a8524f63c461b5cc650de15f | [
"BSD-3-Clause"
] | 7 | 2016-06-05T22:12:29.000Z | 2018-09-25T23:15:52.000Z | samples/source/AML_SearchAndDeleteComponent.cpp | ThE-TiGeR/XMP-Toolkit | 064cde77086c1e13a8524f63c461b5cc650de15f | [
"BSD-3-Clause"
] | 11 | 2015-05-07T06:25:51.000Z | 2021-12-23T19:43:35.000Z | // =================================================================================================
// Copyright 2008 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
/**
* Tutorial solution for the AssetRelationships.pdf. An AssetManagement Object is created from
* composed metadata. Then a part is used for deleting all the relationship from composed Asset.
*/
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <fstream>
#include <iostream>
// Must be defined to instantiate template classes
#define TXMP_STRING_TYPE std::string
// Must be defined to give access to XMPFiles
#define XMP_INCLUDE_XMPFILES 0
#define ENABLE_NEW_DOM_MODEL 1
#include "XMPCore/Interfaces/IXMPDOMImplementationRegistry.h"
#include "XMPCore/Interfaces/IXMPDOMParser.h"
#include "XMPCore/Interfaces/IXMPDOMSerializer.h"
#include "XMPCore/Interfaces/IXMPMetadata.h"
#include "XMPCore/Interfaces/IXMPCoreObjectFactory.h"
#include "XMPCore/Interfaces/IXMPSimpleNode.h"
#include "XMPCore/Interfaces/IXMPStructureNode.h"
// Ensure XMP templates are instantiated
#include "public/include/XMP.incl_cpp"
// Provide access to the API
#include "public/include/XMP.hpp"
#include "XMPAssetManagement/XMPAssetManagementDefines.h"
#include "XMPAssetManagement/XMPAssetManagementFwdDeclarations.h"
#include "XMPCore/Interfaces/IXMPMetadata.h"
#include "XMPCommon/Interfaces/IUTF8String.h"
#include "XMPAssetManagement/XMPAssetManagement.h"
#include "XMPAssetManagement/Interfaces/IAssetUtilities.h"
#include "XMPAssetManagement/Interfaces/IAssetPart.h"
#include "XMPAssetManagement/Interfaces/IComposedAssetManager.h"
#include "XMPAssetManagement/Interfaces/ICompositionRelationship.h"
#include "XMPCore/Interfaces/IXMPCoreObjectFactory.h"
#include "XMPAssetManagement/XMPAssetManagementFwdDeclarations.h"
using namespace std;
static string GetStringFromFile(string filename)
{
string buffer;
string line;
ifstream in(filename);
if (in.is_open()) {
while (getline(in, line))
buffer = buffer + "\n" + line;
in.close();
}
else {
cout << "Connot open file for converting into string\n";
}
return buffer;
}
void static SerializeIXMPMetadata(NS_XMPCORE::spIXMPMetadata imetadata, string outfile = "")
{
NS_XMPCORE::spIXMPDOMImplementationRegistry DOMRegistry = NS_XMPCORE::IXMPDOMImplementationRegistry::GetDOMImplementationRegistry();
NS_XMPCORE::spIXMPDOMSerializer DOMSerializer = DOMRegistry->CreateSerializer("rdf");
std::string targetfilebuffer = DOMSerializer->Serialize(imetadata)->c_str();
//std::cout << targetfilebuffer << std::endl;
//write into file
if (!outfile.empty()) {
ofstream out(outfile);
if (out.is_open()) {
out << targetfilebuffer;
out.close();
}
}
}
NS_XMPCORE::spIXMPMetadata static GetIXMPMetadataFromRDF(string filename)
{
string buffer = GetStringFromFile(filename);
NS_XMPCORE::spIXMPDOMImplementationRegistry DOMRegistry = NS_XMPCORE::IXMPDOMImplementationRegistry::GetDOMImplementationRegistry();
NS_XMPCORE::spIXMPDOMParser DOMParser = DOMRegistry->CreateParser("rdf");
NS_XMPCORE::spIXMPMetadata ixmpmeta = DOMParser->Parse(buffer.c_str());
return ixmpmeta;
}
/**
* Initializes the toolkit (XMPCore, XMPFiles & XMPAssetManagement and attempts to open a file
* for reading metadata. Initially an attempt to open the file is done with a handler, if this
* fails then the file is opened with packet scanning. Once opened, meta is obtained, from meta
* ixmpmeta (DOM based Metadata object) is get. AssetManagement object is created from composed
* ixmpmeta (the above ixmpmetadata). A part is created and used for search & deletion of that
* part from relationship.
*/
int main(int argc, const char * argv[])
{
string composed_file = "AML_SearchAndDelete_Sample_Input.xmp";
string composed_out_file = "AML_SearchAndDelete_Sample_Output.xmp";
if (!SXMPMeta::Initialize())
{
cout << "Could not initialize toolkit!";
return -1;
}
NS_XMPCORE::spIXMPMetadata& composed_ixmp_meta = GetIXMPMetadataFromRDF(composed_file);
//for both the files, metadata has been obtained, get IXMPMeta from SXMPMeta
NS_XMPCORE::pIXMPCoreObjectFactory factoryObj = NS_XMPCORE::IXMPCoreObjectFactory::GetInstance();
NS_XMPASSETMANAGEMENT::XMPAM_ClientInitialize();
//Check if composed / component is not trackable, make it
NS_XMPASSETMANAGEMENT::pIAssetUtilities utilityObj = NS_XMPASSETMANAGEMENT::IAssetUtilities::GetAssetUtilities();
if (utilityObj->IsTrackable(composed_ixmp_meta) == false)
utilityObj->MakeTrackable(composed_ixmp_meta);
//composed/toPart
NS_XMPASSETMANAGEMENT::spIAssetPart composedassetpart = NS_XMPASSETMANAGEMENT::IAssetPart::CreateStandardGenericPart(NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartComponentMetadata);
//creating ComposedAssetManager
NS_XMPASSETMANAGEMENT::spIComposedAssetManager composedAsset = NS_XMPASSETMANAGEMENT::IComposedAssetManager::CreateComposedAssetManager(composed_ixmp_meta);
//Get list of all relationship and traverse it
NS_XMPASSETMANAGEMENT::spcICompositionRelationshipList relationshipNodes = composedAsset->GetAllRelationships();
for (NS_XMPASSETMANAGEMENT::cICompositionRelationshipList::iterator it = relationshipNodes->begin(); it != relationshipNodes->end(); ++it) {
//get part for part specific data
NS_XMPASSETMANAGEMENT::spcIAssetPart assetPart = (*it)->GetComponentPart();
switch (assetPart->GetType()) {
case NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeGeneric:
cout << "Part type is NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeGeneric";
break;
case NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeTime:
cout << "Part type is NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeTime";
break;
case NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeArtboard:
cout << "Part type is NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeArtboard";
break;
case NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeLayer:
cout << "Part type is NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypeLayer";
break;
case NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypePage:
cout << "Part type is NS_XMPASSETMANAGEMENT::IAssetPart_v1::kAssetPartTypePage";
break;
default:
;
}
//get other relationship properties
NS_XMPCOMMON::spcIUTF8String filepath = (*it)->GetComponentFilePath();
}
//call GetRelationships(toPart) to get all relationship which matches a part value, and traverse it
relationshipNodes = composedAsset->GetRelationships(composedassetpart);
for (NS_XMPASSETMANAGEMENT::cICompositionRelationshipList::iterator it = relationshipNodes->begin(); it != relationshipNodes->end(); ++it) {
//get part for part specific data
NS_XMPASSETMANAGEMENT::spcIAssetPart assetPart = (*it)->GetComponentPart();
//get other relationship properties
NS_XMPCOMMON::spcIUTF8String filepath = (*it)->GetComponentFilePath();
}
////// Remove relationship which maches the part
composedAsset->RemoveComponents(composedassetpart);
//Get all the relationship and check verify all the Relationship having the above part must not be present
relationshipNodes = composedAsset->GetAllRelationships();
for (NS_XMPASSETMANAGEMENT::cICompositionRelationshipList::iterator it = relationshipNodes->begin(); it != relationshipNodes->end(); ++it) {
//get part for part specific data
NS_XMPASSETMANAGEMENT::spcIAssetPart assetPart = (*it)->GetComponentPart();
//get other relationship properties
NS_XMPCOMMON::spcIUTF8String filepath = (*it)->GetComponentFilePath();
}
//verify the added node from pantry
SerializeIXMPMetadata(composed_ixmp_meta, composed_out_file);
NS_XMPASSETMANAGEMENT::XMPAM_ClientTerminate();
SXMPMeta::Terminate();
return 0;
}
| 38.65534 | 185 | 0.77182 | [
"object",
"vector"
] |
6ff24f12b935b84dd6b9e92093f6089e9d7065ee | 5,103 | cpp | C++ | native/src/python_module.cpp | Photonomie/previewer | 5353f453b7ae60f506af2f013ae8f870c1eec90c | [
"MIT"
] | 7 | 2017-02-10T12:40:21.000Z | 2021-01-31T23:17:56.000Z | native/src/python_module.cpp | Photonomie/previewer | 5353f453b7ae60f506af2f013ae8f870c1eec90c | [
"MIT"
] | null | null | null | native/src/python_module.cpp | Photonomie/previewer | 5353f453b7ae60f506af2f013ae8f870c1eec90c | [
"MIT"
] | null | null | null | #define PY_ARRAY_UNIQUE_SYMBOL libpreviewer_ARRAY_API
#include <iostream>
#include <boost/python.hpp>
#include <pyboostcvconverter/pyboostcvconverter.hpp>
namespace libpreviewer {
using namespace boost::python;
std::ostream& operator<<(std::ostream& os, const boost::python::object& o) {
return os << boost::python::extract<std::string>(boost::python::str(o))();
}
class Projector {
private:
double scale;
double imageMidWidth;
double imageMidHeight;
int previewWidth;
int previewHeight;
cv::Mat R_Kinv;
cv::Mat mapX;
cv::Mat mapY;
/**
* Map backward the final preview image pixel (x,y) to the
* original equirectangular coords (u,v)
*/
void mapBackward(double x, double y, double& u, double& v) {
double x_ = R_Kinv.at<double>(0,0) * x + R_Kinv.at<double>(0,1) * y + R_Kinv.at<double>(0,2);
double y_ = R_Kinv.at<double>(1,0) * x + R_Kinv.at<double>(1,1) * y + R_Kinv.at<double>(1,2);
double z_ = R_Kinv.at<double>(2,0) * x + R_Kinv.at<double>(2,1) * y + R_Kinv.at<double>(2,2);
// project on a spherical map
// DEBUG
// std::cout << "(x,y,z) = " << "(" << x_ << ", " << y_ << ", " << z_ << ")" << std::endl;
// ENDDEBUG
u = scale * atan2f(x_, z_) + imageMidWidth;
v = scale * ((M_PI / 2.0) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))) + imageMidHeight;
}
public:
Projector(int _imageWidth, int _imageHeight, int _previewWidth, int _previewHeight, cv::Mat _R_Kinv) :
imageMidWidth(static_cast<double>(_imageWidth)/2),
imageMidHeight(static_cast<double>(_imageHeight)/2),
previewWidth(_previewWidth),
previewHeight(_previewHeight),
R_Kinv(_R_Kinv) {
scale = imageMidWidth / M_PI;
// DEBUG
// std::cout << std::endl;
// std::cout << "scale = " << scale << std::endl;
// std::cout << "R_Kinv[0] = " << R_Kinv.at<double>(0,0) << ", " << R_Kinv.at<double>(0,1) << ", " << R_Kinv.at<double>(0,2) << std::endl;
// std::cout << "R_Kinv[1] = " << R_Kinv.at<double>(1,0) << ", " << R_Kinv.at<double>(1,1) << ", " << R_Kinv.at<double>(1,2) << std::endl;
// std::cout << "R_Kinv[2] = " << R_Kinv.at<double>(2,0) << ", " << R_Kinv.at<double>(2,1) << ", " << R_Kinv.at<double>(2,2) << std::endl;
// std::cout << std::endl;
// ENDDEBUG
}
cv::Mat get_map_x() const { return mapX; }
cv::Mat get_map_y() const { return mapY; }
void unproject() {
mapX = cv::Mat(previewHeight, previewWidth, CV_32FC1);
mapY = cv::Mat(previewHeight, previewWidth, CV_32FC1);
for (int x = 0; x < previewWidth; ++x) {
for (int y = 0; y < previewHeight; ++y) {
double u,v;
mapBackward(static_cast<double>(x), static_cast<double>(y), u, v);
// std::cout << "u,v = " << u << "," << v << std::endl;
mapX.at<float>(y,x) = static_cast<float>(u);
mapY.at<float>(y,x) = static_cast<float>(v);
}
}
}
};
/**
* Unproject. Basic inner matrix product using implicit matrix conversion.
* @param leftMat left-hand matrix operand
* @param rightMat right-hand matrix operand
* @return an NdArray representing the dot-product of the left and right operands
*/
// cv::Mat unproject(cv::Mat leftMat, cv::Mat rightMat) {
// auto c1 = leftMat.cols, r2 = rightMat.rows;
// if (c1 != r2) {
// PyErr_SetString(PyExc_TypeError,
// "Incompatible sizes for matrix multiplication.");
// throw_error_already_set();
// }
// cv::Mat result = leftMat * rightMat;
// return result;
// }
#if (PY_VERSION_HEX >= 0x03000000)
static void *init_ar() {
#else
static void init_ar(){
#endif
Py_Initialize();
import_array();
return NUMPY_IMPORT_ARRAY_RETVAL;
}
BOOST_PYTHON_MODULE (libpreviewer) {
//using namespace XM;
init_ar();
//initialize converters
boost::python::type_info info = boost::python::type_id<cv::Mat>();
const boost::python::converter::registration* reg = boost::python::converter::registry::query(info);
if (reg == NULL || (*reg).m_to_python == NULL) {
to_python_converter<cv::Mat, libpreviewer::matToNDArrayBoostConverter>();
libpreviewer::matFromNDArrayBoostConverter();
}
//expose module-level functions
class_<Projector>("Projector", init<int, int, int, int, cv::Mat>())
.def("unproject", &Projector::unproject)
.def("get_map_x", &Projector::get_map_x)
.def("get_map_y", &Projector::get_map_y);
}
} //end namespace libpreviewer
| 38.368421 | 154 | 0.538311 | [
"object"
] |
b50c7a21d7c7902b59133a8e9dd2071bcd7609a5 | 4,784 | cpp | C++ | src/SHAPER1.cpp | squinkylabs/Demo | 7d2e140303dd3877ae8d0a9a5862c8d179c0eae1 | [
"MIT"
] | 43 | 2020-06-21T02:17:03.000Z | 2022-03-05T16:10:12.000Z | src/SHAPER1.cpp | squinkylabs/Demo | 7d2e140303dd3877ae8d0a9a5862c8d179c0eae1 | [
"MIT"
] | 3 | 2020-06-22T00:34:47.000Z | 2021-12-23T19:42:38.000Z | src/SHAPER1.cpp | squinkylabs/Demo | 7d2e140303dd3877ae8d0a9a5862c8d179c0eae1 | [
"MIT"
] | 5 | 2020-06-21T09:06:01.000Z | 2021-12-06T06:43:30.000Z | /**
* This file contains the entire implementation of the FILTER1 demo module.
*/
#include "OverSamplingShaper.h"
#include "demo-plugin.hpp"
float dumbChopper(float x) {
x *= 10;
x = std::max(x, -5.f);
x = std::min(x, 5.f);
return x;
}
class MyShaper : public OverSamplingShaper {
private:
float processShape(float x) override {
return dumbChopper(x);
}
};
/**
* Every synth module must have a Module structure.
* This is where all the real-time processing code goes.
*/
struct SHAPER1Module : Module {
enum ParamIds {
NUM_PARAMS
};
enum InputIds {
INPUT,
NUM_INPUTS
};
enum OutputIds {
DIRTY_OUTPUT,
OVERSAMPLED_OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
MyShaper shaper;
SHAPER1Module() {
// Your module must call config from its constructor, passing in
// how many ins, outs, etc... it has.
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
}
void process(const ProcessArgs& args) override {
const float input = inputs[INPUT].value;
const float output = shaper.process(input);
outputs[OVERSAMPLED_OUTPUT].value = output;
outputs[DIRTY_OUTPUT].value = dumbChopper(input);
}
};
/**
* At least in VCV 1.0, every module must have a Widget, too.
* The widget provides the user interface for a module.
* Widgets may draw to the screen, get mouse and keyboard input, etc...
* Widgets cannot actually process or generate audio.
*/
struct SHAPER1Widget : ModuleWidget {
SHAPER1Widget(SHAPER1Module* module) {
// The widget always retains a reference to the module.
// you must call this function first in your widget constructor.
setModule(module);
// Typically the panel graphic is added first, then the other
// UI elements are placed on TOP.
// In VCV the Z-order of added children is such that later
// children are always higher than children added earlier.
setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/vco1_panel.svg")));
// VCV modules usually have image is "screws" to make them
// look more like physical module. You may design your own screws,
// or not use screws at all.
addChild(createWidget<ScrewSilver>(Vec(15, 0)));
addChild(createWidget<ScrewSilver>(Vec(box.size.x - 30, 0)));
addChild(createWidget<ScrewSilver>(Vec(15, 365)));
addChild(createWidget<ScrewSilver>(Vec(box.size.x - 30, 365)));
// It's purely personal style whether you want to set variables like this
// For the position of your widgets. It's fine to do it inline also.
float x = 50;
float headingY = 20;
float inputY = 75;
float outputY = 140;
float outputY2 = 220;
float labelAbove = 20;
// Now we place the widgets that represent the inputs, outputs, controls,
// and lights for the module. VCO1 does not have any lights, but does have
// the other widgets.
addInput(createInput<PJ301MPort>(Vec(x, inputY), module, SHAPER1Module::INPUT));
addOutput(createOutput<PJ301MPort>(Vec(x, outputY), module, SHAPER1Module::DIRTY_OUTPUT));
addOutput(createOutput<PJ301MPort>(Vec(x, outputY2), module, SHAPER1Module::OVERSAMPLED_OUTPUT));
// Add some quick hack labels to the panel.
addLabel(Vec(20, headingY), "Demo Shaper 1");
addLabel(Vec(x - 20, outputY - labelAbove), "Out Dirty");
addLabel(Vec(x - 1, inputY - labelAbove), "In");
addLabel(Vec(x - 45, outputY2 - labelAbove), "Out Oversampled");
}
// Simple helper function to add test labels to the panel.
// In a real module you would draw this on the panel itself.
// Labels are fine for hacking, but they are discouraged for real use.
// Some of the problems are that they don't draw particularly efficiently,
// and they don't give as much control as putting them into the panel SVG.
Label* addLabel(const Vec& v, const std::string& str) {
NVGcolor black = nvgRGB(0, 0, 0);
Label* label = new Label();
label->box.pos = v;
label->text = str;
label->color = black;
addChild(label);
return label;
}
};
// This mysterious line must appear for each module. The
// name in quotes at then end is the same string that will be in
// plugin.json in the entry for corresponding plugin.
// This line basically tells VCV Rack:
// I'm called "demo-shaper1", my module is SHAPER1Module, and my Widget is SHAPER1Widget.
// In effect, it implements a module factory.
Model* modelSHAPER1 = createModel<SHAPER1Module, SHAPER1Widget>("demo-shaper1"); | 36.242424 | 105 | 0.652592 | [
"model"
] |
b510eae8f4bddd3f547b21213d87bf0d1a09945e | 3,461 | cpp | C++ | main/src/jumpnrun/mover/bullet/ShotGun.cpp | wonderhorn/mkfj | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | [
"MIT"
] | null | null | null | main/src/jumpnrun/mover/bullet/ShotGun.cpp | wonderhorn/mkfj | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | [
"MIT"
] | null | null | null | main/src/jumpnrun/mover/bullet/ShotGun.cpp | wonderhorn/mkfj | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | [
"MIT"
] | null | null | null | #define _USE_MATH_DEFINES
#include<cmath>
#include"jumpnrun/mover/character/Character.h"
#include"jumpnrun/mover/bullet/Bullet.h"
#include"jumpnrun/mover/effect/Effect.h"
#include"jumpnrun/system/Parmanent.h"
#include"jumpnrun/GRAPHICS.h"
using namespace jnr;
using namespace gfw;
using namespace gmtr;
#define $V gmtr::Vector2D
RegisterMoverClass(ShotGun);
void ShotGun::run(jnr::JumpnRunData& data)
{
if (lifetime < age)
{
finalize();
return;
}
auto prev_v = this->V();
Mover::run(data);
if (num_bounding > 0)
{
bool b1 = v_reaction.x != 0.0;
bool b2 = v_reaction.y != 0.0;
if (b1)
{
phys.v.x = -prev_v.x * bound_rate;
}
if (b2)
{
phys.v.y = -prev_v.y * bound_rate;
}
if (b1 || b2)
num_bounding--;
}
else if (num_bounding == 0)
alive = 0;
if (this->collided_with_earth)
{
for (int i = 0; i < 6; i++)
{
double theta = M_PI * 2 / 6 * i;
$V dp(cos(theta), sin(theta));
auto ptr = generate<Bullet>(*tl);
//auto ptr = generateMover(Bullet, tl);
ptr->initialize(REFPOINT_STAR1_X, REFPOINT_STAR1_Y,
Center() - $V(16, 16) + 32 * dp, Owner(), power, dp, 0);
ptr->LifeTime(5);
}
}
}
void ShotGun::interact(jnr::Character& chara, jnr::JumpnRunData& data)
{
if (chara.Owner() == this->Owner())
return;
$V center = phys.p + $V(width / 2, height / 2);
bool hitting = false;
if (radius <= 0)
hitting = chara.Shape().includes(center);
else
{
hitting = chara.Shape().includes(center);
hitting |= chara.Shape().includes(center + $V(radius, 0));
hitting |= chara.Shape().includes(center + $V(-radius, 0));
hitting |= chara.Shape().includes(center + $V(0, radius));
hitting |= chara.Shape().includes(center + $V(0, -radius));
}
if (hitting)
{
Damage dam;
dam.power = power;
dam.stun_time = Constants::time_stun;
dam.invinc_time = Constants::time_invinc;
dam.isPhysical = false;
dam.owner = this->Owner();
auto smashv = this->phys.v.regularized();
if (smashv.l2() == 0)
smashv = $V(0, -1);
dam.smash = smashv * 4.0 + $V(0, -4) - chara.V();
int d = chara.damage(dam);
if (d >= 0)
{
generate<Effect>(*tl)->initialize(REFPOINT_HIT1_X, REFPOINT_HIT1_Y, 32, 32, phys.p, 2, $V(0.0, 0.0), 0);
generate<Effect>(*tl)->initialize(REFPOINT_HIT2_X, REFPOINT_HIT2_Y, 32, 32, phys.p, 4, $V(0.0, 0.0), 0);
//chara.Smash(smashv * 4.0 + $V(0, -4) - chara.V());
finalize();
if (snd_hit >= 0)
$P.sound_stack.push_back(snd_hit);
for (int i = 0; i < 6; i++)
{
double theta = M_PI * 2 / 6 * i;
$V dp(cos(theta), sin(theta));
auto ptr = generate<Bullet>(*tl);
//auto ptr = generateMover(Bullet, tl);
ptr->initialize(REFPOINT_STAR1_X, REFPOINT_STAR1_Y,
Center() - $V(16, 16) + 32 * dp, Owner(), power, dp, 0);
ptr->LifeTime(5);
}
}
else if (d == eDamage::Repelled)
{
collided_with_earth = true;
generate<Effect>(*tl)->initialize(REFPOINT_REPELED_X, REFPOINT_REPELED_Y, 32, 32
, phys.p, 4, $V(0.0, 0.0), 0);
generate<Effect>(*tl)->initialize(REFPOINT_REPELED_X, REFPOINT_REPELED_Y + 32, 32, 32
, phys.p, 6, $V(0.0, 0.0), 0);
finalize();
$P.sound_stack.push_back($P.snd_repell);
for (int i = 0; i < 6; i++)
{
double theta = M_PI * 2 / 6 * i;
$V dp(cos(theta), sin(theta));
auto ptr = generateMover(Bullet, tl);
ptr->initialize(REFPOINT_STAR1_X, REFPOINT_STAR1_Y,
Center() - $V(16, 16) + 32 * dp, Owner(), power, dp, 0);
ptr->LifeTime(5);
}
}
}
}
| 25.448529 | 107 | 0.613695 | [
"shape"
] |
b517089dbce8fa1a4478e0a0d67920ed3ea27104 | 1,647 | cpp | C++ | engine/src/fabric/gameobjectHandler.cpp | batburger/fabricEngine | 438c6094d244720b452bd4638c76e80316023398 | [
"MIT"
] | null | null | null | engine/src/fabric/gameobjectHandler.cpp | batburger/fabricEngine | 438c6094d244720b452bd4638c76e80316023398 | [
"MIT"
] | 5 | 2017-07-24T17:24:43.000Z | 2017-10-07T08:38:32.000Z | engine/src/fabric/gameobjectHandler.cpp | batburger/fabricEngine | 438c6094d244720b452bd4638c76e80316023398 | [
"MIT"
] | null | null | null | #include <fabric/gameobjectHandler.hpp>
int fabric::GameObjectHandler::renderAll() {
if (!fabric::GameObjectHandler::sorted)
GameObjectHandler::sortVector();
for (unsigned int i = 0; i < GameObjectHandler::gObjs.size(); i++) {
GameObjectHandler::gObjs.at(i)->render();
}
return 0;
}
int fabric::GameObjectHandler::updateAll(){
if (!fabric::GameObjectHandler::sorted)
GameObjectHandler::sortVector();
for (auto gObj : GameObjectHandler::gObjs) {
for (auto updateFunc : gObj->updatePointers) {
updateFunc();
}
}
return 0;
}
int fabric::GameObjectHandler::setupAll()
{
if (!fabric::GameObjectHandler::sorted)
GameObjectHandler::sortVector();
for (auto gObj : GameObjectHandler::gObjs) {
for (auto setupPointer : gObj->setupPointers) {
setupPointer();
}
}
return 0;
}
int fabric::GameObjectHandler::sortVector()
{
std::vector<GameObject*> tmp;
for (unsigned int i = 0; i < GameObjectHandler::gObjs.size(); i++) {
GameObject* curGameObject = GameObjectHandler::gObjs.at(i);
if (tmp.size() == 0)
tmp.push_back(curGameObject);
else{
for (int j = tmp.size(); j > 0; j--) {
if (curGameObject->priority > tmp.at(j - 1)->priority){
tmp.insert(tmp.begin() + j, curGameObject);
break;
}
else{
if (j - 1 == 0) {
tmp.insert(tmp.begin(), curGameObject);
}
}
}
}
}
return 0;
}
int fabric::GameObjectHandler::addGameObject(GameObject* gObj, bool toSort)
{
GameObjectHandler::gObjs.push_back(gObj);
if(toSort)
GameObjectHandler::sortVector();
return 0;
}
int fabric::GameObjectHandler::removeGameObjectByName(std::string name)
{
return 0;
} | 19.843373 | 75 | 0.667881 | [
"render",
"vector"
] |
dde2f13aff4e82ce660e20c91e866e25f2e528a6 | 9,872 | cpp | C++ | saga/impl/exception.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | saga/impl/exception.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | saga/impl/exception.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | // Copyright (c) 2005-2009 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <saga/saga/base.hpp>
#include <saga/saga/adaptors/task.hpp>
#include <saga/impl/runtime.hpp>
#include <saga/saga/exception.hpp>
#include <saga/impl/engine/proxy.hpp>
#include <saga/impl/engine/cpi.hpp>
#include <saga/impl/exception.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace saga {
///////////////////////////////////////////////////////////////////////////
namespace impl {
///////////////////////////////////////////////////////////////////////
// throw a saga::exception
void throw_exception(saga::object const& obj, std::string const& m,
error e)
{
switch (e) {
case NotImplemented:
throw saga::not_implemented(obj, m);
case IncorrectURL:
throw saga::incorrect_url(obj, m);
case BadParameter:
throw saga::bad_parameter(obj, m);
case AlreadyExists:
throw saga::already_exists(obj, m);
case DoesNotExist:
throw saga::does_not_exist(obj, m);
case IncorrectState:
throw saga::incorrect_state(obj, m);
case PermissionDenied:
throw saga::permission_denied(obj, m);
case AuthorizationFailed:
throw saga::authorization_failed(obj, m);
case AuthenticationFailed:
throw saga::authentication_failed(obj, m);
case Timeout:
throw saga::timeout(obj, m);
case (saga::error)adaptors::AdaptorDeclined:
case (saga::error)adaptors::NoAdaptor:
case (saga::error)adaptors::NoAdaptorInfo:
case (saga::error)adaptors::Unexpected:
throw saga::exception(obj, m, e);
case NoSuccess:
throw saga::no_success(obj, m);
default:
throw saga::exception(obj, m, e);
}
}
void throw_exception(saga::object const& obj,
std::vector<saga::exception> const& l, saga::error e)
{
switch (e) {
case NotImplemented:
throw saga::not_implemented(obj, l);
case IncorrectURL:
throw saga::incorrect_url(obj, l);
case BadParameter:
throw saga::bad_parameter(obj, l);
case AlreadyExists:
throw saga::already_exists(obj, l);
case DoesNotExist:
throw saga::does_not_exist(obj, l);
case IncorrectState:
throw saga::incorrect_state(obj, l);
case PermissionDenied:
throw saga::permission_denied(obj, l);
case AuthorizationFailed:
throw saga::authorization_failed(obj, l);
case AuthenticationFailed:
throw saga::authentication_failed(obj, l);
case Timeout:
throw saga::timeout(obj, l);
case (saga::error)adaptors::AdaptorDeclined:
case (saga::error)adaptors::NoAdaptor:
case (saga::error)adaptors::NoAdaptorInfo:
case (saga::error)adaptors::Unexpected:
throw saga::exception(obj, l, e);
case NoSuccess:
throw saga::no_success(obj, l);
default:
throw saga::exception(obj, l);
}
}
void throw_exception(saga::object const& obj, exception_list const& l)
{
throw_exception(obj, l.get_all_exceptions(), l.get_error());
}
void throw_exception(saga::object const& obj, exception_list const& l,
saga::error e)
{
throw_exception(obj, l.get_all_exceptions(), e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception
void throw_exception(saga::object const& obj, std::string const& m,
adaptors::error e)
{
throw_exception(obj, m, (saga::error)e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception from a saga object member function
void throw_exception(saga::impl::object const *this_,
std::string const& m, error e)
{
throw_exception(
runtime::get_object(
TR1::const_pointer_cast<saga::impl::object>(
this_->shared_from_this())
),
m, e);
}
void throw_exception(saga::impl::object const *this_,
exception_list const& l)
{
throw_exception(
runtime::get_object(
TR1::const_pointer_cast<saga::impl::object>(
this_->shared_from_this())
),
l);
}
void throw_exception(saga::impl::object const *this_,
exception_list const& l, saga::error e)
{
throw_exception(
runtime::get_object(
TR1::const_pointer_cast<saga::impl::object>(
this_->shared_from_this())
),
l, e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception from a saga object member function
void throw_exception(saga::impl::object const *this_,
std::string const& m, adaptors::error e)
{
throw_exception(this_, m, (saga::error)e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception from an adaptor member function
void throw_exception(saga::impl::v1_0::cpi const *this_,
std::string const& m, error e)
{
TR1::shared_ptr<saga::impl::object> impl(
TR1::static_pointer_cast<saga::impl::object>(
TR1::const_pointer_cast<saga::impl::proxy>(
this_->get_proxy()->shared_from_this())));
throw_exception(runtime::get_object(impl), m, e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception from an adaptor member function
void throw_exception(saga::impl::v1_0::cpi const *this_,
std::string const& m, adaptors::error e)
{
throw_exception(this_, m, (saga::error)e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception from any other function
void throw_exception(void const *this_, std::string const& m, error e)
{
throw_exception(saga::object(), m, e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::exception from any other function
void throw_exception(void const *this_, std::string const& m,
adaptors::error e)
{
throw_exception(saga::object(), m, e);
}
///////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////
namespace adaptors
{
///////////////////////////////////////////////////////////////////////
// throw a saga::adaptors::exception
void throw_adaptor_exception(saga::impl::v1_0::cpi const *this_,
std::string const& adaptor_name, std::string const& m,
saga::error e)
{
TR1::shared_ptr<saga::impl::object> impl(
TR1::static_pointer_cast<saga::impl::object>(
TR1::const_pointer_cast<saga::impl::proxy>(
this_->get_proxy()->shared_from_this())));
throw saga::adaptors::exception(
saga::impl::runtime::get_object(impl), adaptor_name, m, e);
}
void throw_adaptor_exception(saga::impl::v1_0::cpi const *this_,
saga::impl::exception_list const& l)
{
TR1::shared_ptr<saga::impl::object> impl(
TR1::static_pointer_cast<saga::impl::object>(
TR1::const_pointer_cast<saga::impl::proxy>(
this_->get_proxy()->shared_from_this())));
throw saga::adaptors::exception(
saga::impl::runtime::get_object(impl), l.get_all_exceptions());
}
void throw_adaptor_exception(saga::impl::v1_0::cpi const *this_,
std::string const& adaptor_name, std::string const& m,
saga::adaptors::error e)
{
throw_adaptor_exception(this_, adaptor_name, m, (saga::error)e);
}
///////////////////////////////////////////////////////////////////////
// throw a saga::adaptors::exception
void throw_adaptor_exception(std::string const& adaptor_name,
std::string const& m, saga::error e)
{
throw saga::adaptors::exception(saga::object(), adaptor_name, m, e);
}
void throw_adaptor_exception(std::string const& adaptor_name,
std::string const& m, saga::adaptors::error e)
{
throw saga::adaptors::exception(saga::object(), adaptor_name, m,
(saga::error)e);
}
///////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////////
} // namespace saga::impl
| 39.019763 | 81 | 0.472346 | [
"object",
"vector"
] |
dde3dd6bc360aa048a61122ecf32b793cd3d09bb | 7,183 | cpp | C++ | src/applications/thorough-json.cpp | jingai/xiv-sim | 074b86cb6ccd00149c08e89be7c02f1a7c05ed93 | [
"MIT"
] | 9 | 2015-01-27T11:48:28.000Z | 2020-12-02T16:58:13.000Z | src/applications/thorough-json.cpp | jingai/xiv-sim | 074b86cb6ccd00149c08e89be7c02f1a7c05ed93 | [
"MIT"
] | 21 | 2015-01-03T08:56:42.000Z | 2016-01-01T13:43:42.000Z | src/applications/thorough-json.cpp | ccbrown/xiv-sim | 074b86cb6ccd00149c08e89be7c02f1a7c05ed93 | [
"MIT"
] | 8 | 2015-01-25T04:31:51.000Z | 2017-03-03T17:29:42.000Z | #include "ActorConfigurationParser.h"
#include "json.h"
#include "../Actor.h"
#include "../JITRotation.h"
#include "../Simulation.h"
#include "../models/Dragoon.h"
#include <future>
#include <vector>
#include <map>
#include <inttypes.h>
namespace applications {
struct TrialResults {
uint64_t seed;
Simulation::Configuration configuration;
Actor::SimulationStats overallStats;
std::unordered_map<std::string, Actor::EffectSimulationStats> effectStats;
};
static TrialResults Trial(const Simulation::Configuration&& configuration) {
TrialResults ret;
ret.configuration = configuration;
{
std::random_device rd;
PortableUniformIntDistribution<uint64_t> dist;
ret.seed = dist(rd);
}
Simulation simulation(&ret.configuration, ret.seed);
simulation.run();
for (auto& subject : simulation.subjects()) {
ret.overallStats += subject->simulationStats();
for (auto& kv : subject->effectSimulationStats()) {
ret.effectStats[kv.first] += kv.second;
}
}
return ret;
}
struct SimulationStats {
int iterations = 0;
uint64_t worstSeed = 0;
double worstDPS = 0.0;
std::chrono::microseconds worstTime = 0_us;
uint64_t bestSeed = 0;
double bestDPS = 0.0;
std::chrono::microseconds bestTime = 0_us;
std::chrono::microseconds time = 0_us;
Actor::SimulationStats general;
std::map<std::string, Actor::EffectSimulationStats> effects;
};
void PerformSimulations(int iterations, const std::vector<Actor::Configuration*>& subjectConfigurations, Actor::Configuration* targetConfiguration, std::chrono::microseconds minTime, std::chrono::microseconds maxTime, SimulationStats* stats) {
stats->iterations = iterations;
int remaining = iterations;
while (remaining) {
std::vector<std::future<TrialResults>> futures;
for (int i = 0; remaining && i < 5000; ++i, --remaining) {
Simulation::Configuration configuration;
configuration.length = std::chrono::duration_cast<std::chrono::microseconds>(minTime + (i % 50) / 50.0 * (maxTime - minTime));
configuration.subjectConfigurations = subjectConfigurations;
configuration.targetConfiguration = targetConfiguration;
futures.emplace_back(std::async(std::launch::async, Trial, std::move(configuration)));
}
for (auto& future : futures) {
auto results = future.get();
stats->general += results.overallStats;
for (auto& kv : results.effectStats) {
stats->effects[kv.first] += kv.second;
}
stats->time += results.configuration.length;
auto dps = results.overallStats.damageDealt / std::chrono::duration<double>(results.configuration.length).count();
if (!stats->worstDPS || dps < stats->worstDPS) {
stats->worstSeed = results.seed;
stats->worstDPS = dps;
stats->worstTime = results.configuration.length;
}
if (!stats->bestDPS || dps > stats->bestDPS) {
stats->bestSeed = results.seed;
stats->bestDPS = dps;
stats->bestTime = results.configuration.length;
}
}
}
}
int ThoroughJSON(int argc, const char* argv[]) {
if (argc < 4) {
printf("Usage: simulator thorough-json subject rotation min-length max-length\n");
return 1;
}
ActorConfigurationParser subjectParser;
if (!subjectParser.parseFile(argv[0])) {
printf("Unable to read configuration.\n");
return 1;
}
JITRotation subjectRotation;
if (!subjectRotation.initializeWithFile(argv[1])) {
printf("Unable to read rotation.\n");
return 1;
}
auto minLength = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::duration<double>(strtod(argv[2], nullptr)));
auto maxLength = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::duration<double>(strtod(argv[3], nullptr)));
if (minLength <= 0_us || maxLength <= minLength) {
printf("Invalid lengths.");
return 1;
}
std::vector<Actor::Configuration*> subjectConfigurations;
auto& subjectConfiguration = subjectParser.configuration();
subjectConfiguration.identifier = "player";
subjectConfiguration.rotation = &subjectRotation;
subjectConfigurations.push_back(&subjectConfiguration);
if (subjectConfiguration.petConfiguration) {
auto petConfiguration = *subjectConfiguration.petConfiguration;
petConfiguration.identifier = "player-pet";
petConfiguration.keepsHistory = subjectConfiguration.keepsHistory;
}
models::Dragoon targetModel;
Actor::Configuration targetConfiguration;
targetConfiguration.identifier = "target";
targetConfiguration.model = &targetModel;
printf("{");
SimulationStats unmodifiedStats;
PerformSimulations(100000, subjectConfigurations, &targetConfiguration, minLength, maxLength, &unmodifiedStats);
JSONPrint("iterations"); printf(":"); JSONPrint(unmodifiedStats.iterations); printf(",");
JSONPrint("min-time"); printf(":"); JSONPrint(minLength); printf(",");
JSONPrint("max-time"); printf(":"); JSONPrint(maxLength); printf(",");
JSONPrint("time"); printf(":"); JSONPrint(unmodifiedStats.time); printf(",");
JSONPrint("damage"); printf(":"); JSONPrint(unmodifiedStats.general.damageDealt); printf(",");
JSONPrint("best-dps"); printf(":"); JSONPrint(unmodifiedStats.bestDPS); printf(",");
JSONPrint("best-seed"); printf(":"); JSONPrint(std::to_string(unmodifiedStats.bestSeed)); printf(",");
JSONPrint("best-time"); printf(":"); JSONPrint(unmodifiedStats.bestTime); printf(",");
JSONPrint("worst-dps"); printf(":"); JSONPrint(unmodifiedStats.worstDPS); printf(",");
JSONPrint("worst-seed"); printf(":"); JSONPrint(std::to_string(unmodifiedStats.worstSeed)); printf(",");
JSONPrint("worst-time"); printf(":"); JSONPrint(unmodifiedStats.worstTime); printf(",");
JSONPrint("effects"); printf(":"); JSONPrint(unmodifiedStats.effects); printf(",");
const std::unordered_map<std::string, int*> scalingStats({
{"wpdmg", &subjectConfiguration.stats.weaponPhysicalDamage},
{"wmdmg", &subjectConfiguration.stats.weaponMagicDamage},
{"str", &subjectConfiguration.stats.strength},
{"dex", &subjectConfiguration.stats.dexterity},
{"int", &subjectConfiguration.stats.intelligence},
{"pie", &subjectConfiguration.stats.piety},
{"crt", &subjectConfiguration.stats.criticalHitRate},
{"det", &subjectConfiguration.stats.determination},
{"sks", &subjectConfiguration.stats.skillSpeed},
{"sps", &subjectConfiguration.stats.spellSpeed}
});
JSONPrint("scaling"); printf(":{");
auto petConfiguration = subjectParser.petConfiguration();
bool first = true;
for (auto& kv : scalingStats) {
if (!*kv.second) { continue; }
auto original = *kv.second;
auto amount = 5;
// scale up
*kv.second = original + amount;
if (petConfiguration) {
petConfiguration->stats = subjectConfiguration.stats;
}
// simulate
SimulationStats scaleStats;
PerformSimulations(100000, subjectConfigurations, &targetConfiguration, minLength, maxLength, &scaleStats);
if (!first) { printf(","); }
JSONPrint(kv.first); printf(":");
JSONPrintDict(
"amount", amount,
"iterations", scaleStats.iterations,
"time", scaleStats.time,
"damage", scaleStats.general.damageDealt
);
first = false;
// scale back down
*kv.second = original;
if (petConfiguration) {
petConfiguration->stats = subjectConfiguration.stats;
}
}
printf("}");
printf("}");
return 0;
}
} | 32.502262 | 243 | 0.719337 | [
"vector",
"model"
] |
dde66094bc594d6b3d89f176a689ef40641803c8 | 2,065 | cpp | C++ | intel_extension_for_pytorch/csrc/aten/cpu/MergedEmbeddingBag.cpp | Manny27nyc/intel-extension-for-pytorch | b40faedf6b00d520f6483d519d2e82bce0a6c0d1 | [
"Apache-2.0"
] | null | null | null | intel_extension_for_pytorch/csrc/aten/cpu/MergedEmbeddingBag.cpp | Manny27nyc/intel-extension-for-pytorch | b40faedf6b00d520f6483d519d2e82bce0a6c0d1 | [
"Apache-2.0"
] | null | null | null | intel_extension_for_pytorch/csrc/aten/cpu/MergedEmbeddingBag.cpp | Manny27nyc/intel-extension-for-pytorch | b40faedf6b00d520f6483d519d2e82bce0a6c0d1 | [
"Apache-2.0"
] | null | null | null | #include "MergedEmbeddingBag.h"
#include <ATen/AccumulateType.h>
#include <ATen/Tensor.h>
#include <torch/extension.h>
#include "csrc/autocast/autocast_mode.h"
namespace torch_ipex {
namespace cpu {
DEFINE_DISPATCH(merged_embeddingbag_forward_cpu_kernel_stub);
std::vector<Tensor> merged_embeddingbag_forward_cpu(
const Tensor& indices,
const Tensor& offsets,
const std::vector<Tensor>& weights,
const std::vector<int64_t> pooling_modes) {
#if defined(DYN_DISP_BUILD)
return merged_embeddingbag_forward_cpu_kernel_stub(
kCPU, indices, offsets, weights, pooling_modes);
#else
return merged_embeddingbag_forward_cpu_kernel_impl(
indices, offsets, weights, pooling_modes);
#endif
}
} // namespace cpu
} // namespace torch_ipex
namespace torch_ipex {
namespace autocast {
std::vector<Tensor> merged_embeddingbag_forward(
const Tensor& indices,
const Tensor& offsets,
const std::vector<Tensor>& weights,
const std::vector<int64_t> pooling_modes) {
c10::impl::ExcludeDispatchKeyGuard no_autocastCPU(DispatchKey::AutocastCPU);
static auto op =
torch::Dispatcher::singleton()
.findSchemaOrThrow("torch_ipex::merged_embeddingbag_forward", "")
.typed<decltype(merged_embeddingbag_forward)>();
bool cast_to_bfloat16 =
!at::GradMode::is_enabled() && at::kBFloat16 == get_autocast_dtype();
auto casted_weights =
cast_to_bfloat16 ? cpu_cached_cast(at::kBFloat16, weights) : weights;
return op.call(indices, offsets, casted_weights, pooling_modes);
}
} // namespace autocast
} // namespace torch_ipex
namespace {
TORCH_LIBRARY_FRAGMENT(torch_ipex, m) {
m.def(
"merged_embeddingbag_forward(Tensor indices, Tensor offsets, Tensor[] weight, int[] pooling_modes) -> Tensor[]");
m.impl(
"merged_embeddingbag_forward",
c10::DispatchKey::CPU,
torch_ipex::cpu::merged_embeddingbag_forward_cpu);
m.impl(
"merged_embeddingbag_forward",
c10::DispatchKey::AutocastCPU,
torch_ipex::autocast::merged_embeddingbag_forward);
}
} // namespace
| 30.367647 | 119 | 0.74092 | [
"vector"
] |
ddf6bc6c4cd16c7f81cd61851545040274e5ea57 | 4,944 | cpp | C++ | src/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.java
#include <org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/util/Collection.hpp>
#include <java/util/HashMap.hpp>
#include <java/util/HashSet.hpp>
#include <java/util/Iterator.hpp>
#include <java/util/Map.hpp>
#include <java/util/Set.hpp>
#include <org/apache/poi/poifs/eventfilesystem/POIFSReaderListener.hpp>
#include <org/apache/poi/poifs/filesystem/DocumentDescriptor.hpp>
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::poifs::eventfilesystem::POIFSReaderRegistry::POIFSReaderRegistry(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::poifs::eventfilesystem::POIFSReaderRegistry::POIFSReaderRegistry()
: POIFSReaderRegistry(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
void poi::poifs::eventfilesystem::POIFSReaderRegistry::ctor()
{
super::ctor();
omnivorousListeners = new ::java::util::HashSet();
selectiveListeners = new ::java::util::HashMap();
chosenDocumentDescriptors = new ::java::util::HashMap();
}
void poi::poifs::eventfilesystem::POIFSReaderRegistry::registerListener(POIFSReaderListener* listener, ::poi::poifs::filesystem::POIFSDocumentPath* path, ::java::lang::String* documentName)
{
if(!npc(omnivorousListeners)->contains(static_cast< ::java::lang::Object* >(listener))) {
auto descriptors = java_cast< ::java::util::Set* >(npc(selectiveListeners)->get(listener));
if(descriptors == nullptr) {
descriptors = new ::java::util::HashSet();
npc(selectiveListeners)->put(listener, descriptors);
}
auto descriptor = new ::poi::poifs::filesystem::DocumentDescriptor(path, documentName);
if(npc(descriptors)->add(static_cast< ::java::lang::Object* >(descriptor))) {
auto listeners = java_cast< ::java::util::Set* >(npc(chosenDocumentDescriptors)->get(descriptor));
if(listeners == nullptr) {
listeners = new ::java::util::HashSet();
npc(chosenDocumentDescriptors)->put(descriptor, listeners);
}
npc(listeners)->add(static_cast< ::java::lang::Object* >(listener));
}
}
}
void poi::poifs::eventfilesystem::POIFSReaderRegistry::registerListener(POIFSReaderListener* listener)
{
if(!npc(omnivorousListeners)->contains(static_cast< ::java::lang::Object* >(listener))) {
removeSelectiveListener(listener);
npc(omnivorousListeners)->add(static_cast< ::java::lang::Object* >(listener));
}
}
java::util::Iterator* poi::poifs::eventfilesystem::POIFSReaderRegistry::getListeners(::poi::poifs::filesystem::POIFSDocumentPath* path, ::java::lang::String* name)
{
::java::util::Set* rval = new ::java::util::HashSet(static_cast< ::java::util::Collection* >(omnivorousListeners));
auto selectiveListenersInner = java_cast< ::java::util::Set* >(npc(chosenDocumentDescriptors)->get(new ::poi::poifs::filesystem::DocumentDescriptor(path, name)));
if(selectiveListenersInner != nullptr) {
npc(rval)->addAll(static_cast< ::java::util::Collection* >(selectiveListenersInner));
}
return npc(rval)->iterator();
}
void poi::poifs::eventfilesystem::POIFSReaderRegistry::removeSelectiveListener(POIFSReaderListener* listener)
{
auto selectedDescriptors = java_cast< ::java::util::Set* >(npc(selectiveListeners)->remove(listener));
if(selectedDescriptors != nullptr) {
auto iter = npc(selectedDescriptors)->iterator();
while (npc(iter)->hasNext()) {
dropDocument(listener, java_cast< ::poi::poifs::filesystem::DocumentDescriptor* >(npc(iter)->next()));
}
}
}
void poi::poifs::eventfilesystem::POIFSReaderRegistry::dropDocument(POIFSReaderListener* listener, ::poi::poifs::filesystem::DocumentDescriptor* descriptor)
{
auto listeners = java_cast< ::java::util::Set* >(npc(chosenDocumentDescriptors)->get(descriptor));
npc(listeners)->remove(static_cast< ::java::lang::Object* >(listener));
if(npc(listeners)->size() == 0) {
npc(chosenDocumentDescriptors)->remove(descriptor);
}
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::poifs::eventfilesystem::POIFSReaderRegistry::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.poifs.eventfilesystem.POIFSReaderRegistry", 56);
return c;
}
java::lang::Class* poi::poifs::eventfilesystem::POIFSReaderRegistry::getClass0()
{
return class_();
}
| 40.195122 | 189 | 0.697209 | [
"object"
] |
ddff1f379c3ca7710b08bd3bd38b4355899827ec | 3,135 | hpp | C++ | src/PreviewData.hpp | rc2server/compute | cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc | [
"0BSD"
] | 1 | 2021-08-20T06:44:10.000Z | 2021-08-20T06:44:10.000Z | src/PreviewData.hpp | rc2server/compute | cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc | [
"0BSD"
] | 4 | 2017-03-27T17:55:29.000Z | 2018-01-29T22:51:40.000Z | src/PreviewData.hpp | rc2server/compute | cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc | [
"0BSD"
] | 1 | 2021-08-20T06:44:10.000Z | 2021-08-20T06:44:10.000Z | #pragma once
#include <string>
#include <map>
#include <memory>
#include <sstream>
#include "common/ZeroInitializedStruct.hpp"
#include "EnvironmentWatcher.hpp"
#include "parser/RmdParser.hpp"
#include "common/RC2Utils.hpp"
#include "PreviewDelegate.hpp"
#include "FileManager.hpp"
using std::string;
using std::vector;
using std::unique_ptr;
namespace RC2 {
// need to handle referenced files that changed (csv, etc.)
struct ChunkCacheEntry: ZeroInitializedStruct {
int chunkNumber;
int crc;
string lastSource;
string lastOutput;
EnvironmentWatcher envWatcher;
bool outputCached;
ChunkCacheEntry(int num, string source, string output, EnvironmentWatcher *parentEnv)
: chunkNumber(num), lastSource(source), lastOutput(output),
envWatcher(parentEnv), outputCached(false)
{}
ChunkCacheEntry(int num, EnvironmentWatcher *parentEnv)
: chunkNumber(num), envWatcher(parentEnv)
{}
void cacheOutput(string newOuput) {
lastOutput = newOuput;
outputCached = true;
}
int generateCRC() {
string csrc = lastSource + lastOutput + std::to_string(chunkNumber);
return calculateCRCChecksum(csrc);
}
};
typedef std::map<int, unique_ptr<ChunkCacheEntry>> ChunkCacheMap;
struct UpdateResponse: ZeroInitializedStruct {
int previewId;
int chunkId;
string resultText;
UpdateResponse(int preId, int chunkId, string results = "")
: previewId(preId), chunkId(chunkId), resultText(results) {};
};
struct PreviewData: ZeroInitializedStruct {
int previewId;
FileManager* fileManager;
FileInfo fileInfo;
ChunkCacheMap chunkMap;
RmdParser parser;
boost::signals2::connection* fileConnection;
PreviewData(int pid, FileManager* fmanager, FileInfo& finfo, EnvironmentWatcher* globalEnv, PreviewDelegate *delegate);
virtual ~PreviewData();
vector<Chunk*> currentChunks() const { return currentChunks_; }
/**
* @brief update the cache and return changed results
*
* @param updatedInfo the updated info about the file
* @param updateIdent a unique identifier included in all result messages
* @param targetChunkId the target chunk to start with. If < 0, all chunks are updated
* @param includePrevious should chunks before targetChunkId be updated
*/
void update(FileInfo& updatedInfo, string& updateIdent, int targetChunkId, bool includePrevious = false);
void fileChanged(long changedId, ChangeType type);
protected:
vector<int> whichChunksNeedUpdate(int start, bool includePrevious);
void executeChunks(vector<int> chunksToUpdate);
void checkCache();
/**
* @brief Executes the chunk's code
* @param chunk the chunk to executeChunk
* @param cacheEntry the cache entry for this chunk
* @return the console output for the chunk
* @throws GenericException kError_QueryFailed
*
*/
string executeChunk(Chunk* chunk, ChunkCacheEntry* cacheEntry);
EnvironmentWatcher previewEnv;
string currentUpdateIdentifier_;
vector<Chunk*> currentChunks_;
PreviewDelegate* delegate_;
};
}; // end namespace
| 29.027778 | 121 | 0.722488 | [
"vector"
] |
fb01217def40d73c4d2c82165731a37486265e74 | 16,740 | cc | C++ | test/src/unit-rtree.cc | Ari0nhh/TileDB | 6207c24ea4771f71a2ab9dab3fd3b37f73a685d3 | [
"MIT"
] | null | null | null | test/src/unit-rtree.cc | Ari0nhh/TileDB | 6207c24ea4771f71a2ab9dab3fd3b37f73a685d3 | [
"MIT"
] | null | null | null | test/src/unit-rtree.cc | Ari0nhh/TileDB | 6207c24ea4771f71a2ab9dab3fd3b37f73a685d3 | [
"MIT"
] | null | null | null | /**
* @file unit-rtree.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2020 TileDB, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* Tests the `RTree` class.
*/
#include "tiledb/sm/array_schema/dimension.h"
#include "tiledb/sm/enums/datatype.h"
#include "tiledb/sm/enums/layout.h"
#include "tiledb/sm/rtree/rtree.h"
#include <catch.hpp>
#include <iostream>
using namespace tiledb::sm;
// `mbrs` contains a flattened vector of values (low, high)
// per dimension per MBR
template <class T, unsigned D>
std::vector<NDRange> create_mbrs(const std::vector<T>& mbrs) {
assert(mbrs.size() % 2 * D == 0);
uint64_t mbr_num = (uint64_t)(mbrs.size() / (2 * D));
std::vector<NDRange> ret(mbr_num);
uint64_t r_size = 2 * sizeof(T);
for (uint64_t m = 0; m < mbr_num; ++m) {
ret[m].resize(D);
for (unsigned d = 0; d < D; ++d) {
ret[m][d].set_range(&mbrs[2 * D * m + 2 * d], r_size);
}
}
return ret;
}
Domain create_domain(
const std::vector<std::string>& dim_names,
const std::vector<Datatype>& dim_types,
const std::vector<const void*>& dim_domains,
const std::vector<const void*>& dim_tile_extents) {
assert(!dim_names.empty());
assert(dim_names.size() == dim_types.size());
assert(dim_names.size() == dim_domains.size());
assert(dim_names.size() == dim_tile_extents.size());
Domain domain(dim_types[0]);
for (size_t d = 0; d < dim_names.size(); ++d) {
Dimension dim(dim_names[d], dim_types[d]);
dim.set_domain(dim_domains[d]);
dim.set_tile_extent(dim_tile_extents[d]);
domain.add_dimension(&dim);
}
domain.init(Layout::ROW_MAJOR, Layout::ROW_MAJOR);
return domain;
}
TEST_CASE("RTree: Test R-Tree, basic functions", "[rtree][basic]") {
// Empty tree
RTree rtree0;
CHECK(rtree0.height() == 0);
CHECK(rtree0.dim_num() == 0);
CHECK(rtree0.domain() == nullptr);
CHECK(rtree0.fanout() == 0);
// 1D
int32_t dim_dom[] = {1, 1000};
int32_t dim_extent = 10;
Domain dom1 =
create_domain({"d"}, {Datatype::INT32}, {dim_dom}, {&dim_extent});
std::vector<NDRange> mbrs_1d = create_mbrs<int32_t, 1>({1, 3, 5, 10, 20, 22});
RTree rtree1(&dom1, 3);
CHECK(!rtree1.set_leaf(0, mbrs_1d[0]).ok());
rtree1.set_leaf_num(mbrs_1d.size());
for (size_t m = 0; m < mbrs_1d.size(); ++m)
CHECK(rtree1.set_leaf(m, mbrs_1d[m]).ok());
CHECK(!rtree1.set_leaf_num(1).ok());
rtree1.build_tree();
CHECK(!rtree1.set_leaf(0, mbrs_1d[0]).ok());
CHECK(rtree1.height() == 2);
CHECK(rtree1.dim_num() == 1);
CHECK(rtree1.subtree_leaf_num(0) == 3);
CHECK(rtree1.subtree_leaf_num(1) == 1);
CHECK(rtree1.subtree_leaf_num(2) == 0);
CHECK(rtree1.leaf(0) == mbrs_1d[0]);
CHECK(rtree1.leaf(1) == mbrs_1d[1]);
CHECK(rtree1.leaf(2) == mbrs_1d[2]);
NDRange range1(1);
NDRange mbr1(1);
int32_t mbr1_r[] = {5, 10};
mbr1[0].set_range(mbr1_r, 2 * sizeof(int32_t));
int32_t r1_no_left[] = {0, 1};
int32_t r1_left[] = {4, 7};
int32_t r1_exact[] = {5, 10};
int32_t r1_full[] = {4, 11};
int32_t r1_contained[] = {6, 7};
int32_t r1_right[] = {7, 11};
int32_t r1_no_right[] = {11, 15};
range1[0].set_range(r1_no_left, 2 * sizeof(int32_t));
double ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 0.0);
range1[0].set_range(r1_left, 2 * sizeof(int32_t));
ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 3.0 / 6);
range1[0].set_range(r1_exact, 2 * sizeof(int32_t));
ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 1.0);
range1[0].set_range(r1_full, 2 * sizeof(int32_t));
ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 1.0);
range1[0].set_range(r1_contained, 2 * sizeof(int32_t));
ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 2.0 / 6);
range1[0].set_range(r1_right, 2 * sizeof(int32_t));
ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 4.0 / 6);
range1[0].set_range(r1_no_right, 2 * sizeof(int32_t));
ratio1 = dom1.overlap_ratio(range1, mbr1);
CHECK(ratio1 == 0.0);
// 2D
int64_t dim_dom_2[] = {1, 1000};
int64_t dim_extent_2 = 10;
Domain dom2 = create_domain(
{"d1", "d2"},
{Datatype::INT64, Datatype::INT64},
{dim_dom_2, dim_dom_2},
{&dim_extent_2, &dim_extent_2});
std::vector<NDRange> mbrs_2d =
create_mbrs<int64_t, 2>({1, 3, 5, 10, 20, 22, 24, 25, 11, 15, 30, 31});
RTree rtree2(&dom2, 5);
rtree2.set_leaves(mbrs_2d);
rtree2.build_tree();
CHECK(rtree2.height() == 2);
CHECK(rtree2.dim_num() == 2);
CHECK(rtree2.fanout() == 5);
CHECK(rtree2.leaf(0) == mbrs_2d[0]);
CHECK(rtree2.leaf(1) == mbrs_2d[1]);
CHECK(rtree2.leaf(2) == mbrs_2d[2]);
NDRange range2(2);
int64_t mbr2_r[] = {5, 10, 2, 9};
NDRange mbr2(2);
mbr2[0].set_range(&mbr2_r[0], 2 * sizeof(int64_t));
mbr2[1].set_range(&mbr2_r[2], 2 * sizeof(int64_t));
int64_t r2_no[] = {6, 7, 10, 12};
int64_t r2_full[] = {4, 11, 2, 9};
int64_t r2_partial[] = {7, 11, 4, 5};
range2[0].set_range(&r2_no[0], 2 * sizeof(int64_t));
range2[1].set_range(&r2_no[2], 2 * sizeof(int64_t));
double ratio2 = dom2.overlap_ratio(range2, mbr2);
CHECK(ratio2 == 0.0);
range2[0].set_range(&r2_full[0], 2 * sizeof(int64_t));
range2[1].set_range(&r2_full[2], 2 * sizeof(int64_t));
ratio2 = dom2.overlap_ratio(range2, mbr2);
CHECK(ratio2 == 1.0);
range2[0].set_range(&r2_partial[0], 2 * sizeof(int64_t));
range2[1].set_range(&r2_partial[2], 2 * sizeof(int64_t));
ratio2 = dom2.overlap_ratio(range2, mbr2);
CHECK(ratio2 == (4.0 / 6) * (2.0 / 8));
// Float datatype
float dim_dom_f[] = {1.0, 1000.0};
float dim_extent_f = 10.0;
std::vector<NDRange> mbrs_f =
create_mbrs<float, 1>({1.0f, 3.0f, 5.0f, 10.0f, 20.0f, 22.0f});
Domain dom2f =
create_domain({"d"}, {Datatype::FLOAT32}, {dim_dom_f}, {&dim_extent_f});
RTree rtreef(&dom2f, 5);
rtreef.set_leaves(mbrs_f);
rtreef.build_tree();
NDRange rangef(1);
float mbrf_r[] = {5.0f, 10.0f};
NDRange mbrf(1);
mbrf[0].set_range(mbrf_r, 2 * sizeof(float));
float rf_no_left[] = {0.0, 1.0};
float rf_left[] = {4.0, 7.0};
float rf_exact[] = {5.0, 10.0};
float rf_full[] = {4.0, 11.0};
float rf_right[] = {7.0, 11.0};
float rf_no_right[] = {11.0, 15.0};
rangef[0].set_range(rf_no_left, 2 * sizeof(float));
double ratiof = dom2f.overlap_ratio(rangef, mbrf);
CHECK(ratiof == 0.0);
rangef[0].set_range(rf_left, 2 * sizeof(float));
ratiof = dom2f.overlap_ratio(rangef, mbrf);
CHECK(ratiof == 2.0 / 5);
rangef[0].set_range(rf_exact, 2 * sizeof(float));
ratiof = dom2f.overlap_ratio(rangef, mbrf);
CHECK(ratiof == 1.0);
rangef[0].set_range(rf_full, 2 * sizeof(float));
ratiof = dom2f.overlap_ratio(rangef, mbrf);
CHECK(ratiof == 1.0);
rangef[0].set_range(rf_right, 2 * sizeof(float));
ratiof = dom2f.overlap_ratio(rangef, mbrf);
CHECK(ratiof == 3.0 / 5);
rangef[0].set_range(rf_no_right, 2 * sizeof(float));
ratiof = dom2f.overlap_ratio(rangef, mbrf);
CHECK(ratiof == 0.0);
}
TEST_CASE("RTree: Test 1D R-tree, height 2", "[rtree][1d][2h]") {
// Build tree
int32_t dim_dom[] = {1, 1000};
int32_t dim_extent = 10;
Domain dom1 =
create_domain({"d"}, {Datatype::INT32}, {dim_dom}, {&dim_extent});
std::vector<NDRange> mbrs = create_mbrs<int32_t, 1>({1, 3, 5, 10, 20, 22});
RTree rtree(&dom1, 3);
rtree.set_leaves(mbrs);
rtree.build_tree();
CHECK(rtree.height() == 2);
CHECK(rtree.dim_num() == 1);
CHECK(rtree.fanout() == 3);
// Subtree leaf num
CHECK(rtree.subtree_leaf_num(0) == 3);
CHECK(rtree.subtree_leaf_num(1) == 1);
CHECK(rtree.subtree_leaf_num(2) == 0);
// Tile overlap
NDRange range(1);
int32_t r_no[] = {25, 30};
int32_t r_full[] = {0, 22};
int32_t r_partial[] = {6, 21};
range[0].set_range(r_no, 2 * sizeof(int32_t));
auto overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.empty());
range[0].set_range(r_full, 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.size() == 1);
CHECK(overlap.tile_ranges_[0].first == 0);
CHECK(overlap.tile_ranges_[0].second == 2);
range[0].set_range(r_partial, 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tile_ranges_.empty());
CHECK(overlap.tiles_.size() == 2);
CHECK(overlap.tiles_[0].first == 1);
CHECK(overlap.tiles_[0].second == 5.0 / 6);
CHECK(overlap.tiles_[1].first == 2);
CHECK(overlap.tiles_[1].second == 2.0 / 3);
}
TEST_CASE("RTree: Test 1D R-tree, height 3", "[rtree][1d][3h]") {
// Build tree
int32_t dim_dom[] = {1, 1000};
int32_t dim_extent = 10;
std::vector<NDRange> mbrs = create_mbrs<int32_t, 1>(
{1, 3, 5, 10, 20, 22, 30, 35, 36, 38, 40, 49, 50, 51, 65, 69});
Domain dom1 =
create_domain({"d"}, {Datatype::INT32}, {dim_dom}, {&dim_extent});
RTree rtree(&dom1, 3);
rtree.set_leaves(mbrs);
rtree.build_tree();
CHECK(rtree.height() == 3);
CHECK(rtree.dim_num() == 1);
CHECK(rtree.fanout() == 3);
// Subtree leaf num
CHECK(rtree.subtree_leaf_num(0) == 9);
CHECK(rtree.subtree_leaf_num(1) == 3);
CHECK(rtree.subtree_leaf_num(2) == 1);
CHECK(rtree.subtree_leaf_num(3) == 0);
// Tile overlap
NDRange range(1);
int32_t r_no[] = {0, 0};
int32_t r_full[] = {1, 69};
int32_t r_only_tiles[] = {10, 20};
int32_t r_only_ranges[] = {30, 69};
int32_t r_tiles_and_ranges[] = {1, 32};
range[0].set_range(r_no, 2 * sizeof(int32_t));
auto overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.empty());
range[0].set_range(r_full, 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.size() == 1);
CHECK(overlap.tile_ranges_[0].first == 0);
CHECK(overlap.tile_ranges_[0].second == 7);
range[0].set_range(r_only_tiles, 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tile_ranges_.empty());
CHECK(overlap.tiles_.size() == 2);
CHECK(overlap.tiles_[0].first == 1);
CHECK(overlap.tiles_[0].second == 1.0 / 6);
CHECK(overlap.tiles_[1].first == 2);
CHECK(overlap.tiles_[1].second == 1.0 / 3);
range[0].set_range(r_only_ranges, 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.size() == 2);
CHECK(overlap.tile_ranges_[0].first == 3);
CHECK(overlap.tile_ranges_[0].second == 5);
CHECK(overlap.tile_ranges_[1].first == 6);
CHECK(overlap.tile_ranges_[1].second == 7);
range[0].set_range(r_tiles_and_ranges, 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tile_ranges_.size() == 1);
CHECK(overlap.tile_ranges_[0].first == 0);
CHECK(overlap.tile_ranges_[0].second == 2);
CHECK(overlap.tiles_.size() == 1);
CHECK(overlap.tiles_[0].first == 3);
CHECK(overlap.tiles_[0].second == 3.0 / 6);
}
TEST_CASE("RTree: Test 2D R-tree, height 2", "[rtree][2d][2h]") {
// Build tree
int32_t dim_dom[] = {1, 1000};
int32_t dim_extent = 10;
Domain dom2 = create_domain(
{"d1", "d2"},
{Datatype::INT32, Datatype::INT32},
{dim_dom, dim_dom},
{&dim_extent, &dim_extent});
std::vector<NDRange> mbrs =
create_mbrs<int32_t, 2>({1, 3, 2, 4, 5, 7, 6, 9, 10, 12, 10, 15});
RTree rtree(&dom2, 3);
rtree.set_leaves(mbrs);
rtree.build_tree();
CHECK(rtree.height() == 2);
CHECK(rtree.dim_num() == 2);
CHECK(rtree.fanout() == 3);
// Subtree leaf num
CHECK(rtree.subtree_leaf_num(0) == 3);
CHECK(rtree.subtree_leaf_num(1) == 1);
CHECK(rtree.subtree_leaf_num(2) == 0);
// Tile overlap
NDRange range(2);
int32_t r_no[] = {25, 30, 1, 10};
int32_t r_full[] = {1, 20, 1, 20};
int32_t r_partial[] = {5, 12, 8, 12};
range[0].set_range(&r_no[0], 2 * sizeof(int32_t));
range[1].set_range(&r_no[2], 2 * sizeof(int32_t));
auto overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.empty());
range[0].set_range(&r_full[0], 2 * sizeof(int32_t));
range[1].set_range(&r_full[2], 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.size() == 1);
CHECK(overlap.tile_ranges_[0].first == 0);
CHECK(overlap.tile_ranges_[0].second == 2);
range[0].set_range(&r_partial[0], 2 * sizeof(int32_t));
range[1].set_range(&r_partial[2], 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tile_ranges_.empty());
CHECK(overlap.tiles_.size() == 2);
CHECK(overlap.tiles_[0].first == 1);
CHECK(overlap.tiles_[0].second == 2.0 / 4);
CHECK(overlap.tiles_[1].first == 2);
CHECK(overlap.tiles_[1].second == 3.0 / 6);
}
TEST_CASE("RTree: Test 2D R-tree, height 3", "[rtree][2d][3h]") {
// Build tree
int32_t dim_dom[] = {1, 1000};
int32_t dim_extent = 10;
Domain dom2 = create_domain(
{"d1", "d2"},
{Datatype::INT32, Datatype::INT32},
{dim_dom, dim_dom},
{&dim_extent, &dim_extent});
std::vector<NDRange> mbrs = create_mbrs<int32_t, 2>(
{1, 3, 2, 4, 5, 7, 6, 9, 10, 12, 10, 15, 11, 15, 20, 22, 16, 16,
23, 23, 19, 20, 24, 26, 25, 28, 30, 32, 30, 35, 35, 37, 40, 42, 40, 42});
RTree rtree(&dom2, 3);
rtree.set_leaves(mbrs);
rtree.build_tree();
CHECK(rtree.height() == 3);
CHECK(rtree.dim_num() == 2);
CHECK(rtree.fanout() == 3);
// Subtree leaf num
CHECK(rtree.subtree_leaf_num(0) == 9);
CHECK(rtree.subtree_leaf_num(1) == 3);
CHECK(rtree.subtree_leaf_num(2) == 1);
CHECK(rtree.subtree_leaf_num(3) == 0);
// Tile overlap
NDRange range(2);
int32_t r_no[] = {0, 0, 0, 0};
int32_t r_full[] = {1, 50, 1, 50};
int32_t r_only_tiles[] = {10, 14, 12, 21};
int32_t r_only_ranges[] = {11, 42, 20, 42};
int32_t r_tiles_and_ranges[] = {19, 50, 25, 50};
range[0].set_range(&r_no[0], 2 * sizeof(int32_t));
range[1].set_range(&r_no[2], 2 * sizeof(int32_t));
auto overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.empty());
range[0].set_range(&r_full[0], 2 * sizeof(int32_t));
range[1].set_range(&r_full[2], 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.size() == 1);
CHECK(overlap.tile_ranges_[0].first == 0);
CHECK(overlap.tile_ranges_[0].second == 8);
range[0].set_range(&r_only_tiles[0], 2 * sizeof(int32_t));
range[1].set_range(&r_only_tiles[2], 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tile_ranges_.empty());
CHECK(overlap.tiles_.size() == 2);
CHECK(overlap.tiles_[0].first == 2);
CHECK(overlap.tiles_[0].second == 4.0 / 6);
CHECK(overlap.tiles_[1].first == 3);
CHECK(overlap.tiles_[1].second == (4.0 / 5) * (2.0 / 3));
range[0].set_range(&r_only_ranges[0], 2 * sizeof(int32_t));
range[1].set_range(&r_only_ranges[2], 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tiles_.empty());
CHECK(overlap.tile_ranges_.size() == 2);
CHECK(overlap.tile_ranges_[0].first == 3);
CHECK(overlap.tile_ranges_[0].second == 5);
CHECK(overlap.tile_ranges_[1].first == 6);
CHECK(overlap.tile_ranges_[1].second == 8);
range[0].set_range(&r_tiles_and_ranges[0], 2 * sizeof(int32_t));
range[1].set_range(&r_tiles_and_ranges[2], 2 * sizeof(int32_t));
overlap = rtree.get_tile_overlap(range);
CHECK(overlap.tile_ranges_.size() == 1);
CHECK(overlap.tile_ranges_[0].first == 6);
CHECK(overlap.tile_ranges_[0].second == 8);
CHECK(overlap.tiles_.size() == 1);
CHECK(overlap.tiles_[0].first == 5);
CHECK(overlap.tiles_[0].second == 2.0 / 3);
}
| 36.312364 | 80 | 0.653345 | [
"vector"
] |
fb01ac0f7ee7f9f1bd9cfbb968b44323c341612e | 1,005 | cpp | C++ | TwinStickGame/TwinStickGame/Levels/Level1.cpp | Isetta-Team/Isetta-Game | a4c7e37b51d567d875ed0e3f10b6206df1de39b9 | [
"MIT"
] | 2 | 2020-11-30T02:07:27.000Z | 2021-04-06T12:14:44.000Z | TwinStickGame/TwinStickGame/Levels/Level1.cpp | Isetta-Team/Isetta-Game | a4c7e37b51d567d875ed0e3f10b6206df1de39b9 | [
"MIT"
] | null | null | null | TwinStickGame/TwinStickGame/Levels/Level1.cpp | Isetta-Team/Isetta-Game | a4c7e37b51d567d875ed0e3f10b6206df1de39b9 | [
"MIT"
] | 1 | 2019-05-10T09:17:28.000Z | 2019-05-10T09:17:28.000Z | /*
* Copyright (c) 2018 Isetta
*/
#include <IsettaEngine.h>
#include "Levels/Level1.h"
#include <Components/Editor/EditorComponent.h>
#include "Enemy/EnemyManager.h"
#include "Gameplay/BulletManager.h"
#include "Gameplay/GameManager.h"
#include "Player/CameraController.h"
void Level1::Load() {
Entity* camera = Entity::Instantiate("Camera");
camera->AddComponent<CameraComponent>();
camera->AddComponent<CameraController>();
camera->AddComponent<AudioListener>();
camera->transform->SetWorldPos({15, 15, -30});
camera->transform->LookAt(Math::Vector3::zero);
// temp. instantiate the ground
level1Map.Load();
Entity* editor = Entity::Instantiate("Editor");
editor->AddComponent<EditorComponent>();
Entity* enemyManager = Entity::Instantiate("Enemy Manager");
enemyManager->AddComponent<EnemyManager>();
Entity* bulletManager = Entity::Instantiate("Bullet Manager");
bulletManager->AddComponent<BulletManager>();
GameManager::Instance().SendLevelLoadedMessage();
}
| 27.916667 | 64 | 0.737313 | [
"transform"
] |
fb0afab48753c35c8e5a51dd996014a5bb5ba5cc | 13,530 | cpp | C++ | src/imapindex.cpp | d99kris/nmail | 71b118f9e701d457caac9479686bdf30d05bf214 | [
"MIT"
] | 42 | 2019-05-04T14:08:05.000Z | 2022-02-19T17:56:02.000Z | src/imapindex.cpp | d99kris/nmail | 71b118f9e701d457caac9479686bdf30d05bf214 | [
"MIT"
] | 89 | 2019-09-22T15:03:18.000Z | 2022-03-31T13:11:14.000Z | src/imapindex.cpp | d99kris/nmail | 71b118f9e701d457caac9479686bdf30d05bf214 | [
"MIT"
] | 8 | 2020-06-03T13:19:16.000Z | 2022-02-02T13:03:45.000Z | // imapindex.cpp
//
// Copyright (c) 2020-2021 Kristofer Berggren
// All rights reserved.
//
// nmail is distributed under the MIT license, see LICENSE for details.
#include "imapindex.h"
#include <unistd.h>
#include "addressbook.h"
#include "body.h"
#include "cacheutil.h"
#include "crypto.h"
#include "header.h"
#include "imapcache.h"
#include "lockfile.h"
#include "log.h"
#include "loghelp.h"
#include "maphelp.h"
#include "sethelp.h"
ImapIndex::ImapIndex(const bool p_CacheIndexEncrypt,
const std::string& p_Pass,
std::shared_ptr<ImapCache> p_ImapCache,
const std::function<void(const StatusUpdate&)>& p_StatusHandler)
: m_CacheIndexEncrypt(p_CacheIndexEncrypt)
, m_Pass(p_Pass)
, m_ImapCache(p_ImapCache)
, m_StatusHandler(p_StatusHandler)
{
LOG_DEBUG_FUNC(STR(p_CacheIndexEncrypt));
LOG_DEBUG("start thread");
m_Running = true;
m_Thread = std::thread(&ImapIndex::Process, this);
}
ImapIndex::~ImapIndex()
{
LOG_DEBUG_FUNC(STR());
LOG_DEBUG("stop thread");
if (m_Running)
{
std::unique_lock<std::mutex> lock(m_ProcessMutex);
m_Running = false;
m_ProcessCondVar.notify_one();
}
if (m_Thread.joinable())
{
m_Thread.join();
}
}
bool ImapIndex::ChangePass(const bool p_CacheEncrypt,
const std::string& p_OldPass, const std::string& p_NewPass)
{
if (!p_CacheEncrypt) return true;
InitCacheTempDir();
if (!CacheUtil::DecryptCacheDir(p_OldPass, GetCacheIndexDbDir(), GetCacheIndexDbTempDir())) return false;
Util::RmDir(GetCacheIndexDbDir());
Util::MkDir(GetCacheIndexDbDir());
if (!CacheUtil::EncryptCacheDir(p_NewPass, GetCacheIndexDbTempDir(), GetCacheIndexDbDir())) return false;
CleanupCacheTempDir();
return true;
}
void ImapIndex::NotifyIdle(bool p_IsIdle)
{
std::unique_lock<std::mutex> lock(m_ProcessMutex);
m_IsIdle = p_IsIdle;
if (m_IsIdle)
{
m_ProcessCondVar.notify_one();
}
}
void ImapIndex::SetFolders(const std::set<std::string>& p_Folders)
{
LOG_DEBUG_FUNC(STR(p_Folders));
Notify notify;
notify.m_SetFolders = p_Folders;
std::unique_lock<std::mutex> lock(m_ProcessMutex);
m_Queue.push(notify);
m_QueueSize = m_Queue.size();
m_ProcessCondVar.notify_one();
}
void ImapIndex::SetUids(const std::string& p_Folder, const std::set<uint32_t>& p_Uids)
{
LOG_DEBUG_FUNC(STR(p_Folder, p_Uids));
std::unique_lock<std::mutex> lock(m_ProcessMutex);
if (!m_SyncDone) return; // to avoid double work at first idle (sync)
Notify notify;
notify.m_Folder = p_Folder;
notify.m_SetUids = p_Uids;
m_Queue.push(notify);
m_QueueSize = m_Queue.size();
m_ProcessCondVar.notify_one();
}
void ImapIndex::DeleteMessages(const std::string& p_Folder, const std::set<uint32_t>& p_Uids)
{
LOG_DEBUG_FUNC(STR(p_Folder, p_Uids));
std::unique_lock<std::mutex> lock(m_ProcessMutex);
if (!m_SyncDone) return; // to avoid double work at first idle (sync)
Notify notify;
notify.m_Folder = p_Folder;
notify.m_DeleteUids = p_Uids;
m_Queue.push(notify);
m_QueueSize = m_Queue.size();
m_ProcessCondVar.notify_one();
}
void ImapIndex::SetBodys(const std::string& p_Folder, const std::set<uint32_t>& p_Uids)
{
LOG_DEBUG_FUNC(STR(p_Folder, p_Uids));
std::unique_lock<std::mutex> lock(m_ProcessMutex);
if (!m_SyncDone) return; // to avoid double work at first idle (sync)
Notify notify;
notify.m_Folder = p_Folder;
notify.m_SetBodys = p_Uids;
m_Queue.push(notify);
m_QueueSize = m_Queue.size();
m_ProcessCondVar.notify_one();
}
void ImapIndex::Search(const std::string& p_QueryStr, const unsigned p_Offset, const unsigned p_Max,
std::vector<Header>& p_Headers, std::vector<std::pair<std::string, uint32_t>>& p_FolderUids,
bool& p_HasMore)
{
LOG_DEBUG_FUNC(STR(p_QueryStr, p_Offset, p_Max, p_HasMore));
if (m_SearchEngine)
{
std::vector<std::string> docIds = m_SearchEngine->Search(p_QueryStr, p_Offset, p_Max, p_HasMore);
for (const auto& docId : docIds)
{
const std::string& folder = GetFolderFromDocId(docId);
const uint32_t uid = GetUidFromDocId(docId);
std::map<uint32_t, Header> uidHeaders = m_ImapCache->GetHeaders(folder, std::set<uint32_t>({ uid }), false);
if (!uidHeaders.empty())
{
p_Headers.push_back(uidHeaders.begin()->second);
p_FolderUids.push_back(std::make_pair(folder, uid));
}
}
}
}
void ImapIndex::Process()
{
LOG_DEBUG("start process");
AddressBook::Init(Util::GetAddressBookEncrypt(), m_Pass);
InitCacheIndexDir();
if (m_CacheIndexEncrypt)
{
InitCacheTempDir();
CacheUtil::DecryptCacheDir(m_Pass, GetCacheIndexDbDir(), GetCacheIndexDbTempDir());
m_SearchEngine.reset(new SearchEngine(GetCacheIndexDbTempDir()));
}
else
{
m_SearchEngine.reset(new SearchEngine(GetCacheIndexDbDir()));
}
LOG_DEBUG("entering loop");
while (m_Running)
{
std::unique_lock<std::mutex> lock(m_ProcessMutex);
while (m_Running && !(m_IsIdle && (!m_Queue.empty() || !m_SyncDone)))
{
ClearStatus(Status::FlagIndexing);
m_ProcessCondVar.wait(lock);
}
if (!m_Running)
{
lock.unlock();
break;
}
if (m_IsIdle && !m_SyncDone)
{
m_SyncDone = true;
lock.unlock();
HandleSyncEnqueue();
continue;
}
if (m_IsIdle && !m_Queue.empty())
{
Notify notify = m_Queue.front();
m_Queue.pop();
const bool isQueueEmpty = m_Queue.empty();
lock.unlock();
uint32_t progress = 0;
if (m_QueueSize > 1)
{
int32_t completed = (int)m_QueueSize - (int)m_Queue.size();
if (completed > 0)
{
progress = (completed * 100) / m_QueueSize;
}
}
SetStatus(Status::FlagIndexing, progress);
HandleNotify(notify);
HandleCommit(isQueueEmpty);
}
}
LOG_DEBUG("exiting loop");
HandleCommit(true);
m_SearchEngine.reset();
if (m_CacheIndexEncrypt && m_Dirty)
{
Util::RmDir(GetCacheIndexDbDir());
Util::MkDir(GetCacheIndexDbDir());
CacheUtil::EncryptCacheDir(m_Pass, GetCacheIndexDbTempDir(), GetCacheIndexDbDir());
CleanupCacheTempDir();
m_Dirty = false;
}
AddressBook::Cleanup();
LOG_DEBUG("exit process");
}
void ImapIndex::HandleNotify(const Notify& p_Notify)
{
if (!p_Notify.m_SetFolders.empty())
{
// Delete folders not present
const std::vector<std::string>& docIds = m_SearchEngine->List();
for (const auto& docId : docIds)
{
const std::string& folder = GetFolderFromDocId(docId);
if (!p_Notify.m_SetFolders.count(folder))
{
// not found in the set of folders to keep, so remove from index
LOG_DEBUG("remove %s", docId.c_str());
m_SearchEngine->Remove(docId);
m_Dirty = true;
}
}
}
else if (!p_Notify.m_SetUids.empty())
{
// Delete uids not present
const std::vector<std::string>& docIds = m_SearchEngine->List();
for (const auto& docId : docIds)
{
const std::string& folder = GetFolderFromDocId(docId);
const uint32_t uid = GetUidFromDocId(docId);
if (folder == p_Notify.m_Folder)
{
if (!p_Notify.m_SetUids.count(uid))
{
// not found in the set of uids to keep, so remove from index
LOG_DEBUG("remove %s", docId.c_str());
m_SearchEngine->Remove(docId);
m_Dirty = true;
}
}
}
}
else if (!p_Notify.m_DeleteUids.empty())
{
for (const auto& uid : p_Notify.m_DeleteUids)
{
// delete specified uid from index
const std::string& docId = GetDocId(p_Notify.m_Folder, uid);
LOG_DEBUG("remove %s", docId.c_str());
m_SearchEngine->Remove(docId);
m_Dirty = true;
}
}
else if (!p_Notify.m_SetBodys.empty())
{
for (const auto& uid : p_Notify.m_SetBodys)
{
// add specified uid to index
AddMessage(p_Notify.m_Folder, uid);
}
}
}
void ImapIndex::HandleCommit(bool p_ForceCommit)
{
// commit
static std::chrono::time_point<std::chrono::system_clock> lastCommit =
std::chrono::system_clock::now();
std::chrono::duration<double> secsSinceLastCommit =
std::chrono::system_clock::now() - lastCommit;
if (p_ForceCommit || (secsSinceLastCommit.count() >= 5.0f))
{
LOG_DEBUG("commit");
m_SearchEngine->Commit();
lastCommit = std::chrono::system_clock::now();
}
}
void ImapIndex::HandleSyncEnqueue()
{
LOG_DEBUG("sync enqueue start");
std::map<std::string, std::set<uint32_t>> docFolderUids;
const std::vector<std::string>& docIds = m_SearchEngine->List();
for (const auto& docId : docIds)
{
const std::string& folder = GetFolderFromDocId(docId);
const uint32_t uid = GetUidFromDocId(docId);
docFolderUids[folder].insert(uid);
}
const std::set<std::string>& folders = m_ImapCache->GetFolders();
for (const auto& folder : folders)
{
const std::set<uint32_t>& uids = m_ImapCache->GetUids(folder);
const std::set<uint32_t>& bodyUids = MapKey(m_ImapCache->GetBodys(folder, uids, true /* p_Prefetch */));
const std::set<uint32_t>& docUids = docFolderUids[folder];
std::set<uint32_t> uidsToAdd = bodyUids - docUids; // present in cache, but not in index
std::set<uint32_t> uidsToDel = docUids - bodyUids; // present in index, but not in cache
std::unique_lock<std::mutex> lock(m_ProcessMutex);
if (!uidsToAdd.empty())
{
const int maxAdd = 10;
std::set<uint32_t> subsetUids;
for (auto it = uidsToAdd.begin(); it != uidsToAdd.end(); ++it)
{
subsetUids.insert(*it);
if ((subsetUids.size() == maxAdd) ||
(std::next(it) == uidsToAdd.end()))
{
Notify notifyAdd;
notifyAdd.m_Folder = folder;
notifyAdd.m_SetBodys = subsetUids;
m_Queue.push(notifyAdd);
subsetUids.clear();
}
}
}
if (!uidsToDel.empty())
{
Notify notifyDel;
notifyDel.m_Folder = folder;
notifyDel.m_DeleteUids = uidsToDel;
m_Queue.push(notifyDel);
}
m_QueueSize = m_Queue.size();
}
LOG_DEBUG("sync enqueue end");
}
void ImapIndex::AddMessage(const std::string& p_Folder, uint32_t p_Uid)
{
LOG_TRACE_FUNC(STR(p_Folder, p_Uid));
const std::string& docId = GetDocId(p_Folder, p_Uid);
if (!m_SearchEngine->Exists(docId))
{
const std::map<uint32_t, Body>& uidBodys = m_ImapCache->GetBodys(p_Folder, std::set<uint32_t>({ p_Uid }), false);
const std::map<uint32_t, Header>& uidHeaders = m_ImapCache->GetHeaders(p_Folder, std::set<uint32_t>(
{ p_Uid }), false);
if (!uidBodys.empty() && !uidHeaders.empty())
{
const Header& header = uidHeaders.begin()->second;
const Body& body = uidBodys.begin()->second;
const int64_t timeStamp = header.GetTimeStamp();
const std::string& bodyText = body.GetTextPlain();
const std::string& subject = header.GetSubject();
const std::string& from = header.GetFrom();
const std::string& to = header.GetTo() + " " + header.GetCc() + " " + header.GetBcc();
LOG_DEBUG("add %s", docId.c_str());
m_SearchEngine->Index(docId, timeStamp, bodyText, subject, from, to);
m_Dirty = true;
// @todo: decouple addressbook population from cache index
AddressBook::Add(header.GetUniqueId(), header.GetAddresses());
}
}
}
std::string ImapIndex::GetDocId(const std::string& p_Folder, const uint32_t p_Uid)
{
return p_Folder + "_" + std::to_string(p_Uid);
}
std::string ImapIndex::GetFolderFromDocId(const std::string& p_DocId)
{
const std::size_t lastUnderscorePos = p_DocId.find_last_of("_");
if (lastUnderscorePos != std::string::npos)
{
return p_DocId.substr(0, lastUnderscorePos);
}
else
{
return "";
}
}
uint32_t ImapIndex::GetUidFromDocId(const std::string& p_DocId)
{
const std::size_t lastUnderscorePos = p_DocId.find_last_of("_");
if (lastUnderscorePos != std::string::npos)
{
const std::string& uidStr = p_DocId.substr(lastUnderscorePos + 1);
return static_cast<uint32_t>(std::stoul(uidStr));
}
else
{
return 0;
}
}
std::string ImapIndex::GetCacheIndexDir()
{
return CacheUtil::GetCacheDir() + std::string("searchindex/");
}
std::string ImapIndex::GetCacheIndexDbDir()
{
return CacheUtil::GetCacheDir() + std::string("searchindex/db/");
}
std::string ImapIndex::GetCacheIndexDbTempDir()
{
return Util::GetTempDir() + std::string("searchindexdb/");
}
void ImapIndex::InitCacheIndexDir()
{
static const int version = 6; // note: keep synchronized with AddressBook (for now)
const std::string cacheDir = GetCacheIndexDir();
CacheUtil::CommonInitCacheDir(cacheDir, version, m_CacheIndexEncrypt);
Util::MkDir(GetCacheIndexDbDir());
}
void ImapIndex::InitCacheTempDir()
{
Util::RmDir(GetCacheIndexDbTempDir());
Util::MkDir(GetCacheIndexDbTempDir());
}
void ImapIndex::CleanupCacheTempDir()
{
Util::RmDir(GetCacheIndexDbTempDir());
}
void ImapIndex::SetStatus(uint32_t p_Flags, int32_t p_Progress /* = -1 */)
{
StatusUpdate statusUpdate;
statusUpdate.SetFlags = p_Flags;
statusUpdate.Progress = p_Progress;
if (m_StatusHandler)
{
m_StatusHandler(statusUpdate);
}
}
void ImapIndex::ClearStatus(uint32_t p_Flags)
{
StatusUpdate statusUpdate;
statusUpdate.ClearFlags = p_Flags;
if (m_StatusHandler)
{
m_StatusHandler(statusUpdate);
}
}
| 27.06 | 117 | 0.661863 | [
"vector"
] |
fb24ec32a9d772ba6eff88c31172296d66d62aa7 | 2,186 | cpp | C++ | demos/tutorial/generic_programming/example_hashing.cpp | serosko/seqan | 584ae4fbff8312cfe31b3e0aea651edfb1b580ef | [
"BSD-3-Clause"
] | 409 | 2015-01-12T22:02:01.000Z | 2022-03-29T06:17:05.000Z | demos/tutorial/generic_programming/example_hashing.cpp | serosko/seqan | 584ae4fbff8312cfe31b3e0aea651edfb1b580ef | [
"BSD-3-Clause"
] | 1,269 | 2015-01-02T22:42:25.000Z | 2022-03-08T13:31:46.000Z | demos/tutorial/generic_programming/example_hashing.cpp | serosko/seqan | 584ae4fbff8312cfe31b3e0aea651edfb1b580ef | [
"BSD-3-Clause"
] | 193 | 2015-01-14T16:21:27.000Z | 2022-03-19T22:47:02.000Z | #include <seqan/basic.h>
#include <seqan/sequence.h>
using namespace seqan;
//![hashAll]
template <typename TShape, typename TString>
void hashAll(TShape & shape, TString & str)
{
typedef typename Iterator<TString>::Type TIterator;
TIterator it = begin(str);
TIterator it_end = end(str) - span(shape);
while (it != it_end)
{
unsigned int hash_value = hash(shape, it);
/* do some things with the hash value */ ++it;
//![hashAll]
ignoreUnusedVariableWarning(hash_value);
//![hashAll]
}
}
//![hashAll]
//![classShape]
struct SimpleShape_;
typedef Tag<SimpleShape_> SimpleShape;
template <typename TValue, typename TSpec = SimpleShape>
class Shape;
//![classShape]
//![classSimpleShape]
template <typename TValue>
class Shape< TValue, SimpleShape >
{
public:
unsigned int span;
};
//![classSimpleShape]
//![classUngappedShape]
template <unsigned int q = 0>
struct UngappedShape;
template <typename TValue, unsigned int q>
class Shape< TValue, UngappedShape<q> >
{
public:
static unsigned int const span = q;
};
//![classUngappedShape]
//![hashNext]
template <typename TValue, unsigned int q, typename TIterator>
inline unsigned int
hashNext(Shape< TValue, UngappedShape<q> > const & shape, TIterator it, unsigned int prev)
{
unsigned int val = prev * ValueSize<TValue>::VALUE - *it * shape.fac
+ *(it + shape.span);
return val;
// shape.fac stores |Σ|^q
}
//![hashNext]
//![specializedHashAll]
template <typename TValue, unsigned int q, typename TString>
void specializedHashAll(Shape< TValue, UngappedShape<q> > & shape, TString & str)
{
typedef typename Iterator<TString>::Type TIterator;
TIterator it = begin(str);
TIterator it_end = end(str) - span(shape);
unsigned int hash_value = hash(shape, it);
/* do some things with the hash value */
//![specializedHashAll]
ignoreUnusedVariableWarning(hash_value);
//![specializedHashAll]
while (++it != it_end)
{
unsigned int hash_value = hashNext(shape, it, hash_value);
/* do some things with the hash value */
}
}
//![specializedHashAll]
int main()
{
return 0;
}
| 24.288889 | 90 | 0.672919 | [
"shape"
] |
fb294d62b39c017fbbcbaad080aeddf4cb26abe3 | 5,174 | cpp | C++ | src/log.cpp | logpicker/prototype | 0a25fccc24a8e298dee9bae240fcd73a4e5d185e | [
"MIT"
] | null | null | null | src/log.cpp | logpicker/prototype | 0a25fccc24a8e298dee9bae240fcd73a4e5d185e | [
"MIT"
] | null | null | null | src/log.cpp | logpicker/prototype | 0a25fccc24a8e298dee9bae240fcd73a4e5d185e | [
"MIT"
] | null | null | null | #include "log.hpp"
#include "printfn.hpp"
#include "error_out.hpp"
#include <utility>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
extern "C" {
#include "rsa_util.h"
}
Log::Log(int id_, std::string hostname_, vector<uint8_t> seed) : id(id_), sk(crypto::generate_secret_key(std::move(seed))), pk(crypto::secret_to_public_key(sk)), pkv(crypto::secret_to_public_key_vec(sk)), hostname(std::move(hostname_)) {
rsa_new(this->rsa_pk);
rsa_new(this->rsa_sk);
auto r = cp_rsa_gen(this->rsa_pk, this->rsa_sk, RSA_KEY_LEN);
if(r != RLC_OK) {
throw std::logic_error("RLC IS FUCKED");
}
}
std::optional<Log> Log::read_log(const std::string& filename, int id) {
pt::ptree tree;
pt::read_xml(filename, tree);
for(pt::ptree::value_type &v : tree.get_child("lpp.logs")) {
const std::string& key = v.first;
lpp::printfn("Read key: {}\n", key);
const pt::ptree& subtree = v.second;
if(subtree.empty()) {
lpp::error_out("Subtree of key {} is empty!", key);
}
auto lid = subtree.get<int>("id");
if(lid == id) {
auto hostname = subtree.get<std::string>("host");
auto sks = subtree.get<std::string>("sk");
auto skb = bls::Util::HexToBytes(sks);
auto pks = subtree.get<std::string>("pk");
auto pkb = bls::Util::HexToBytes(sks);
auto rsa_pk = subtree.get<std::string>("rsa_pk");
auto rsa_sk = subtree.get<std::string>("rsa_sk");
lpp::printfn("Constructing Log with id {} on host: {}\nSK: {}\nPK: {}, RSA PK: {}, RSA SK: {}\n", lid, hostname, sks, pks, rsa_pk, rsa_sk);
return Log{lid, hostname, skb, pkb, rsa_pk, rsa_sk};
}
}
//lpp::error_out("ERROR");
return {};
}
int Log::get_id() const { return this->id; }
pk_t Log::getPublicKey() const { return this->pk; }
pkv_t Log::getPublicKeyVec() const { return this->pkv; }
sigv_t Log::sign_rsa(const msg_t &msg) {
uint8_t out[RLC_BN_BITS / 8 + 1];
int ol = RLC_BN_BITS / 8 + 1;
auto ret = cp_rsa_sig(out, &ol, (uint8_t*) msg.data(), msg.size(), 0, this->rsa_sk);
if(ret != RLC_OK) {
throw std::logic_error("RLC IS FUCKED");
}
sigv_t sig;
sig.reserve(ol);
sig.assign(out, out+ol);
return sig;
}
std::string Log::get_rsa_pk() const {
int pub_len = rsa_key_size_bin(this->rsa_pk);
uint8_t pub_bin[pub_len];
rsa_key_write_bin(pub_bin, this->rsa_pk);
return bls::Util::HexStr(pub_bin, pub_len);
}
sigv_t Log::sign_rsa(msg_t &&msg) {
uint8_t out[RLC_BN_BITS / 8 + 1];
int ol = RLC_BN_BITS / 8 + 1;
auto ret = cp_rsa_sig(out, &ol, msg.data(), msg.size(), 0, this->rsa_sk);
if(ret != RLC_OK) {
throw std::logic_error("RLC IS FUCKED");
}
sigv_t sig;
sig.reserve(ol);
sig.assign(out, out+ol);
return sig;
}
signature_t Log::sign(const msg_t &msg) const {
return crypto::sign(this->sk, msg);
}
signature_t Log::sign(msg_t &&msg) const {
return crypto::sign(this->sk, msg);
}
Log::Log(int id_, std::string hostname_, skv_t skv, pkv_t pkv_, std::string rsa_pk_, std::string rsa_sk_) : id(id_), sk(bls::PrivateKey::FromByteVector(std::move(skv))), pk(crypto::secret_to_public_key(sk)), pkv(pk.Serialize()), hostname(std::move(hostname_)) {
rsa_new(this->rsa_pk);
rsa_new(this->rsa_sk);
auto bs_pk = bls::Util::HexToBytes(std::move(rsa_pk_));
rsa_key_read_bin(this->rsa_pk, bs_pk.data());
auto bs_sk = bls::Util::HexToBytes(std::move(rsa_sk_));
rsa_key_read_bin(this->rsa_sk, bs_sk.data());
}
pt::ptree Log::to_ptree() const {
pt::ptree tree;
std::string sks = bls::Util::HexStr(this->sk.Serialize());
std::string pks = bls::Util::HexStr(this->pkv);
tree.put("id", this->get_id());
tree.put("host", this->get_hostname());
tree.put("sk", sks);
tree.put("pk", pks);
int pub_len = rsa_key_size_bin(this->rsa_pk);
uint8_t pub_bin[pub_len];
rsa_key_write_bin(pub_bin, this->rsa_pk);
std::string pub_str = bls::Util::HexStr(pub_bin, pub_len);
int prv_len = rsa_key_size_bin(this->rsa_sk);
uint8_t prv_bin[prv_len];
rsa_key_write_bin(prv_bin, this->rsa_sk);
std::string prv_str = bls::Util::HexStr(prv_bin, prv_len);
tree.put("rsa_pk", pub_str);
tree.put("rsa_sk", prv_str);
return tree;
}
Log Log::read_leader(const std::string &filename) {
pt::ptree tree;
pt::read_xml(filename, tree);
auto lid = tree.get<int>("lpp.leader.id");
auto hostname = tree.get<std::string>("lpp.leader.host");
auto sks = tree.get<std::string>("lpp.leader.sk");
auto skb = bls::Util::HexToBytes(sks);
auto pks = tree.get<std::string>("lpp.leader.pk");
auto pkb = bls::Util::HexToBytes(sks);
auto rsa_pk = tree.get<std::string>("lpp.leader.rsa_pk");
auto rsa_sk = tree.get<std::string>("lpp.leader.rsa_sk");
lpp::printfn("Constructing Leader with id {} on host: {}\nSK: {}\nPK: {}, RSA PK: {}, RSA SK: {}", lid, hostname, sks, pks, rsa_pk, rsa_sk);
return Log{lid, hostname, skb, pkb, rsa_pk, rsa_sk};
}
std::string Log::get_hostname() const {
return this->hostname;
}
| 36.957143 | 261 | 0.626015 | [
"vector"
] |
fb2e51ab5514e3bc590c8c96346ed5e47760e8d1 | 12,017 | hpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ha_eem_cfg.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ha_eem_cfg.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ha_eem_cfg.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_IOS_XR_HA_EEM_CFG_
#define _CISCO_IOS_XR_HA_EEM_CFG_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_ha_eem_cfg {
class EventManager : public ydk::Entity
{
public:
EventManager();
~EventManager();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
ydk::YLeaf refresh_time; //type: uint32
ydk::YLeaf schedule_suspend; //type: boolean
ydk::YLeaf directory_user_policy; //type: string
ydk::YLeaf directory_user_library; //type: string
class Policies; //type: EventManager::Policies
class SchedulerScript; //type: EventManager::SchedulerScript
class Environments; //type: EventManager::Environments
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_ha_eem_cfg::EventManager::Policies> policies;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_ha_eem_cfg::EventManager::SchedulerScript> scheduler_script;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_ha_eem_cfg::EventManager::Environments> environments;
}; // EventManager
class EventManager::Policies : public ydk::Entity
{
public:
Policies();
~Policies();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Policy; //type: EventManager::Policies::Policy
ydk::YList policy;
}; // EventManager::Policies
class EventManager::Policies::Policy : public ydk::Entity
{
public:
Policy();
~Policy();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf policy_name; //type: string
ydk::YLeaf username; //type: string
ydk::YLeaf persist_time; //type: uint32
ydk::YLeaf policy_type; //type: EventManagerPolicy
ydk::YLeaf checksum_type; //type: EventManagerChecksum
ydk::YLeaf check_sum_value; //type: string
ydk::YLeaf policy_security_mode; //type: EventManagerPolicyMode
ydk::YLeaf policy_security_level; //type: EventManagerPolicySec
}; // EventManager::Policies::Policy
class EventManager::SchedulerScript : public ydk::Entity
{
public:
SchedulerScript();
~SchedulerScript();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class ThreadClasses; //type: EventManager::SchedulerScript::ThreadClasses
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_ha_eem_cfg::EventManager::SchedulerScript::ThreadClasses> thread_classes;
}; // EventManager::SchedulerScript
class EventManager::SchedulerScript::ThreadClasses : public ydk::Entity
{
public:
ThreadClasses();
~ThreadClasses();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class ThreadClass; //type: EventManager::SchedulerScript::ThreadClasses::ThreadClass
ydk::YList thread_class;
}; // EventManager::SchedulerScript::ThreadClasses
class EventManager::SchedulerScript::ThreadClasses::ThreadClass : public ydk::Entity
{
public:
ThreadClass();
~ThreadClass();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf thread_class_name; //type: string
ydk::YLeaf num_threads; //type: uint32
}; // EventManager::SchedulerScript::ThreadClasses::ThreadClass
class EventManager::Environments : public ydk::Entity
{
public:
Environments();
~Environments();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Environment; //type: EventManager::Environments::Environment
ydk::YList environment;
}; // EventManager::Environments
class EventManager::Environments::Environment : public ydk::Entity
{
public:
Environment();
~Environment();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf environment_name; //type: string
ydk::YLeaf environment_value; //type: string
}; // EventManager::Environments::Environment
class EventManagerPolicySec : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf rsa_2048;
static const ydk::Enum::YLeaf trust;
static int get_enum_value(const std::string & name) {
if (name == "rsa-2048") return 2;
if (name == "trust") return 3;
return -1;
}
};
class EventManagerPolicyMode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf cisco;
static const ydk::Enum::YLeaf trust;
static int get_enum_value(const std::string & name) {
if (name == "cisco") return 1;
if (name == "trust") return 2;
return -1;
}
};
class EventManagerChecksum : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf sha_1;
static const ydk::Enum::YLeaf md5;
static int get_enum_value(const std::string & name) {
if (name == "sha-1") return 1;
if (name == "md5") return 2;
return -1;
}
};
class EventManagerPolicy : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf system;
static const ydk::Enum::YLeaf user;
static int get_enum_value(const std::string & name) {
if (name == "system") return 0;
if (name == "user") return 1;
return -1;
}
};
}
}
#endif /* _CISCO_IOS_XR_HA_EEM_CFG_ */
| 43.382671 | 162 | 0.683698 | [
"vector"
] |
fb307008eec35605bc7ca8833eb208bf7a0adc58 | 1,052 | hpp | C++ | include/ari/ResourceLoader.hpp | kochol/ariyana_old | efdd20eea0f1fafa803fb254d4775aa1915ba3a1 | [
"MIT"
] | 1 | 2022-01-11T01:15:43.000Z | 2022-01-11T01:15:43.000Z | include/ari/ResourceLoader.hpp | kochol/ariyana_old | efdd20eea0f1fafa803fb254d4775aa1915ba3a1 | [
"MIT"
] | null | null | null | include/ari/ResourceLoader.hpp | kochol/ariyana_old | efdd20eea0f1fafa803fb254d4775aa1915ba3a1 | [
"MIT"
] | 2 | 2020-09-02T17:24:58.000Z | 2020-09-02T17:40:44.000Z | #pragma once
#include "aridef.hpp"
#include <vector>
#include "bx/readerwriter.h"
#include "bx/file.h"
namespace ari
{
class Resource;
class ARI_API ResourceLoader
{
public:
//! Constructor
ResourceLoader() : m_bSwapEndian(false)
{}
//! Destructor
virtual ~ResourceLoader() = default;
//! returns true if the file maybe is able to be loaded by this Loader
//! based on the file extension (e.g. ".mesh")
virtual bool IsALoadableFileExtension(std::string _extention);
//! Loads a resource from a FileSystem and return its pointer.
/*!
\param pStream
\param _extraParams
\return Returns the created resource pointer. Note resource may not loaded yet.
*/
virtual Resource* LoadResource(bx::FileReaderI* pStream, uint32_t _handle,
const std::string& _filename, void* _extraParams) = 0;
protected:
std::vector<std::string> m_aFileExtension; //!< The file extension list that this loader is capable to load
bool m_bSwapEndian; //!< Swap the loaded data or not
};
} // ari
| 24.465116 | 118 | 0.691065 | [
"mesh",
"vector"
] |
fb31c232b5f5743ec2e982f969c4fac88229870f | 4,599 | hpp | C++ | third_party/libsmart-1.01e/include/smart/unique_priority_queue.hpp | Chrizzly/libunicomm | 3aefc02445a5b1e047cc40daaddb7cf9b5082404 | [
"BSL-1.0"
] | null | null | null | third_party/libsmart-1.01e/include/smart/unique_priority_queue.hpp | Chrizzly/libunicomm | 3aefc02445a5b1e047cc40daaddb7cf9b5082404 | [
"BSL-1.0"
] | null | null | null | third_party/libsmart-1.01e/include/smart/unique_priority_queue.hpp | Chrizzly/libunicomm | 3aefc02445a5b1e047cc40daaddb7cf9b5082404 | [
"BSL-1.0"
] | 2 | 2019-03-16T07:07:16.000Z | 2020-01-05T11:14:58.000Z | ///////////////////////////////////////////////////////////////////////////////
// unique_priority_queue.hpp
//
// Copyright (c) 2011 Dmitry Timoshenko.
//
// 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)
//
// smart++ Multipurpose C++ Library.
/// @file unique_priority_queue.hpp Priority queue provides the uniquness of
/// stored elements.
#ifdef _MSC_VER
# pragma once
#endif // _MSC_VER
#ifndef SMART_UNIQUE_PRIORITY_QUEUE_HPP_
#define SMART_UNIQUE_PRIORITY_QUEUE_HPP_
#include <smart/stable_priority_queue.hpp>
#include <deque>
#include <functional>
#include <algorithm>
/// @namespace smart Library root namespace.
namespace smart
{
/// Unique priority queue.
///
/// @tparam T Queue elements type.
/// @tparam ContainerT Container type the queue is implemented by.
/// @tparam ComparatorT Represents the operation elements are compared by.
template<typename T,
typename ContainerT = std::deque<T>,
typename ComparatorT = std::less<typename ContainerT::value_type> >
class unique_priority_queue
{
//////////////////////////////////////////////////////////////////////////
// interface
public:
/// Container type used to store elements.
typedef ContainerT container_type;
/// Stored value type.
typedef typename container_type::value_type value_type;
/// Size type.
typedef typename container_type::size_type size_type;
/// Reference type to a value.
typedef typename container_type::reference reference;
/// Const reference type to a value.
typedef typename container_type::const_reference const_reference;
public:
/// Constructs a queue object.
unique_priority_queue(void)
{
// empty
}
/// Constructs a queue object.
///
/// @param comp Comparator object to be used. A copy is made.
explicit unique_priority_queue(const ComparatorT& comp):
_queue(comp)
{
// empty
}
/// Constructs a queue object.
///
/// @param comp Comparator object to be used. A copy is made.
/// @param cont Container
unique_priority_queue(const ComparatorT& comp, const container_type& cont):
_queue(comp, cont)
{
// empty
}
/// Constructs a queue object.
///
/// Creates the queue based on range [first, last). The elements are
/// sorted accordingly to comparator specified.
///
/// @param first Designates first element in the range to copy from.
/// @param last Designates past the last element to be copied.
template<typename IteratorT>
unique_priority_queue(IteratorT first, IteratorT last):
_queue(first, last)
{
// empty
}
/// Constructs a queue object.
///
/// Creates the queue based on range [first, last). The elements are
/// sorted accordingly to comparator specified.
///
/// @param first Designates first element in the range to copy from.
/// @param last Designates past the last element to be copied.
/// @param comp Comparator object to be used. A copy is made.
template<typename IteratorT>
unique_priority_queue(IteratorT first, IteratorT last, const ComparatorT& comp):
_queue(first, last, comp)
{
// empty
}
public:
/// Removes element from queue front.
void pop(void) { queue().pop(); }
/// Pushes element into queue end.
///
/// @param elem Element to be pushed to queue.
bool push(const value_type& element)
{
return push_if_unique(queue(), element, is_equal<value_type>());
}
/// Whether queue empty.
///
/// @return Returns true if the queue is empty and false otherwise.
bool empty(void) const { return queue().empty(); }
/// Returns elements count stored by the queue.
///
/// @return Returns elements count contained by the queue.
size_type size(void) const { return queue().size(); }
/// Returns a reference to a first object in the queue.
///
/// @return Returns a reference to the queue front element.
reference front(void) { return queue().front(); }
/// Returns a const reference to a first object in the queue.
///
/// @return Returns a const reference to the queue front element.
const_reference front(void) const { return queue().front(); }
//////////////////////////////////////////////////////////////////////////
// private stuff
private:
typedef stable_priority_queue<T, ContainerT, ComparatorT> impl_queue_type;
private:
impl_queue_type& queue(void) { return _queue; }
const impl_queue_type& queue(void) const { return _queue; }
private:
impl_queue_type _queue;
};
} // namespace smart
#endif // SMART_UNIQUE_PRIORITY_QUEUE_HPP_
| 28.042683 | 83 | 0.672972 | [
"object"
] |
fb323e279fbdcd897b21ba5ccda1cbb8cefd9683 | 40,952 | hpp | C++ | alectrnn/nervous_system/layer.hpp | neuro-evolution/alectrnn | f39476b6eb3f4270c5f7f2f93ebcc5940b9c39e4 | [
"MIT"
] | null | null | null | alectrnn/nervous_system/layer.hpp | neuro-evolution/alectrnn | f39476b6eb3f4270c5f7f2f93ebcc5940b9c39e4 | [
"MIT"
] | 33 | 2018-03-30T03:18:03.000Z | 2020-12-14T05:13:17.000Z | alectrnn/nervous_system/layer.hpp | Nathaniel-Rodriguez/alectrnn | f39476b6eb3f4270c5f7f2f93ebcc5940b9c39e4 | [
"MIT"
] | null | null | null | #ifndef NN_LAYER_H_
#define NN_LAYER_H_
#include <vector>
#include <cstddef>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <utility>
#include <random>
#include <Eigen/Core>
#include "../common/graphs.hpp"
#include "activator.hpp"
#include "integrator.hpp"
#include "../common/multi_array.hpp"
#include "parameter_types.hpp"
#include "../random/pcg_random.hpp"
namespace nervous_system {
/*
* Layers take ownership of the integrators and activations functions they use.
* This is necessary as the Layer will be the only remaining access point to
* those objects once it is pushed off to the nervous system.
*/
template<typename TReal>
class Layer {
public:
typedef std::size_t Index;
typedef float Factor;
Layer() {
back_integrator_ = nullptr;
self_integrator_ = nullptr;
activation_function_ = nullptr;
parameter_count_ = 0;
}
Layer(const std::vector<Index>& shape,
Integrator<TReal>* back_integrator,
Integrator<TReal>* self_integrator,
Activator<TReal>* activation_function)
: back_integrator_(back_integrator),
self_integrator_(self_integrator),
activation_function_(activation_function),
layer_state_(shape), input_buffer_(shape), shape_(shape) {
parameter_count_ = 0;
if (back_integrator_ != nullptr)
{
parameter_count_ += back_integrator_->GetParameterCount();
}
if (self_integrator_ != nullptr)
{
parameter_count_ += self_integrator_->GetParameterCount();
}
if (activation_function_ != nullptr)
{
parameter_count_ += activation_function_->GetParameterCount();
}
}
virtual ~Layer() {
delete back_integrator_;
delete self_integrator_;
delete activation_function_;
}
/*
* Update neuron state. Calls both integrator and activator.
*/
virtual void operator()(const Layer<TReal>* prev_layer) {
// First clear input buffer
input_buffer_.Fill(0.0);
// Call back integrator first to resolve input from prev layer
(*back_integrator_)(prev_layer->state(), input_buffer_);
// Resolve self-connections if there are any
(*self_integrator_)(input_buffer_, input_buffer_);
// Apply activation and update state
(*activation_function_)(layer_state_, input_buffer_);
}
/*
* Passes the needed parameters to the Layer - Should be Slice with
* parameter_count_ in size. Layer will then make and assign Slices to
* The activation_function and Integrator function
*/
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {
if (parameters.size() != parameter_count_) {
std::cerr << "parameter size: " << parameters.size() << std::endl;
std::cerr << "parameter count: " << parameter_count_ << std::endl;
throw std::invalid_argument("Wrong number of parameters given.");
}
back_integrator_->Configure(
parameters.slice(0, back_integrator_->GetParameterCount()));
self_integrator_->Configure(
parameters.slice(parameters.stride() * back_integrator_->GetParameterCount(),
self_integrator_->GetParameterCount()));
activation_function_->Configure(
parameters.slice(parameters.stride() * back_integrator_->GetParameterCount()
+ parameters.stride() * self_integrator_->GetParameterCount(),
activation_function_->GetParameterCount()));
}
virtual void Reset() {
layer_state_.Fill(0.0);
input_buffer_.Fill(0.0);
activation_function_->Reset();
}
std::size_t GetParameterCount() const {
return parameter_count_;
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {
std::vector<PARAMETER_TYPE> layout(parameter_count_);
// layout produced in configure order: back->self->act
Index order = 0;
std::vector<PARAMETER_TYPE> back_layout = back_integrator_->GetParameterLayout();
for (auto par_type_ptr = back_layout.begin();
par_type_ptr != back_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> self_layout = self_integrator_->GetParameterLayout();
for (auto par_type_ptr = self_layout.begin();
par_type_ptr != self_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> act_layout = activation_function_->GetParameterLayout();
for (auto par_type_ptr = act_layout.begin();
par_type_ptr != act_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
return layout;
}
/*
* Constructs a normalization factor vector. Each element corresponds to
* a parameter. Parameters associated with weights should be set to a
* non-zero value == to the degree of the post-synaptic neuron.
*/
virtual std::vector<Factor> GetWeightNormalizationFactors() const {
std::vector<Factor> normalization_factors(parameter_count_);
// initializes values to 0
for (auto& factor : normalization_factors) {
factor = 0.0;
}
EvaluateNormalizationFactors(normalization_factors, back_integrator_,
self_integrator_, NumNeurons());
return normalization_factors;
}
std::size_t NumNeurons() const {
return layer_state_.size();
}
template<typename T>
void SetNeuronState(Index neuron, T value) {
layer_state_[neuron] = value;
}
const multi_array::Tensor<TReal>& state() const {
return layer_state_;
}
multi_array::Tensor<TReal>& state() {
return layer_state_;
}
const std::vector<Index>& shape() const {
return shape_;
}
const Integrator<TReal>* GetBackIntegrator() const {
return back_integrator_;
}
const Integrator<TReal>* GetSelfIntegrator() const {
return self_integrator_;
}
protected:
// calculates inputs from other layers and applies them to input buffer
Integrator<TReal>* back_integrator_;
// claculates inputs from neurons within the layer and applies them to input buffer
Integrator<TReal>* self_integrator_;
// updates the layer's state using the input buffer (may also contain internal state)
Activator<TReal>* activation_function_;
// maintains the current layer's state
multi_array::Tensor<TReal> layer_state_;
// holds input values used to update the layer's state
multi_array::Tensor<TReal> input_buffer_;
std::vector<Index> shape_;
// Number of parameters required by layer
std::size_t parameter_count_;
};
template <typename TReal>
class RecurrentLayer : public Layer<TReal>
{
public:
typedef Layer<TReal> super_type;
typedef typename super_type::Index Index;
typedef Eigen::Matrix<TReal, Eigen::Dynamic, 1> ColVector;
typedef const Eigen::Matrix<TReal, Eigen::Dynamic, 1> ConstColVector;
typedef Eigen::Map<ColVector> ColVectorView;
typedef const Eigen::Map<ConstColVector> ConstColVectorView;
RecurrentLayer(const std::vector<Index>& shape,
Integrator<TReal>* back_integrator,
Integrator<TReal>* self_integrator,
Activator<TReal>* activation_function)
: super_type(shape, back_integrator, self_integrator, activation_function),
recurrent_state_buffer_(shape)
{}
virtual ~RecurrentLayer()=default;
virtual void Reset()
{
super_type::Reset();
recurrent_state_buffer_.Fill(0.0);
}
virtual void operator()(const Layer<TReal>* prev_layer) override
{
super_type::input_buffer_.Fill(0.0);
(*super_type::back_integrator_)(prev_layer->state(),
super_type::input_buffer_);
(*super_type::self_integrator_)(super_type::layer_state_,
recurrent_state_buffer_);
ColVectorView state_vector(recurrent_state_buffer_.data(),
recurrent_state_buffer_.size());
ConstColVectorView buffer(super_type::input_buffer_.data(),
super_type::input_buffer_.size());
state_vector += buffer;
(*super_type::activation_function_)(super_type::input_buffer_,
recurrent_state_buffer_);
std::swap(super_type::layer_state_, super_type::input_buffer_);
}
protected:
multi_array::Tensor<TReal> recurrent_state_buffer_;
};
template <typename TReal>
class FeedbackLayer : public RecurrentLayer<TReal>
{
public:
typedef RecurrentLayer<TReal> super_type;
typedef typename super_type::Index Index;
typedef Eigen::Matrix<TReal, Eigen::Dynamic, 1> ColVector;
typedef const Eigen::Matrix<TReal, Eigen::Dynamic, 1> ConstColVector;
typedef Eigen::Map<ColVector> ColVectorView;
typedef const Eigen::Map<ConstColVector> ConstColVectorView;
FeedbackLayer(const std::vector<Index>& shape,
Integrator<TReal>* back_integrator,
Integrator<TReal>* self_integrator,
Activator<TReal>* activation_function,
Index motor_size,
Integrator<TReal>* feedback_integrator)
: super_type(shape, back_integrator, self_integrator, activation_function),
feedback_state_({motor_size + 1}), // 1 added for reward
feedback_integrator_(feedback_integrator)
{
super_type::parameter_count_ += feedback_integrator_->GetParameterCount();
}
virtual ~FeedbackLayer()
{
delete feedback_integrator_;
}
virtual void Reset() {
super_type::Reset();
feedback_state_.Fill(0.0);
}
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {
if (parameters.size() != super_type::parameter_count_) {
std::cerr << "parameter size: " << parameters.size() << std::endl;
std::cerr << "parameter count: " << super_type::parameter_count_ << std::endl;
throw std::invalid_argument("Wrong number of parameters given.");
}
super_type::back_integrator_->Configure(
parameters.slice(0, super_type::back_integrator_->GetParameterCount()));
super_type::self_integrator_->Configure(
parameters.slice(parameters.stride() * super_type::back_integrator_->GetParameterCount(),
super_type::self_integrator_->GetParameterCount()));
feedback_integrator_->Configure(
parameters.slice(parameters.stride() * super_type::back_integrator_->GetParameterCount()
+ parameters.stride() * super_type::self_integrator_->GetParameterCount(),
feedback_integrator_->GetParameterCount()));
super_type::activation_function_->Configure(
parameters.slice(parameters.stride() * super_type::back_integrator_->GetParameterCount()
+ parameters.stride() * super_type::self_integrator_->GetParameterCount()
+ parameters.stride() * feedback_integrator_->GetParameterCount(),
super_type::activation_function_->GetParameterCount()));
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {
std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);
// layout produced in configure order: back->self->act
Index order = 0;
std::vector<PARAMETER_TYPE> back_layout = super_type::back_integrator_->GetParameterLayout();
for (auto par_type_ptr = back_layout.begin();
par_type_ptr != back_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> self_layout = super_type::self_integrator_->GetParameterLayout();
for (auto par_type_ptr = self_layout.begin();
par_type_ptr != self_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> feedback_layout = feedback_integrator_->GetParameterLayout();
for (auto par_type_ptr = feedback_layout.begin();
par_type_ptr != feedback_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> act_layout = super_type::activation_function_->GetParameterLayout();
for (auto par_type_ptr = act_layout.begin();
par_type_ptr != act_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
return layout;
}
virtual void operator()(const Layer<TReal>* prev_layer) override
{
super_type::input_buffer_.Fill(0.0);
(*super_type::back_integrator_)(prev_layer->state(),
super_type::input_buffer_);
(*super_type::self_integrator_)(super_type::layer_state_,
super_type::recurrent_state_buffer_);
(*feedback_integrator_)(feedback_state_,
super_type::layer_state_);
ColVectorView state_vector(super_type::layer_state_.data(),
super_type::layer_state_.size());
ColVectorView recurrent_state(super_type::recurrent_state_buffer_.data(),
super_type::recurrent_state_buffer_.size());
ConstColVectorView buffer(super_type::input_buffer_.data(),
super_type::input_buffer_.size());
state_vector += buffer;
state_vector += recurrent_state;
(*super_type::activation_function_)(super_type::input_buffer_,
super_type::recurrent_state_buffer_);
std::swap(super_type::layer_state_, super_type::input_buffer_);
}
virtual void update_feedback(TReal reward, const Layer<TReal>* motor_layer)
{
auto motor_state = motor_layer->state();
Index state_size(motor_state.size());
for (Index i = 0; i < (state_size - 1); ++i)
{
feedback_state_[i] = motor_state[i];
}
// Temporary hack to set the reward [0,1] at same scale as inputs (255)
if (reward > 0.00001)
{
feedback_state_[feedback_state_.size() - 1] = 255.0;
}
else
{
feedback_state_[feedback_state_.size() - 1] = 0.0;
}
}
protected:
multi_array::Tensor<TReal> feedback_state_;
Integrator<TReal>* feedback_integrator_;
};
template <typename TReal>
class RewardModulatedLayer : public Layer<TReal> {
public:
typedef Layer<TReal> super_type;
typedef typename super_type::Index Index;
RewardModulatedLayer(const std::vector<Index>& shape,
Integrator<TReal>* back_integrator,
Integrator<TReal>* self_integrator,
Activator<TReal>* activation_function,
TReal reward_smoothing_factor,
TReal activation_smoothing_factor)
: super_type(shape, back_integrator, self_integrator,
activation_function),
activation_averages_({super_type::input_buffer_.size()}),
reward_average_(0.0),
reward_smoothing_factor_(reward_smoothing_factor),
activation_smoothing_factor_(activation_smoothing_factor)
{
// super_type::parameter_count_ += 2; // reward and activation smoothing factors
Reset();
}
virtual ~RewardModulatedLayer()=default;
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) override {
super_type::Configure(parameters);
// reward_smoothing_factor_ = utilities::Wrap0to1(parameters[parameters.size()-2]);
// activation_smoothing_factor_ = utilities::Wrap0to1(parameters[parameters.size()-1]);
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const override {
std::vector<PARAMETER_TYPE> layout = super_type::GetParameterLayout();
// layout.push_back(SMOOTHING);
// layout.push_back(SMOOTHING);
return layout;
}
virtual void Reset() override {
super_type::Reset();
for (auto& avg : activation_averages_) {
avg = 0;
}
reward_average_ = 0.0;
}
/*
* Called after all integrators and activators have been called.
*/
virtual void UpdateWeights(const TReal reward, const Layer<TReal>* prev_layer) {
// call weight update function using the input_buffer of this layer
// the input buffer contains the states prior to application of the
// activation function.
if (super_type::back_integrator_->GetIntegratorType() == REWARD_MODULATED)
{
dynamic_cast<RewardModulatedIntegrator<TReal>*>(super_type::back_integrator_)->UpdateWeights(
reward, reward_average_, prev_layer->state(), super_type::input_buffer_,
activation_averages_);
}
if (super_type::self_integrator_->GetIntegratorType() == REWARD_MODULATED)
{
dynamic_cast<RewardModulatedIntegrator<TReal>*>(super_type::self_integrator_)->UpdateWeights(
reward, reward_average_, prev_layer->state(), super_type::input_buffer_,
activation_averages_);
}
// update rolling averages
reward_average_ = utilities::ExponentialRollingAverage(reward, reward_average_,
reward_smoothing_factor_);
for (Index i = 0; i < activation_averages_.size(); ++i) {
activation_averages_[i] = utilities::ExponentialRollingAverage(super_type::input_buffer_[i],
activation_averages_[i],
activation_smoothing_factor_);
}
}
protected:
multi_array::Tensor<TReal> activation_averages_;
TReal reward_average_;
TReal reward_smoothing_factor_; // between [0,1]
TReal activation_smoothing_factor_; // between [0,1]
};
/*
* This uses the correct equation. We need the noise applied to the input_buffer
* in order to calculate the correct average.
*/
template <typename TReal>
class NoisyRewardModulatedLayer : public Layer<TReal> {
public:
typedef Layer<TReal> super_type;
typedef typename super_type::Index Index;
NoisyRewardModulatedLayer(const std::vector<Index>& shape,
Integrator<TReal>* back_integrator,
Integrator<TReal>* self_integrator,
Activator<TReal>* activation_function,
TReal reward_smoothing_factor,
TReal activation_smoothing_factor,
const TReal standard_deviation,
const std::uint64_t seed)
: super_type(shape, back_integrator, self_integrator,
activation_function),
activation_averages_({super_type::input_buffer_.size()}),
reward_average_(0.0),
reward_smoothing_factor_(reward_smoothing_factor),
activation_smoothing_factor_(activation_smoothing_factor),
standard_deviation_(standard_deviation),
rng_(seed),
normal_distribution_{}
{
Reset();
}
virtual ~NoisyRewardModulatedLayer()=default;
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) override {
super_type::Configure(parameters);
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const override {
std::vector<PARAMETER_TYPE> layout = super_type::GetParameterLayout();
return layout;
}
virtual void Reset() override {
super_type::Reset();
for (auto& avg : activation_averages_) {
avg = 0;
}
reward_average_ = 0.0;
}
virtual void operator()(const Layer<TReal>* prev_layer) {
// First clear input buffer
super_type::input_buffer_.Fill(0.0);
// Call back integrator first to resolve input from prev layer
(*super_type::back_integrator_)(prev_layer->state(), super_type::input_buffer_);
// Resolve self-connections if there are any
(*super_type::self_integrator_)(super_type::input_buffer_,
super_type::input_buffer_);
// Apply noise and then activation and update state
ApplyNoise(super_type::input_buffer_);
(*super_type::activation_function_)(super_type::layer_state_,
super_type::input_buffer_);
}
/*
* Called after all integrators and activators have been called.
*/
virtual void UpdateWeights(const TReal reward, const Layer<TReal>* prev_layer) {
// call weight update function using the input_buffer of this layer
// the input buffer contains the states prior to application of the
// activation function.
if (super_type::back_integrator_->GetIntegratorType() == REWARD_MODULATED)
{
dynamic_cast<RewardModulatedIntegrator<TReal>*>(super_type::back_integrator_)->UpdateWeights(
reward, reward_average_, prev_layer->state(), super_type::input_buffer_,
activation_averages_);
}
if (super_type::self_integrator_->GetIntegratorType() == REWARD_MODULATED)
{
dynamic_cast<RewardModulatedIntegrator<TReal>*>(super_type::self_integrator_)->UpdateWeights(
reward, reward_average_, prev_layer->state(), super_type::input_buffer_,
activation_averages_);
}
// update rolling averages
reward_average_ = utilities::ExponentialRollingAverage(reward, reward_average_,
reward_smoothing_factor_);
for (Index i = 0; i < activation_averages_.size(); ++i) {
activation_averages_[i] = utilities::ExponentialRollingAverage(super_type::input_buffer_[i],
activation_averages_[i],
activation_smoothing_factor_);
}
}
virtual void ApplyNoise(multi_array::Tensor<TReal>& inputs)
{
for (Index i = 0; i < inputs.size(); ++i)
{
inputs[i] += standard_deviation_ * normal_distribution_(rng_);
}
}
protected:
multi_array::Tensor<TReal> activation_averages_;
TReal reward_average_;
TReal reward_smoothing_factor_; // between [0,1]
TReal activation_smoothing_factor_; // between [0,1]
TReal standard_deviation_;
pcg32_fast rng_;
std::normal_distribution<TReal> normal_distribution_;
};
template<typename TReal>
class InputLayer : public Layer<TReal> {
public:
typedef Layer<TReal> super_type;
typedef typename super_type::Index Index;
typedef typename super_type::Factor Factor;
InputLayer() : super_type() {
}
InputLayer(const std::vector<Index>& shape) {
super_type::shape_ = shape;
super_type::layer_state_ = shape;
super_type::back_integrator_ = nullptr;
super_type::self_integrator_ = nullptr;
super_type::activation_function_ = nullptr;
super_type::parameter_count_ = 0;
}
InputLayer(const std::initializer_list<Index>& shape) {
super_type::shape_ = shape;
super_type::layer_state_ = shape;
super_type::back_integrator_ = nullptr;
super_type::self_integrator_ = nullptr;
super_type::activation_function_ = nullptr;
super_type::parameter_count_ = 0;
}
virtual void operator()(const Layer<TReal>* prev_layer) {}
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {}
virtual void Reset() { super_type::layer_state_.Fill(0.0); }
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {
return std::vector<PARAMETER_TYPE>(0);
}
};
template<typename TReal>
class MotorLayer : public Layer<TReal> {
public:
typedef Layer<TReal> super_type;
typedef typename super_type::Index Index;
typedef typename super_type::Factor Factor;
MotorLayer() : super_type() {
}
MotorLayer(Index num_outputs, Index num_inputs,
Activator<TReal>* activation_function) {
super_type::activation_function_ = activation_function;
super_type::back_integrator_ = new nervous_system::All2AllIntegrator<TReal>(num_outputs, num_inputs);
super_type::self_integrator_ = nullptr;
super_type::parameter_count_ = super_type::activation_function_->GetParameterCount()
+ super_type::back_integrator_->GetParameterCount();
super_type::layer_state_ = multi_array::Tensor<TReal>({num_outputs});
super_type::input_buffer_ = multi_array::Tensor<TReal>({num_outputs});
}
virtual ~MotorLayer() {};
virtual void operator()(const Layer<TReal>* prev_layer) {
// First clear input buffer
super_type::input_buffer_.Fill(0.0);
// Call back integrator first to resolve input from prev layer
(*super_type::back_integrator_)(prev_layer->state(), super_type::input_buffer_);
// Apply activation and update state
(*super_type::activation_function_)(super_type::layer_state_, super_type::input_buffer_);
}
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {
if (super_type::parameter_count_ != parameters.size()) {
std::cerr << "parameter size: " << parameters.size() << std::endl;
std::cerr << "parameter count: " << super_type::parameter_count_ << std::endl;
throw std::invalid_argument("Wrong number of parameters given");
}
// configure back integrator parameters
super_type::back_integrator_->Configure(
parameters.slice(0, super_type::back_integrator_->GetParameterCount()));
// configure activation parameters
super_type::activation_function_->Configure(
parameters.slice(parameters.stride() * super_type::back_integrator_->GetParameterCount(),
super_type::activation_function_->GetParameterCount()));
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {
std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);
// layout produced in configure order: back->act
Index order = 0;
std::vector<PARAMETER_TYPE> back_layout = super_type::back_integrator_->GetParameterLayout();
for (auto par_type_ptr = back_layout.begin();
par_type_ptr != back_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> act_layout = super_type::activation_function_->GetParameterLayout();
for (auto par_type_ptr = act_layout.begin();
par_type_ptr != act_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
return layout;
}
};
/*
* A motor layer that has no internal memory, and whose outputs represents
* a distribution, so that all state members sum to 1.
*/
template<typename TReal>
class SoftMaxMotorLayer : public MotorLayer<TReal> {
public:
typedef MotorLayer<TReal> super_type;
typedef typename super_type::Index Index;
typedef typename super_type::Factor Factor;
SoftMaxMotorLayer() : super_type() {
}
SoftMaxMotorLayer(Index num_outputs, Index num_inputs, TReal temperature) {
super_type::activation_function_ = new nervous_system::SoftMaxActivator<TReal>(temperature);
super_type::back_integrator_ = new nervous_system::All2AllIntegrator<TReal>(num_outputs, num_inputs);
super_type::self_integrator_ = nullptr;
super_type::parameter_count_ = super_type::activation_function_->GetParameterCount()
+ super_type::back_integrator_->GetParameterCount();
super_type::layer_state_ = multi_array::Tensor<TReal>({num_outputs});
super_type::input_buffer_ = multi_array::Tensor<TReal>({num_outputs});
}
};
/*
* A motor layer that uses the Eigen A2A integrator.
*/
template<typename TReal>
class EigenMotorLayer : public MotorLayer<TReal> {
public:
typedef MotorLayer<TReal> super_type;
typedef typename super_type::Index Index;
typedef typename super_type::Factor Factor;
EigenMotorLayer() : super_type() {
}
EigenMotorLayer(Index num_outputs, Index num_inputs,
Activator<TReal>* activation_function) {
super_type::activation_function_ = activation_function;
super_type::back_integrator_ = new nervous_system::All2AllEigenIntegrator<TReal>(num_outputs,
num_inputs);
super_type::self_integrator_ = nullptr;
super_type::parameter_count_ = super_type::activation_function_->GetParameterCount()
+ super_type::back_integrator_->GetParameterCount();
super_type::layer_state_ = multi_array::Tensor<TReal>({num_outputs});
super_type::input_buffer_ = multi_array::Tensor<TReal>({num_outputs});
}
};
template<typename TReal>
class RewardModulatedMotorLayer : public RewardModulatedLayer<TReal>
{
public:
using super_type = RewardModulatedLayer<TReal>;
using Index = typename super_type::Index;
RewardModulatedMotorLayer(Index num_outputs,
Index num_inputs,
Activator<TReal>* activation_function,
TReal reward_smoothing_factor,
TReal activation_smoothing_factor,
TReal learning_rate)
: super_type({num_outputs},
new nervous_system::RewardModulatedAll2AllIntegrator<TReal>(num_outputs,
num_inputs,
learning_rate),
nullptr, activation_function, reward_smoothing_factor,
activation_smoothing_factor)
{
}
virtual void operator()(const Layer<TReal>* prev_layer) {
// First clear input buffer
super_type::input_buffer_.Fill(0.0);
// Call back integrator first to resolve input from prev layer
(*super_type::back_integrator_)(prev_layer->state(), super_type::input_buffer_);
// Apply activation and update state
(*super_type::activation_function_)(super_type::layer_state_, super_type::input_buffer_);
}
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {
if (super_type::parameter_count_ != parameters.size()) {
std::cerr << "parameter size: " << parameters.size() << std::endl;
std::cerr << "parameter count: " << super_type::parameter_count_ << std::endl;
throw std::invalid_argument("Wrong number of parameters given");
}
// configure back integrator parameters
super_type::back_integrator_->Configure(
parameters.slice(0, super_type::back_integrator_->GetParameterCount()));
// configure activation parameters
super_type::activation_function_->Configure(
parameters.slice(parameters.stride()
* super_type::back_integrator_->GetParameterCount(),
super_type::activation_function_->GetParameterCount()));
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {
std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);
// layout produced in configure order: back->act
Index order = 0;
std::vector<PARAMETER_TYPE> back_layout = super_type::back_integrator_->GetParameterLayout();
for (auto par_type_ptr = back_layout.begin();
par_type_ptr != back_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> act_layout = super_type::activation_function_->GetParameterLayout();
for (auto par_type_ptr = act_layout.begin();
par_type_ptr != act_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
return layout;
}
virtual void UpdateWeights(const TReal reward, const Layer<TReal>* prev_layer) {
// call weight update function
dynamic_cast<RewardModulatedIntegrator<TReal>*>(super_type::back_integrator_)->UpdateWeights(
reward, super_type::reward_average_, prev_layer->state(), super_type::input_buffer_,
super_type::activation_averages_);
// update rolling avgerages
super_type::reward_average_ =
utilities::ExponentialRollingAverage(reward,
super_type::reward_average_,
super_type::reward_smoothing_factor_);
for (Index i = 0; i < super_type::activation_averages_.size(); ++i) {
super_type::activation_averages_[i] =
utilities::ExponentialRollingAverage(super_type::input_buffer_[i],
super_type::activation_averages_[i],
super_type::activation_smoothing_factor_);
}
}
};
template<typename TReal>
class NoisyRewardModulatedMotorLayer : public NoisyRewardModulatedLayer<TReal>
{
public:
using super_type = NoisyRewardModulatedLayer<TReal>;
using Index = typename super_type::Index;
NoisyRewardModulatedMotorLayer(Index num_outputs,
Index num_inputs,
Activator<TReal>* activation_function,
TReal reward_smoothing_factor,
TReal activation_smoothing_factor,
const TReal standard_deviation,
const std::uint64_t seed,
TReal learning_rate)
: super_type({num_outputs},
new nervous_system::RewardModulatedAll2AllIntegrator<TReal>(num_outputs,
num_inputs,
learning_rate),
nullptr, activation_function, reward_smoothing_factor,
activation_smoothing_factor,
standard_deviation, seed)
{
}
virtual void operator()(const Layer<TReal>* prev_layer) {
// First clear input buffer
super_type::input_buffer_.Fill(0.0);
// Call back integrator first to resolve input from prev layer
(*super_type::back_integrator_)(prev_layer->state(), super_type::input_buffer_);
// Apply activation and update state
super_type::ApplyNoise(super_type::input_buffer_);
(*super_type::activation_function_)(super_type::layer_state_,
super_type::input_buffer_);
}
virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {
if (super_type::parameter_count_ != parameters.size()) {
std::cerr << "parameter size: " << parameters.size() << std::endl;
std::cerr << "parameter count: " << super_type::parameter_count_ << std::endl;
throw std::invalid_argument("Wrong number of parameters given");
}
// configure back integrator parameters
super_type::back_integrator_->Configure(
parameters.slice(0, super_type::back_integrator_->GetParameterCount()));
// configure activation parameters
super_type::activation_function_->Configure(
parameters.slice(parameters.stride()
* super_type::back_integrator_->GetParameterCount(),
super_type::activation_function_->GetParameterCount()));
}
virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {
std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);
// layout produced in configure order: back->act
Index order = 0;
std::vector<PARAMETER_TYPE> back_layout = super_type::back_integrator_->GetParameterLayout();
for (auto par_type_ptr = back_layout.begin();
par_type_ptr != back_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
std::vector<PARAMETER_TYPE> act_layout = super_type::activation_function_->GetParameterLayout();
for (auto par_type_ptr = act_layout.begin();
par_type_ptr != act_layout.end(); ++par_type_ptr) {
layout[order] = *par_type_ptr;
++order;
}
return layout;
}
virtual void UpdateWeights(const TReal reward, const Layer<TReal>* prev_layer) {
// call weight update function
dynamic_cast<RewardModulatedIntegrator<TReal>*>(super_type::back_integrator_)->UpdateWeights(
reward, super_type::reward_average_, prev_layer->state(), super_type::input_buffer_,
super_type::activation_averages_);
// update rolling avgerages
super_type::reward_average_ =
utilities::ExponentialRollingAverage(reward,
super_type::reward_average_,
super_type::reward_smoothing_factor_);
for (Index i = 0; i < super_type::activation_averages_.size(); ++i) {
super_type::activation_averages_[i] =
utilities::ExponentialRollingAverage(super_type::input_buffer_[i],
super_type::activation_averages_[i],
super_type::activation_smoothing_factor_);
}
}
};
/*
* Calculates the number of links the integrator has
*/
template <typename Factor, typename TReal>
Factor GetNumOfLinks(const Integrator<TReal>* integrator) {
if (integrator == nullptr) {
return 0; // If there is no integrator (which is valid) it has no links.
}
INTEGRATOR_TYPE integrator_type = integrator->GetIntegratorType();
Factor num_links = 0;
switch (integrator_type) {
case ALL2ALL_INTEGRATOR: {
num_links = integrator->GetParameterCount();
break;
}
case NONE_INTEGRATOR: {
break;
}
case CONV_INTEGRATOR: {
const Conv2DIntegrator<TReal> *conv_integrator = dynamic_cast<const Conv2DIntegrator<TReal> *>(integrator);
const multi_array::Array<std::size_t, 3> filter = conv_integrator->GetFilterShape();
num_links = filter[0] * filter[1] * filter[2] * conv_integrator->GetMinTarSize();
break;
}
case TRUNCATED_RECURRENT_INTEGRATOR:
case RECURRENT_INTEGRATOR: {
const RecurrentIntegrator<TReal> *recurrent_integrator = dynamic_cast<const RecurrentIntegrator<TReal> *>(integrator);
const graphs::PredecessorGraph<> graph = recurrent_integrator->GetGraph();
num_links = graph.NumEdges();
break;
}
case RESERVOIR_INTEGRATOR: {
const ReservoirIntegrator<TReal> *reservoir_integrator = dynamic_cast<const ReservoirIntegrator<TReal> *>(integrator);
const graphs::PredecessorGraph<TReal> graph = reservoir_integrator->GetGraph();
num_links = graph.NumEdges();
break;
}
default:
throw std::invalid_argument("Error: Integrator type not found.");
}
return num_links;
};
/*
* Calculates the average degree by combining information from the back and
* self integrators, and then assigns the values to the respective links
*/
template <typename Factor, typename TReal>
void EvaluateNormalizationFactors(std::vector<Factor>& normalization_factors,
const Integrator<TReal>* back_integrator,
const Integrator<TReal>* self_integrator,
std::size_t layer_size) {
std::size_t num_back_links = 0;
std::pair<std::size_t, std::size_t> back_weight_slice{0,0};
if (back_integrator != nullptr) {
num_back_links = GetNumOfLinks<std::size_t, TReal>(back_integrator);
back_weight_slice = back_integrator->GetWeightIndexRange();
}
std::size_t num_self_links = 0;
std::pair<std::size_t, std::size_t> self_weight_slice{0,0};
if (self_integrator != nullptr) {
num_self_links = GetNumOfLinks<std::size_t, TReal>(self_integrator);
self_weight_slice = self_integrator->GetWeightIndexRange();
}
// Because self params are added after back params, we have to offset the weight indices for self
if (back_integrator != nullptr) {
self_weight_slice.first += back_integrator->GetParameterCount();
self_weight_slice.second += back_integrator->GetParameterCount();
}
// Calculate average degree and the assign it to the weight indices of self and back
Factor average_degree = (num_back_links + num_self_links) / static_cast<double>(layer_size);
for (std::size_t iii = 0; iii < normalization_factors.size(); ++iii) {
if (((iii >= back_weight_slice.first) && (iii < back_weight_slice.second)) ||
((iii >= self_weight_slice.first) && (iii < self_weight_slice.second))) {
normalization_factors[iii] = average_degree;
}
}
};
} // End nervous_system namespace
#endif /* NN_LAYER_H_ */
| 39.376923 | 124 | 0.655792 | [
"shape",
"vector"
] |
fb44868f2c7053f15f5b0387e8ca846134ac420c | 612 | cpp | C++ | Scholarship.cpp | OrlykM/Algotester | 6d0702b191610795beb959d378ab1feef6191b68 | [
"CC0-1.0"
] | null | null | null | Scholarship.cpp | OrlykM/Algotester | 6d0702b191610795beb959d378ab1feef6191b68 | [
"CC0-1.0"
] | null | null | null | Scholarship.cpp | OrlykM/Algotester | 6d0702b191610795beb959d378ab1feef6191b68 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int main()
{
signed int n, m=0;
cin >> n;
if (n >= 1 && n <= 7)
{
vector<int> marks;
for (int i = 0; i < n; i++)
{
signed int mark;
cin >> mark;
if (mark>= 0 && mark <= 100)
{
marks.push_back(mark);
}
}
for (int i = 0; i < marks.size(); i++)
{
if (marks[i] < 51)
{
cout << "Zabud pro stypendiiu";
return 0;
}
else if (marks[i] >= 90)
{
m++;
}
}
if (m == n)
{
cout << "Pidvyshchena";
return 0;
}
else
{
cout << "Zvychaina";
return 0;
}
}
}
| 13.304348 | 40 | 0.468954 | [
"vector"
] |
fb5302bf4d37f3596eed3209c57cfbf8cdd19a06 | 1,045 | cpp | C++ | MegamanX3/MegamanX3/Node.cpp | quangnghiauit/game | 3c0537f96342c6fcb89cf5f3541acfef75b558f1 | [
"MIT"
] | null | null | null | MegamanX3/MegamanX3/Node.cpp | quangnghiauit/game | 3c0537f96342c6fcb89cf5f3541acfef75b558f1 | [
"MIT"
] | null | null | null | MegamanX3/MegamanX3/Node.cpp | quangnghiauit/game | 3c0537f96342c6fcb89cf5f3541acfef75b558f1 | [
"MIT"
] | null | null | null | #include"Node.h"
Node::Node()
{
for (int i = 0; i < 4; i++)
listChils[i] = NULL;
}
Node::Node(Box b)
{
this->bound = b;
for (int i = 0; i < 4; i++)
listChils[i] = NULL;
}
Node::Node(int x, int y, int w, int h)
{
bound.SetingBox(x, y, w, h);
for (int i = 0; i < 4; i++)
listChils[i] = NULL;
}
Node::~Node()
{
}
void Node::AddObject(int key, Object * value)
{
this->listObjects[key] = value;
}
map<int, Object*> Node::GetListObject()
{
return this->listObjects;
}
map<int, Object*> Node::GetListObject(Box cam)
{
map<int, Object*> list_object;
list_object.clear();
if (!this->listChils[0])
return this->listObjects;
else
{
for (int i = 0; i < 4; i++)
{
if (this->listChils[i]->GetBound().IsOverlap(cam))
{
map<int, Object*> list_object_in_childs = listChils[i]->GetListObject(cam);
for(auto o : list_object_in_childs) {
list_object[o.first] = o.second;
}
}
}
}
return list_object;
}
Box Node::GetBound()
{
return this->bound;
}
Node ** Node::GetChilds()
{
return listChils;
}
| 14.513889 | 79 | 0.6 | [
"object"
] |
fb622d7f90a2b4ff9f114d71dcd7fc9efe26b7d1 | 764 | cpp | C++ | Dataset/Leetcode/test/55/564.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/55/564.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/55/564.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
bool XXX(vector<int>& nums) {
//避开0
//每次尽可能跳跃长的长度?不对
//从后往前找,遇到0就在0之前找有没有能跳过这个0的步数,找到起点都没找到就返回f
//找到了就从该数之前开始继续查找0,直到找到起点
if (nums.size() == 1 && nums[0] == 0)
return true;
for(int i=nums.size()-1;i>=0;--i)
{
if(nums[i]==0)
{
int j=i-1;
for(;j>=0;--j)
{
if(nums[j]>i-j|| (i == nums.size() - 1 && nums[j] >= i - j))//找到能够跳过0的长度
{
i=j;
break;
}
}
if(j==-1)//没有找到
return false;
}
}
return true;
}
};
| 23.875 | 92 | 0.331152 | [
"vector"
] |
fb6613ac6ec7ddf2e378da380c8dd651d2fbd405 | 5,811 | cpp | C++ | convert/mumdex2sam.cpp | docpaa/mumdex | 571f2d03a457da2f51d525ac038aef455e3467c1 | [
"Zlib",
"MIT"
] | 5 | 2018-02-07T15:58:30.000Z | 2019-11-23T00:58:54.000Z | convert/mumdex2sam.cpp | docpaa/mumdex | 571f2d03a457da2f51d525ac038aef455e3467c1 | [
"Zlib",
"MIT"
] | null | null | null | convert/mumdex2sam.cpp | docpaa/mumdex | 571f2d03a457da2f51d525ac038aef455e3467c1 | [
"Zlib",
"MIT"
] | 1 | 2019-11-20T15:47:54.000Z | 2019-11-20T15:47:54.000Z | //
// mumdex2sam
//
// convert mumdex format to SAM format
//
// Copyright 2015 Peter Andrews @ CSHL
//
#include <array>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "encode.h"
#include "error.h"
#include "mumdex.h"
#include "sam.h"
using std::array;
using std::cout;
using std::cerr;
using std::endl;
using std::exception;
using std::ostringstream;
using std::string;
using std::to_string;
using std::vector;
using paa::Error;
using paa::MUMdex;
using paa::MUM;
using paa::OptionalSavers;
using paa::read_optional_formats;
int main(int argc, char * argv[]) try {
paa::exit_on_pipe_close();
if (--argc != 1) throw Error("usage: mumdex2sam mumdex_name");
const string mumdex_name{argv[1]};
const MUMdex mumdex{mumdex_name};
const auto & ref = mumdex.reference();
const vector<string> optional_formats{read_optional_formats(mumdex_name)};
OptionalSavers saver{optional_formats};
saver.load("mumdex", mumdex.n_pairs() * 2);
const auto quality_saver = [&saver]() {
for (uint64_t s = 0; s != saver.size(); ++s) {
if (saver[s].name() == "err") {
return s;
}
}
return saver.size();
}();
cout << "@HD\tVN:1.0\tGO:query\tSO:queryname" << endl;
for (unsigned int c = 0; c != ref.n_chromosomes(); ++c) {
cout << "@SQ\tSN:" << ref.name(c) << "\tLN:" << ref.size(c) << endl;
}
cout << "@FI\tNP:" << mumdex.n_pairs() << "\tNM:" << mumdex.mums().size()
<< endl;
for (const auto & format : optional_formats) {
cout << "@OF\tOF:" << format << endl;
}
cout << "@PG\tID:mumdex2sam\tCL:mumdex2sam " << mumdex_name << endl;
for (uint64_t p = 0; p != mumdex.n_pairs(); ++p) {
const auto pair = mumdex.pair(p);
const string name = "r" + to_string(p + 1);
const array<string, 2> sequences(mumdex.sequences(p));
// First mum read 2
const auto m2 = [&mumdex, p]() {
for (auto m = mumdex.mums_begin(p); m != mumdex.mums_end(p); ++m) {
if (m->read_2()) {
return m;
}
}
return mumdex.mums_end(p);
}();
const array<const MUM *, 2> read_1_mum_limits{{mumdex.mums_begin(p), m2}};
const array<const MUM *, 2> read_2_mum_limits{{m2, mumdex.mums_end(p)}};
const array<array<const MUM *, 2>, 2> read_mum_limits{{
read_1_mum_limits, read_2_mum_limits}};
for (const bool r : {false, true}) {
const auto & sequence = sequences[r];
ostringstream mate_info;
const auto other_r = 1 - r;
if (read_mum_limits[other_r][0] != read_mum_limits[other_r][1]) {
const auto other_mum = *read_mum_limits[other_r][0];
mate_info << ref.name(other_mum.chromosome()) << '\t'
<< other_mum.position1();
} else {
mate_info << "*\t0";
}
// Optional fields
ostringstream optional;
string quality_scores = "*";
for (unsigned int s = 0; s != saver.size(); ++s) {
string value = saver[s][p * 2 + r];
while (value.size() && value.back() == ' ') {
value.pop_back();
}
if (s == quality_saver) {
quality_scores = value;
} else {
optional << '\t' << saver[s].name().substr(4) << ":Z:" << value;
}
}
const unsigned int mapq = 0;
const unsigned int tlen = 0;
const unsigned int flag = sam::is_paired |
(pair.dupe() ? sam::is_a_duplicate : 0) |
(pair.bad(r) ? sam::is_bad_vendor_quality : 0) |
(read_mum_limits[other_r][0] == read_mum_limits[other_r][1] ?
sam::is_mate_unmapped : 0) |
((read_mum_limits[other_r][0] != read_mum_limits[other_r][1] &&
read_mum_limits[other_r][0]->flipped()) ?
sam::is_mate_reversed : 0) |
(r ? sam::is_second : sam::is_first);
if (read_mum_limits[r][0] != read_mum_limits[r][1]) {
for (auto m = read_mum_limits[r][0]; m != read_mum_limits[r][1]; ++m) {
const auto mum = *m;
const string quality = "*";
ostringstream cigar;
if (mum.offset()) {
cigar << mum.offset() << "S";
}
cigar << mum.length() << "=";
if (!mum.touches_end()) {
cigar << pair.length(mum.read_2()) - mum.length() - mum.offset()
<< "S";
}
const unsigned int mum_flag = flag |
(mum.flipped() ? sam::is_reversed : 0) |
(m != read_mum_limits[r][0] ? sam::is_not_primary : 0);
cout << name << '\t';
cout << mum_flag << '\t';
cout << ref.name(mum.chromosome()) << '\t';
cout << mum.position1() << '\t';
cout << mapq << '\t';
cout << cigar.str() << '\t';
cout << mate_info.str() << '\t';
cout << tlen << '\t';
if (m == read_mum_limits[r][0]) {
cout << sequence << '\t';
cout << quality_scores;
cout << optional.str();
} else {
cout << "*\t*";
}
cout << endl;
}
} else {
ostringstream cigar;
cout << name << '\t';
cout << (flag | sam::is_unmapped) << '\t';
cout << "*" << '\t';
cout << 0 << '\t';
cout << mapq << '\t';
cout << "*" << '\t';
cout << mate_info.str() << '\t';
cout << tlen << '\t';
cout << sequence << '\t';
cout << quality_scores;
cout << optional.str();
cout << endl;
}
}
}
return 0;
} catch (Error & e) {
cerr << "paa::Error:" << endl;
cerr << e.what() << endl;
return 1;
} catch (exception & e) {
cerr << "std::exception" << endl;
cerr << e.what() << endl;
return 1;
} catch (...) {
cerr << "unknown exception was caught" << endl;
return 1;
}
| 29.953608 | 79 | 0.528308 | [
"vector"
] |
fb6f2c2be0592758ba2843c6106b5751fa958bd8 | 64,423 | cpp | C++ | source/Lib/EncoderLib/EncModeCtrl.cpp | 0qinghao/VTM12.3_Src | 20587035d1acdb715a7346eb244473b434d58dfd | [
"BSD-3-Clause"
] | null | null | null | source/Lib/EncoderLib/EncModeCtrl.cpp | 0qinghao/VTM12.3_Src | 20587035d1acdb715a7346eb244473b434d58dfd | [
"BSD-3-Clause"
] | null | null | null | source/Lib/EncoderLib/EncModeCtrl.cpp | 0qinghao/VTM12.3_Src | 20587035d1acdb715a7346eb244473b434d58dfd | [
"BSD-3-Clause"
] | null | null | null | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2021, ITU/ISO/IEC
* 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 ITU/ISO/IEC 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.
*/
/** \file EncModeCtrl.cpp
\brief Encoder controller for trying out specific modes
*/
#include "EncModeCtrl.h"
#include "AQp.h"
#include "RateCtrl.h"
#include "CommonLib/RdCost.h"
#include "CommonLib/CodingStructure.h"
#include "CommonLib/Picture.h"
#include "CommonLib/UnitTools.h"
#include "CommonLib/dtrace_next.h"
#include <cmath>
void EncModeCtrl::init(EncCfg *pCfg, RateCtrl *pRateCtrl, RdCost *pRdCost)
{
m_pcEncCfg = pCfg;
m_pcRateCtrl = pRateCtrl;
m_pcRdCost = pRdCost;
m_fastDeltaQP = false;
#if SHARP_LUMA_DELTA_QP
m_lumaQPOffset = 0;
initLumaDeltaQpLUT();
#endif
}
bool EncModeCtrl::tryModeMaster(const EncTestMode &encTestmode, const CodingStructure &cs, Partitioner &partitioner)
{
return tryMode(encTestmode, cs, partitioner);
}
void EncModeCtrl::setEarlySkipDetected()
{
m_ComprCUCtxList.back().earlySkip = true;
}
void EncModeCtrl::xExtractFeatures(const EncTestMode encTestmode, CodingStructure &cs)
{
CHECK(cs.features.size() < NUM_ENC_FEATURES, "Features vector is not initialized");
cs.features[ENC_FT_DISTORTION] = double(cs.dist);
cs.features[ENC_FT_FRAC_BITS] = double(cs.fracBits);
cs.features[ENC_FT_RD_COST] = double(cs.cost);
cs.features[ENC_FT_ENC_MODE_TYPE] = double(encTestmode.type);
cs.features[ENC_FT_ENC_MODE_OPTS] = double(encTestmode.opts);
}
bool EncModeCtrl::nextMode(const CodingStructure &cs, Partitioner &partitioner)
{
m_ComprCUCtxList.back().lastTestMode = m_ComprCUCtxList.back().testModes.back();
m_ComprCUCtxList.back().testModes.pop_back();
while (!m_ComprCUCtxList.back().testModes.empty() && !tryModeMaster(currTestMode(), cs, partitioner))
{
m_ComprCUCtxList.back().testModes.pop_back();
}
return !m_ComprCUCtxList.back().testModes.empty();
}
EncTestMode EncModeCtrl::currTestMode() const
{
return m_ComprCUCtxList.back().testModes.back();
}
EncTestMode EncModeCtrl::lastTestMode() const
{
return m_ComprCUCtxList.back().lastTestMode;
}
bool EncModeCtrl::anyMode() const
{
return !m_ComprCUCtxList.back().testModes.empty();
}
void EncModeCtrl::setBest(CodingStructure &cs)
{
if (cs.cost != MAX_DOUBLE && !cs.cus.empty())
{
m_ComprCUCtxList.back().bestCS = &cs;
m_ComprCUCtxList.back().bestCU = cs.cus[0];
m_ComprCUCtxList.back().bestTU = cs.cus[0]->firstTU;
m_ComprCUCtxList.back().lastTestMode = getCSEncMode(cs);
}
}
void EncModeCtrl::xGetMinMaxQP(int &minQP, int &maxQP, const CodingStructure &cs, const Partitioner &partitioner,
const int baseQP, const SPS &sps, const PPS &pps, const PartSplit splitMode)
{
if (m_pcEncCfg->getUseRateCtrl())
{
minQP = m_pcRateCtrl->getRCQP();
maxQP = m_pcRateCtrl->getRCQP();
return;
}
const unsigned subdivIncr = (splitMode == CU_QUAD_SPLIT) ? 2 : (splitMode == CU_BT_SPLIT) ? 1 : 0;
const bool qgEnable = partitioner.currQgEnable(); // QG possible at current level
const bool qgEnableChildren = qgEnable && ((partitioner.currSubdiv + subdivIncr) <= cs.slice->getCuQpDeltaSubdiv())
&& (subdivIncr > 0); // QG possible at next level
const bool isLeafQG = (qgEnable && !qgEnableChildren);
if (isLeafQG) // QG at deepest level
{
int deltaQP = m_pcEncCfg->getMaxDeltaQP();
minQP = Clip3(-sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, baseQP - deltaQP);
maxQP = Clip3(-sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, baseQP + deltaQP);
}
else if (qgEnableChildren) // more splits and not the deepest QG level
{
minQP = baseQP;
maxQP = baseQP;
}
else // deeper than QG
{
minQP = cs.currQP[partitioner.chType];
maxQP = cs.currQP[partitioner.chType];
}
}
int EncModeCtrl::xComputeDQP(const CodingStructure &cs, const Partitioner &partitioner)
{
Picture * picture = cs.picture;
unsigned uiAQDepth = std::min(partitioner.currSubdiv / 2, (uint32_t) picture->aqlayer.size() - 1);
AQpLayer *pcAQLayer = picture->aqlayer[uiAQDepth];
double dMaxQScale = pow(2.0, m_pcEncCfg->getQPAdaptationRange() / 6.0);
double dAvgAct = pcAQLayer->getAvgActivity();
double dCUAct = pcAQLayer->getActivity(cs.area.Y().topLeft());
double dNormAct = (dMaxQScale * dCUAct + dAvgAct) / (dCUAct + dMaxQScale * dAvgAct);
double dQpOffset = log(dNormAct) / log(2.0) * 6.0;
int iQpOffset = int(floor(dQpOffset + 0.49999));
return iQpOffset;
}
#if SHARP_LUMA_DELTA_QP
void EncModeCtrl::initLumaDeltaQpLUT()
{
const LumaLevelToDeltaQPMapping &mapping = m_pcEncCfg->getLumaLevelToDeltaQPMapping();
if (!mapping.isEnabled())
{
return;
}
// map the sparse LumaLevelToDeltaQPMapping.mapping to a fully populated linear table.
int lastDeltaQPValue = 0;
std::size_t nextSparseIndex = 0;
for (int index = 0; index < LUMA_LEVEL_TO_DQP_LUT_MAXSIZE; index++)
{
while (nextSparseIndex < mapping.mapping.size() && index >= mapping.mapping[nextSparseIndex].first)
{
lastDeltaQPValue = mapping.mapping[nextSparseIndex].second;
nextSparseIndex++;
}
m_lumaLevelToDeltaQPLUT[index] = lastDeltaQPValue;
}
}
int EncModeCtrl::calculateLumaDQP(const CPelBuf &rcOrg)
{
double avg = 0;
// Get QP offset derived from Luma level
#if !WCG_EXT
if (m_pcEncCfg->getLumaLevelToDeltaQPMapping().mode == LUMALVL_TO_DQP_AVG_METHOD)
#else
CHECK(m_pcEncCfg->getLumaLevelToDeltaQPMapping().mode != LUMALVL_TO_DQP_AVG_METHOD, "invalid delta qp mode");
#endif
{
// Use average luma value
avg = (double) rcOrg.computeAvg();
}
#if !WCG_EXT
else
{
// Use maximum luma value
int maxVal = 0;
for (uint32_t y = 0; y < rcOrg.height; y++)
{
for (uint32_t x = 0; x < rcOrg.width; x++)
{
const Pel &v = rcOrg.at(x, y);
if (v > maxVal)
{
maxVal = v;
}
}
}
// use a percentage of the maxVal
avg = (double) maxVal * m_pcEncCfg->getLumaLevelToDeltaQPMapping().maxMethodWeight;
}
#endif
int lumaBD = m_pcEncCfg->getBitDepth(CHANNEL_TYPE_LUMA);
int lumaIdxOrg = Clip3<int>(0, int(1 << lumaBD) - 1, int(avg + 0.5));
int lumaIdx = lumaBD < 10 ? lumaIdxOrg << (10 - lumaBD) : lumaBD > 10 ? lumaIdxOrg >> (lumaBD - 10) : lumaIdxOrg;
int QP = m_lumaLevelToDeltaQPLUT[lumaIdx];
return QP;
}
#endif
void CacheBlkInfoCtrl::create()
{
const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
m_numWidths = gp_sizeIdxInfo->numWidths();
m_numHeights = gp_sizeIdxInfo->numHeights();
bool isLog2MttPartitioning = !!dynamic_cast<SizeIndexInfoLog2 *>(gp_sizeIdxInfo);
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
m_codedCUInfo[x][y] = new CodedCUInfo **[m_numWidths];
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (!(gp_sizeIdxInfo->isCuSize(gp_sizeIdxInfo->sizeFrom(wIdx))
&& x + (gp_sizeIdxInfo->sizeFrom(wIdx) >> MIN_CU_LOG2) <= (MAX_CU_SIZE >> MIN_CU_LOG2)))
{
m_codedCUInfo[x][y][wIdx] = nullptr;
continue;
}
const int wLog2 = floorLog2(gp_sizeIdxInfo->sizeFrom(wIdx));
if (isLog2MttPartitioning && ((x << MIN_CU_LOG2) & ((1 << (wLog2 - 1)) - 1)) != 0)
{
m_codedCUInfo[x][y][wIdx] = nullptr;
continue;
}
m_codedCUInfo[x][y][wIdx] = new CodedCUInfo *[gp_sizeIdxInfo->numHeights()];
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (!(gp_sizeIdxInfo->isCuSize(gp_sizeIdxInfo->sizeFrom(hIdx))
&& y + (gp_sizeIdxInfo->sizeFrom(hIdx) >> MIN_CU_LOG2) <= (MAX_CU_SIZE >> MIN_CU_LOG2)))
{
m_codedCUInfo[x][y][wIdx][hIdx] = nullptr;
continue;
}
const int hLog2 = floorLog2(gp_sizeIdxInfo->sizeFrom(hIdx));
if (isLog2MttPartitioning && (((y << MIN_CU_LOG2) & ((1 << (hLog2 - 1)) - 1)) != 0))
{
m_codedCUInfo[x][y][wIdx][hIdx] = nullptr;
continue;
}
m_codedCUInfo[x][y][wIdx][hIdx] = new CodedCUInfo;
}
}
}
}
}
void CacheBlkInfoCtrl::destroy()
{
const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (m_codedCUInfo[x][y][wIdx])
{
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (m_codedCUInfo[x][y][wIdx][hIdx])
{
delete m_codedCUInfo[x][y][wIdx][hIdx];
}
}
delete[] m_codedCUInfo[x][y][wIdx];
}
}
delete[] m_codedCUInfo[x][y];
}
}
}
void CacheBlkInfoCtrl::init(const Slice &slice)
{
const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (m_codedCUInfo[x][y][wIdx])
{
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (m_codedCUInfo[x][y][wIdx][hIdx])
{
memset(m_codedCUInfo[x][y][wIdx][hIdx], 0, sizeof(CodedCUInfo));
}
}
}
}
}
}
m_slice_chblk = &slice;
}
CodedCUInfo &CacheBlkInfoCtrl::getBlkInfo(const UnitArea &area)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
return *m_codedCUInfo[idx1][idx2][idx3][idx4];
}
bool CacheBlkInfoCtrl::isSkip(const UnitArea &area)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
return m_codedCUInfo[idx1][idx2][idx3][idx4]->isSkip;
}
char CacheBlkInfoCtrl::getSelectColorSpaceOption(const UnitArea &area)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
return m_codedCUInfo[idx1][idx2][idx3][idx4]->selectColorSpaceOption;
}
bool CacheBlkInfoCtrl::isMMVDSkip(const UnitArea &area)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
return m_codedCUInfo[idx1][idx2][idx3][idx4]->isMMVDSkip;
}
void CacheBlkInfoCtrl::setMv(const UnitArea &area, const RefPicList refPicList, const int iRefIdx, const Mv &rMv)
{
if (iRefIdx >= MAX_STORED_CU_INFO_REFS)
return;
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
m_codedCUInfo[idx1][idx2][idx3][idx4]->saveMv[refPicList][iRefIdx] = rMv;
m_codedCUInfo[idx1][idx2][idx3][idx4]->validMv[refPicList][iRefIdx] = true;
}
bool CacheBlkInfoCtrl::getMv(const UnitArea &area, const RefPicList refPicList, const int iRefIdx, Mv &rMv) const
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
if (iRefIdx >= MAX_STORED_CU_INFO_REFS)
{
rMv = m_codedCUInfo[idx1][idx2][idx3][idx4]->saveMv[refPicList][0];
return false;
}
rMv = m_codedCUInfo[idx1][idx2][idx3][idx4]->saveMv[refPicList][iRefIdx];
return m_codedCUInfo[idx1][idx2][idx3][idx4]->validMv[refPicList][iRefIdx];
}
void SaveLoadEncInfoSbt::init(const Slice &slice)
{
m_sliceSbt = &slice;
}
void SaveLoadEncInfoSbt::create()
{
int numSizeIdx = gp_sizeIdxInfo->idxFrom(SBT_MAX_SIZE) - MIN_CU_LOG2 + 1;
int numPosIdx = MAX_CU_SIZE >> MIN_CU_LOG2;
m_saveLoadSbt = new SaveLoadStructSbt ***[numPosIdx];
for (int xIdx = 0; xIdx < numPosIdx; xIdx++)
{
m_saveLoadSbt[xIdx] = new SaveLoadStructSbt **[numPosIdx];
for (int yIdx = 0; yIdx < numPosIdx; yIdx++)
{
m_saveLoadSbt[xIdx][yIdx] = new SaveLoadStructSbt *[numSizeIdx];
for (int wIdx = 0; wIdx < numSizeIdx; wIdx++)
{
m_saveLoadSbt[xIdx][yIdx][wIdx] = new SaveLoadStructSbt[numSizeIdx];
}
}
}
}
void SaveLoadEncInfoSbt::destroy()
{
int numSizeIdx = gp_sizeIdxInfo->idxFrom(SBT_MAX_SIZE) - MIN_CU_LOG2 + 1;
int numPosIdx = MAX_CU_SIZE >> MIN_CU_LOG2;
for (int xIdx = 0; xIdx < numPosIdx; xIdx++)
{
for (int yIdx = 0; yIdx < numPosIdx; yIdx++)
{
for (int wIdx = 0; wIdx < numSizeIdx; wIdx++)
{
delete[] m_saveLoadSbt[xIdx][yIdx][wIdx];
}
delete[] m_saveLoadSbt[xIdx][yIdx];
}
delete[] m_saveLoadSbt[xIdx];
}
delete[] m_saveLoadSbt;
}
uint16_t SaveLoadEncInfoSbt::findBestSbt(const UnitArea &area, const uint32_t curPuSse)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_sliceSbt->getPPS()->pcv, idx1, idx2, idx3, idx4);
SaveLoadStructSbt *pSbtSave = &m_saveLoadSbt[idx1][idx2][idx3 - MIN_CU_LOG2][idx4 - MIN_CU_LOG2];
for (int i = 0; i < pSbtSave->numPuInfoStored; i++)
{
if (curPuSse == pSbtSave->puSse[i])
{
return pSbtSave->puSbt[i] + (pSbtSave->puTrs[i] << 8);
}
}
return MAX_UCHAR + (MAX_UCHAR << 8);
}
bool SaveLoadEncInfoSbt::saveBestSbt(const UnitArea &area, const uint32_t curPuSse, const uint8_t curPuSbt,
const uint8_t curPuTrs)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_sliceSbt->getPPS()->pcv, idx1, idx2, idx3, idx4);
SaveLoadStructSbt *pSbtSave = &m_saveLoadSbt[idx1][idx2][idx3 - MIN_CU_LOG2][idx4 - MIN_CU_LOG2];
if (pSbtSave->numPuInfoStored == SBT_NUM_SL)
{
return false;
}
pSbtSave->puSse[pSbtSave->numPuInfoStored] = curPuSse;
pSbtSave->puSbt[pSbtSave->numPuInfoStored] = curPuSbt;
pSbtSave->puTrs[pSbtSave->numPuInfoStored] = curPuTrs;
pSbtSave->numPuInfoStored++;
return true;
}
void SaveLoadEncInfoSbt::resetSaveloadSbt(int maxSbtSize)
{
int numSizeIdx = gp_sizeIdxInfo->idxFrom(maxSbtSize) - MIN_CU_LOG2 + 1;
int numPosIdx = MAX_CU_SIZE >> MIN_CU_LOG2;
for (int xIdx = 0; xIdx < numPosIdx; xIdx++)
{
for (int yIdx = 0; yIdx < numPosIdx; yIdx++)
{
for (int wIdx = 0; wIdx < numSizeIdx; wIdx++)
{
memset(m_saveLoadSbt[xIdx][yIdx][wIdx], 0, numSizeIdx * sizeof(SaveLoadStructSbt));
}
}
}
}
bool CacheBlkInfoCtrl::getInter(const UnitArea &area)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
return m_codedCUInfo[idx1][idx2][idx3][idx4]->isInter;
}
void CacheBlkInfoCtrl::setBcwIdx(const UnitArea &area, uint8_t gBiIdx)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
m_codedCUInfo[idx1][idx2][idx3][idx4]->BcwIdx = gBiIdx;
}
uint8_t CacheBlkInfoCtrl::getBcwIdx(const UnitArea &area)
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
return m_codedCUInfo[idx1][idx2][idx3][idx4]->BcwIdx;
}
#if REUSE_CU_RESULTS
static bool isTheSameNbHood(const CodingUnit &cu, const CodingStructure &cs, const Partitioner &partitioner,
const PredictionUnit &pu, int picW, int picH)
{
if (cu.chType != partitioner.chType)
{
return false;
}
const PartitioningStack &ps = partitioner.getPartStack();
int i = 1;
for (; i < ps.size(); i++)
{
if (ps[i].split != CU::getSplitAtDepth(cu, i - 1))
{
break;
}
}
const UnitArea &cmnAnc = ps[i - 1].parts[ps[i - 1].idx];
const UnitArea cuArea = CS::getArea(cs, cu, partitioner.chType);
//#endif
for (int i = 0; i < cmnAnc.blocks.size(); i++)
{
if (i < cuArea.blocks.size() && cuArea.blocks[i].valid() && cuArea.blocks[i].pos() != cmnAnc.blocks[i].pos())
{
return false;
}
}
return true;
}
void BestEncInfoCache::create(const ChromaFormat chFmt)
{
const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
m_numWidths = gp_sizeIdxInfo->numWidths();
m_numHeights = gp_sizeIdxInfo->numHeights();
bool isLog2MttPartitioning = !!dynamic_cast<SizeIndexInfoLog2 *>(gp_sizeIdxInfo);
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
m_bestEncInfo[x][y] = new BestEncodingInfo **[m_numWidths];
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (!(gp_sizeIdxInfo->isCuSize(gp_sizeIdxInfo->sizeFrom(wIdx))
&& x + (gp_sizeIdxInfo->sizeFrom(wIdx) >> MIN_CU_LOG2) <= (MAX_CU_SIZE >> MIN_CU_LOG2)))
{
m_bestEncInfo[x][y][wIdx] = nullptr;
continue;
}
const int wLog2 = floorLog2(gp_sizeIdxInfo->sizeFrom(wIdx));
if (isLog2MttPartitioning && ((x << MIN_CU_LOG2) & ((1 << (wLog2 - 1)) - 1)) != 0)
{
m_bestEncInfo[x][y][wIdx] = nullptr;
continue;
}
m_bestEncInfo[x][y][wIdx] = new BestEncodingInfo *[gp_sizeIdxInfo->numHeights()];
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (!(gp_sizeIdxInfo->isCuSize(gp_sizeIdxInfo->sizeFrom(hIdx))
&& y + (gp_sizeIdxInfo->sizeFrom(hIdx) >> MIN_CU_LOG2) <= (MAX_CU_SIZE >> MIN_CU_LOG2)))
{
m_bestEncInfo[x][y][wIdx][hIdx] = nullptr;
continue;
}
const int hLog2 = floorLog2(gp_sizeIdxInfo->sizeFrom(hIdx));
if (isLog2MttPartitioning && (((y << MIN_CU_LOG2) & ((1 << (hLog2 - 1)) - 1)) != 0))
{
m_bestEncInfo[x][y][wIdx][hIdx] = nullptr;
continue;
}
m_bestEncInfo[x][y][wIdx][hIdx] = new BestEncodingInfo;
int w = gp_sizeIdxInfo->sizeFrom(wIdx);
int h = gp_sizeIdxInfo->sizeFrom(hIdx);
const UnitArea area(chFmt, Area(0, 0, w, h));
new (&m_bestEncInfo[x][y][wIdx][hIdx]->cu) CodingUnit(area);
new (&m_bestEncInfo[x][y][wIdx][hIdx]->pu) PredictionUnit(area);
#if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
m_bestEncInfo[x][y][wIdx][hIdx]->numTus = 0;
for (int i = 0; i < MAX_NUM_TUS; i++)
{
new (&m_bestEncInfo[x][y][wIdx][hIdx]->tus[i]) TransformUnit(area);
}
#else
new (&m_bestEncInfo[x][y][wIdx][hIdx]->tu) TransformUnit(area);
#endif
m_bestEncInfo[x][y][wIdx][hIdx]->poc = -1;
m_bestEncInfo[x][y][wIdx][hIdx]->testMode = EncTestMode();
}
}
}
}
}
void BestEncInfoCache::destroy()
{
const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (m_bestEncInfo[x][y][wIdx])
{
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (m_bestEncInfo[x][y][wIdx][hIdx])
{
delete m_bestEncInfo[x][y][wIdx][hIdx];
}
}
delete[] m_bestEncInfo[x][y][wIdx];
}
}
delete[] m_bestEncInfo[x][y];
}
}
delete[] m_pCoeff;
delete[] m_pPcmBuf;
if (m_runType != nullptr)
{
delete[] m_runType;
m_runType = nullptr;
}
}
void BestEncInfoCache::init(const Slice &slice)
{
bool isInitialized = m_slice_bencinf;
m_slice_bencinf = &slice;
if (isInitialized)
return;
const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
m_numWidths = gp_sizeIdxInfo->numWidths();
m_numHeights = gp_sizeIdxInfo->numHeights();
size_t numCoeff = 0;
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (m_bestEncInfo[x][y][wIdx])
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (m_bestEncInfo[x][y][wIdx][hIdx])
{
for (const CompArea &blk: m_bestEncInfo[x][y][wIdx][hIdx]->cu.blocks)
{
numCoeff += blk.area();
}
}
}
}
}
}
#if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
m_pCoeff = new TCoeff[numCoeff * MAX_NUM_TUS];
m_pPcmBuf = new Pel[numCoeff * MAX_NUM_TUS];
if (slice.getSPS()->getPLTMode())
{
m_runType = new bool[numCoeff * MAX_NUM_TUS];
}
#else
m_pCoeff = new TCoeff[numCoeff];
m_pPcmBuf = new Pel[numCoeff];
if (slice.getSPS()->getPLTMode())
{
m_runType = new bool[numCoeff];
}
#endif
TCoeff *coeffPtr = m_pCoeff;
Pel * pcmPtr = m_pPcmBuf;
bool * runTypePtr = m_runType;
m_dummyCS.pcv = m_slice_bencinf->getPPS()->pcv;
for (unsigned x = 0; x < numPos; x++)
{
for (unsigned y = 0; y < numPos; y++)
{
for (int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++)
{
if (m_bestEncInfo[x][y][wIdx])
for (int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++)
{
if (m_bestEncInfo[x][y][wIdx][hIdx])
{
TCoeff *coeff[MAX_NUM_TBLOCKS] = {
0,
};
Pel *pcmbf[MAX_NUM_TBLOCKS] = {
0,
};
bool *runType[MAX_NUM_TBLOCKS - 1] = {
0,
};
#if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
for (int i = 0; i < MAX_NUM_TUS; i++)
{
TransformUnit & tu = m_bestEncInfo[x][y][wIdx][hIdx]->tus[i];
const UnitArea &area = tu;
for (int i = 0; i < area.blocks.size(); i++)
{
coeff[i] = coeffPtr;
coeffPtr += area.blocks[i].area();
pcmbf[i] = pcmPtr;
pcmPtr += area.blocks[i].area();
if (i < 2)
{
runType[i] = runTypePtr;
runTypePtr += area.blocks[i].area();
}
}
tu.cs = &m_dummyCS;
tu.init(coeff, pcmbf, runType);
}
#else
const UnitArea &area = m_bestEncInfo[x][y][wIdx][hIdx]->tu;
for (int i = 0; i < area.blocks.size(); i++)
{
coeff[i] = coeffPtr;
coeffPtr += area.blocks[i].area();
pcmbf[i] = pcmPtr;
pcmPtr += area.blocks[i].area();
runType[i] = runTypePtr;
runTypePtr += area.blocks[i].area();
runLength[i] = runLengthPtr;
runLengthPtr += area.blocks[i].area();
}
m_bestEncInfo[x][y][wIdx][hIdx]->tu.cs = &m_dummyCS;
m_bestEncInfo[x][y][wIdx][hIdx]->tu.init(coeff, pcmbf, runLength, runType);
#endif
}
}
}
}
}
}
bool BestEncInfoCache::setFromCs(const CodingStructure &cs, const Partitioner &partitioner)
{
#if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
if (cs.cus.size() != 1 || cs.pus.size() != 1)
#else
if (cs.cus.size() != 1 || cs.tus.size() != 1 || cs.pus.size() != 1)
#endif
{
return false;
}
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(cs.area.Y(), *m_slice_bencinf->getPPS()->pcv, idx1, idx2, idx3, idx4);
BestEncodingInfo &encInfo = *m_bestEncInfo[idx1][idx2][idx3][idx4];
encInfo.poc = cs.picture->poc;
encInfo.cu.repositionTo(*cs.cus.front());
encInfo.pu.repositionTo(*cs.pus.front());
#if !REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
encInfo.tu.repositionTo(*cs.tus.front());
#endif
encInfo.cu = *cs.cus.front();
encInfo.pu = *cs.pus.front();
#if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
int tuIdx = 0;
for (auto tu: cs.tus)
{
encInfo.tus[tuIdx].repositionTo(*tu);
encInfo.tus[tuIdx].resizeTo(*tu);
for (auto &blk: tu->blocks)
{
if (blk.valid())
encInfo.tus[tuIdx].copyComponentFrom(*tu, blk.compID);
}
tuIdx++;
}
CHECKD(cs.tus.size() > MAX_NUM_TUS, "Exceeding tus array boundaries");
encInfo.numTus = cs.tus.size();
#else
for (auto &blk: cs.tus.front()->blocks)
{
if (blk.valid())
encInfo.tu.copyComponentFrom(*cs.tus.front(), blk.compID);
}
#endif
encInfo.testMode = getCSEncMode(cs);
return true;
}
bool BestEncInfoCache::isValid(const CodingStructure &cs, const Partitioner &partitioner, int qp)
{
if (partitioner.treeType == TREE_C)
{
return false; // if save & load is allowed for chroma CUs, we should check whether luma info (pred, recon, etc) is
// the same, which is quite complex
}
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(cs.area.Y(), *m_slice_bencinf->getPPS()->pcv, idx1, idx2, idx3, idx4);
BestEncodingInfo &encInfo = *m_bestEncInfo[idx1][idx2][idx3][idx4];
if (encInfo.cu.treeType != partitioner.treeType || encInfo.cu.modeType != partitioner.modeType)
{
return false;
}
if (encInfo.cu.qp != qp || cs.slice->getUseChromaQpAdj())
return false;
if (cs.picture->poc != encInfo.poc
|| CS::getArea(cs, cs.area, partitioner.chType) != CS::getArea(cs, encInfo.cu, partitioner.chType)
|| !isTheSameNbHood(encInfo.cu, cs, partitioner, encInfo.pu, (cs.picture->Y().width), (cs.picture->Y().height))
|| CU::isIBC(encInfo.cu) || partitioner.currQgEnable() || cs.currQP[partitioner.chType] != encInfo.cu.qp)
{
return false;
}
else
{
return true;
}
}
bool BestEncInfoCache::setCsFrom(CodingStructure &cs, EncTestMode &testMode, const Partitioner &partitioner) const
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(cs.area.Y(), *m_slice_bencinf->getPPS()->pcv, idx1, idx2, idx3, idx4);
BestEncodingInfo &encInfo = *m_bestEncInfo[idx1][idx2][idx3][idx4];
if (cs.picture->poc != encInfo.poc
|| CS::getArea(cs, cs.area, partitioner.chType) != CS::getArea(cs, encInfo.cu, partitioner.chType)
|| !isTheSameNbHood(encInfo.cu, cs, partitioner, encInfo.pu, (cs.picture->Y().width), (cs.picture->Y().height))
|| partitioner.currQgEnable() || cs.currQP[partitioner.chType] != encInfo.cu.qp)
{
return false;
}
CodingUnit & cu = cs.addCU(CS::getArea(cs, cs.area, partitioner.chType), partitioner.chType);
PredictionUnit &pu = cs.addPU(CS::getArea(cs, cs.area, partitioner.chType), partitioner.chType);
#if !REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
TransformUnit &tu = cs.addTU(CS::getArea(cs, cs.area, partitioner.chType), partitioner.chType);
#endif
cu.repositionTo(encInfo.cu);
pu.repositionTo(encInfo.pu);
#if !REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
tu.repositionTo(encInfo.tu);
#endif
cu = encInfo.cu;
pu = encInfo.pu;
#if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
CHECKD(!(encInfo.numTus > 0), "Empty tus array");
for (int i = 0; i < encInfo.numTus; i++)
{
TransformUnit &tu = cs.addTU(encInfo.tus[i], partitioner.chType);
for (auto &blk: tu.blocks)
{
if (blk.valid())
tu.copyComponentFrom(encInfo.tus[i], blk.compID);
}
}
#else
for (auto &blk: tu.blocks)
{
if (blk.valid())
tu.copyComponentFrom(encInfo.tu, blk.compID);
}
#endif
testMode = encInfo.testMode;
return true;
}
#endif
static bool interHadActive(const ComprCUCtx &ctx)
{
return ctx.interHad != 0;
}
//////////////////////////////////////////////////////////////////////////
// EncModeCtrlQTBT
//////////////////////////////////////////////////////////////////////////
void EncModeCtrlMTnoRQT::create(const EncCfg &cfg)
{
#if GDR_ENABLED
m_encCfg = cfg;
#endif
CacheBlkInfoCtrl::create();
#if REUSE_CU_RESULTS
BestEncInfoCache::create(cfg.getChromaFormatIdc());
#endif
SaveLoadEncInfoSbt::create();
}
void EncModeCtrlMTnoRQT::destroy()
{
CacheBlkInfoCtrl::destroy();
#if REUSE_CU_RESULTS
BestEncInfoCache::destroy();
#endif
SaveLoadEncInfoSbt::destroy();
}
void EncModeCtrlMTnoRQT::initCTUEncoding(const Slice &slice)
{
CacheBlkInfoCtrl::init(slice);
#if REUSE_CU_RESULTS
BestEncInfoCache::init(slice);
#endif
SaveLoadEncInfoSbt::init(slice);
CHECK(!m_ComprCUCtxList.empty(), "Mode list is not empty at the beginning of a CTU");
m_slice = &slice;
if (m_pcEncCfg->getUseE0023FastEnc())
{
if (m_pcEncCfg->getUseCompositeRef())
m_skipThreshold = ((slice.getMinPictureDistance() <= PICTURE_DISTANCE_TH * 2) ? FAST_SKIP_DEPTH : SKIP_DEPTH);
else
m_skipThreshold = ((slice.getMinPictureDistance() <= PICTURE_DISTANCE_TH) ? FAST_SKIP_DEPTH : SKIP_DEPTH);
}
else
{
m_skipThreshold = SKIP_DEPTH;
}
}
void EncModeCtrlMTnoRQT::initCULevel(Partitioner &partitioner, const CodingStructure &cs)
{
// Min/max depth
unsigned minDepth = 0;
unsigned maxDepth =
floorLog2(cs.sps->getCTUSize()) - floorLog2(cs.sps->getMinQTSize(m_slice->getSliceType(), partitioner.chType));
if (m_pcEncCfg->getUseFastLCTU())
{
if (auto adPartitioner = dynamic_cast<AdaptiveDepthPartitioner *>(&partitioner))
{
// LARGE CTU
adPartitioner->setMaxMinDepth(minDepth, maxDepth, cs);
}
}
m_ComprCUCtxList.push_back(ComprCUCtx(cs, minDepth, maxDepth, NUM_EXTRA_FEATURES));
const CodingUnit *cuLeft = cs.getCU(cs.area.blocks[partitioner.chType].pos().offset(-1, 0), partitioner.chType);
const CodingUnit *cuAbove = cs.getCU(cs.area.blocks[partitioner.chType].pos().offset(0, -1), partitioner.chType);
const bool qtBeforeBt =
((cuLeft && cuAbove && cuLeft->qtDepth > partitioner.currQtDepth && cuAbove->qtDepth > partitioner.currQtDepth)
|| (cuLeft && !cuAbove && cuLeft->qtDepth > partitioner.currQtDepth)
|| (!cuLeft && cuAbove && cuAbove->qtDepth > partitioner.currQtDepth)
|| (!cuAbove && !cuLeft && cs.area.lwidth() >= (32 << cs.slice->getDepth())))
&& (cs.area.lwidth() > (cs.pcv->getMinQtSize(*cs.slice, partitioner.chType) << 1));
// set features
ComprCUCtx &cuECtx = m_ComprCUCtxList.back();
cuECtx.set(BEST_NON_SPLIT_COST, MAX_DOUBLE);
cuECtx.set(BEST_VERT_SPLIT_COST, MAX_DOUBLE);
cuECtx.set(BEST_HORZ_SPLIT_COST, MAX_DOUBLE);
cuECtx.set(BEST_TRIH_SPLIT_COST, MAX_DOUBLE);
cuECtx.set(BEST_TRIV_SPLIT_COST, MAX_DOUBLE);
cuECtx.set(DO_TRIH_SPLIT, 1);
cuECtx.set(DO_TRIV_SPLIT, 1);
cuECtx.set(BEST_IMV_COST, MAX_DOUBLE * .5);
cuECtx.set(BEST_NO_IMV_COST, MAX_DOUBLE * .5);
cuECtx.set(QT_BEFORE_BT, qtBeforeBt);
cuECtx.set(DID_QUAD_SPLIT, false);
cuECtx.set(IS_BEST_NOSPLIT_SKIP, false);
cuECtx.set(MAX_QT_SUB_DEPTH, 0);
// QP
int baseQP = cs.baseQP;
if (!partitioner.isSepTree(cs) || isLuma(partitioner.chType))
{
if (m_pcEncCfg->getUseAdaptiveQP())
{
baseQP = Clip3(-cs.sps->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, baseQP + xComputeDQP(cs, partitioner));
}
#if ENABLE_QPA_SUB_CTU
else if (m_pcEncCfg->getUsePerceptQPA() && !m_pcEncCfg->getUseRateCtrl() && cs.pps->getUseDQP()
&& cs.slice->getCuQpDeltaSubdiv() > 0)
{
const PreCalcValues &pcv = *cs.pcv;
if ((partitioner.currArea().lwidth() < pcv.maxCUWidth) && (partitioner.currArea().lheight() < pcv.maxCUHeight)
&& cs.picture)
{
const Position &pos = partitioner.currQgPos;
const unsigned mtsLog2 = (unsigned) floorLog2(std::min(cs.sps->getMaxTbSize(), pcv.maxCUWidth));
const unsigned stride = pcv.maxCUWidth >> mtsLog2;
baseQP = cs.picture->m_subCtuQP[((pos.x & pcv.maxCUWidthMask) >> mtsLog2)
+ stride * ((pos.y & pcv.maxCUHeightMask) >> mtsLog2)];
}
}
#endif
#if SHARP_LUMA_DELTA_QP
if (m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled())
{
if (partitioner.currQgEnable())
{
m_lumaQPOffset = calculateLumaDQP(cs.getOrgBuf(clipArea(cs.area.Y(), cs.picture->Y())));
}
baseQP = Clip3(-cs.sps->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, baseQP - m_lumaQPOffset);
}
#endif
}
int minQP = baseQP;
int maxQP = baseQP;
xGetMinMaxQP(minQP, maxQP, cs, partitioner, baseQP, *cs.sps, *cs.pps, CU_QUAD_SPLIT);
bool checkIbc = true;
if (partitioner.chType == CHANNEL_TYPE_CHROMA)
{
checkIbc = false;
}
// Add coding modes here
// NOTE: Working back to front, as a stack, which is more efficient with the container
// NOTE: First added modes will be processed at the end.
//////////////////////////////////////////////////////////////////////////
// Add unit split modes
if (!cuECtx.get<bool>(QT_BEFORE_BT))
{
for (int qp = maxQP; qp >= minQP; qp--)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_SPLIT_QT, ETO_STANDARD, qp });
}
}
if (partitioner.canSplit(CU_TRIV_SPLIT, cs))
{
// add split modes
for (int qp = maxQP; qp >= minQP; qp--)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_SPLIT_TT_V, ETO_STANDARD, qp });
}
}
if (partitioner.canSplit(CU_TRIH_SPLIT, cs))
{
// add split modes
for (int qp = maxQP; qp >= minQP; qp--)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_SPLIT_TT_H, ETO_STANDARD, qp });
}
}
int minQPq = minQP;
int maxQPq = maxQP;
xGetMinMaxQP(minQP, maxQP, cs, partitioner, baseQP, *cs.sps, *cs.pps, CU_BT_SPLIT);
if (partitioner.canSplit(CU_VERT_SPLIT, cs))
{
// add split modes
for (int qp = maxQP; qp >= minQP; qp--)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_SPLIT_BT_V, ETO_STANDARD, qp });
}
m_ComprCUCtxList.back().set(DID_VERT_SPLIT, true);
}
else
{
m_ComprCUCtxList.back().set(DID_VERT_SPLIT, false);
}
if (partitioner.canSplit(CU_HORZ_SPLIT, cs))
{
// add split modes
for (int qp = maxQP; qp >= minQP; qp--)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_SPLIT_BT_H, ETO_STANDARD, qp });
}
m_ComprCUCtxList.back().set(DID_HORZ_SPLIT, true);
}
else
{
m_ComprCUCtxList.back().set(DID_HORZ_SPLIT, false);
}
if (cuECtx.get<bool>(QT_BEFORE_BT))
{
for (int qp = maxQPq; qp >= minQPq; qp--)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_SPLIT_QT, ETO_STANDARD, qp });
}
}
m_ComprCUCtxList.back().testModes.push_back({ ETM_POST_DONT_SPLIT });
xGetMinMaxQP(minQP, maxQP, cs, partitioner, baseQP, *cs.sps, *cs.pps, CU_DONT_SPLIT);
int lowestQP = minQP;
//////////////////////////////////////////////////////////////////////////
// Add unit coding modes: Intra, InterME, InterMerge ...
bool tryIntraRdo = true;
bool tryInterRdo = true;
bool tryIBCRdo = true;
if (partitioner.isConsIntra())
{
tryInterRdo = false;
}
else if (partitioner.isConsInter())
{
tryIntraRdo = tryIBCRdo = false;
}
checkIbc &= tryIBCRdo;
for (int qpLoop = maxQP; qpLoop >= minQP; qpLoop--)
{
const int qp = std::max(qpLoop, lowestQP);
#if REUSE_CU_RESULTS
const bool isReusingCu = isValid(cs, partitioner, qp);
cuECtx.set(IS_REUSING_CU, isReusingCu);
if (isReusingCu)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_RECO_CACHED, ETO_STANDARD, qp });
}
#endif
// add intra modes
if (tryIntraRdo)
{
if (cs.slice->getSPS()->getPLTMode()
&& (partitioner.treeType != TREE_D || cs.slice->isIntra()
|| (cs.area.lwidth() == 4 && cs.area.lheight() == 4))
&& getPltEnc())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_PALETTE, ETO_STANDARD, qp });
}
m_ComprCUCtxList.back().testModes.push_back({ ETM_INTRA, ETO_STANDARD, qp });
if (cs.slice->getSPS()->getPLTMode() && partitioner.treeType == TREE_D && !cs.slice->isIntra()
&& !(cs.area.lwidth() == 4 && cs.area.lheight() == 4) && getPltEnc())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_PALETTE, ETO_STANDARD, qp });
}
}
// add ibc mode to intra path
if (cs.sps->getIBCFlag() && checkIbc)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_IBC, ETO_STANDARD, qp });
if (partitioner.chType == CHANNEL_TYPE_LUMA)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_IBC_MERGE, ETO_STANDARD, qp });
}
}
}
// add first pass modes
if (!m_slice->isIntra() && !(cs.area.lwidth() == 4 && cs.area.lheight() == 4) && tryInterRdo)
{
for (int qpLoop = maxQP; qpLoop >= minQP; qpLoop--)
{
const int qp = std::max(qpLoop, lowestQP);
if (m_pcEncCfg->getIMV())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_INTER_ME, EncTestModeOpts(4 << ETO_IMV_SHIFT), qp });
}
if (m_pcEncCfg->getIMV() || m_pcEncCfg->getUseAffineAmvr())
{
int imv = m_pcEncCfg->getIMV4PelFast() ? 3 : 2;
m_ComprCUCtxList.back().testModes.push_back({ ETM_INTER_ME, EncTestModeOpts(imv << ETO_IMV_SHIFT), qp });
m_ComprCUCtxList.back().testModes.push_back({ ETM_INTER_ME, EncTestModeOpts(1 << ETO_IMV_SHIFT), qp });
}
// add inter modes
if (m_pcEncCfg->getUseEarlySkipDetection())
{
if (cs.sps->getUseGeo() && cs.slice->isInterB())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_MERGE_GEO, ETO_STANDARD, qp });
}
m_ComprCUCtxList.back().testModes.push_back({ ETM_MERGE_SKIP, ETO_STANDARD, qp });
if (cs.sps->getUseAffine() || cs.sps->getSbTMVPEnabledFlag())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_AFFINE, ETO_STANDARD, qp });
}
m_ComprCUCtxList.back().testModes.push_back({ ETM_INTER_ME, ETO_STANDARD, qp });
}
else
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_INTER_ME, ETO_STANDARD, qp });
if (cs.sps->getUseGeo() && cs.slice->isInterB())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_MERGE_GEO, ETO_STANDARD, qp });
}
m_ComprCUCtxList.back().testModes.push_back({ ETM_MERGE_SKIP, ETO_STANDARD, qp });
if (cs.sps->getUseAffine() || cs.sps->getSbTMVPEnabledFlag())
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_AFFINE, ETO_STANDARD, qp });
}
}
if (m_pcEncCfg->getUseHashME())
{
int minSize = min(cs.area.lwidth(), cs.area.lheight());
if (minSize < 128 && minSize >= 4)
{
m_ComprCUCtxList.back().testModes.push_back({ ETM_HASH_INTER, ETO_STANDARD, qp });
}
}
}
}
// ensure to skip unprobable modes
if (!tryModeMaster(m_ComprCUCtxList.back().testModes.back(), cs, partitioner))
{
nextMode(cs, partitioner);
}
m_ComprCUCtxList.back().lastTestMode = EncTestMode();
}
void EncModeCtrlMTnoRQT::finishCULevel(Partitioner &partitioner)
{
m_ComprCUCtxList.pop_back();
}
bool EncModeCtrlMTnoRQT::tryMode(const EncTestMode &encTestmode, const CodingStructure &cs, Partitioner &partitioner)
{
ComprCUCtx &cuECtx = m_ComprCUCtxList.back();
// Fast checks, partitioning depended
if (cuECtx.isHashPerfectMatch && encTestmode.type != ETM_MERGE_SKIP && encTestmode.type != ETM_INTER_ME
&& encTestmode.type != ETM_AFFINE && encTestmode.type != ETM_MERGE_GEO)
{
#if GDR_ENABLED // disable hash perfect match when GDR is on
if (!m_encCfg.getGdrEnabled())
{
return false;
}
#else
return false;
#endif
}
// if early skip detected, skip all modes checking but the splits
if (cuECtx.earlySkip && m_pcEncCfg->getUseEarlySkipDetection() && !isModeSplit(encTestmode)
&& !(isModeInter(encTestmode)))
{
return false;
}
const PartSplit implicitSplit = partitioner.getImplicitSplit(cs);
const bool isBoundary = implicitSplit != CU_DONT_SPLIT;
if (isBoundary && encTestmode.type != ETM_SPLIT_QT)
{
return getPartSplit(encTestmode) == implicitSplit;
}
else if (isBoundary && encTestmode.type == ETM_SPLIT_QT)
{
return partitioner.canSplit(CU_QUAD_SPLIT, cs);
}
#if REUSE_CU_RESULTS
if (cuECtx.get<bool>(IS_REUSING_CU))
{
if (encTestmode.type == ETM_RECO_CACHED)
{
return true;
}
if (isModeNoSplit(encTestmode))
{
return false;
}
}
#endif
const Slice & slice = *m_slice;
const SPS & sps = *slice.getSPS();
const uint32_t numComp = getNumberValidComponents(slice.getSPS()->getChromaFormatIdc());
const uint32_t width = partitioner.currArea().lumaSize().width;
const CodingStructure *bestCS = cuECtx.bestCS;
const CodingUnit * bestCU = cuECtx.bestCU;
const EncTestMode bestMode = bestCS ? getCSEncMode(*bestCS) : EncTestMode();
CodedCUInfo &relatedCU = getBlkInfo(partitioner.currArea());
if (cuECtx.minDepth > partitioner.currQtDepth && partitioner.canSplit(CU_QUAD_SPLIT, cs))
{
// enforce QT
return encTestmode.type == ETM_SPLIT_QT;
}
else if (encTestmode.type == ETM_SPLIT_QT && cuECtx.maxDepth <= partitioner.currQtDepth)
{
// don't check this QT depth
return false;
}
if (bestCS && bestCS->cus.size() == 1)
{
// update the best non-split cost
cuECtx.set(BEST_NON_SPLIT_COST, bestCS->cost);
}
if (encTestmode.type == ETM_INTRA)
{
if (getFastDeltaQp())
{
if (cs.area.lumaSize().width > cs.pcv->fastDeltaQPCuMaxSize)
{
return false; // only check necessary 2Nx2N Intra in fast delta-QP mode
}
}
if (m_pcEncCfg->getUseFastLCTU() && partitioner.currArea().lumaSize().area() > 4096)
{
return (m_pcEncCfg->getDualITree() == 0 && m_pcEncCfg->getMaxMTTHierarchyDepthI() == 0
&& cs.sps->getMinQTSize(cs.slice->getSliceType(), partitioner.chType) > 64);
}
if (CS::isDualITree(cs)
&& (partitioner.currArea().lumaSize().width > 64 || partitioner.currArea().lumaSize().height > 64))
{
return false;
}
if (m_pcEncCfg->getUsePbIntraFast() && (!cs.slice->isIntra() || cs.slice->getSPS()->getIBCFlag())
&& !interHadActive(cuECtx) && cuECtx.bestCU && !CU::isIntra(*cuECtx.bestCU))
{
return false;
}
// INTRA MODES
if (cs.sps->getIBCFlag() && !cuECtx.bestTU)
return true;
if (partitioner.isConsIntra() && !cuECtx.bestTU)
{
return true;
}
if (partitioner.currArea().lumaSize().width == 4 && partitioner.currArea().lumaSize().height == 4
&& !slice.isIntra() && !cuECtx.bestTU)
{
return true;
}
if (!(slice.isIntra() || bestMode.type == ETM_INTRA || !cuECtx.bestTU
|| ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (!relatedCU.isInter || !relatedCU.isIBC)
&& ((cuECtx.bestTU->cbf[0] != 0) || ((numComp > COMPONENT_Cb) && cuECtx.bestTU->cbf[1] != 0)
|| ((numComp > COMPONENT_Cr)
&& cuECtx.bestTU->cbf[2] != 0) // avoid very complex intra if it is unlikely
))))
{
return false;
}
if ((m_pcEncCfg->getIBCFastMethod() & IBC_FAST_METHOD_NOINTRA_IBCCBF0)
&& (bestMode.type == ETM_IBC || bestMode.type == ETM_IBC_MERGE)
&& (!cuECtx.bestCU->Y().valid() || cuECtx.bestTU->cbf[0] == 0)
&& (!cuECtx.bestCU->Cb().valid() || cuECtx.bestTU->cbf[1] == 0)
&& (!cuECtx.bestCU->Cr().valid() || cuECtx.bestTU->cbf[2] == 0))
{
return false;
}
if (lastTestMode().type != ETM_INTRA && cuECtx.bestCS && cuECtx.bestCU && interHadActive(cuECtx))
{
// Get SATD threshold from best Inter-CU
if (!cs.slice->isIntra() && m_pcEncCfg->getUsePbIntraFast() && !cs.slice->getDisableSATDForRD())
{
CodingUnit *bestCU = cuECtx.bestCU;
if (bestCU && !CU::isIntra(*bestCU))
{
DistParam distParam;
const bool useHad = true;
m_pcRdCost->setDistParam(distParam, cs.getOrgBuf(COMPONENT_Y), cuECtx.bestCS->getPredBuf(COMPONENT_Y),
cs.sps->getBitDepth(CHANNEL_TYPE_LUMA), COMPONENT_Y, useHad);
cuECtx.interHad = distParam.distFunc(distParam);
}
}
}
if (bestMode.type == ETM_PALETTE && !slice.isIntra() && partitioner.treeType == TREE_D
&& !(partitioner.currArea().lumaSize().width == 4
&& partitioner.currArea().lumaSize().height == 4)) // inter slice
{
return false;
}
if (m_pcEncCfg->getUseFastISP() && relatedCU.relatedCuIsValid)
{
cuECtx.ispPredModeVal = relatedCU.ispPredModeVal;
cuECtx.bestDCT2NonISPCost = relatedCU.bestDCT2NonISPCost;
cuECtx.relatedCuIsValid = relatedCU.relatedCuIsValid;
cuECtx.bestNonDCT2Cost = relatedCU.bestNonDCT2Cost;
cuECtx.bestISPIntraMode = relatedCU.bestISPIntraMode;
}
return true;
}
else if (encTestmode.type == ETM_PALETTE)
{
if (partitioner.currArea().lumaSize().width > 64 || partitioner.currArea().lumaSize().height > 64
|| ((partitioner.currArea().lumaSize().width * partitioner.currArea().lumaSize().height <= 16)
&& (isLuma(partitioner.chType)))
|| ((partitioner.currArea().chromaSize().width * partitioner.currArea().chromaSize().height <= 16)
&& (!isLuma(partitioner.chType)) && partitioner.isSepTree(cs))
|| (partitioner.isLocalSepTree(cs) && (!isLuma(partitioner.chType))))
{
return false;
}
const Area curr_cu =
CS::getArea(cs, cs.area, partitioner.chType).blocks[getFirstComponentOfChannel(partitioner.chType)];
try
{
double stored_cost = slice.m_mapPltCost[isChroma(partitioner.chType)].at(curr_cu.pos()).at(curr_cu.size());
if (bestMode.type != ETM_INVALID && stored_cost > cuECtx.bestCS->cost)
{
return false;
}
}
catch (const std::out_of_range &)
{
// do nothing if no stored cost value was found.
}
return true;
}
else if (encTestmode.type == ETM_IBC || encTestmode.type == ETM_IBC_MERGE)
{
// IBC MODES
return sps.getIBCFlag()
&& (partitioner.currArea().lumaSize().width < 128 && partitioner.currArea().lumaSize().height < 128);
}
else if (isModeInter(encTestmode))
{
// INTER MODES (ME + MERGE/SKIP)
CHECK(slice.isIntra(), "Inter-mode should not be in the I-Slice mode list!");
if (getFastDeltaQp())
{
if (encTestmode.type == ETM_MERGE_SKIP)
{
return false;
}
if (cs.area.lumaSize().width > cs.pcv->fastDeltaQPCuMaxSize)
{
return false; // only check necessary 2Nx2N Inter in fast deltaqp mode
}
}
// --- Check if we can quit current mode using SAVE/LOAD coding history
if (encTestmode.type == ETM_INTER_ME)
{
if (encTestmode.opts == ETO_STANDARD)
{
// NOTE: ETO_STANDARD is always done when early SKIP mode detection is enabled
if (!m_pcEncCfg->getUseEarlySkipDetection())
{
if (relatedCU.isSkip || relatedCU.isIntra)
{
return false;
}
}
}
else if ((encTestmode.opts & ETO_IMV) != 0)
{
int imvOpt = (encTestmode.opts & ETO_IMV) >> ETO_IMV_SHIFT;
if (imvOpt == 3 && cuECtx.get<double>(BEST_NO_IMV_COST) * 1.06 < cuECtx.get<double>(BEST_IMV_COST))
{
if (!m_pcEncCfg->getUseAffineAmvr())
return false;
}
}
}
if (encTestmode.type == ETM_AFFINE && relatedCU.isIntra)
{
return false;
}
if (encTestmode.type == ETM_MERGE_GEO
&& (partitioner.currArea().lwidth() < GEO_MIN_CU_SIZE || partitioner.currArea().lheight() < GEO_MIN_CU_SIZE
|| partitioner.currArea().lwidth() > GEO_MAX_CU_SIZE || partitioner.currArea().lheight() > GEO_MAX_CU_SIZE
|| partitioner.currArea().lwidth() >= 8 * partitioner.currArea().lheight()
|| partitioner.currArea().lheight() >= 8 * partitioner.currArea().lwidth()))
{
return false;
}
return true;
}
else if (isModeSplit(encTestmode))
{
//////////////////////////////////////////////////////////////////////////
// skip-history rule - don't split further if at least for three past levels
// in the split tree it was found that skip is the best mode
//////////////////////////////////////////////////////////////////////////
int skipScore = 0;
if ((!slice.isIntra() || slice.getSPS()->getIBCFlag()) && cuECtx.get<bool>(IS_BEST_NOSPLIT_SKIP))
{
for (int i = 2; i < m_ComprCUCtxList.size(); i++)
{
if ((m_ComprCUCtxList.end() - i)->get<bool>(IS_BEST_NOSPLIT_SKIP))
{
skipScore += 1;
}
else
{
break;
}
}
}
const PartSplit split = getPartSplit(encTestmode);
if (!partitioner.canSplit(split, cs) || skipScore >= 2)
{
if (split == CU_HORZ_SPLIT)
cuECtx.set(DID_HORZ_SPLIT, false);
if (split == CU_VERT_SPLIT)
cuECtx.set(DID_VERT_SPLIT, false);
if (split == CU_QUAD_SPLIT)
cuECtx.set(DID_QUAD_SPLIT, false);
return false;
}
if (m_pcEncCfg->getUseContentBasedFastQtbt())
{
const CompArea &currArea = partitioner.currArea().Y();
int cuHeight = currArea.height;
int cuWidth = currArea.width;
const bool condIntraInter =
m_pcEncCfg->getIntraPeriod() == 1 ? (partitioner.currBtDepth == 0) : (cuHeight > 32 && cuWidth > 32);
if (cuWidth == cuHeight && condIntraInter && getPartSplit(encTestmode) != CU_QUAD_SPLIT)
{
const CPelBuf bufCurrArea = cs.getOrgBuf(partitioner.currArea().block(COMPONENT_Y));
double horVal = 0;
double verVal = 0;
double dupVal = 0;
double dowVal = 0;
const double th = m_pcEncCfg->getIntraPeriod() == 1 ? 1.2 : 1.0;
unsigned j, k;
for (j = 0; j < cuWidth - 1; j++)
{
for (k = 0; k < cuHeight - 1; k++)
{
horVal += abs(bufCurrArea.at(j + 1, k) - bufCurrArea.at(j, k));
verVal += abs(bufCurrArea.at(j, k + 1) - bufCurrArea.at(j, k));
dowVal += abs(bufCurrArea.at(j + 1, k) - bufCurrArea.at(j, k + 1));
dupVal += abs(bufCurrArea.at(j + 1, k + 1) - bufCurrArea.at(j, k));
}
}
if (horVal > th * verVal && sqrt(2) * horVal > th * dowVal && sqrt(2) * horVal > th * dupVal
&& (getPartSplit(encTestmode) == CU_HORZ_SPLIT || getPartSplit(encTestmode) == CU_TRIH_SPLIT))
{
return false;
}
if (th * dupVal < sqrt(2) * verVal && th * dowVal < sqrt(2) * verVal && th * horVal < verVal
&& (getPartSplit(encTestmode) == CU_VERT_SPLIT || getPartSplit(encTestmode) == CU_TRIV_SPLIT))
{
return false;
}
}
if (m_pcEncCfg->getIntraPeriod() == 1 && cuWidth <= 32 && cuHeight <= 32 && bestCS && bestCS->tus.size() == 1
&& bestCU && bestCU->depth == partitioner.currDepth && partitioner.currBtDepth > 1
&& isLuma(partitioner.chType))
{
if (!bestCU->rootCbf)
{
return false;
}
}
}
if (bestCU && bestCU->skip && bestCU->mtDepth >= m_skipThreshold && !isModeSplit(cuECtx.lastTestMode))
{
return false;
}
int featureToSet = -1;
switch (getPartSplit(encTestmode))
{
case CU_QUAD_SPLIT:
{
if (!cuECtx.get<bool>(QT_BEFORE_BT) && bestCU)
{
unsigned maxBTD = cs.pcv->getMaxBtDepth(slice, partitioner.chType);
const CodingUnit *cuBR = bestCS->cus.back();
unsigned height = partitioner.currArea().lumaSize().height;
if (bestCU
&& ((bestCU->btDepth == 0 && maxBTD >= ((slice.isIntra() && !slice.getSPS()->getIBCFlag()) ? 3 : 2))
|| (bestCU->btDepth == 1 && cuBR && cuBR->btDepth == 1
&& maxBTD >= ((slice.isIntra() && !slice.getSPS()->getIBCFlag()) ? 4 : 3)))
&& (width <= MAX_TB_SIZEY && height <= MAX_TB_SIZEY) && cuECtx.get<bool>(DID_HORZ_SPLIT)
&& cuECtx.get<bool>(DID_VERT_SPLIT))
{
return false;
}
}
if (m_pcEncCfg->getUseEarlyCU() && bestCS->cost != MAX_DOUBLE && bestCU && bestCU->skip)
{
return false;
}
if (getFastDeltaQp() && width <= slice.getPPS()->pcv->fastDeltaQPCuMaxSize)
{
return false;
}
}
break;
case CU_HORZ_SPLIT: featureToSet = DID_HORZ_SPLIT; break;
case CU_VERT_SPLIT: featureToSet = DID_VERT_SPLIT; break;
case CU_TRIH_SPLIT:
if (cuECtx.get<bool>(DID_HORZ_SPLIT) && bestCU && bestCU->btDepth == partitioner.currBtDepth && !bestCU->rootCbf)
{
return false;
}
if (!cuECtx.get<bool>(DO_TRIH_SPLIT))
{
return false;
}
break;
case CU_TRIV_SPLIT:
if (cuECtx.get<bool>(DID_VERT_SPLIT) && bestCU && bestCU->btDepth == partitioner.currBtDepth && !bestCU->rootCbf)
{
return false;
}
if (!cuECtx.get<bool>(DO_TRIV_SPLIT))
{
return false;
}
break;
default:
THROW("Only CU split modes are governed by the EncModeCtrl");
return false;
break;
}
switch (split)
{
case CU_HORZ_SPLIT:
case CU_TRIH_SPLIT:
if (cuECtx.get<bool>(QT_BEFORE_BT) && cuECtx.get<bool>(DID_QUAD_SPLIT))
{
if (cuECtx.get<int>(MAX_QT_SUB_DEPTH) > partitioner.currQtDepth + 1)
{
if (featureToSet >= 0)
cuECtx.set(featureToSet, false);
return false;
}
}
break;
case CU_VERT_SPLIT:
case CU_TRIV_SPLIT:
if (cuECtx.get<bool>(QT_BEFORE_BT) && cuECtx.get<bool>(DID_QUAD_SPLIT))
{
if (cuECtx.get<int>(MAX_QT_SUB_DEPTH) > partitioner.currQtDepth + 1)
{
if (featureToSet >= 0)
cuECtx.set(featureToSet, false);
return false;
}
}
break;
default: break;
}
if (split == CU_QUAD_SPLIT)
cuECtx.set(DID_QUAD_SPLIT, true);
if (cs.sps->getLog2ParallelMergeLevelMinus2())
{
const CompArea &area = partitioner.currArea().Y();
const SizeType size = 1 << (cs.sps->getLog2ParallelMergeLevelMinus2() + 2);
if (!cs.slice->isIntra() && (area.width > size || area.height > size))
{
if (area.height <= size && split == CU_HORZ_SPLIT)
return false;
if (area.width <= size && split == CU_VERT_SPLIT)
return false;
if (area.height <= 2 * size && split == CU_TRIH_SPLIT)
return false;
if (area.width <= 2 * size && split == CU_TRIV_SPLIT)
return false;
}
}
return true;
}
else
{
CHECK(encTestmode.type != ETM_POST_DONT_SPLIT, "Unknown mode");
// if ((cuECtx.get<double>(BEST_NO_IMV_COST) == (MAX_DOUBLE * .5) || cuECtx.get<bool>(IS_REUSING_CU)) &&
// !slice.isIntra())
if ((cuECtx.get<double>(BEST_NO_IMV_COST) == (MAX_DOUBLE * .5) || NULL) && !slice.isIntra())
{
unsigned idx1, idx2, idx3, idx4;
getAreaIdx(partitioner.currArea().Y(), *slice.getPPS()->pcv, idx1, idx2, idx3, idx4);
if (g_isReusedUniMVsFilled[idx1][idx2][idx3][idx4])
{
m_pcInterSearch->insertUniMvCands(partitioner.currArea().Y(), g_reusedUniMVs[idx1][idx2][idx3][idx4]);
}
}
if (!bestCS || (bestCS && isModeSplit(bestMode)))
{
return false;
}
else
{
#if REUSE_CU_RESULTS
setFromCs(*bestCS, partitioner);
#endif
if (partitioner.modeType == MODE_TYPE_INTRA && partitioner.chType == CHANNEL_TYPE_LUMA)
{
return false; // not set best coding mode for intra coding pass
}
// assume the non-split modes are done and set the marks for the best found mode
if (bestCS && bestCU)
{
if (CU::isInter(*bestCU))
{
relatedCU.isInter = true;
relatedCU.isSkip |= bestCU->skip;
relatedCU.isMMVDSkip |= bestCU->mmvdSkip;
relatedCU.BcwIdx = bestCU->BcwIdx;
if (bestCU->slice->getSPS()->getUseColorTrans())
{
if (m_pcEncCfg->getRGBFormatFlag())
{
if (bestCU->colorTransform && bestCU->rootCbf)
{
relatedCU.selectColorSpaceOption = 1;
}
else
{
relatedCU.selectColorSpaceOption = 2;
}
}
else
{
if (!bestCU->colorTransform || !bestCU->rootCbf)
{
relatedCU.selectColorSpaceOption = 1;
}
else
{
relatedCU.selectColorSpaceOption = 2;
}
}
}
}
else if (CU::isIBC(*bestCU))
{
relatedCU.isIBC = true;
relatedCU.isSkip |= bestCU->skip;
if (bestCU->slice->getSPS()->getUseColorTrans())
{
if (m_pcEncCfg->getRGBFormatFlag())
{
if (bestCU->colorTransform && bestCU->rootCbf)
{
relatedCU.selectColorSpaceOption = 1;
}
else
{
relatedCU.selectColorSpaceOption = 2;
}
}
else
{
if (!bestCU->colorTransform || !bestCU->rootCbf)
{
relatedCU.selectColorSpaceOption = 1;
}
else
{
relatedCU.selectColorSpaceOption = 2;
}
}
}
}
else if (CU::isIntra(*bestCU))
{
relatedCU.isIntra = true;
if (m_pcEncCfg->getUseFastISP() && cuECtx.ispWasTested
&& (!relatedCU.relatedCuIsValid || bestCS->cost < relatedCU.bestCost))
{
// Compact data
int bit0 = true;
int bit1 = cuECtx.ispMode == NOT_INTRA_SUBPARTITIONS ? 1 : 0;
int bit2 = cuECtx.ispMode == VER_INTRA_SUBPARTITIONS;
int bit3 = cuECtx.ispLfnstIdx > 0;
int bit4 = cuECtx.ispLfnstIdx == 2;
int bit5 = cuECtx.mipFlag;
int bit6 = cuECtx.bestCostIsp < cuECtx.bestNonDCT2Cost * 0.95;
int val = (bit0) | (bit1 << 1) | (bit2 << 2) | (bit3 << 3) | (bit4 << 4) | (bit5 << 5) | (bit6 << 6)
| (cuECtx.bestPredModeDCT2 << 9);
relatedCU.ispPredModeVal = val;
relatedCU.bestDCT2NonISPCost = cuECtx.bestDCT2NonISPCost;
relatedCU.bestCost = bestCS->cost;
relatedCU.bestNonDCT2Cost = cuECtx.bestNonDCT2Cost;
relatedCU.bestISPIntraMode = cuECtx.bestISPIntraMode;
relatedCU.relatedCuIsValid = true;
}
}
cuECtx.set(IS_BEST_NOSPLIT_SKIP, bestCU->skip);
}
}
return false;
}
}
bool EncModeCtrlMTnoRQT::checkSkipOtherLfnst(const EncTestMode &encTestmode, CodingStructure *&tempCS,
Partitioner &partitioner)
{
xExtractFeatures(encTestmode, *tempCS);
ComprCUCtx &cuECtx = m_ComprCUCtxList.back();
bool skipOtherLfnst = false;
if (encTestmode.type == ETM_INTRA)
{
if (!cuECtx.bestCS
|| (tempCS->cost >= cuECtx.bestCS->cost && cuECtx.bestCS->cus.size() == 1
&& CU::isIntra(*cuECtx.bestCS->cus[0]))
|| (tempCS->cost < cuECtx.bestCS->cost && CU::isIntra(*tempCS->cus[0])))
{
skipOtherLfnst = !tempCS->cus[0]->rootCbf;
}
}
return skipOtherLfnst;
}
bool EncModeCtrlMTnoRQT::useModeResult(const EncTestMode &encTestmode, CodingStructure *&tempCS,
Partitioner &partitioner)
{
xExtractFeatures(encTestmode, *tempCS);
ComprCUCtx &cuECtx = m_ComprCUCtxList.back();
if (encTestmode.type == ETM_SPLIT_BT_H)
{
cuECtx.set(BEST_HORZ_SPLIT_COST, tempCS->cost);
}
else if (encTestmode.type == ETM_SPLIT_BT_V)
{
cuECtx.set(BEST_VERT_SPLIT_COST, tempCS->cost);
}
else if (encTestmode.type == ETM_SPLIT_TT_H)
{
cuECtx.set(BEST_TRIH_SPLIT_COST, tempCS->cost);
}
else if (encTestmode.type == ETM_SPLIT_TT_V)
{
cuECtx.set(BEST_TRIV_SPLIT_COST, tempCS->cost);
}
else if (encTestmode.type == ETM_INTRA)
{
const CodingUnit cu = *tempCS->getCU(partitioner.chType);
if (!cu.mtsFlag)
{
cuECtx.bestMtsSize2Nx2N1stPass = tempCS->cost;
}
if (!cu.ispMode)
{
cuECtx.bestCostMtsFirstPassNoIsp = tempCS->cost;
}
}
if (m_pcEncCfg->getIMV4PelFast() && m_pcEncCfg->getIMV() && encTestmode.type == ETM_INTER_ME)
{
int imvMode = (encTestmode.opts & ETO_IMV) >> ETO_IMV_SHIFT;
if (imvMode == 1)
{
if (tempCS->cost < cuECtx.get<double>(BEST_IMV_COST))
{
cuECtx.set(BEST_IMV_COST, tempCS->cost);
}
}
else if (imvMode == 0)
{
if (tempCS->cost < cuECtx.get<double>(BEST_NO_IMV_COST))
{
cuECtx.set(BEST_NO_IMV_COST, tempCS->cost);
}
}
}
if (encTestmode.type == ETM_SPLIT_QT)
{
int maxQtD = 0;
for (const auto &cu: tempCS->cus)
{
maxQtD = std::max<int>(maxQtD, cu->qtDepth);
}
cuECtx.set(MAX_QT_SUB_DEPTH, maxQtD);
}
int maxMtD = tempCS->pcv->getMaxBtDepth(*tempCS->slice, partitioner.chType) + partitioner.currImplicitBtDepth;
if (encTestmode.type == ETM_SPLIT_BT_H)
{
if (tempCS->cus.size() > 2)
{
int h_2 = tempCS->area.blocks[partitioner.chType].height / 2;
int cu1_h = tempCS->cus.front()->blocks[partitioner.chType].height;
int cu2_h = tempCS->cus.back()->blocks[partitioner.chType].height;
cuECtx.set(DO_TRIH_SPLIT, cu1_h < h_2 || cu2_h < h_2 || partitioner.currMtDepth + 1 == maxMtD);
}
}
else if (encTestmode.type == ETM_SPLIT_BT_V)
{
if (tempCS->cus.size() > 2)
{
int w_2 = tempCS->area.blocks[partitioner.chType].width / 2;
int cu1_w = tempCS->cus.front()->blocks[partitioner.chType].width;
int cu2_w = tempCS->cus.back()->blocks[partitioner.chType].width;
cuECtx.set(DO_TRIV_SPLIT, cu1_w < w_2 || cu2_w < w_2 || partitioner.currMtDepth + 1 == maxMtD);
}
}
// for now just a simple decision based on RD-cost or choose tempCS if bestCS is not yet coded
if (tempCS->features[ENC_FT_RD_COST] != MAX_DOUBLE
&& (!cuECtx.bestCS
|| ((tempCS->features[ENC_FT_RD_COST] + (tempCS->useDbCost ? tempCS->costDbOffset : 0))
< (cuECtx.bestCS->features[ENC_FT_RD_COST] + (tempCS->useDbCost ? cuECtx.bestCS->costDbOffset : 0)))))
{
cuECtx.bestCS = tempCS;
cuECtx.bestCU = tempCS->cus[0];
cuECtx.bestTU = cuECtx.bestCU->firstTU;
if (isModeInter(encTestmode))
{
// Here we take the best cost of both inter modes. We are assuming only the inter modes (and all of them) have
// come before the intra modes!!!
cuECtx.bestInterCost = cuECtx.bestCS->cost;
}
return true;
}
else
{
return false;
}
}
| 31.798124 | 120 | 0.610481 | [
"vector"
] |
fb7044b68d997f3a7f969489242619815076d311 | 3,866 | cpp | C++ | source/scene/ParticleSystem.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | 6 | 2017-06-26T11:42:26.000Z | 2018-09-10T17:53:53.000Z | source/scene/ParticleSystem.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | 8 | 2017-06-24T20:25:42.000Z | 2017-08-09T10:50:40.000Z | source/scene/ParticleSystem.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | null | null | null | /*
MIT License
Copyright(c) 2017 Daniel Suttor
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 "ParticleSystem.h"
#include <random>
#include <functional>
#include <limits>
ParticleSystem::ParticleSystem(int particleCount, int emissionsPerSecond, float particleLifetime) :
particleCount_{particleCount},
emissionsPerSecond_{emissionsPerSecond},
particleLifetime_{particleLifetime}
{
positions_.resize(particleCount, glm::vec3(0.0f));
lifetime_.resize(particleCount, 0.0f);
}
void ParticleSystem::Update(float dt)
{
emissionsPerFrame_ += emissionsPerSecond_ * dt;
int emitCount = static_cast<int>(floor(emissionsPerFrame_));
if (emitCount > 0)
{
emissionsPerFrame_ -= Spawn(emitCount);
}
boundingBox_.min = glm::vec3(FLT_MAX);
boundingBox_.max = glm::vec3(-FLT_MAX);
Advect(dt);
Kill();
if (aliveCount_ <= 0)
{
boundingBox_.min = glm::vec3(0.0f);
boundingBox_.max = glm::vec3(0.0f);
}
else
{
static const glm::vec3 radius = glm::vec3(particleRadius_, particleRadius_, particleRadius_);
boundingBox_.max += radius;
boundingBox_.min -= radius;
}
}
void ParticleSystem::ApplyTransform(const Transform& transform)
{
origin_ += transform.pos;
}
int ParticleSystem::Spawn(int emitCount)
{
static std::default_random_engine generator;
static std::uniform_real_distribution<float> distribution(-emitRadius_, emitRadius_);
static auto RandPos = std::bind(distribution, generator);
int count = 0;
for (int i = 0; i < emitCount; ++i)
{
if (aliveCount_ < positions_.size())
{
positions_[aliveCount_] = origin_ + glm::vec3(RandPos(), RandPos(), RandPos());
lifetime_[aliveCount_] = 0.0f;
++aliveCount_;
++count;
}
}
return count;
}
void ParticleSystem::Advect(float dt)
{
for (int i = 0; i < aliveCount_; ++i)
{
lifetime_[i] += dt;
if (lifetime_[i] > particleLifetime_)
{
deadParticles_.push_back(i);
continue;
}
static std::default_random_engine generator;
static std::uniform_real_distribution<float> distribution(0.02f, 0.02f);
static auto RandPos = std::bind(distribution, generator);
positions_[i].y -= dt * RandPos() + 0.02f;
positions_[i].x += dt * RandPos();
positions_[i].z += dt * RandPos();
UpdateBounds(positions_[i]);
}
}
void ParticleSystem::Kill()
{
for (auto index : deadParticles_)
{
--aliveCount_;
std::swap(positions_[index], positions_[aliveCount_]);
}
deadParticles_.clear();
}
void ParticleSystem::UpdateBounds(const glm::vec3 pos)
{
boundingBox_.min = glm::min(pos, boundingBox_.min);
boundingBox_.max = glm::max(pos, boundingBox_.max);
}
void ParticleSystem::CheckBounds()
{
boundingBox_.min = glm::clamp(boundingBox_.min, boundingBox_.max, boundingBox_.min);
boundingBox_.max = glm::clamp(boundingBox_.max, boundingBox_.max, boundingBox_.min);
} | 28.014493 | 99 | 0.722193 | [
"transform"
] |
fb788422aad8dac6c1cac6f2aa043257abe3d853 | 4,305 | cpp | C++ | src/input_parsers/acas_example/main.cpp | muizzk/Marabou | b938c474bbf7820854822ca407b64b53dfcf6c7c | [
"BSD-3-Clause"
] | null | null | null | src/input_parsers/acas_example/main.cpp | muizzk/Marabou | b938c474bbf7820854822ca407b64b53dfcf6c7c | [
"BSD-3-Clause"
] | null | null | null | src/input_parsers/acas_example/main.cpp | muizzk/Marabou | b938c474bbf7820854822ca407b64b53dfcf6c7c | [
"BSD-3-Clause"
] | 1 | 2021-06-29T06:54:29.000Z | 2021-06-29T06:54:29.000Z | /********************* */
/*! \file main.cpp
** \verbatim
** Top contributors (to current version):
** Guy Katz, Derek Huang
** This file is part of the Marabou project.
** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file COPYING in the top-level source
** directory for licensing information.\endverbatim
**
** [[ Add lengthier description here ]]
**/
#include <cstdio>
#include "AcasParser.h"
#include "Engine.h"
#include "FloatUtils.h"
#include "GlobalConfiguration.h"
#include "InputQuery.h"
#include "Preprocessor.h"
#include "MarabouError.h"
int main()
{
try
{
// Extract an input query from the network
InputQuery inputQuery;
AcasParser acasParser( "./ACASXU_run2a_1_1_batch_2000.nnet" );
// Trimmed network: 5-5-5, 5 Relus
// AcasParser acasParser( "ACASXU_run2a_1_1_tiny.nnet" );
// Trimmed network: 5-50-5, 50 Relus
// AcasParser acasParser( "ACASXU_run2a_1_1_tiny_2.nnet" );
// Trimmed network: 5-50-50-5, 100 Relus
// AcasParser acasParser( "ACASXU_run2a_1_1_tiny_3.nnet" );
// Trimmed network: 5-50-50-50-5, 150 Relus
// AcasParser acasParser( "ACASXU_run2a_1_1_tiny_4.nnet" );
// Trimmed network: 5-50-50-50-50-5, 200 Relus
// AcasParser acasParser( "ACASXU_run2a_1_1_tiny_5.nnet" );
acasParser.generateQuery( inputQuery );
// A simple query: all inputs are fixed to 0
// for ( unsigned i = 0; i < 5; ++i )
// {
// unsigned variable = acasParser.getInputVariable( i );
// inputQuery.setLowerBound( variable, 0.0 );
// inputQuery.setUpperBound( variable, 0.0 );
// }
// Simple constraint on an output variable
// unsigned variable = acasParser.getOutputVariable( 0 );
// inputQuery.setLowerBound( variable, 0.5 );
// Feed the query to the engine
Engine engine;
bool preprocess = engine.processInputQuery( inputQuery );
if ( !preprocess || !engine.solve() )
{
printf( "\n\nQuery is unsat\n" );
return 0;
}
printf( "\n\nQuery is sat! Extracting solution...\n" );
engine.extractSolution( inputQuery );
Vector<double> inputs;
for ( unsigned i = 0; i < 5; ++i )
{
unsigned variable = acasParser.getInputVariable( i );
printf( "Input[%u] = %.15lf\n", i, inputQuery.getSolutionValue( variable ) );
inputs.append( inputQuery.getSolutionValue( variable ) );
}
// for ( unsigned i = 0; i < 5; ++i )
// {
// unsigned b = acasParser.getBVariable( 1, i );
// unsigned f = acasParser.getFVariable( 1, i );
// unsigned aux = acasParser.getAuxVariable( 1, i );
// unsigned slack = acasParser.getSlackVariable( 1, i );
// printf( "Node (%u, %u): b = %.15lf, f = %.15lf, aux = %.15lf, slack = %.15lf\n",
// 1, i,
// inputQuery.getSolutionValue( b ),
// inputQuery.getSolutionValue( f ),
// inputQuery.getSolutionValue( aux ),
// inputQuery.getSolutionValue( slack ) );
// }
// Run the inputs through the real network, to evaluate the error
Vector<double> outputs;
acasParser.evaluate( inputs, outputs );
double error = 0.0;
for ( unsigned i = 0; i < 5; ++i )
{
unsigned variable = acasParser.getOutputVariable( i );
printf( "Output[%u] = %.15lf\n", i, inputQuery.getSolutionValue( variable ) );
error += FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) );
}
printf( "\nTotal error: %.15lf\n", error );
}
catch ( const MarabouError &e )
{
printf( "Caught a MarabouError. Code: %u. Message: %s\n", e.getCode(), e.getUserMessage() );
return 0;
}
return 0;
}
//
// Local Variables:
// compile-command: "make -C ../../.. "
// tags-file-name: "../../../TAGS"
// c-basic-offset: 4
// End:
//
| 33.115385 | 100 | 0.566551 | [
"vector"
] |
fb84a2015fdb31a7895bf9e93e084aa46a880324 | 2,091 | hpp | C++ | module-db/Tables/Table.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-db/Tables/Table.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-db/Tables/Table.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "Record.hpp"
#include <Database/Database.hpp>
#include <functional>
#include <stdint.h>
#include <vector>
template <typename T, typename F> class Table
{
protected:
explicit Table(Database *db) : db(db)
{}
virtual ~Table()
{}
virtual bool create() = 0;
virtual bool add(T entry) = 0;
virtual bool removeAll()
{
return false;
}
virtual bool removeById(uint32_t id) = 0;
virtual bool removeByField([[maybe_unused]] F field, [[maybe_unused]] const char *str)
{
return false;
}
virtual bool update(T entry) = 0;
virtual T getById(uint32_t id) = 0;
virtual std::vector<T> getLimitOffset(uint32_t offset, uint32_t limit) = 0;
virtual std::vector<T> getLimitOffsetByField(uint32_t offset, uint32_t limit, F field, const char *str) = 0;
virtual uint32_t count() = 0;
virtual uint32_t countByFieldId(const char *field, uint32_t id) = 0;
uint32_t getLastInsertRowId()
{
return db->getLastInsertRowId();
}
virtual std::vector<T> retQueryUnpack(std::unique_ptr<QueryResult> retQuery) const
{
if ((retQuery == nullptr) || (retQuery->getRowCount() == 0) || (createTableRow == nullptr)) {
return {};
}
std::vector<T> outVector;
outVector.reserve(retQuery->getRowCount());
do {
outVector.push_back(createTableRow(*retQuery));
} while (retQuery->nextRow());
return outVector;
}
Database *db = nullptr;
std::function<T(const QueryResult &result)> createTableRow = nullptr;
};
| 32.671875 | 112 | 0.531803 | [
"vector"
] |
fb86127f308244f86b41d86ee04a7697e043c51a | 8,517 | cpp | C++ | src/main.cpp | hobby-dev/vsign | 893e48f4598e69ed8b6158de62f71b7b0a60834b | [
"Zlib"
] | null | null | null | src/main.cpp | hobby-dev/vsign | 893e48f4598e69ed8b6158de62f71b7b0a60834b | [
"Zlib"
] | null | null | null | src/main.cpp | hobby-dev/vsign | 893e48f4598e69ed8b6158de62f71b7b0a60834b | [
"Zlib"
] | null | null | null | #include <atomic>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <thread>
#include <vector>
// Best hash that I could find so far:
#include "meow_hash/meow_hash_x64_aesni.h"
// Cross-platform memory mapping:
#include "portable-memory-mapping/MemoryMapped.h"
#define REPORT_ERROR_AND_EXIT(user_description) \
do { \
std::cerr << user_description << "\n"; \
exit(EXIT_FAILURE); \
} while (0);
#if ASSERTIONS
#define Assert(Expression) \
do { \
if (!(Expression)) { \
*(volatile int *)0 = 0; \
} \
} while (0);
#else
#define Assert(Expression)
#endif
namespace vsign {
struct Settings {
int verbose = 0;
int verify = 0;
unsigned long long block_size = 1024 * 1024;
unsigned long long threads = std::thread::hardware_concurrency();
const char *input = nullptr;
const char *output = nullptr;
};
const char *USAGE_TEXT = "\nUsage: vsign [OPTIONS] INPUT_FILE [OUTPUT_FILE]\n";
const char *HELP_TEXT =
"\n"
"Creates binary signature of contents of INPUT_FILE and writes to "
"OUTPUT_FILE\n"
"(by default will write to 'INPUT_FILE.signature')\n\n"
"Options:\n"
" -b\t\tBlock size (bytes), default is 1 048 576 bytes\n"
" -h\t\tPrint help text\n"
" -t\t\tThreads count, equals to number of logical cores by default \n"
" -v\t\tVerbose output\n"
" -y\t\tVerify that OUTPUT_FILE contains correct signature of INPUT_FILE\n";
void print_help_and_exit() {
std::cout << USAGE_TEXT << HELP_TEXT;
exit(0);
}
Settings parse_arguments(int argc, char **argv) {
vsign::Settings settings{};
for (int count = 1; count < argc; ++count) {
const char *current_arg = argv[count];
if (current_arg[0] == '-') {
if (!strcmp(current_arg, "-v"))
settings.verbose = 1;
else if (!strcmp(current_arg, "-y")) {
REPORT_ERROR_AND_EXIT("Verification is not implemented yet");
settings.verify = 1;
}
else if (!strcmp(current_arg, "-b"))
settings.block_size = std::strtoull(argv[++count], nullptr, 0);
else if (!strcmp(current_arg, "-t"))
settings.threads = std::strtoull(argv[++count], nullptr, 0);
else if (!strcmp(current_arg, "-h"))
print_help_and_exit();
else
REPORT_ERROR_AND_EXIT("Wrong argument: " << current_arg << USAGE_TEXT);
} else {
if (settings.input == nullptr) {
settings.input = current_arg;
} else if (settings.output == nullptr) {
settings.output = current_arg;
} else {
REPORT_ERROR_AND_EXIT(
"What do you mean by this argument?\n"
<< current_arg
<< "\ninput file already defined as: " << settings.input
<< "\nand output file already defined as: " << settings.output
<< USAGE_TEXT);
}
}
}
// Verify that settings are correct:
if (settings.input == nullptr) {
REPORT_ERROR_AND_EXIT("Missing required argument: input file name\n"
<< USAGE_TEXT);
} else if (settings.output == nullptr) {
static std::string output_name{settings.input};
output_name += ".signature";
settings.output = output_name.c_str();
}
constexpr size_t MIN_BLOCK_SIZE = sizeof(meow_u128);
if (settings.block_size < MIN_BLOCK_SIZE) {
REPORT_ERROR_AND_EXIT("You've set block size (-b) to "
<< settings.block_size
<< " bytes but minimal block size is "
<< MIN_BLOCK_SIZE << " bytes\n"
<< USAGE_TEXT);
}
return settings;
}
void execute_worker(
const std::shared_ptr<std::atomic<size_t>> &total_blocks_read,
size_t block_size, const std::shared_ptr<MemoryMapped> &input,
const std::shared_ptr<MemoryMapped> &output) {
try {
// calculate block sizes and last block position
int last_block_size = input->size() % block_size;
const size_t last_position =
input->size() / block_size - (last_block_size ? 0 : 1);
if (last_block_size == 0) {
last_block_size = block_size;
}
// get raw pointers to data
uint8_t *in_mem_begin = static_cast<uint8_t *>(input->accessData());
meow_u128 *out_mem_begin = static_cast<meow_u128 *>(output->accessData());
for (;;) {
// interlocked increment, strong memory ordering
const size_t position = ++(*total_blocks_read) - 1;
// calculate memory positions where to read/write
void *input_memory = in_mem_begin + position * block_size;
meow_u128 *output_memory = out_mem_begin + position;
if (position < last_position) {
*output_memory = MeowHash(MeowDefaultSeed, block_size, input_memory);
} else if (position == last_position) {
*output_memory =
MeowHash(MeowDefaultSeed, last_block_size, input_memory);
} else {
// end of file reached
break;
}
}
} catch (const std::exception &error) {
printf("Sorry, something went wrong: %s\n", error.what());
exit(EXIT_FAILURE);
} catch (...) {
printf("Sorry, something went wrong\n");
exit(EXIT_FAILURE);
}
}
void run(const Settings &settings) {
if (settings.verbose) {
std::cout << "Running vsign with settings:\n"
<< "verbose: " << settings.verbose << "\n"
<< "verify: " << settings.verify << "\n"
<< "block_size: " << settings.block_size << "\n"
<< "threads: " << settings.threads << "\n"
<< "input: " << settings.input << "\n"
<< "output: " << settings.output << "\n";
}
auto total_blocks_read = std::make_shared<std::atomic<size_t>>();
// Init input
auto input = std::make_shared<MemoryMapped>();
bool ok = input->open_read(settings.input);
if (!ok) {
REPORT_ERROR_AND_EXIT("Can't map input file " << settings.input
<< " into memory");
}
// Init output
const size_t last_block_size =
input->size() % settings.block_size > 0 ? sizeof(meow_u128) : 0;
const size_t output_size =
sizeof(meow_u128) * (input->size() / settings.block_size) +
last_block_size;
auto output = std::make_shared<MemoryMapped>();
ok = output->open_write(settings.output, output_size);
if (!ok) {
REPORT_ERROR_AND_EXIT("Can't map output file " << settings.output
<< " into memory");
}
// start workers
std::vector<std::thread> threads;
const size_t threads_to_create = settings.threads - 1;
threads.reserve(threads_to_create);
size_t failed_threads = 0;
for (size_t i = 0; i < threads_to_create; ++i) {
try {
threads.emplace_back(execute_worker, total_blocks_read,
settings.block_size, input, output);
} catch (const std::system_error &error) {
if (settings.verbose) {
std::cout << "Couldn't create thread: " << error.what() << "\n";
}
++failed_threads;
if (failed_threads < threads_to_create) {
--i; // retry for some time, but not infinitely
}
}
}
// main thread already exists, so do some useful work here too:
execute_worker(total_blocks_read, settings.block_size, input, output);
// Wait for completion of all threads
for (std::thread &thread : threads) {
thread.join();
}
}
} // namespace vsign
int main(int argc, char **argv) {
try {
auto start_time = std::chrono::system_clock::now();
vsign::Settings settings = vsign::parse_arguments(argc, argv);
vsign::run(settings);
auto duration = std::chrono::system_clock::now() - start_time;
auto duration_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(duration);
if (settings.verbose) {
std::cout << "Completed in " << duration_ms.count() << " milliseconds\n";
}
} catch (const std::exception &error) {
printf("Sorry, something went wrong: %s\n", error.what());
} catch (...) {
printf("Sorry, something went wrong\n");
}
return 0;
}
| 34.763265 | 80 | 0.580134 | [
"vector"
] |
fb89eb25e9a621f5b11ee2a6070a650893b10f6f | 4,412 | hpp | C++ | include/glw/OpenGlDevice.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 11 | 2015-08-19T23:15:41.000Z | 2018-05-15T21:53:28.000Z | include/glw/OpenGlDevice.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 2 | 2015-05-21T06:37:24.000Z | 2015-05-23T05:37:16.000Z | include/glw/OpenGlDevice.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 5 | 2016-10-31T08:02:15.000Z | 2018-08-24T07:40:23.000Z | #ifndef OPENGLDEVICE_H_
#define OPENGLDEVICE_H_
#include <memory>
#include <unordered_map>
#include "Configure.hpp"
#ifdef OS_WINDOWS
#include <windows.h>
#endif
#include "IOpenGlDevice.hpp"
#include "shaders/ShaderProgramManager.hpp"
#include "shaders/IShaderProgramBindListener.hpp"
#include "glw/IMaterialManager.hpp"
#include "glw/ITextureManager.hpp"
#include "glw/IMeshManager.hpp"
#include "glw/IAnimationManager.hpp"
namespace glmd = glm::detail;
namespace glr
{
namespace glw
{
class OpenGlDevice : public IOpenGlDevice
{
public:
OpenGlDevice(const OpenGlDeviceSettings& settings = OpenGlDeviceSettings());
virtual ~OpenGlDevice();
/* Implementation of IOpenGlDevice methods */
virtual const glm::mat4& getViewMatrix();
virtual const glm::mat4& getProjectionMatrix();
virtual const glm::mat4& getModelMatrix();
virtual void setModelMatrix(const glm::mat4& modelMatrix);
virtual void setViewMatrix(const glm::mat4& viewMatrix);
virtual void setProjectionMatrix(const glm::mat4& projectionMatrix);
virtual GLuint createBufferObject(GLenum target, glm::detail::uint32 totalSize, const void* dataPointer, GLenum usage = GL_DYNAMIC_DRAW);
virtual void releaseBufferObject(GLuint bufferId);
virtual GLuint createFrameBufferObject(GLenum target, glm::detail::uint32 totalSize, const void* dataPointer);
virtual void releaseFrameBufferObject(GLuint bufferId);
virtual void bindBuffer(GLuint bufferId, GLuint bindPoint);
virtual void unbindBuffer(GLuint bufferId);
virtual GLuint getBindPoint();
virtual void invalidateBindPoints();
virtual glm::detail::uint32 getMaximumNumberOfBindPoints();
virtual GlError getGlError();
virtual shaders::IShaderProgramManager* getShaderProgramManager();
virtual IMaterialManager* getMaterialManager();
virtual ITextureManager* getTextureManager();
virtual IMeshManager* getMeshManager();
virtual IAnimationManager* getAnimationManager();
virtual const OpenGlDeviceSettings& getOpenGlDeviceSettings();
virtual void addBindListener(shaders::IShaderProgramBindListener* bindListener);
virtual void removeBindListener(shaders::IShaderProgramBindListener* bindListener);
void removeAllBindListeners();
virtual void addBindListener(ITextureBindListener* bindListener);
virtual void removeBindListener(ITextureBindListener* bindListener);
void removeAllTextureBindListeners();
virtual void addBindListener(IMaterialBindListener* bindListener);
virtual void removeBindListener(IMaterialBindListener* bindListener);
void removeAllMaterialBindListeners();
virtual shaders::IShaderProgram* getCurrentlyBoundShaderProgram() const;
virtual IMaterial* getCurrentlyBoundMaterial() const;
virtual ITexture* getCurrentlyBoundTexture() const;
virtual void unbindAllShaderPrograms();
virtual void unbindAllTextures();
virtual void unbindAllMaterials();
virtual void shaderBindCallback(shaders::IShaderProgram* shader);
virtual void textureBindCallback(ITexture* texture);
virtual void materialBindCallback(IMaterial* material);
private:
std::vector<GLuint> bufferIds_;
std::vector<GLuint> bindPoints_;
std::unordered_map<GLuint, GLuint> boundBuffers_;
GLuint maxNumBindPoints_;
glmd::uint32 currentBindPoint_;
//std::vector< glmd::int32 > bindings_;
std::unique_ptr<IMaterialManager> materialManager_;
std::unique_ptr<ITextureManager> textureManager_;
std::unique_ptr<IMeshManager> meshManager_;
std::unique_ptr<IAnimationManager> animationManager_;
// Matrices
glm::mat4 modelMatrix_;
glm::mat4 viewMatrix_;
glm::mat4 projectionMatrix_;
std::unique_ptr< shaders::ShaderProgramManager > shaderProgramManager_;
OpenGlDeviceSettings settings_;
std::vector<shaders::IShaderProgramBindListener*> bindListeners_;
std::vector<IMaterialBindListener*> materialBindListeners_;
std::vector<ITextureBindListener*> textureBindListeners_;
shaders::IShaderProgram* currentlyBoundShaderProgram_;
IMaterial* currentlyBoundMaterial_;
ITexture* currentlyBoundTexture_;
void setupUniformBufferObjectBindings(shaders::IShaderProgram* shader);
void setupLightUbo(std::string name, shaders::IShaderProgram* shader);
void releaseLightUbo(std::string name);
void bindUniformBufferObjects(shaders::IShaderProgram* shader);
void initialize(const OpenGlDeviceSettings& settings);
void initializeSettings(const OpenGlDeviceSettings& settings);
void destroy();
};
}
}
#endif /* OPENGLDEVICE_H_ */
| 32.681481 | 138 | 0.81097 | [
"vector"
] |
65203d6ea637196c60c53c74ba88228dd943f798 | 1,591 | cpp | C++ | Leetcode/Subarrays with K Different Integers/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 205 | 2021-09-30T15:41:05.000Z | 2022-03-27T18:34:56.000Z | Leetcode/Subarrays with K Different Integers/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 566 | 2021-09-30T15:27:27.000Z | 2021-10-16T21:21:02.000Z | Leetcode/Subarrays with K Different Integers/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 399 | 2021-09-29T05:40:46.000Z | 2022-03-27T18:34:58.000Z | // In this,first we will find out subarrays with atleast k different integers,then to get subarrays with exactly k different integers we will
//use logic i.e. subarrays with atleast k different integers - subarrays with stleast k-1 different integers
class Solution {
public:
int atleast(vector<int>&nums , int k)
{
unordered_map<int,int>m; // map to store frequencies of diffent integers in a subarray
int diff = 0; // count of different integers in currently processing subarray
int total = 0;
int l = 0; // left index
int r = 0; // right index
int n = nums.size();
for(;r<n;r++)
{
if(m[nums[r]] == 0) // if a integer is not already present in map then increment value of diff.
{
diff++;
}
m[nums[r]]++; // Storing frequency of integer
if(diff<=k)
{
total+=(r-l+1); // r-l+1 => no. of all possible subarrays with right and left index
}
else
{
while(l<=r && diff > k) // if no. of different integers becomes greater than k , then i will simply move left towards right
{
m[nums[l]]--; //Decrementing frequency of integer present at left index;
if(m[nums[l]] == 0)diff--; // if decrementing makes frequency of that integer = 0 , then diff = diff -1 ;
l++;
}
total+=(r-l+1);
}
}
return total; //Returning Total number of subarrays having atleast k different integers.
}
int subarraysWithKDistinct(vector<int>& nums, int k) {
return atleast(nums,k) - atleast(nums,k-1);
}
};
// Time Complexity = O(n);
// Spce Complexity = O(n): As , we are using the map
| 34.586957 | 141 | 0.640478 | [
"vector"
] |
6527e7fe010de0f4aa5d635c1bfd7cfe95a4fb82 | 3,876 | hpp | C++ | src/multi_cg/multi_cg.hpp | simonpp/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | 1 | 2019-05-10T08:48:55.000Z | 2019-05-10T08:48:55.000Z | src/multi_cg/multi_cg.hpp | simonpintarelli/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | null | null | null | src/multi_cg/multi_cg.hpp | simonpintarelli/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | null | null | null | #ifndef MULTICG_
#define MULTICG_
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iostream>
#include <complex>
namespace sirius {
namespace cg {
template <class T>
void repack(std::vector<T> &data, std::vector<size_t> const&ids) {
for (size_t i = 0; i < ids.size(); ++i) {
data[i] = data[ids[i]];
}
}
template<class Matrix, class Prec, class StateVec>
std::vector<std::vector<typename StateVec::value_type>> multi_cg(
Matrix &A, Prec &P, StateVec &X, StateVec &B, StateVec &U, StateVec &C,
size_t maxiters = 10, double tol = 1e-3, bool initial_guess_is_zero = false
) {
auto n = X.cols();
U.fill(0);
// Use R for residual, we modify the right-hand side B in-place.
auto &R = B;
// Use B effectively as the residual block-vector
// R = B - A * X -- don't multiply when initial guess is zero.
if (!initial_guess_is_zero)
A.multiply(-1.0, X, 1.0, R, n);
auto rhos = std::vector<typename StateVec::value_type>(n);
auto rhos_old = rhos;
auto sigmas = rhos;
auto alphas = rhos;
// When vectors converge we move them to the front, but we can't really do
// that with X, so we have to keep track of where is what.
auto ids = std::vector<size_t>(n);
std::iota(ids.begin(), ids.end(), 0);
size_t num_unconverged = n;
auto residual_history = std::vector<std::vector<typename StateVec::value_type>>(n);
for (size_t iter = 0; iter < maxiters; ++iter) {
// Check the residual norms in the P-norm
// that means whenever P is approximately inv(A)
// since (r, Pr) = (Ae, PAe) ~= (e, Ae)
// we check the errors roughly in the A-norm.
// When P = I, we just check the residual norm.
// C = P * R.
P.apply(C, R);
rhos_old = rhos;
// rhos = dot(C, R)
C.block_dot(R, rhos, num_unconverged);
for (size_t i = 0; i < num_unconverged; ++i) {
residual_history[ids[i]].push_back(std::sqrt(std::abs(rhos[i])));
}
auto not_converged = std::vector<size_t>{};
for (size_t i = 0; i < num_unconverged; ++i) {
if (std::abs(rhos[i]) > tol * tol) {
not_converged.push_back(i);
}
}
num_unconverged = not_converged.size();
if (not_converged.empty()) {
break;
}
// Move everything contiguously to the front,
// except for X, since that's updated in-place.
repack(ids, not_converged);
repack(rhos, not_converged);
repack(rhos_old, not_converged);
U.repack(not_converged);
C.repack(not_converged);
R.repack(not_converged);
A.repack(not_converged);
P.repack(not_converged);
// In the first iteration we have U == 0, so no need for an axpy.
if (iter == 0) {
U.copy(C, num_unconverged);
} else {
for (size_t i = 0; i < num_unconverged; ++i) {
alphas[i] = rhos[i] / rhos_old[i];
}
// U[:, i] = C[:, i] + alpha[i] * U[:, i] for i < num_unconverged
U.block_xpby(C, alphas, num_unconverged);
}
// C = A * U.
A.multiply(1.0, U, 0.0, C, num_unconverged);
// compute the optimal distance for the search direction
// sigmas = dot(U, C)
U.block_dot(C, sigmas, num_unconverged);
// Update the solution and the residual
for (size_t i = 0; i < num_unconverged; ++i) {
alphas[i] = rhos[i] / sigmas[i];
}
// X[:, ids[i]] += alpha[i] * U[:, i]
X.block_axpy_scatter(alphas, U, ids);
for (size_t i = 0; i < num_unconverged; ++i) {
alphas[i] *= -1;
}
R.block_axpy(alphas, C, num_unconverged);
}
return residual_history;
}
}
}
#endif | 28.5 | 87 | 0.561662 | [
"vector"
] |
652b93e6cb9b4613fd809b60918b1744fbdaca1a | 2,201 | cpp | C++ | cpp/euler032/euler032.cpp | marvins/ProjectEuler | 55a377bb9702067bac6908c1316c578498402668 | [
"MIT"
] | null | null | null | cpp/euler032/euler032.cpp | marvins/ProjectEuler | 55a377bb9702067bac6908c1316c578498402668 | [
"MIT"
] | null | null | null | cpp/euler032/euler032.cpp | marvins/ProjectEuler | 55a377bb9702067bac6908c1316c578498402668 | [
"MIT"
] | 1 | 2020-12-16T09:25:19.000Z | 2020-12-16T09:25:19.000Z | /**
* @file euler032.cpp
* @author Marvin Smith
* @date 5/2/2015
*/
// C++ Standard Libraries
#include <cinttypes>
#include <iostream>
#include <set>
#include <vector>
// Common Libraries
#include "../common/Permutation_Engine.hpp"
#include "../common/StringUtilities.hpp"
using namespace std;
/**
* @brief Check if values are pandigital
*/
bool Is_Pandigital( const int64_t& value01,
const int64_t& value02,
const int64_t& value03 )
{
// Convert all to strings
std::string val_str_01 = num2str( value01 );
std::string val_str_02 = num2str( value02 );
std::string val_str_03 = num2str( value03 );
// Check the size
int val_size = val_str_01.size() + val_str_02.size() + val_str_03.size();
if( val_size != 9 ){
return false;
}
// Create histogram
std::vector<bool> histogram(10, false);
// Check each value
for( int i=0; i<(int)val_str_01.size(); i++ )
histogram[val_str_01[i]-'0'] = true;
for( int i=0; i<(int)val_str_02.size(); i++ )
histogram[val_str_02[i]-'0'] = true;
for( int i=0; i<(int)val_str_03.size(); i++ )
histogram[val_str_03[i]-'0'] = true;
// Check if there are any false values
for( int i=1; i<(int)histogram.size(); i++ )
if( histogram[i] == false )
return false;
return true;
}
/**
* @brief Main Functions
*/
int main( int argc, char* argv[] )
{
// Sum value
int64_t sum = 0;
int64_t max_a = 2000;
int64_t max_b = 2000;
int64_t product;
std::set<int32_t> dictionary;
// Iterate over value range
for( int64_t a=0; a<max_a; a++ )
for( int64_t b=0; b<max_b; b++ ){
// Set the product
product = a * b;
// Check if pandigital
if( Is_Pandigital( a, b, product) == true ){
// Check if the sum as been posted to the dictionary
if( dictionary.find(product) == dictionary.end() ){
dictionary.insert(product);
sum += product;
}
}
}
// Print the sum
std::cout << sum << std::endl;
// Exit Program
return 0;
}
| 22.927083 | 77 | 0.562017 | [
"vector"
] |
6534667da9bb014b480f4f5f82191bd65c0d12a6 | 36,065 | cpp | C++ | main.cpp | M-Mabrouk/MiniRaster | fbf3cbb3790762c9abc21c88ae7715e76980e927 | [
"MIT"
] | null | null | null | main.cpp | M-Mabrouk/MiniRaster | fbf3cbb3790762c9abc21c88ae7715e76980e927 | [
"MIT"
] | null | null | null | main.cpp | M-Mabrouk/MiniRaster | fbf3cbb3790762c9abc21c88ae7715e76980e927 | [
"MIT"
] | null | null | null | #if defined(UNICODE) && !defined(_UNICODE)
#define _UNICODE
#elif defined(_UNICODE) && !defined(UNICODE)
#define UNICODE
#endif
#include "menuHeader.h"
#include <bits/stdc++.h>
#include <tchar.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <stack>
#include <queue>
#include <string>
using namespace std;
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
TCHAR szClassName[ ] = _T("LineWindow");
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nCmdShow)
{
HWND hwnd;
MSG messages;
WNDCLASSEX wincl;
wincl.hInstance = hThisInstance; // Handle to the application instance
wincl.lpszClassName = szClassName; // The name of the window class to identify it
wincl.lpfnWndProc = WindowProcedure; // The window procedure method name (pointer to the window procedure)
wincl.style = CS_DBLCLKS; /* Catch double-clicks */ // CS* is the class style
wincl.cbSize = sizeof (WNDCLASSEX); // The size of the stucture
/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION); // The large icon shown for the window when the user presses ALT+TAB
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);// The small icon shown in the task bar for this window
wincl.hCursor = LoadCursor (NULL, IDC_ARROW); // the cursor used (IDC_ARROW) the standard arrow cursor
wincl.lpszMenuName = NULL; // The name of a menu resource to be used for the window (no menu in our case)
wincl.cbClsExtra = 0; // Amount of extra data allocated for this class in memory. Usually 0.
wincl.cbWndExtra = 0; // Amount of extra data allocated in memory per window of this type. Usually 0.
/* Use Windows's default colour as the background of the window */
wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND; // The background brush to set background color for the window GetStockObject(WHITE_BRUSH);
/* Register the window class, and if it fails quit the program */
// Register the window class to be able to associate it with windows
if (!RegisterClassEx (&wincl))
return 0;
HMENU menu = LoadMenu(NULL, MAKEINTRESOURCE(MENU_ID));
hwnd = CreateWindowEx (
0,//WS_EX_CLIENTEDGE, // Window style for borders
szClassName, // Name of the class registered above for windows of this app
_T("Project"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
544,
375,
HWND_DESKTOP,
menu,
hThisInstance,
NULL
);
ShowWindow (hwnd, nCmdShow);
while (GetMessage (&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
}
int Round(double v)
{
return (int)(v + 0.5);
}
void Swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void drawLine(HDC hdc, int xs, int ys, int xe, int ye)
{
COLORREF color = RGB(0, 0, 0);
int x, y;
int dx = xe - xs;
int dy = ye - ys;
double dt = 1.0/sqrt(dx*dx + dy*dy);
for(double t = 0 ; t <=1 ; t+= dt)
{
x = Round(xs + t*dx);
y = Round(ys + t*dy);
SetPixel(hdc, x, y, color);
}
}
void drawDDA(HDC hdc, int xs, int ys, int xe, int ye) {
COLORREF color = RGB(0,0,0);
int dx = xe - xs;
int dy = ye - ys;
if(abs(dy) <= abs(dx))
{
if(dx < 0)
{
Swap(xe,xs);
Swap(ye,ys);
dx = -dx;
dy = -dy;
}
double m = 0;
if(dx != 0)
{
m = (double)dy/dx;
}
SetPixel(hdc,xs,ys,color);
int x = xs;
double y = (double)ys;
while(x<xe)
{
x += 1 ;
y += m ;
SetPixel(hdc,x,Round(y),color);
}
}
else
{
if(dy < 0)
{
Swap(xe,xs);
Swap(ye,ys);
dx = -dx;
dy = -dy;
}
double m = 0;
double change = 0;
if(dx != 0)
{
m = (double)dy/dx;
change = 1.0/m;
}
SetPixel(hdc,xs,ys,color);
int y = ys;
double x = (double)xs;
while(y<ye)
{
y += 1 ;
x += change ;
SetPixel(hdc,Round(x),y,color);
}
}
}
void drawLineMidpoint(HDC hdc, int xs, int ys, int xe, int ye) {
COLORREF color = RGB(0,0,0);
int dx = xe - xs;
int dy = ye - ys;
if(abs(dy) <= abs(dx))
{
if(dx < 0)
{
Swap(xe,xs);
Swap(ye,ys);
dx = -dx;
dy = -dy;
}
int d = dx - abs(2*dy) ;
int changeNeg = 2*dx - abs(2*dy);
int changePos = -2*abs(dy) ;
SetPixel(hdc,xs,ys,color);
int x = xs;
int y = ys;
while(x<xe)
{
x++;
if(d<=0)
{
d+=changeNeg;
if(dy<=0)
y-=1;
else
y+=1;
}
else
{
d+=changePos;
}
SetPixel(hdc,x,y,color);
}
}
else
{
if(dy < 0)
{
Swap(ye,ys);
Swap(xe,xs);
dy = -dy;
dx = -dx;
}
int d = dy - abs(2*dx) ;
int changeNeg = 2*dy - abs(2*dx);
int changePos = -2*abs(dx) ;
SetPixel(hdc,xs,ys,color);
int y = ys;
int x = xs;
while(y<ye)
{
y++;
if(d<=0)
{
d+=changeNeg;
if(dx<=0)
x-=1;
else
x+=1;
}
else
{
d+=changePos;
}
SetPixel(hdc,x,y,color);
}
}
}
double Length(POINT a, POINT b)
{
double dx = b.x - a.x;
double dy = b.y - a.y;
return sqrt(dx*dx + dy*dy);
}
void drawPolygon(HDC hdc, vector<int> items)
{
for(int i = 3 ; i < items.size() ; i+= 2)
{
drawLineMidpoint(hdc, items[i-3], items[i-2], items[i-1], items[i]);
}
if(items.size())
drawLineMidpoint(hdc, items[0], items[1], items[items.size()-2], items[items.size()-1]);
}
void draw8Points(HDC hdc, int x, int y, int xc, int yc)
{
COLORREF color = RGB(0,0,0);
SetPixel(hdc, x+xc, y+yc, color);
SetPixel(hdc, -x+xc, y+yc, color);
SetPixel(hdc, x+xc, -y+yc, color);
SetPixel(hdc, -x+xc, -y+yc, color);
SetPixel(hdc, y+xc, x+yc, color);
SetPixel(hdc, -y+xc, x+yc, color);
SetPixel(hdc, y+xc, -x+yc, color);
SetPixel(hdc, -y+xc, -x+yc, color);
}
void drawCircleCartesian(HDC hdc, int xc, int yc, int xe, int ye)
{
int dx = xe-xc;
int dy = ye-yc;
int R = sqrt(dx*dx + dy*dy);
int x = 0, y = R;
draw8Points(hdc, x, y, xc, yc);
while(x<y)
{
x++;
y = sqrt(R*R - x*x);
draw8Points(hdc, x, y, xc, yc);
}
}
void drawCirclePolar(HDC hdc, int xc, int yc, int xe, int ye)
{
int dx = xe-xc;
int dy = ye-yc;
double R = sqrt(dx*dx + dy*dy);
double x = R;
double y = 0;
draw8Points(hdc, Round(x), Round(y), xc, yc);
double da = 1.0/R;
double c = cos(da);
double s = sin(da);
while(y < x)
{
double tempX = x*c - y*s;
y = x*s + y*c;
x = tempX;
draw8Points(hdc, Round(x), Round(y), xc, yc);
}
}
void drawCircleMidpoint(HDC hdc, int xc, int yc, int xe, int ye)
{
int dx = xe-xc;
int dy = ye-yc;
int R = sqrt(dx*dx + dy*dy);
int x = 0, y = R;
int d = 1 - R;
draw8Points(hdc, x, y, xc, yc);
while(x<y)
{
if(d<=0)
{
d += 2*x + 3;
}
else
{
d+= 2*(x-y) + 5;
y--;
}
x++;
draw8Points(hdc, x, y, xc, yc);
}
}
POINT makeP(int x, int y)
{
POINT point;
point.x = x;
point.y = y;
return point;
}
void drawHermite(HDC hdc, POINT s, POINT e, POINT cs, POINT ce)
{
COLORREF color = RGB(0, 0, 0);
int a0 = s.x;
int a1 = cs.x;
int a2 = -3*s.x + 3*e.x - 2*cs.x - ce.x;
int a3 = 2*s.x - 2*e.x + cs.x + ce.x;
int b0 = s.y;
int b1 = cs.y;
int b2 = -3*s.y + 3*e.y - 2*cs.y - ce.y;
int b3 = 2*s.y - 2*e.y + cs.y + ce.y;
int x, y;
double length = Length(s, cs) + Length(cs, ce) + Length(ce, e) + Length(s, e);
length /= 2;
double dt = 1.0/length;
for(double t = 0 ; t <=1 ; t+= dt)
{
x = Round(a0 + a1*t + a2*t*t + a3*t*t*t);
y = Round(b0 + b1*t + b2*t*t + b3*t*t*t);
SetPixel(hdc, x, y, color);
}
}
void drawBezier(HDC hdc, POINT s, POINT e, POINT cs, POINT ce)
{
COLORREF color = RGB(0, 0, 0);
int a0 = s.x;
int a1 = -3*s.x + 3*cs.x;
int a2 = 3*s.x - 6*cs.x + 3*ce.x;
int a3 = -s.x + 3*cs.x - 3*ce.x + e.x;
int b0 = s.y;
int b1 = -3*s.y + 3*cs.y;
int b2 = 3*s.y - 6*cs.y + 3*ce.y;
int b3 = -s.y + 3*cs.y - 3*ce.y + e.y;
int x, y;
double length = Length(s, cs) + Length(cs, ce) + Length(ce, e) + Length(s, e);
length /= 2;
double dt = 1.0/length;
for(double t = 0 ; t <=1 ; t+= dt)
{
x = Round(a0 + a1*t + a2*t*t + a3*t*t*t);
y = Round(b0 + b1*t + b2*t*t + b3*t*t*t);
SetPixel(hdc, x, y, color);
}
}
bool InRange(int x, int y, int width, int height)
{
return (x > -1 && x < width && y > -1 && y < height);
}
void dfsFill(HWND hwnd, HDC hdc, int xs, int ys)
{
COLORREF background = GetPixel(hdc, xs, ys);
COLORREF border = RGB(0,0,0);
stack<POINT> points ;
POINT point = makeP(xs, ys);
points.push(point);
RECT rect;
int width, height;
if(GetClientRect(hwnd, &rect))
{
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
else
{
return;
}
while(!points.empty())
{
point = points.top();
points.pop();
if(!InRange(point.x, point.y, width, height)) continue;
if(GetPixel(hdc, point.x, point.y) == border) continue;
SetPixel(hdc, point.x, point.y, border);
if(InRange(point.x+1, point.y, width, height))
if(GetPixel(hdc, point.x+1, point.y) != border)
points.push(makeP(point.x+1, point.y));
if(InRange(point.x-1, point.y, width, height))
if(GetPixel(hdc, point.x-1, point.y) != border)
points.push(makeP(point.x-1, point.y));
if(InRange(point.x, point.y+1, width, height))
if(GetPixel(hdc, point.x, point.y+1) != border)
points.push(makeP(point.x, point.y+1));
if(InRange(point.x, point.y-1, width, height))
if(GetPixel(hdc, point.x, point.y-1) != border)
points.push(makeP(point.x, point.y-1));
}
}
void bfsFill(HWND hwnd, HDC hdc, int xs, int ys)
{
COLORREF background = GetPixel(hdc, xs, ys);
COLORREF border = RGB(0,0,0);
queue<POINT> points ;
POINT point = makeP(xs, ys);
points.push(point);
while(!points.empty())
{
RECT rect;
int width, height;
if(GetClientRect(hwnd, &rect))
{
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
else
{
return;
}
point = points.front();
points.pop();
if(!InRange(point.x, point.y, width, height)) continue;
if(GetPixel(hdc, point.x, point.y) == border) continue;
SetPixel(hdc, point.x, point.y, border);
points.push(makeP(point.x+1, point.y));
points.push(makeP(point.x-1, point.y));
points.push(makeP(point.x, point.y+1));
points.push(makeP(point.x, point.y-1));
}
}
vector <int> lines;
vector <vector<int> > polygons;
int xr, xl, yt, yb;
void drawClipper(HDC hdc, int xs, int ys, int xe, int ye)
{
xl = min(xs, xe);
xr = max(xs, xe);
yb = min(ys, ye);
yt = max(ys, ye);;
drawDDA(hdc, xl, yt, xl, yb);
drawDDA(hdc, xl, yt, xr, yt);
drawDDA(hdc, xl, yb, xr, yb);
drawDDA(hdc, xr, yt, xr, yb);
}
vector<string> getBounds(POINT p)
{
vector <string> vs;
if(p.x > xr)
{
vs.push_back("right");
}
if(p.y > yt)
{
vs.push_back("top");
}
if(p.x < xl)
{
vs.push_back("left");
}
if(p.y < yb)
{
vs.push_back("bottom");
}
return vs;
}
double getSlope(POINT s, POINT e)
{
int dx = e.x - s.x;
int dy = e.y - s.y;
double m = 0;
if(dx != 0)
{
m = (double)dy/dx;
}
return m;
}
POINT intersection(POINT s, POINT e, POINT Line)
{
double slope = getSlope(s, e);
if(Line.x == 0)
{
Line.x = (Line.y - s.y)/slope + s.x;
}
if(Line.y == 0)
{
Line.y = (Line.x - s.x)*slope + s.y;
}
return Line;
}
POINT correctEnds(POINT s, POINT e, vector<string> vs)
{
if(!vs.size())return s;
POINT ret = s;
string intersec = vs[0];
if(intersec == "top")
ret = intersection(s, e, makeP(0, yt));
if(intersec == "bottom")
ret = intersection(s, e, makeP(0, yb));
if(intersec == "right")
ret = intersection(s, e, makeP(xr, 0));
if(intersec == "left")
ret = intersection(s, e, makeP(xl, 0));
return ret;
}
void drawClipLine(HDC hdc, int xs, int ys, int xe, int ye)
{
POINT Start = makeP(xs,ys);
POINT End = makeP(xe,ye);
vector<string> sBound = getBounds(Start);
vector<string> eBound = getBounds(End);
if(!sBound.size() && !eBound.size())
{
drawLineMidpoint(hdc, xs, ys, xe, ye);
return;
}
for(int i = 0 ; i < sBound.size() ; i++)
{
for(int j = 0 ; j < eBound.size() ; j++)
{
if(sBound[i] == eBound[j]) return;
}
}
Start = correctEnds(Start, End, sBound);
End = correctEnds(End, Start, eBound);
drawClipLine(hdc, Start.x, Start.y, End.x, End.y);
}
bool inside(int x, int y, string side)
{
if(side == "top")
{
return y <= yt;
}
if(side == "right")
{
return x <= xr;
}
if(side == "left")
{
return xl <= x;
}
if(side == "bottom")
{
return yb <= y;
}
}
vector<int> ClipSide(vector <int> polys, string side)
{
vector<int> out;
vector<string> sideV;
sideV.push_back(side);
for(int i = 3 ; i < polys.size() ; i+=2)
{
if(!inside(polys[i-3], polys[i-2], side) && inside(polys[i-1], polys[i], side))
{
POINT p = correctEnds(makeP(polys[i-3], polys[i-2]), makeP(polys[i-1], polys[i]), sideV);
out.push_back(p.x);
out.push_back(p.y);
out.push_back(polys[i-1]);
out.push_back(polys[i]);
}
if(inside(polys[i-3], polys[i-2], side) && inside(polys[i-1], polys[i], side))
{
out.push_back(polys[i-1]);
out.push_back(polys[i]);
}
if(inside(polys[i-3], polys[i-2], side) && !inside(polys[i-1], polys[i], side))
{
POINT p = correctEnds(makeP(polys[i-3], polys[i-2]), makeP(polys[i-1], polys[i]), sideV);
out.push_back(p.x);
out.push_back(p.y);
}
}
if(polys.size() > 2)
{
POINT p = correctEnds( makeP(polys[polys.size()-2], polys[polys.size()-1]),makeP(polys[0], polys[1]), sideV);
if(inside(polys[0], polys[1], side) && !inside(polys[polys.size()-2], polys[polys.size()-1], side))
{
out.push_back(p.x);
out.push_back(p.y);
out.push_back(polys[0]);
out.push_back(polys[1]);
}
if(inside(polys[0], polys[1], side) && inside(polys[polys.size()-2], polys[polys.size()-1], side))
{
out.push_back(polys[0]);
out.push_back(polys[1]);
}
if(!inside(polys[0], polys[1], side) && inside(polys[polys.size()-2], polys[polys.size()-1], side))
{
out.push_back(p.x);
out.push_back(p.y);
}
}
return out;
}
void drawClipPoly(HDC hdc, vector<int> polys)
{
vector<int> out;
out = ClipSide(polys, "top");
out = ClipSide(out, "bottom");
out = ClipSide(out, "right");
out = ClipSide(out, "left");
drawPolygon(hdc, out);
}
string toString(int n)
{
string out = "";
while(n)
{
out = (char)('0'+(n%10)) + out ;
n/=10;
}
if(out == "")
{
out = "0";
}
return out;
}
string operations = "";
int drawn = 0;
vector<int> xy;
void Save(HWND hwnd)
{
RECT rect;
HDC hdc = GetDC(hwnd);
GetClientRect(hwnd, &rect);
OPENFILENAME ofn; // common dialog box structure
char szFile[260];
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Page\0*.PG\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT;
COLORREF border = RGB(0,0,0);
int width, height;
if(GetClientRect(hwnd, &rect))
{
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
else
{
return;
}
operations = toString(drawn) + "\n" + operations;
operations += "\0";
if(GetSaveFileName(&ofn)==FALSE)return;
ofstream file;
file.open(ofn.lpstrFile, ios::trunc|ios::binary);
file.write(operations.c_str(), operations.size());
file.close();
ReleaseDC(hwnd, hdc);
InvalidateRect(hwnd,NULL,FALSE);
}
int toInt(string s)
{
int ret = 0;
int i = 0;
while(i < s.size())
{
ret = ret*10 + (int)(s[i++]-'0');
}
return ret;
}
void Load(HWND hwnd)
{
OPENFILENAME ofn; // common dialog box structure
char szFile[260]; // buffer for file name
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Page\0*.PG\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==FALSE)return;
ifstream file;
file.open(ofn.lpstrFile, ios::binary);
int drawn ;
file >> drawn;
RECT rect;
HDC hdc = GetDC(hwnd);
GetClientRect(hwnd, &rect);
int width, height;
if(GetClientRect(hwnd, &rect))
{
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
else
{
return;
}
int i = 0;
int Xs, Ys, Xe, Ye;
int cXs, cYs, cXe, cYe;
int OP;
while(drawn--)
{
file >> OP;
if(OP == 1)
{
file >> Xs >> Ys >> Xe >> Ye;
lines.push_back(Xs);
lines.push_back(Ys);
lines.push_back(Xe);
lines.push_back(Ye);
drawLine(hdc, Xs, Ys, Xe, Ye);
}
if(OP == 2)
{
file >> Xs >> Ys >> Xe >> Ye;
lines.push_back(Xs);
lines.push_back(Ys);
lines.push_back(Xe);
lines.push_back(Ye);
drawDDA(hdc, Xs, Ys, Xe, Ye);
}
if(OP == 3)
{
file >> Xs >> Ys >> Xe >> Ye;
lines.push_back(Xs);
lines.push_back(Ys);
lines.push_back(Xe);
lines.push_back(Ye);
drawLineMidpoint(hdc, Xs, Ys, Xe, Ye);
}
if(OP == 4)
{
file >> Xs >> Ys >> Xe >> Ye;
drawCircleCartesian(hdc, Xs, Ys, Xe, Ye);
}
if(OP == 5)
{
file >> Xs >> Ys >> Xe >> Ye;
drawCirclePolar(hdc, Xs, Ys, Xe, Ye);
}
if(OP == 6)
{
file >> Xs >> Ys >> Xe >> Ye;
drawCircleMidpoint(hdc, Xs, Ys, Xe, Ye);
}
if(OP == 7)
{
file >> Xs >> Ys;
bfsFill(hwnd, hdc, Xs, Ys);
}
if(OP == 8)
{
file >> Xs >> Ys;
dfsFill(hwnd,hdc, Xs, Ys);
}
if(OP == 9)
{
xy.clear();
int s;
file >> s;
while(s)
{
file >> Xs >> Ys;
xy.push_back(Xs);
xy.push_back(Ys);
s-=2;
}
polygons.push_back(xy);
drawPolygon(hdc, xy);
xy.clear();
}
if(OP == 10)
{
file >> Xs >> Ys >> Xe >> Ye;
file >> cXs >> cYs >> cXe >> cYe;
drawBezier(hdc, makeP(Xs, Ys), makeP(Xe, Ye), makeP(cXs, cYs), makeP(cXe, cYe));
}
if(OP == 11)
{
file >> Xs >> Ys >> Xe >> Ye;
file >> cXs >> cYs >> cXe >> cYe;
drawHermite(hdc, makeP(Xs, Ys), makeP(Xe, Ye), makeP(cXs, cYs), makeP(cXe, cYe));
}
}
ReleaseDC(hwnd, hdc);
InvalidateRect(hwnd,NULL,FALSE);
file.close();
}
int xs, ys, xe, ye;
int cxs, cys, cxe, cye;
bool pointSet = false;
bool draw = false;
bool Fill = false;
bool drawPoly = false;
bool Curve = false;
bool Line, ddaLine, mLine, cCircle, mCircle, pCircle, dFill, bFill, hCurve, bCurve, clipLine, clipPoly, Poly;
int item;
int curveC = 0;
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT p;
int x, y;
switch (message)
{
case WM_COMMAND:
item = LOWORD(wParam);
switch(item)
{
case EXIT_ID:
PostQuitMessage(0);
break;
case LINE:
ddaLine = false;
mLine = false;
mCircle = false;
cCircle = false;
dFill = false;
bFill = false;
clipLine = false;
Line = true;
Poly = false;
clipPoly = false;
pCircle = false;
hCurve = false;
bCurve = false;
break;
case DDA:
ddaLine = true;
mLine = false;
mCircle = false;
cCircle = false;
dFill = false;
bFill = false;
Line = false;
Poly = false;
clipLine = false;
pCircle = false;
clipPoly = false;
hCurve = false;
bCurve = false;
break;
case MIDPOINT_LINE:
ddaLine = false;
mLine = true;
mCircle = false;
cCircle = false;
dFill = false;
bFill = false;
Line = false;
Poly = false;
clipPoly = false;
hCurve = false;
bCurve = false;
clipLine = false;
pCircle = false;
break;
case MIDPOINT_CIRCLE:
ddaLine = false;
mLine = false;
mCircle = true;
cCircle = false;
dFill = false;
hCurve = false;
bCurve = false;
bFill = false;
Line = false;
clipPoly = false;
Poly = false;
pCircle = false;
clipLine = false;
break;
case CARTESIAN_CIRCLE:
ddaLine = false;
mLine = false;
mCircle = false;
cCircle = true;
dFill = false;
clipPoly = false;
bFill = false;
hCurve = false;
bCurve = false;
Line = false;
Poly = false;
pCircle = false;
clipLine = false;
break;
case POLAR_CIRCLE:
ddaLine = false;
mLine = false;
mCircle = false;
clipPoly = false;
cCircle = false;
dFill = false;
hCurve = false;
bCurve = false;
bFill = false;
Line = false;
Poly = false;
pCircle = true;
clipLine = false;
break;
case DFS:
ddaLine = false;
mLine = false;
mCircle = false;
cCircle = false;
clipPoly = false;
dFill = true;
bFill = false;
Line = false;
hCurve = false;
bCurve = false;
Poly = false;
pCircle = false;
clipLine = false;
break;
case BFS:
ddaLine = false;
mLine = false;
mCircle = false;
cCircle = false;
dFill = false;
bFill = true;
clipPoly = false;
pCircle = false;
hCurve = false;
bCurve = false;
Line = false;
Poly = false;
clipLine = false;
break;
case HERMITE:
ddaLine = false;
mLine = false;
mCircle = false;
cCircle = false;
dFill = false;
hCurve = true;
bCurve = false;
clipPoly = false;
bFill = false;
Line = false;
Poly = false;
pCircle = false;
clipLine = false;
break;
case BEZIER:
ddaLine = false;
mLine = false;
mCircle = false;
hCurve = false;
bCurve = true;
clipPoly = false;
cCircle = false;
dFill = false;
bFill = false;
pCircle = false;
Line = false;
Poly = false;
clipLine = false;
break;
case POLYGON:
ddaLine = false;
pCircle = false;
mLine = false;
mCircle = false;
clipPoly = false;
hCurve = false;
bCurve = false;
cCircle = false;
dFill = false;
bFill = false;
Line = false;
Poly = true;
clipLine = false;
break;
case SAVE_ID:
Save(hwnd);
break;
case LOAD_ID:
InvalidateRect(hwnd,NULL,TRUE);
Load(hwnd);
break;
case CLIP_LINE:
ddaLine = false;
pCircle = false;
mLine = false;
mCircle = false;
hCurve = false;
bCurve = false;
cCircle = false;
dFill = false;
bFill = false;
clipPoly = false;
Line = false;
Poly = false;
clipLine = true;
break;
case CLIP_POLY:
ddaLine = false;
pCircle = false;
mLine = false;
mCircle = false;
hCurve = false;
bCurve = false;
cCircle = false;
dFill = false;
bFill = false;
Line = false;
Poly = false;
clipLine = false;
clipPoly = true;
break;
}
case WM_PAINT:
BeginPaint(hwnd, &p);
if(draw)
{
draw = false;
drawn++;
if(Line)
{
lines.push_back(xs);
lines.push_back(ys);
lines.push_back(xe);
lines.push_back(ye);
drawLine(p.hdc, xs, ys, xe, ye);
operations += "1\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
}
if(ddaLine)
{
lines.push_back(xs);
lines.push_back(ys);
lines.push_back(xe);
lines.push_back(ye);
drawDDA(p.hdc, xs, ys, xe, ye);
operations += "2\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
}
if(mLine)
{
lines.push_back(xs);
lines.push_back(ys);
lines.push_back(xe);
lines.push_back(ye);
drawLineMidpoint(p.hdc, xs, ys, xe, ye);
operations += "3\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
}
if(cCircle)
{
drawCircleMidpoint(p.hdc, xs, ys, xe, ye);
operations += "4\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
}
if(pCircle)
{
drawCirclePolar(p.hdc, xs, ys, xe, ye);
operations += "5\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
}
if(mCircle)
{
drawCircleCartesian(p.hdc, xs, ys, xe, ye);
operations += "6\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
}
if(drawPoly)
{
drawPoly = false;
operations += "9\n";
operations += toString(xy.size()) + "\n";
for(int i = 1 ; i < xy.size() ; i+=2)
{
operations += toString(xy[i-1]) + "\n" + toString(xy[i]) + "\n";
}
drawPolygon(p.hdc, xy);
polygons.push_back(xy);
xy.clear();
}
if(clipLine)
{
drawClipper(p.hdc, xs, ys, xe, ye);
for(int i = 3 ; i < lines.size() ; i+=4)
{
drawClipLine(p.hdc, lines[i-3], lines[i-2], lines[i-1], lines[i]);
}
}
if(clipPoly)
{
drawClipper(p.hdc, xs, ys, xe, ye);
for(int i = 0 ; i < polygons.size() ; i++)
{
drawClipPoly(p.hdc, polygons[i]);
}
}
}
if(Fill)
{
Fill = false;
if(bFill)
{
drawn++;
bfsFill(hwnd, p.hdc, xs, ys);
operations += "7\n" + toString(xs) + "\n" + toString(ys) + "\n";
pointSet = false;
}
if(dFill)
{
drawn++;
dfsFill(hwnd, p.hdc, xs, ys);
operations += "8\n" + toString(xs) + "\n" + toString(ys) + "\n";
pointSet = false;
}
}
if(Curve)
{
drawn++;
Curve = false;
if(bCurve)
{
drawBezier(p.hdc, makeP(xs, ys), makeP(xe, ye), makeP(cxs, cys), makeP(cxe, cye));
operations += "10\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
operations += toString(cxs) + "\n" + toString(cys) + "\n" + toString(cxe) + "\n" + toString(cye) + "\n";
}
if(hCurve)
{
drawHermite(p.hdc, makeP(xs, ys), makeP(xe, ye), makeP(cxs, cys), makeP(cxe, cye));
operations += "11\n" + toString(xs) + "\n" + toString(ys) + "\n" + toString(xe) + "\n" + toString(ye) + "\n";
operations += toString(cxs) + "\n" + toString(cys) + "\n" + toString(cxe) + "\n" + toString(cye) + "\n";
}
}
EndPaint(hwnd, &p);
break;
case WM_LBUTTONDOWN:
x = LOWORD(lParam);
y = HIWORD(lParam);
if(Poly)
{
xy.push_back(x);
xy.push_back(y);
}
if(pointSet)
{
if((bCurve || hCurve) && curveC == 3)
{
cxe = x;
cye = y;
Curve = true;
}
else
{
xe = x;
ye = y;
}
draw = true;
pointSet = false;
Fill = true;
}
else
{
if((bCurve || hCurve) && curveC == 2)
{
cxs = x;
cys = y;
}
else
{
xs = x;
ys = y;
}
pointSet = true;
Fill = true;
}
curveC = (curveC+1)%4;
InvalidateRect(hwnd,NULL,(clipLine || clipPoly) && (!pointSet));
break;
case WM_RBUTTONDOWN:
if(Poly)
{
pointSet = false;
drawPoly = true;
draw = true;
InvalidateRect(hwnd,NULL,FALSE);
}
break;
case WM_DESTROY:
PostQuitMessage (0);
break;
default:
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}
| 28.131825 | 147 | 0.430362 | [
"vector"
] |
65372173c5c1fb4e9386dbe4a80325394a8e00d0 | 990 | cpp | C++ | sources/cards/creatures/blues/ElectroDragon.cpp | angeluriot/Magic_royal | a337ce4ad6c3215bbdec8c376d6e88fe97f48f94 | [
"MIT"
] | 1 | 2022-02-02T21:41:59.000Z | 2022-02-02T21:41:59.000Z | sources/cards/creatures/blues/ElectroDragon.cpp | angeluriot/Magic_royal | a337ce4ad6c3215bbdec8c376d6e88fe97f48f94 | [
"MIT"
] | null | null | null | sources/cards/creatures/blues/ElectroDragon.cpp | angeluriot/Magic_royal | a337ce4ad6c3215bbdec8c376d6e88fe97f48f94 | [
"MIT"
] | 2 | 2022-02-01T12:59:57.000Z | 2022-03-05T12:50:27.000Z | #include "cards/creatures/blues/ElectroDragon.hpp"
ElectroDragon::ElectroDragon(): Creature(get_full_power(), get_full_toughness(), get_capacities()) {}
ElectroDragon::~ElectroDragon() {}
std::string ElectroDragon::get_full_type() const
{
return Creature::get_full_type() + " - Dragon";
}
Card::Color ElectroDragon::get_color() const
{
return Color::Blue;
}
std::string ElectroDragon::get_name() const
{
return "Electro Dragon";
}
std::vector<Creature::Capacity> ElectroDragon::get_capacities() const
{
return
{
Capacity::Flying,
Capacity::Reach,
Capacity::Freeze
};
}
std::string ElectroDragon::get_description() const
{
return Creature::get_description() + "";
}
Card::Cost ElectroDragon::get_cost() const
{
return
{
{ Color::Colorless, 3 },
{ Color::Blue, 2 }
};
}
int ElectroDragon::get_full_power() const
{
return 4;
}
int ElectroDragon::get_full_toughness() const
{
return 3;
}
Card* ElectroDragon::clone() const
{
return new ElectroDragon(*this);
}
| 16.5 | 101 | 0.714141 | [
"vector"
] |
6537414c651d3a6679e1841b0da9149640acb7cf | 2,962 | cpp | C++ | src/imageprocessing/Threshold_inRange.cpp | snandasena/opencv-cpp-examples | 7423445d52f38fff80df37698b77ac9f9f5e7945 | [
"MIT"
] | null | null | null | src/imageprocessing/Threshold_inRange.cpp | snandasena/opencv-cpp-examples | 7423445d52f38fff80df37698b77ac9f9f5e7945 | [
"MIT"
] | 1 | 2020-04-28T03:35:49.000Z | 2020-04-28T03:35:49.000Z | src/imageprocessing/Threshold_inRange.cpp | snandasena/opencv-cpp-examples | 7423445d52f38fff80df37698b77ac9f9f5e7945 | [
"MIT"
] | null | null | null | #include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>
#include <iostream>
using namespace std;
using namespace cv;
const int max_value_H = 360 / 2;
const int max_value = 255;
const String window_capture_name = "Video Capture";
const String window_detection_name = "Object Detection";
int low_H = 0, low_S = 0, low_V = 0;
int high_H = max_value_H, high_S = max_value, high_V = max_value;
static void on_low_H_thresh_trackbar(int, void *) {
low_H = cv::min(high_H - 1, low_H);
cv::setTrackbarPos("Low H", window_detection_name, low_H);
}
static void on_high_H_thresh_trackbar(int, void *) {
high_H = cv::max(high_H, low_H + 1);
cv::setTrackbarPos("High H", window_detection_name, high_H);
}
static void on_low_S_thresh_trackbar(int, void *) {
low_S = cv::min(high_S - 1, low_S);
cv::setTrackbarPos("Low S", window_detection_name, low_S);
}
static void on_high_S_thresh_trackbar(int, void *) {
high_S = cv::max(high_S, low_S + 1);
cv::setTrackbarPos("High S", window_detection_name, high_S);
}
static void on_low_V_thresh_trackbar(int, void *) {
low_V = cv::min(high_V - 1, low_V);
cv::setTrackbarPos("Low V", window_detection_name, low_V);
}
static void on_high_V_thresh_trackbar(int, void *) {
high_V = cv::max(high_V, low_V + 1);
cv::setTrackbarPos("High V", window_detection_name, high_V);
}
int main(int argc, char *argv[]) {
cv::VideoCapture cap("./videos/mov_bbb.mp4");
cv::namedWindow(window_capture_name);
cv::namedWindow(window_detection_name);
// Trackbars to set thresholds for HSV values
cv::createTrackbar("Low H", window_detection_name, &low_H, max_value_H, on_low_H_thresh_trackbar);
cv::createTrackbar("High H", window_detection_name, &high_H, max_value_H, on_high_H_thresh_trackbar);
cv::createTrackbar("Low S", window_detection_name, &low_S, max_value, on_low_S_thresh_trackbar);
cv::createTrackbar("High S", window_detection_name, &high_S, max_value, on_high_S_thresh_trackbar);
cv::createTrackbar("Low V", window_detection_name, &low_V, max_value, on_low_V_thresh_trackbar);
cv::createTrackbar("High V", window_detection_name, &high_V, max_value, on_high_V_thresh_trackbar);
cv::Mat frame, frame_HSV, frame_threshold;
while (true) {
cap >> frame;
if (frame.empty()) {
break;
}
// convert from BGR to HSV colorspace
cv::cvtColor(frame, frame_HSV, cv::COLOR_BGR2HSV);
// detect the object based on HSV range values
cv::inRange(frame_HSV, cv::Scalar(low_H, low_S, low_V), cv::Scalar(high_H, high_S, high_V), frame_threshold);
// show the frames
cv::imshow(window_capture_name, frame);
cv::imshow(window_detection_name, frame_threshold);
auto key = (char) waitKey(30);
if (key == 'q' || key == 27) {
break;
}
}
return 0;
} | 32.911111 | 117 | 0.690412 | [
"object"
] |
653e5eed0873212678acf1be6b7d8bb851b69de5 | 3,817 | cpp | C++ | source/AlgebraicMethods/UTerm.cpp | CoghettoR/gclc | b481b15d28ee66f995b73283e26c285ca8c4a821 | [
"MIT"
] | 21 | 2020-12-08T20:06:01.000Z | 2022-02-13T22:52:02.000Z | source/AlgebraicMethods/UTerm.cpp | CoghettoR/gclc | b481b15d28ee66f995b73283e26c285ca8c4a821 | [
"MIT"
] | 9 | 2020-12-20T03:54:55.000Z | 2022-03-31T19:30:04.000Z | source/AlgebraicMethods/UTerm.cpp | CoghettoR/gclc | b481b15d28ee66f995b73283e26c285ca8c4a821 | [
"MIT"
] | 5 | 2021-04-25T18:47:17.000Z | 2022-01-23T02:37:30.000Z | #include "UTerm.h"
UTerm::UTerm(REAL coeff)
: _coeff(coeff)
{
COSTR("uterm");
}
void UTerm::Construct(REAL coeff)
{
_coeff = coeff;
COSTR("reused uterm");
}
UTerm::~UTerm()
{
DESTR("uterm");
}
void UTerm::Dispose()
{
_refCount --;
if (_refCount == 0)
{
#ifdef UTERMS_BANK
for (int ii = 0, size = _powers.size(); ii < size; ii++)
{
_powers[ii]->Dispose();
}
_powers.clear();
UTermsBank::UTermsFactory.ReleaseObject(this);
#else
delete this;
#endif
}
}
Term* UTerm::Clone()
{
#ifdef UTERMS_BANK
UTerm* utClone = UTermsBank::UTermsFactory.AcquireUTerm(this->GetCoeff());
#else
UTerm* utClone = new UTerm(this->GetCoeff());
#endif
uint count = this->GetPowerCount();
for (unsigned int ii = 0; ii < count; ii++)
{
Power* uwClone = this->GetPower(ii)->Clone();
utClone->AddPower(uwClone);
uwClone->Dispose();
}
return utClone;
}
TERM_TYPE UTerm::Type() const
{
return UTERM;
}
REAL UTerm::GetCoeff() const
{
return _coeff;
}
void UTerm::SetCoeff(REAL coeff)
{
_coeff = coeff;
}
//
// add on the end
// this method is used in deserialization
//
void UTerm::AddPower(Power* power)
{
power->AddRef();
_powers.push_back(power);
}
bool UTerm::IsUnit() const
{
return _powers.size() == 0 && _coeff == 1;
}
// aritmetic operations
// merge powers and mul coefficients
int UTerm::Mul(Term* t)
{
UTerm* ut = (UTerm*)t;
// coefficients are non-zero by design!
this->SetCoeff(this->GetCoeff() * ut->GetCoeff());
// merge powers
this->MergePowers(ut, true);
return 0;
}
// simple multiplication
// cannot mul with zero!
int UTerm::Mul(REAL r)
{
// coefficients are non-zero by design!
this->SetCoeff(this->GetCoeff() * r);
return 0;
}
// merge powers and divide coefficients
int UTerm::Divide(Term* t)
{
UTerm* ut = (UTerm*)t;
// coefficients are non-zero by design!
this->SetCoeff(this->GetCoeff() / ut->GetCoeff());
// merge powers
this->MergePowers(ut, false);
return 0;
}
//
// Negation
//
int UTerm::Inverse()
{
this->SetCoeff(- this->GetCoeff());
return 0;
}
// printing
//
// {coeff, UP1, UP2, ...}
void UTerm::PrettyPrint() const
{
Log::PrintLogF(0, "{");
Object::PrintREAL(_coeff);
Log::PrintLogF(0, ", ", _coeff);
uint size = this->GetPowerCount();
for (uint ii = 0; ii < size; ii++)
{
if (ii > 0)
{
Log::PrintLogF(0, ", ");
}
this->GetPower(ii)->PrettyPrint();
}
Log::PrintLogF(0, "}");
}
//
// multiplication of coeff and upowers
//
void UTerm::PrintLatex(StringBuilder* sb) const
{
if (this->GetPowerCount() == 0 || this->GetCoeff() * this->GetCoeff() != 1)
{
//Object::PrintREAL(this->GetCoeff());
sb->AddREAL(this->GetCoeff());
}
else if (this->GetCoeff() == -1)
{
//Log::PrintLogF(0, " - ");
sb->AddChar('-');
}
uint size = this->GetPowerCount();
for (uint ii = 0; ii < size; ii++)
{
this->GetPower(ii)->PrintLatex(sb);
}
}
int UTerm::Compare(Term* other) const
{
UTerm* ut = (UTerm*)other;
uint c1 = this->GetPowerCount();
uint c2 = ut->GetPowerCount();
uint ii = 0;
while (ii < c1 && ii < c2)
{
int cmp = this->GetPower(ii)->Compare(ut->GetPower(ii));
if (cmp != 0)
{
return cmp;
}
ii ++;
}
return (c1 < c2 ? -1 : (c1 > c2 ? 1 : 0));
}
//
// Merge with another term
// this is actualy Sum operation
//
void UTerm::Merge(Term* t)
{
UTerm* ut = (UTerm*)t;
// powers are same, must sum real coefficients
this->SetCoeff(this->GetCoeff() + ut->GetCoeff());
}
//
// check zeroness
//
bool UTerm::IsZero() const
{
// exact zero or in [-epsilon, epsilon] range
//return this->GetCoeff() == 0;
return fabs(this->GetCoeff()) < 0.000001;
}
| 17.040179 | 77 | 0.587634 | [
"object"
] |
653fb67fe2f2a5f8e21c12d788a2c444d2b676e5 | 3,268 | cpp | C++ | CPP/Space/src/shape3D.cpp | A-G-D/Jass-vJass-Resources | 9e5d3929c0651e9fa039e2c6c5dac9b6a4e22e46 | [
"MIT"
] | 1 | 2018-01-04T12:10:47.000Z | 2018-01-04T12:10:47.000Z | CPP/Space/src/shape3D.cpp | A-G-D/Libraries | 9e5d3929c0651e9fa039e2c6c5dac9b6a4e22e46 | [
"MIT"
] | null | null | null | CPP/Space/src/shape3D.cpp | A-G-D/Libraries | 9e5d3929c0651e9fa039e2c6c5dac9b6a4e22e46 | [
"MIT"
] | null | null | null | #include <cmath>
#include "vector3D.hpp"
#include "shape3D.hpp"
using namespace Space;
using namespace Space::Shape;
FLOAT GetObliqueComponentLength(VEC *u, VEC *v, VEC *w, FLOAT dx, FLOAT dy, FLOAT dz)
{
FLOAT
rx = v->x + w->x,
ry = v->y + w->y,
rz = v->z + w->z,
r = (dx*rx + dy*ry + dz*rz)/(rx*rx + ry*ry + rz*rz);
return (dx - r*rx)/u->x + (dy - r*ry)/u->y + (dz - r*rz)/u->z;
}
/*
* Space class definition
*/
#define __ Shape3D
void __::update(VEC *o, VEC *s)
{
this->__o = o;
this->__s = s;
}
void __::replace(VEC *o, VEC *s)
{
delete this->__o;
delete this->__s;
this->update(o, s);
}
inline VEC &__::o() const
{
return *this->__o;
}
inline VEC &__::s() const
{
return *this->__s;
}
inline __ &__::move(VEC const &v)
{
return this->move(v.x, v.y, v.z);
}
__ &__::move(FLOAT ox, FLOAT oy, FLOAT oz)
{
this->__s->update(ox, oy, oz);
return *this;
}
inline __ &__::scale(VEC const &v)
{
return this->scale(v.x, v.y, v.z);
}
inline __ &__::scale(FLOAT f)
{
return this->scale(f, f, f);
}
__ &__::scale(FLOAT a, FLOAT b, FLOAT c)
{
this->__s->scale(a, b, c);
return *this;
}
__ &__::orient(FLOAT xi, FLOAT xj, FLOAT xk, FLOAT yi, FLOAT yj, FLOAT yk, FLOAT zi, FLOAT zj, FLOAT zk)
{
this->Orientation::orient(xi, xj, xk, yi, yj, yk, zi, zj, zk);
this->__s->scale(sqrt(xi*xi + xj*xj + xk*xk), sqrt(yi*yi + yj*yj + yk*yk), sqrt(zi*zi + zj*zj + zk*zk));
return *this;
}
__ &__::operator=(__ const &shape)
{
this->Orientation::operator=(shape);
this->replace(new VEC(shape.o()), new VEC(shape.s()));
this->__state = shape.__state;
return *this;
}
__ &__::operator=(__ &&shape)
{
this->Orientation::operator=(shape);
this->replace(shape.__o, shape.__s);
this->__state = shape.__state;
shape.update(nullptr);
return *this;
}
bool __::operator==(__ const &shape)
{
return this->Orientation::operator==(shape) && this->o() == shape.o() && this->s() == shape.s();
}
inline bool __::operator!=(__ const &shape)
{
return !(this->operator==(shape));
}
__::__
(
FLOAT ox, FLOAT oy, FLOAT oz,
FLOAT xi, FLOAT xj, FLOAT xk,
FLOAT yi, FLOAT yj, FLOAT yk,
FLOAT zi, FLOAT zj, FLOAT zk,
FLOAT a, FLOAT b, FLOAT c
)
: Orientation(VEC(xi, xj, xk), VEC(yi, yj, yk), VEC(zi, zj, zk)), __o(new VEC(ox, oy, oz)), __s(new VEC(a, b, c))
{
}
__::__(FLOAT ox, FLOAT oy, FLOAT oz, FLOAT a, FLOAT b, FLOAT c)
: Orientation(), __o(new VEC(ox, oy, oz)), __s(new VEC(a, b, c))
{
}
__::__(VEC const &o, Orientation const &orientation, VEC const &s)
: Orientation(orientation), __o(new VEC(o)), __s(new VEC(s))
{
}
__::__(VEC const &o, VEC const &x, VEC const &y, VEC const &z, VEC const &s)
: Orientation(x, y, z), __o(new VEC(o)), __s(new VEC(s))
{
}
__::__(VEC const &o, VEC const &s)
: Orientation(), __o(new VEC(o)), __s(new VEC(s))
{
}
__::__(__ const &shape)
: Orientation(shape), __o(new VEC(shape.o())), __s(new VEC(shape.s()))
{
}
__::__(__ &&shape)
: Orientation(shape), __o(shape.__o), __s(shape.__s)
{
shape.update(nullptr);
}
__::__()
: Orientation(), __o(new VEC), __s(new VEC)
{
}
__::~__()
{
if (this->__o != nullptr)
this->replace(nullptr);
} | 21.5 | 117 | 0.580783 | [
"shape"
] |
654f17af28dfe0958137912cba5c82cd8c0ae8dc | 1,554 | hpp | C++ | src/matrix/proto.hpp | Ralith/nachat | 7f58fe7ce9c71912a4001435d0ba82f52b8e5b19 | [
"Apache-2.0"
] | 52 | 2016-08-03T00:34:00.000Z | 2019-10-26T09:46:11.000Z | src/matrix/proto.hpp | Ralith/nachat | 7f58fe7ce9c71912a4001435d0ba82f52b8e5b19 | [
"Apache-2.0"
] | 10 | 2016-07-29T04:48:51.000Z | 2018-02-22T05:11:12.000Z | src/matrix/proto.hpp | Ralith/nachat | 7f58fe7ce9c71912a4001435d0ba82f52b8e5b19 | [
"Apache-2.0"
] | 16 | 2016-07-29T00:01:16.000Z | 2018-08-10T20:03:10.000Z | #ifndef NATIVE_CHAT_MATRIX_PROTO_HPP_
#define NATIVE_CHAT_MATRIX_PROTO_HPP_
#include <vector>
#include <QString>
#include "Event.hpp"
#include "ID.hpp"
class QJsonValue;
namespace matrix {
namespace proto {
struct Presence {
std::vector<Event> events;
};
struct State {
std::vector<event::room::State> events;
};
struct Timeline {
bool limited;
TimelineCursor prev_batch;
std::vector<event::Room> events;
explicit Timeline(TimelineCursor &&prev) : prev_batch{std::move(prev)} {}
};
struct UnreadNotifications {
uint64_t highlight_count;
uint64_t notification_count;
};
struct AccountData {
std::vector<Event> events;
};
struct Ephemeral {
std::vector<Event> events;
};
struct JoinedRoom {
RoomID id;
UnreadNotifications unread_notifications;
Timeline timeline;
State state;
AccountData account_data;
Ephemeral ephemeral;
JoinedRoom(RoomID &&id, Timeline &&t) : id(std::move(id)), timeline(std::move(t)) {}
};
struct LeftRoom {
RoomID id;
Timeline timeline;
State state;
LeftRoom(RoomID &&id, Timeline &&timeline) : id(std::move(id)), timeline(std::move(timeline)) {}
};
struct InviteState {
std::vector<Event> events;
};
struct InvitedRoom {
InviteState invite_state;
};
struct Rooms {
std::vector<JoinedRoom> join;
std::vector<LeftRoom> leave;
std::vector<InvitedRoom> invite;
};
struct Sync {
SyncCursor next_batch;
Presence presence;
Rooms rooms;
explicit Sync(SyncCursor &&next) : next_batch{std::move(next)} {}
};
}
proto::Sync parse_sync(QJsonValue v);
}
#endif
| 16.531915 | 98 | 0.714929 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.