text string | size int64 | token_count int64 |
|---|---|---|
//
// UIButtonLoader.cpp
// Clover
//
// Created by C218-pc on 15/6/29.
//
//
#include "UIButtonLoader.h"
#include "UIButton.h"
#include "UIHelper.h"
cocos2d::Node * UIButtonLoader::createObject(rapidjson::Value & config)
{
return uilib::Button::create();
}
bool UIButtonLoader::setProperty(cocos2d::Node *p, const std::string & name, const rapidjson::Value & value, rapidjson::Value & properties)
{
uilib::Button * btn = dynamic_cast<uilib::Button*>(p);
CCAssert(btn, "UIButtonLoader::setProperty");
if(name == "enable")
{
if(value.IsBool())
{
btn->setEnable(value.GetBool());
}
}
else if(name == "text")
{
if(value.IsString())
{
btn->setText(value.GetString());
}
}
else if(name == "fontName")
{
if(value.IsString())
{
btn->setFontName(value.GetString());
}
}
else if(name == "fontSize")
{
if(value.IsInt())
{
btn->setFontSize(value.GetInt());
}
}
else if(name == "fontColor")
{
cocos2d::Color3B cr;
if(helper::parseValue(value, cr))
{
btn->setFontColor(cr);
}
}
else if(name == "image")
{
std::string imageNormal, imagePressed, imageDisable;
if(value.IsArray())
{
do
{
if(value.Size() < 1 || !value[0u].IsString()) break;
imageNormal = value[0u].GetString();
if(value.Size() < 2 || !value[1].IsString()) break;
imagePressed = value[1].GetString();
if(value.Size() < 3 || !value[2].IsString()) break;
imageDisable = value[2].GetString();
}while(0);
btn->setImages(imageNormal, imagePressed, imageDisable);
}
}
else if(name == "tileImage")
{
std::string imageTile, imageDisable;
if(value.IsArray())
{
do
{
if(value.Size() < 1 || !value[0u].IsString()) break;
imageTile = value[0u].GetString();
if(value.Size() < 2 || !value[1].IsString()) break;
imageDisable = value[1].GetString();
}while(0);
btn->setTileImage(imageTile, imageDisable);
}
}
else if(name == "customSizeEnable")
{
if(value.IsBool())
{
btn->setCustomSizeEnable(value.GetBool());
}
}
else
{
return base_class::setProperty(p, name, value, properties);
}
return true;
}
void UIButtonLoader::trimProperty(rapidjson::Value & property, rapidjson::Value::AllocatorType & allocator)
{
rapidjson::Value *jvalue = &property["customSizeEnable"];
if(!jvalue->IsBool() || !jvalue->GetBool())
{
property.RemoveMemberStable("size");
property.RemoveMemberStable("percentSize");
property.RemoveMemberStable("sizeType");
}
base_class::trimProperty(property, allocator);
}
bool UIButtonLoader::hookPropertyChange(PropertyParam & param)
{
if(param.name == "size" || param.name == "percentSize" || param.name == "sizeType")
{
rapidjson::Value & jvalue = param.properties["customSizeEnable"];
if(!jvalue.IsBool() || !jvalue.GetBool())
{
return false;
}
}
return base_class::hookPropertyChange(param);
}
| 3,545 | 1,095 |
/*=========================================================================
Program: Visualization Toolkit
Module: vtkExternalOpenGLRenderer.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkExternalOpenGLRenderer.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkExternalOpenGLCamera.h"
#include "vtkLightCollection.h"
#include "vtkLight.h"
#include "vtkMath.h"
#include "vtkMatrix4x4.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGL.h"
#include "vtkRenderWindow.h"
#include "vtkTexture.h"
#define MAX_LIGHTS 8
vtkStandardNewMacro(vtkExternalOpenGLRenderer);
//----------------------------------------------------------------------------
vtkExternalOpenGLRenderer::vtkExternalOpenGLRenderer()
{
this->PreserveColorBuffer = 1;
this->PreserveDepthBuffer = 1;
this->SetAutomaticLightCreation(0);
}
//----------------------------------------------------------------------------
vtkExternalOpenGLRenderer::~vtkExternalOpenGLRenderer()
{
}
//----------------------------------------------------------------------------
void vtkExternalOpenGLRenderer::Render(void)
{
GLdouble mv[16],p[16];
glGetDoublev(GL_MODELVIEW_MATRIX,mv);
glGetDoublev(GL_PROJECTION_MATRIX,p);
vtkExternalOpenGLCamera* camera = vtkExternalOpenGLCamera::SafeDownCast(
this->GetActiveCameraAndResetIfCreated());
camera->SetProjectionTransformMatrix(p);
camera->SetViewTransformMatrix(mv);
vtkMatrix4x4* matrix = vtkMatrix4x4::New();
matrix->DeepCopy(mv);
matrix->Transpose();
matrix->Invert();
// Synchronize camera viewUp
double viewUp[4] = {0.0, 1.0, 0.0, 0.0}, newViewUp[4];
matrix->MultiplyPoint(viewUp, newViewUp);
vtkMath::Normalize(newViewUp);
camera->SetViewUp(newViewUp);
// Synchronize camera position
double position[4] = {0.0, 0.0, 1.0, 1.0}, newPosition[4];
matrix->MultiplyPoint(position, newPosition);
if (newPosition[3] != 0.0)
{
newPosition[0] /= newPosition[3];
newPosition[1] /= newPosition[3];
newPosition[2] /= newPosition[3];
newPosition[3] = 1.0;
}
camera->SetPosition(newPosition);
// Synchronize focal point
double focalPoint[4] = {0.0, 0.0, 0.0, 1.0}, newFocalPoint[4];
matrix->MultiplyPoint(focalPoint, newFocalPoint);
camera->SetFocalPoint(newFocalPoint);
matrix->Delete();
// Remove all VTK lights
this->RemoveAllLights();
// Query OpenGL lights
GLenum curLight;
for (curLight = GL_LIGHT0;
curLight < GL_LIGHT0 + MAX_LIGHTS;
curLight++)
{
GLboolean status;
GLfloat info[4];
glGetBooleanv(curLight, &status);
if (status)
{
// For each enabled OpenGL light, add a new VTK headlight.
// Headlight because VTK will apply transform matrices.
vtkLight* light = vtkLight::New();
light->SetLightTypeToHeadlight();
// Set color parameters
glGetLightfv(curLight, GL_AMBIENT, info);
light->SetAmbientColor(info[0], info[1], info[2]);
glGetLightfv(curLight, GL_DIFFUSE, info);
light->SetDiffuseColor(info[0], info[1], info[2]);
glGetLightfv(curLight, GL_SPECULAR, info);
light->SetSpecularColor(info[0], info[1], info[2]);
// Position, focal point and positional
glGetLightfv(curLight, GL_POSITION, info);
light->SetPositional(info[3] > 0.0 ? 1 : 0);
if (!light->GetPositional())
{
light->SetFocalPoint(0, 0, 0);
light->SetPosition(-info[0], -info[1], -info[2]);
}
else
{
light->SetFocalPoint(0, 0, 0);
light->SetPosition(info[0], info[1], info[2]);
// Attenuation
glGetLightfv(curLight, GL_CONSTANT_ATTENUATION, &info[0]);
glGetLightfv(curLight, GL_LINEAR_ATTENUATION, &info[1]);
glGetLightfv(curLight, GL_QUADRATIC_ATTENUATION, &info[2]);
light->SetAttenuationValues(info[0], info[1], info[2]);
// Cutoff
glGetLightfv(curLight, GL_SPOT_CUTOFF, &info[0]);
light->SetConeAngle(info[0]);
if (light->GetConeAngle() < 180.0)
{
// Exponent
glGetLightfv(curLight, GL_SPOT_EXPONENT, &info[0]);
light->SetExponent(info[0]);
// Direction
glGetLightfv(curLight, GL_SPOT_DIRECTION, info);
for (unsigned int i = 0; i < 3; ++i)
{
info[i] += light->GetPosition()[i];
}
light->SetFocalPoint(info[0], info[1], info[2]);
}
}
this->AddLight(light);
light->Delete();
}
}
// Forward the call to the Superclass
this->Superclass::Render();
}
//----------------------------------------------------------------------------
vtkCamera* vtkExternalOpenGLRenderer::MakeCamera()
{
vtkCamera* cam = vtkExternalOpenGLCamera::New();
this->InvokeEvent(vtkCommand::CreateCameraEvent, cam);
return cam;
}
//----------------------------------------------------------------------------
void vtkExternalOpenGLRenderer::PrintSelf(ostream &os, vtkIndent indent)
{
os << indent << "PreserveColorBuffer: " << this->PreserveColorBuffer << "\n";
this->Superclass::PrintSelf(os, indent);
}
| 5,565 | 1,885 |
#include "../src/uWS.h"
#include "addon.h"
//#include "http.h"
void Main(Local<Object> exports) {
isolate = exports->GetIsolate();
exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "server").ToLocalChecked(), Namespace<uWS::SERVER>(isolate).object);
exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "client").ToLocalChecked(), Namespace<uWS::CLIENT>(isolate).object);
//exports->Set(String::NewFromUtf8(isolate, "httpServer"), HttpServer::getHttpServer(isolate));
NODE_SET_METHOD(exports, "setUserData", setUserData<uWS::SERVER>);
NODE_SET_METHOD(exports, "getUserData", getUserData<uWS::SERVER>);
NODE_SET_METHOD(exports, "clearUserData", clearUserData<uWS::SERVER>);
NODE_SET_METHOD(exports, "getAddress", getAddress<uWS::SERVER>);
NODE_SET_METHOD(exports, "transfer", transfer);
NODE_SET_METHOD(exports, "upgrade", upgrade);
NODE_SET_METHOD(exports, "connect", connect);
NODE_SET_METHOD(exports, "setNoop", setNoop);
registerCheck(isolate);
}
NODE_MODULE(uws, Main)
| 1,071 | 391 |
//
// Created by xmac on 18-10-22.
//
#include "../include/unp.h"
void dg_cli(FILE* fp, int sockfd, const SA* servaddr, socklen_t addrlen) {
int n;
int recvline[MAXLINE], sendline[MAXLINE];
while(Fgets(sendline, MAXLINE, fp) != NULL) {
Sendto(sockfd, sendline, strlen(recvline), 0, servaddr, addrlen);
Recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);
Fputs(recvline, stdout);
}
} | 426 | 180 |
// HomeWork220126.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <iostream>
class MyInt
{
public:
int Value;
public:
MyInt(int _Value)
: Value(_Value)
{
}
MyInt& operator++()
{
Value += 1;
return *this;
}
MyInt operator++(int)
{
MyInt result(Value);
Value += 1;
return result;
}
};
int main()
{
int Value = 0;
int Result = 0;
Result = ++Value;
Result = 0;
Result = Value++;
MyInt MyValue = 0;
MyInt MyResult = 0;
// ++ 쓰지마세요
MyResult = ++MyValue;
MyResult = 0;
MyResult = MyValue++;
int a = 0;
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| 1,099 | 888 |
/*
** v_palette.cpp
** Automatic colormap generation for "colored lights", etc.
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 "g_level.h"
#include <stddef.h>
#include <string.h>
#include <math.h>
#include <float.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#define O_BINARY 0
#endif
#include <fcntl.h>
#include "templates.h"
#include "v_video.h"
#include "i_system.h"
#include "w_wad.h"
#include "i_video.h"
#include "c_dispatch.h"
#include "st_stuff.h"
#include "gi.h"
#include "x86.h"
#include "colormatcher.h"
#include "v_palette.h"
#include "g_levellocals.h"
#include "r_data/colormaps.h"
FPalette GPalette;
FColorMatcher ColorMatcher;
/* Current color blending values */
int BlendR, BlendG, BlendB, BlendA;
static int sortforremap (const void *a, const void *b);
static int sortforremap2 (const void *a, const void *b);
/**************************/
/* Gamma correction stuff */
/**************************/
uint8_t newgamma[256];
CUSTOM_CVAR (Float, Gamma, 1.f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
{
if (self == 0.f)
{ // Gamma values of 0 are illegal.
self = 1.f;
return;
}
if (screen != NULL)
{
screen->SetGamma (self);
}
}
CCMD (bumpgamma)
{
// [RH] Gamma correction tables are now generated
// on the fly for *any* gamma level.
// Q: What are reasonable limits to use here?
float newgamma = Gamma + 0.1f;
if (newgamma > 3.0)
newgamma = 1.0;
Gamma = newgamma;
Printf ("Gamma correction level %g\n", *Gamma);
}
/****************************/
/* Palette management stuff */
/****************************/
int BestColor (const uint32_t *pal_in, int r, int g, int b, int first, int num)
{
const PalEntry *pal = (const PalEntry *)pal_in;
int bestcolor = first;
int bestdist = 257 * 257 + 257 * 257 + 257 * 257;
for (int color = first; color < num; color++)
{
int x = r - pal[color].r;
int y = g - pal[color].g;
int z = b - pal[color].b;
int dist = x*x + y*y + z*z;
if (dist < bestdist)
{
if (dist == 0)
return color;
bestdist = dist;
bestcolor = color;
}
}
return bestcolor;
}
FPalette::FPalette ()
{
}
FPalette::FPalette (const uint8_t *colors)
{
SetPalette (colors);
}
void FPalette::SetPalette (const uint8_t *colors)
{
for (int i = 0; i < 256; i++, colors += 3)
{
BaseColors[i] = PalEntry (colors[0], colors[1], colors[2]);
Remap[i] = i;
}
// Find white and black from the original palette so that they can be
// used to make an educated guess of the translucency % for a BOOM
// translucency map.
WhiteIndex = BestColor ((uint32_t *)BaseColors, 255, 255, 255, 0, 255);
BlackIndex = BestColor ((uint32_t *)BaseColors, 0, 0, 0, 0, 255);
}
// In ZDoom's new texture system, color 0 is used as the transparent color.
// But color 0 is also a valid color for Doom engine graphics. What to do?
// Simple. The default palette for every game has at least one duplicate
// color, so find a duplicate pair of palette entries, make one of them a
// duplicate of color 0, and remap every graphic so that it uses that entry
// instead of entry 0.
void FPalette::MakeGoodRemap ()
{
PalEntry color0 = BaseColors[0];
int i;
// First try for an exact match of color 0. Only Hexen does not have one.
for (i = 1; i < 256; ++i)
{
if (BaseColors[i] == color0)
{
Remap[0] = i;
break;
}
}
// If there is no duplicate of color 0, find the first set of duplicate
// colors and make one of them a duplicate of color 0. In Hexen's PLAYPAL
// colors 209 and 229 are the only duplicates, but we cannot assume
// anything because the player might be using a custom PLAYPAL where those
// entries are not duplicates.
if (Remap[0] == 0)
{
PalEntry sortcopy[256];
for (i = 0; i < 256; ++i)
{
sortcopy[i] = BaseColors[i] | (i << 24);
}
qsort (sortcopy, 256, 4, sortforremap);
for (i = 255; i > 0; --i)
{
if ((sortcopy[i] & 0xFFFFFF) == (sortcopy[i-1] & 0xFFFFFF))
{
int new0 = sortcopy[i].a;
int dup = sortcopy[i-1].a;
if (new0 > dup)
{
// Make the lower-numbered entry a copy of color 0. (Just because.)
swapvalues (new0, dup);
}
Remap[0] = new0;
Remap[new0] = dup;
BaseColors[new0] = color0;
break;
}
}
}
// If there were no duplicates, InitPalette() will remap color 0 to the
// closest matching color. Hopefully nobody will use a palette where all
// 256 entries are different. :-)
}
static int sortforremap (const void *a, const void *b)
{
return (*(const uint32_t *)a & 0xFFFFFF) - (*(const uint32_t *)b & 0xFFFFFF);
}
struct RemappingWork
{
uint32_t Color;
uint8_t Foreign; // 0 = local palette, 1 = foreign palette
uint8_t PalEntry; // Entry # in the palette
uint8_t Pad[2];
};
void FPalette::MakeRemap (const uint32_t *colors, uint8_t *remap, const uint8_t *useful, int numcolors) const
{
RemappingWork workspace[255+256];
int i, j, k;
// Fill in workspace with the colors from the passed palette and this palette.
// By sorting this array, we can quickly find exact matches so that we can
// minimize the time spent calling BestColor for near matches.
for (i = 1; i < 256; ++i)
{
workspace[i-1].Color = uint32_t(BaseColors[i]) & 0xFFFFFF;
workspace[i-1].Foreign = 0;
workspace[i-1].PalEntry = i;
}
for (i = k = 0, j = 255; i < numcolors; ++i)
{
if (useful == NULL || useful[i] != 0)
{
workspace[j].Color = colors[i] & 0xFFFFFF;
workspace[j].Foreign = 1;
workspace[j].PalEntry = i;
++j;
++k;
}
else
{
remap[i] = 0;
}
}
qsort (workspace, j, sizeof(RemappingWork), sortforremap2);
// Find exact matches
--j;
for (i = 0; i < j; ++i)
{
if (workspace[i].Foreign)
{
if (!workspace[i+1].Foreign && workspace[i].Color == workspace[i+1].Color)
{
remap[workspace[i].PalEntry] = workspace[i+1].PalEntry;
workspace[i].Foreign = 2;
++i;
--k;
}
}
}
// Find near matches
if (k > 0)
{
for (i = 0; i <= j; ++i)
{
if (workspace[i].Foreign == 1)
{
remap[workspace[i].PalEntry] = BestColor ((uint32_t *)BaseColors,
RPART(workspace[i].Color), GPART(workspace[i].Color), BPART(workspace[i].Color),
1, 255);
}
}
}
}
static int sortforremap2 (const void *a, const void *b)
{
const RemappingWork *ap = (const RemappingWork *)a;
const RemappingWork *bp = (const RemappingWork *)b;
if (ap->Color == bp->Color)
{
return bp->Foreign - ap->Foreign;
}
else
{
return ap->Color - bp->Color;
}
}
void ReadPalette(int lumpnum, uint8_t *buffer)
{
if (lumpnum < 0)
{
I_FatalError("Palette not found");
}
FMemLump lump = Wads.ReadLump(lumpnum);
uint8_t *lumpmem = (uint8_t*)lump.GetMem();
memset(buffer, 0, 768);
if (memcmp(lumpmem, "JASC-PAL", 8))
{
memcpy(buffer, lumpmem, MIN<size_t>(768, lump.GetSize()));
}
else
{
FScanner sc;
sc.OpenMem(Wads.GetLumpFullName(lumpnum), (char*)lumpmem, int(lump.GetSize()));
sc.MustGetString();
sc.MustGetNumber(); // version - ignore
sc.MustGetNumber();
int colors = MIN(256, sc.Number) * 3;
for (int i = 0; i < colors; i++)
{
sc.MustGetNumber();
if (sc.Number < 0 || sc.Number > 255)
{
sc.ScriptError("Color %d value out of range.", sc.Number);
}
buffer[i] = sc.Number;
}
}
}
void InitPalette ()
{
uint8_t pal[768];
ReadPalette(Wads.CheckNumForName("PLAYPAL"), pal);
GPalette.SetPalette (pal);
GPalette.MakeGoodRemap ();
ColorMatcher.SetPalette ((uint32_t *)GPalette.BaseColors);
if (GPalette.Remap[0] == 0)
{ // No duplicates, so settle for something close to color 0
GPalette.Remap[0] = BestColor ((uint32_t *)GPalette.BaseColors,
GPalette.BaseColors[0].r, GPalette.BaseColors[0].g, GPalette.BaseColors[0].b, 1, 255);
}
// Colormaps have to be initialized before actors are loaded,
// otherwise Powerup.Colormap will not work.
R_InitColormaps ();
}
void DoBlending_MMX (const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a);
void DoBlending_SSE2 (const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a);
void DoBlending (const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a)
{
if (a == 0)
{
if (from != to)
{
memcpy (to, from, count * sizeof(uint32_t));
}
return;
}
else if (a == 256)
{
uint32_t t = MAKERGB(r,g,b);
int i;
for (i = 0; i < count; i++)
{
to[i] = t;
}
return;
}
#if defined(_M_X64) || defined(_M_IX86) || defined(__i386__) || defined(__amd64__)
else if (CPU.bSSE2)
{
if (count >= 4)
{
int not3count = count & ~3;
DoBlending_SSE2 (from, to, not3count, r, g, b, a);
count &= 3;
if (count <= 0)
{
return;
}
from += not3count;
to += not3count;
}
}
#endif
#if defined(_M_IX86) || defined(__i386__)
else if (CPU.bMMX)
{
if (count >= 4)
{
int not3count = count & ~3;
DoBlending_MMX (from, to, not3count, r, g, b, a);
count &= 3;
if (count <= 0)
{
return;
}
from += not3count;
to += not3count;
}
}
#endif
int i, ia;
ia = 256 - a;
r *= a;
g *= a;
b *= a;
for (i = count; i > 0; i--, to++, from++)
{
to->r = (r + from->r * ia) >> 8;
to->g = (g + from->g * ia) >> 8;
to->b = (b + from->b * ia) >> 8;
}
}
void V_SetBlend (int blendr, int blendg, int blendb, int blenda)
{
// Don't do anything if the new blend is the same as the old
if (((blenda|BlendA) == 0) ||
(blendr == BlendR &&
blendg == BlendG &&
blendb == BlendB &&
blenda == BlendA))
return;
V_ForceBlend (blendr, blendg, blendb, blenda);
}
void V_ForceBlend (int blendr, int blendg, int blendb, int blenda)
{
BlendR = blendr;
BlendG = blendg;
BlendB = blendb;
BlendA = blenda;
screen->SetFlash (PalEntry (BlendR, BlendG, BlendB), BlendA);
}
CCMD (testblend)
{
FString colorstring;
int color;
float amt;
if (argv.argc() < 3)
{
Printf ("testblend <color> <amount>\n");
}
else
{
if ( !(colorstring = V_GetColorStringByName (argv[1])).IsEmpty() )
{
color = V_GetColorFromString (NULL, colorstring);
}
else
{
color = V_GetColorFromString (NULL, argv[1]);
}
amt = (float)atof (argv[2]);
if (amt > 1.0f)
amt = 1.0f;
else if (amt < 0.0f)
amt = 0.0f;
BaseBlendR = RPART(color);
BaseBlendG = GPART(color);
BaseBlendB = BPART(color);
BaseBlendA = amt;
}
}
/****** Colorspace Conversion Functions ******/
// Code from http://www.cs.rit.edu/~yxv4997/t_convert.html
// r,g,b values are from 0 to 1
// h = [0,360], s = [0,1], v = [0,1]
// if s == 0, then h = -1 (undefined)
// Green Doom guy colors:
// RGB - 0: { .46 1 .429 } 7: { .254 .571 .206 } 15: { .0317 .0794 .0159 }
// HSV - 0: { 116.743 .571 1 } 7: { 112.110 .639 .571 } 15: { 105.071 .800 .0794 }
void RGBtoHSV (float r, float g, float b, float *h, float *s, float *v)
{
float min, max, delta, foo;
if (r == g && g == b)
{
*h = 0;
*s = 0;
*v = r;
return;
}
foo = r < g ? r : g;
min = (foo < b) ? foo : b;
foo = r > g ? r : g;
max = (foo > b) ? foo : b;
*v = max; // v
delta = max - min;
*s = delta / max; // s
if (r == max)
*h = (g - b) / delta; // between yellow & magenta
else if (g == max)
*h = 2 + (b - r) / delta; // between cyan & yellow
else
*h = 4 + (r - g) / delta; // between magenta & cyan
*h *= 60; // degrees
if (*h < 0)
*h += 360;
}
void HSVtoRGB (float *r, float *g, float *b, float h, float s, float v)
{
int i;
float f, p, q, t;
if (s == 0)
{ // achromatic (grey)
*r = *g = *b = v;
return;
}
h /= 60; // sector 0 to 5
i = (int)floor (h);
f = h - i; // factorial part of h
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch (i)
{
case 0: *r = v; *g = t; *b = p; break;
case 1: *r = q; *g = v; *b = p; break;
case 2: *r = p; *g = v; *b = t; break;
case 3: *r = p; *g = q; *b = v; break;
case 4: *r = t; *g = p; *b = v; break;
default: *r = v; *g = p; *b = q; break;
}
}
| 13,424 | 6,054 |
#include <iostream>
// #include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "checker.h"
/////////////////////////////////////////////////////////////
//fixture class for parameters
class RangeCheckerFixture: public testing::TestWithParam<double>{
public:
RangeCheckerFixture() = default;
protected:
RangeChecker range{ 0.0, 100.0 };
};
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//test with param
TEST_P( RangeCheckerFixture, TEST_IN_RANGE ){
int param = GetParam();
std::cout<< "\n\n" <<param << "\n\n";
bool testval= range( param );
ASSERT_TRUE( testval );
}
/////////////////////////////////////////////////////////////
INSTANTIATE_TEST_CASE_P( TEST_IN_RANGE, RangeCheckerFixture, testing::Values(1,20,30,40,120));
int main( int argc, char* argv[] ){
testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
} | 1,004 | 301 |
/*
* Copyright (c) 2016, Google Inc.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/perf_data_converter.h"
#include <algorithm>
#include <deque>
#include <map>
#include <sstream>
#include <utility>
#include <vector>
#include "src/builder.h"
#include "src/compat/int_compat.h"
#include "src/compat/string_compat.h"
#include "src/perf_data_handler.h"
#include "src/quipper/perf_data.pb.h"
#include "src/quipper/perf_parser.h"
#include "src/quipper/perf_reader.h"
namespace perftools {
namespace {
typedef perftools::profiles::Profile Profile;
typedef perftools::profiles::Builder ProfileBuilder;
typedef uint32 Pid;
typedef uint32 Tid;
enum ExecutionMode {
Unknown,
HostKernel,
HostUser,
GuestKernel,
GuestUser,
Hypervisor
};
const char* ExecModeString(ExecutionMode mode) {
switch (mode) {
case HostKernel:
return ExecutionModeHostKernel;
case HostUser:
return ExecutionModeHostUser;
case GuestKernel:
return ExecutionModeGuestKernel;
case GuestUser:
return ExecutionModeGuestUser;
case Hypervisor:
return ExecutionModeHypervisor;
default:
LOG(ERROR) << "Execution mode not handled: " << mode;
return "";
}
}
ExecutionMode PerfExecMode(const PerfDataHandler::SampleContext& sample) {
if (sample.header.has_misc()) {
switch (sample.header.misc() & quipper::PERF_RECORD_MISC_CPUMODE_MASK) {
case quipper::PERF_RECORD_MISC_KERNEL:
return HostKernel;
case quipper::PERF_RECORD_MISC_USER:
return HostUser;
case quipper::PERF_RECORD_MISC_GUEST_KERNEL:
return GuestKernel;
case quipper::PERF_RECORD_MISC_GUEST_USER:
return GuestUser;
case quipper::PERF_RECORD_MISC_HYPERVISOR:
return Hypervisor;
}
}
return Unknown;
}
// Adds the string to the profile builder. If the UTF-8 library is included,
// this also ensures the string contains structurally valid UTF-8.
// In order to successfully unmarshal the proto in Go, all strings inserted into
// the profile string table must be valid UTF-8.
int64 UTF8StringId(const string& s, ProfileBuilder* builder) {
return builder->StringId(s.c_str());
}
// List of profile location IDs, currently used to represent a call stack.
typedef std::vector<uint64> LocationIdVector;
// It is sufficient to key the location and mapping maps by PID.
// However, when Samples include labels, it is necessary to key their maps
// not only by PID, but also by anything their labels may contain, since labels
// are also distinguishing features. This struct should contain everything
// required to uniquely identify a Sample: if two Samples you consider different
// end up with the same SampleKey, you should extend SampleKey til they don't.
//
// If any of these values are not used as labels, they should be set to 0.
struct SampleKey {
Pid pid = 0;
Tid tid = 0;
uint64 time_ns = 0;
ExecutionMode exec_mode = Unknown;
// The index of the sample's command in the profile's string table.
uint64 comm = 0;
// The index of the sample's thread type in the profile's string table.
uint64 thread_type = 0;
// The index of the sample's thread command in the profile's string table.
uint64 thread_comm = 0;
// The index of the sample's cgroup name in the profiles's string table.
uint64 cgroup = 0;
uint64 code_page_size = 0;
uint64 data_page_size = 0;
LocationIdVector stack;
};
struct SampleKeyEqualityTester {
bool operator()(const SampleKey a, const SampleKey b) const {
return ((a.pid == b.pid) && (a.tid == b.tid) && (a.time_ns == b.time_ns) &&
(a.exec_mode == b.exec_mode) && (a.comm == b.comm) &&
(a.thread_type == b.thread_type) &&
(a.thread_comm == b.thread_comm) && (a.cgroup == b.cgroup) &&
(a.code_page_size == b.code_page_size) &&
(a.data_page_size == b.data_page_size) && (a.stack == b.stack));
}
};
struct SampleKeyHasher {
size_t operator()(const SampleKey k) const {
size_t hash = 0;
hash ^= std::hash<int32>()(k.pid);
hash ^= std::hash<int32>()(k.tid);
hash ^= std::hash<uint64>()(k.time_ns);
hash ^= std::hash<int>()(k.exec_mode);
hash ^= std::hash<uint64>()(k.comm);
hash ^= std::hash<uint64>()(k.thread_type);
hash ^= std::hash<uint64>()(k.thread_comm);
hash ^= std::hash<uint64>()(k.cgroup);
hash ^= std::hash<uint64>()(k.code_page_size);
hash ^= std::hash<uint64>()(k.data_page_size);
for (const auto& id : k.stack) {
hash ^= std::hash<uint64>()(id);
}
return hash;
}
};
// While Locations and Mappings are per-address-space (=per-process), samples
// can be thread-specific. If the requested sample labels include PID and
// TID, we'll need to maintain separate profile sample objects for samples
// that are identical except for TID. Likewise, if the requested sample
// labels include timestamp_ns, then we'll need to have separate
// profile_proto::Samples for samples that are identical except for timestamp.
typedef std::unordered_map<SampleKey, perftools::profiles::Sample*,
SampleKeyHasher, SampleKeyEqualityTester>
SampleMap;
// Map from a virtual address to a profile location ID. It only keys off the
// address, not also the mapping ID since the map / its portions are invalidated
// by Comm() and MMap() methods to force re-creation of those locations.
//
typedef std::map<uint64, uint64> LocationMap;
// Map from the handler mapping object to profile mapping ID. The mappings
// the handler creates are immutable and reasonably shared (as in no new mapping
// object is created per, say, each sample), so using the pointers is OK.
typedef std::unordered_map<const PerfDataHandler::Mapping*, uint64> MappingMap;
// Per-process (aggregated when no PID grouping requested) info.
// See docs on ProcessProfile in the header file for details on the fields.
class ProcessMeta {
public:
// Constructs the object for the specified PID.
explicit ProcessMeta(Pid pid) : pid_(pid) {}
// Updates the bounding time interval ranges per specified timestamp.
void UpdateTimestamps(int64 time_nsec) {
if (min_sample_time_ns_ == 0 || time_nsec < min_sample_time_ns_) {
min_sample_time_ns_ = time_nsec;
}
if (max_sample_time_ns_ == 0 || time_nsec > max_sample_time_ns_) {
max_sample_time_ns_ = time_nsec;
}
}
std::unique_ptr<ProcessProfile> makeProcessProfile(Profile* data) {
ProcessProfile* pp = new ProcessProfile();
pp->pid = pid_;
pp->data.Swap(data);
pp->min_sample_time_ns = min_sample_time_ns_;
pp->max_sample_time_ns = max_sample_time_ns_;
return std::unique_ptr<ProcessProfile>(pp);
}
private:
Pid pid_;
int64 min_sample_time_ns_ = 0;
int64 max_sample_time_ns_ = 0;
};
class PerfDataConverter : public PerfDataHandler {
public:
explicit PerfDataConverter(const quipper::PerfDataProto& perf_data,
uint32 sample_labels = kNoLabels,
uint32 options = kGroupByPids,
const std::map<Tid, string>& thread_types = {})
: perf_data_(perf_data),
sample_labels_(sample_labels),
options_(options) {
for (auto& it : thread_types) {
thread_types_.insert(std::make_pair(it.first, it.second));
}
}
PerfDataConverter(const PerfDataConverter&) = delete;
PerfDataConverter& operator=(const PerfDataConverter&) = delete;
virtual ~PerfDataConverter() {}
ProcessProfiles Profiles();
// Callbacks for PerfDataHandler
void Sample(const PerfDataHandler::SampleContext& sample) override;
void Comm(const CommContext& comm) override;
void MMap(const MMapContext& mmap) override;
private:
// Adds a new sample updating the event counters if such sample is not present
// in the profile initializing its metrics. Updates the metrics associated
// with the sample if the sample was added before.
void AddOrUpdateSample(const PerfDataHandler::SampleContext& context,
const Pid& pid, const SampleKey& sample_key,
ProfileBuilder* builder);
// Adds a new location to the profile if such location is not present in the
// profile, returning the ID of the location. It also adds the profile mapping
// corresponding to the specified handler mapping.
uint64 AddOrGetLocation(const Pid& pid, uint64 addr,
const PerfDataHandler::Mapping* mapping,
ProfileBuilder* builder);
// Adds a new mapping to the profile if such mapping is not present in the
// profile, returning the ID of the mapping. It returns 0 to indicate that the
// mapping was not added (only happens if smap == 0 currently).
uint64 AddOrGetMapping(const Pid& pid, const PerfDataHandler::Mapping* smap,
ProfileBuilder* builder);
// Returns whether pid labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludePidLabels() const { return (sample_labels_ & kPidLabel); }
// Returns whether tid labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeTidLabels() const { return (sample_labels_ & kTidLabel); }
// Returns whether timestamp_ns labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeTimestampNsLabels() const {
return (sample_labels_ & kTimestampNsLabel);
}
// Returns whether execution_mode labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeExecutionModeLabels() const {
return (sample_labels_ & kExecutionModeLabel);
}
// Returns whether comm labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeCommLabels() const { return (sample_labels_ & kCommLabel); }
// Returns whether thread type labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeThreadTypeLabels() const {
return (sample_labels_ & kThreadTypeLabel) && !thread_types_.empty();
}
// Returns whether thread comm labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeThreadCommLabels() const {
return (sample_labels_ & kThreadCommLabel);
}
// Returns whether cgroup labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeCgroupLabels() const { return (sample_labels_ & kCgroupLabel); }
// Returns whether code page size labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeCodePageSizeLabels() const {
return (sample_labels_ & kCodePageSizeLabel);
}
// Returns whether data page size labels were requested for inclusion in the
// profile.proto's Sample.Label field.
bool IncludeDataPageSizeLabels() const {
return (sample_labels_ & kDataPageSizeLabel);
}
SampleKey MakeSampleKey(const PerfDataHandler::SampleContext& sample,
ProfileBuilder* builder);
ProfileBuilder* GetOrCreateBuilder(
const PerfDataHandler::SampleContext& sample);
const quipper::PerfDataProto& perf_data_;
// Using deque so that appends do not invalidate existing pointers.
std::deque<ProfileBuilder> builders_;
std::deque<ProcessMeta> process_metas_;
struct PerPidInfo {
ProfileBuilder* builder = nullptr;
ProcessMeta* process_meta = nullptr;
LocationMap location_map;
MappingMap mapping_map;
std::unordered_map<Tid, string> tid_to_comm_map;
SampleMap sample_map;
void clear() {
builder = nullptr;
process_meta = nullptr;
location_map.clear();
mapping_map.clear();
tid_to_comm_map.clear();
sample_map.clear();
}
};
std::unordered_map<Pid, PerPidInfo> per_pid_;
const uint32 sample_labels_;
const uint32 options_;
std::unordered_map<Tid, string> thread_types_;
};
SampleKey PerfDataConverter::MakeSampleKey(
const PerfDataHandler::SampleContext& sample, ProfileBuilder* builder) {
SampleKey sample_key;
sample_key.pid = sample.sample.has_pid() ? sample.sample.pid() : 0;
sample_key.tid =
(IncludeTidLabels() && sample.sample.has_tid()) ? sample.sample.tid() : 0;
sample_key.time_ns =
(IncludeTimestampNsLabels() && sample.sample.has_sample_time_ns())
? sample.sample.sample_time_ns()
: 0;
if (IncludeExecutionModeLabels()) {
sample_key.exec_mode = PerfExecMode(sample);
}
if (IncludeCommLabels() && sample.sample.has_pid()) {
Pid pid = sample.sample.pid();
string comm = per_pid_[pid].tid_to_comm_map[pid];
sample_key.comm = UTF8StringId(comm, builder);
}
if (IncludeThreadTypeLabels() && sample.sample.has_tid()) {
Tid tid = sample.sample.tid();
auto it = thread_types_.find(tid);
if (it != thread_types_.end()) {
sample_key.thread_type = UTF8StringId(it->second, builder);
}
}
if (IncludeThreadCommLabels() && sample.sample.has_pid() &&
sample.sample.has_tid()) {
Pid pid = sample.sample.pid();
Tid tid = sample.sample.tid();
const string& comm = per_pid_[pid].tid_to_comm_map[tid];
sample_key.thread_comm = UTF8StringId(comm, builder);
}
if (IncludeCgroupLabels() && sample.cgroup) {
sample_key.cgroup = UTF8StringId(*sample.cgroup, builder);
}
if (IncludeCodePageSizeLabels() && sample.sample.has_code_page_size()) {
sample_key.code_page_size = sample.sample.code_page_size();
}
if (IncludeDataPageSizeLabels() && sample.sample.has_data_page_size()) {
sample_key.data_page_size = sample.sample.data_page_size();
}
return sample_key;
}
ProfileBuilder* PerfDataConverter::GetOrCreateBuilder(
const PerfDataHandler::SampleContext& sample) {
Pid builder_pid = (options_ & kGroupByPids) ? sample.sample.pid() : 0;
VLOG(2) << "Processing sample for PID=" << sample.sample.pid();
auto& per_pid = per_pid_[builder_pid];
if (per_pid.builder == nullptr) {
VLOG(2) << "Creating a new profile for PID key " << builder_pid;
builders_.push_back(ProfileBuilder());
per_pid.builder = &builders_.back();
process_metas_.push_back(ProcessMeta(builder_pid));
per_pid.process_meta = &process_metas_.back();
ProfileBuilder* builder = per_pid.builder;
Profile* profile = builder->mutable_profile();
int unknown_event_idx = 0;
for (int event_idx = 0; event_idx < perf_data_.file_attrs_size();
++event_idx) {
// Come up with an event name for this event. perf.data will usually
// contain an event_types section of the same cardinality as its
// file_attrs; in this case we can just use the name there. Otherwise
// we just give it an anonymous name.
string event_name = "";
if (perf_data_.file_attrs_size() == perf_data_.event_types_size()) {
const auto& event_type = perf_data_.event_types(event_idx);
if (event_type.has_name()) {
event_name = event_type.name() + "_";
}
}
if (event_name.empty()) {
event_name = "event_" + std::to_string(unknown_event_idx++) + "_";
}
auto sample_type = profile->add_sample_type();
sample_type->set_type(UTF8StringId(event_name + "sample", builder));
sample_type->set_unit(builder->StringId("count"));
sample_type = profile->add_sample_type();
sample_type->set_type(UTF8StringId(event_name + "event", builder));
sample_type->set_unit(builder->StringId("count"));
}
if (sample.main_mapping == nullptr) {
auto fake_main = profile->add_mapping();
fake_main->set_id(profile->mapping_size());
fake_main->set_memory_start(0);
fake_main->set_memory_limit(1);
} else {
AddOrGetMapping(sample.sample.pid(), sample.main_mapping, builder);
}
if (perf_data_.string_metadata().has_perf_version()) {
string perf_version =
"perf-version:" + perf_data_.string_metadata().perf_version().value();
profile->add_comment(UTF8StringId(perf_version, builder));
}
if (perf_data_.string_metadata().has_perf_command_line_whole()) {
string perf_command =
"perf-command:" +
perf_data_.string_metadata().perf_command_line_whole().value();
profile->add_comment(UTF8StringId(perf_command, builder));
}
} else {
Profile* profile = per_pid.builder->mutable_profile();
if ((options_ & kGroupByPids) && sample.main_mapping != nullptr &&
!sample.main_mapping->filename.empty()) {
const string& filename =
profile->string_table(profile->mapping(0).filename());
const string& sample_filename = MappingFilename(sample.main_mapping);
if (filename != sample_filename) {
if (options_ & kFailOnMainMappingMismatch) {
LOG(FATAL) << "main mapping mismatch: " << sample.sample.pid() << " "
<< filename << " " << sample_filename;
} else {
LOG(WARNING) << "main mapping mismatch: " << sample.sample.pid()
<< " " << filename << " " << sample_filename;
}
}
}
}
if (sample.sample.sample_time_ns()) {
per_pid.process_meta->UpdateTimestamps(sample.sample.sample_time_ns());
}
return per_pid.builder;
}
uint64 PerfDataConverter::AddOrGetMapping(const Pid& pid,
const PerfDataHandler::Mapping* smap,
ProfileBuilder* builder) {
CHECK(builder != nullptr) << "Cannot add mapping to null builder";
if (smap == nullptr) {
return 0;
}
MappingMap& mapmap = per_pid_[pid].mapping_map;
auto it = mapmap.find(smap);
if (it != mapmap.end()) {
return it->second;
}
Profile* profile = builder->mutable_profile();
auto mapping = profile->add_mapping();
uint64 mapping_id = profile->mapping_size();
mapping->set_id(mapping_id);
mapping->set_memory_start(smap->start);
mapping->set_memory_limit(smap->limit);
mapping->set_file_offset(smap->file_offset);
if (!smap->build_id.empty()) {
mapping->set_build_id(UTF8StringId(smap->build_id, builder));
}
string mapping_filename = MappingFilename(smap);
mapping->set_filename(UTF8StringId(mapping_filename, builder));
CHECK_LE(mapping->memory_start(), mapping->memory_limit())
<< "Mapping start must be strictly less than its limit: "
<< mapping->filename();
VLOG(2) << "Added mapping ID=" << mapping_id
<< ", filename=" << mapping_filename
<< ", memory_start=" << mapping->memory_start()
<< ", memory_limit=" << mapping->memory_limit()
<< ", file_offset=" << mapping->file_offset();
mapmap.insert(std::make_pair(smap, mapping_id));
return mapping_id;
}
void PerfDataConverter::AddOrUpdateSample(
const PerfDataHandler::SampleContext& context, const Pid& pid,
const SampleKey& sample_key, ProfileBuilder* builder) {
perftools::profiles::Sample* sample = per_pid_[pid].sample_map[sample_key];
if (sample == nullptr) {
Profile* profile = builder->mutable_profile();
sample = profile->add_sample();
per_pid_[pid].sample_map[sample_key] = sample;
for (const auto& location_id : sample_key.stack) {
sample->add_location_id(location_id);
}
// Emit any requested labels.
if (IncludePidLabels() && context.sample.has_pid()) {
auto* label = sample->add_label();
label->set_key(builder->StringId(PidLabelKey));
label->set_num(static_cast<int64>(context.sample.pid()));
}
if (IncludeTidLabels() && context.sample.has_tid()) {
auto* label = sample->add_label();
label->set_key(builder->StringId(TidLabelKey));
label->set_num(static_cast<int64>(context.sample.tid()));
}
if (IncludeCommLabels() && sample_key.comm != 0) {
auto* label = sample->add_label();
label->set_key(builder->StringId(CommLabelKey));
label->set_str(sample_key.comm);
}
if (IncludeTimestampNsLabels() && context.sample.has_sample_time_ns()) {
auto* label = sample->add_label();
label->set_key(builder->StringId(TimestampNsLabelKey));
int64 timestamp_ns_as_int64 =
static_cast<int64>(context.sample.sample_time_ns());
label->set_num(timestamp_ns_as_int64);
}
if (IncludeExecutionModeLabels() && sample_key.exec_mode != Unknown) {
auto* label = sample->add_label();
label->set_key(builder->StringId(ExecutionModeLabelKey));
label->set_str(builder->StringId(ExecModeString(sample_key.exec_mode)));
}
if (IncludeThreadTypeLabels() && sample_key.thread_type != 0) {
auto* label = sample->add_label();
label->set_key(builder->StringId(ThreadTypeLabelKey));
label->set_str(sample_key.thread_type);
}
if (IncludeThreadCommLabels() && sample_key.thread_comm != 0) {
auto* label = sample->add_label();
label->set_key(builder->StringId(ThreadCommLabelKey));
label->set_str(sample_key.thread_comm);
}
if (IncludeCgroupLabels() && sample_key.cgroup != 0) {
auto* label = sample->add_label();
label->set_key(builder->StringId(CgroupLabelKey));
label->set_str(sample_key.cgroup);
}
if (IncludeCodePageSizeLabels() && sample_key.code_page_size != 0) {
auto* label = sample->add_label();
label->set_key(builder->StringId(CodePageSizeLabelKey));
label->set_num(sample_key.code_page_size);
}
if (IncludeDataPageSizeLabels() && sample_key.data_page_size != 0) {
auto* label = sample->add_label();
label->set_key(builder->StringId(DataPageSizeLabelKey));
label->set_num(sample_key.data_page_size);
}
// Two values per collected event: the first is sample counts, the second is
// event counts (unsampled weight for each sample).
for (int event_id = 0; event_id < perf_data_.file_attrs_size();
++event_id) {
sample->add_value(0);
sample->add_value(0);
}
}
int64 weight = 1;
// If the sample has a period, use that in preference
if (context.sample.period() > 0) {
weight = context.sample.period();
} else if (context.file_attrs_index >= 0) {
uint64 period =
perf_data_.file_attrs(context.file_attrs_index).attr().sample_period();
if (period > 0) {
// If sampling used a fixed period, use that as the weight.
weight = period;
}
}
int event_index = context.file_attrs_index;
sample->set_value(2 * event_index, sample->value(2 * event_index) + 1);
sample->set_value(2 * event_index + 1,
sample->value(2 * event_index + 1) + weight);
}
uint64 PerfDataConverter::AddOrGetLocation(
const Pid& pid, uint64 addr, const PerfDataHandler::Mapping* mapping,
ProfileBuilder* builder) {
LocationMap& loc_map = per_pid_[pid].location_map;
auto loc_it = loc_map.find(addr);
if (loc_it != loc_map.end()) {
return loc_it->second;
}
Profile* profile = builder->mutable_profile();
perftools::profiles::Location* loc = profile->add_location();
uint64 loc_id = profile->location_size();
loc->set_id(loc_id);
loc->set_address(addr);
uint64 mapping_id = AddOrGetMapping(pid, mapping, builder);
if (mapping_id != 0) {
loc->set_mapping_id(mapping_id);
} else {
CHECK(addr == 0) << "Unmapped address in PID " << pid;
}
VLOG(2) << "Added location ID=" << loc_id << ", addr=" << addr
<< ", mapping_id=" << mapping_id;
loc_map[addr] = loc_id;
return loc_id;
}
void PerfDataConverter::Comm(const CommContext& comm) {
Pid pid = comm.comm->pid();
Tid tid = comm.comm->tid();
if (comm.is_exec) {
// The is_exec bit indicates an exec() happened, so clear everything
// from the existing pid.
VLOG(2) << "exec() for PID=" << pid << ", clearing the profile";
per_pid_[pid].clear();
}
per_pid_[pid].tid_to_comm_map[tid] = PerfDataHandler::NameOrMd5Prefix(
comm.comm->comm(), comm.comm->comm_md5_prefix());
}
// Invalidates the locations in location_map in the mmap event's range.
void PerfDataConverter::MMap(const MMapContext& mmap) {
LocationMap& loc_map = per_pid_[mmap.pid].location_map;
loc_map.erase(loc_map.lower_bound(mmap.mapping->start),
loc_map.lower_bound(mmap.mapping->limit));
}
void PerfDataConverter::Sample(const PerfDataHandler::SampleContext& sample) {
if (sample.file_attrs_index < 0 ||
sample.file_attrs_index >= perf_data_.file_attrs_size()) {
LOG(WARNING) << "out of bounds file_attrs_index: "
<< sample.file_attrs_index;
return;
}
Pid event_pid = sample.sample.pid();
ProfileBuilder* builder = GetOrCreateBuilder(sample);
SampleKey sample_key = MakeSampleKey(sample, builder);
uint64 ip = sample.sample_mapping != nullptr ? sample.sample.ip() : 0;
if (ip != 0) {
const auto start = sample.sample_mapping->start;
const auto limit = sample.sample_mapping->limit;
CHECK_GE(ip, start);
CHECK_LT(ip, limit);
}
// Leaf at stack[0]. Record the program counter of the sample as the leaf of
// the stack. When kAddDataAddressFrames is set, add another leaf with the
// virtual data address of the access.
if (options_ & kAddDataAddressFrames) {
uint64 addr = sample.addr_mapping != nullptr ? sample.sample.addr() : 0;
if (addr != 0) {
const auto start = sample.addr_mapping->start;
const auto limit = sample.addr_mapping->limit;
CHECK_GE(addr, start);
CHECK_LT(addr, limit);
}
sample_key.stack.push_back(
AddOrGetLocation(event_pid, addr, sample.addr_mapping, builder));
}
sample_key.stack.push_back(
AddOrGetLocation(event_pid, ip, sample.sample_mapping, builder));
// LBR callstacks include only user call chains. If this is an LBR sample,
// we get the kernel callstack from the sample's callchain, and the user
// callstack from the sample's branch_stack.
const bool lbr_sample = !sample.branch_stack.empty();
bool skipped_dup = false;
for (const auto& frame : sample.callchain) {
if (lbr_sample && frame.ip == quipper::PERF_CONTEXT_USER) {
break;
}
// These aren't real callchain entries, just hints as to kernel / user
// addresses.
if (frame.ip >= quipper::PERF_CONTEXT_MAX) {
continue;
}
// perf_events includes the IP at the leaf of the callchain. If PEBS is on,
// kernels built after
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/arch/x86/events/intel/ds.c?id=b8000586c90b4804902058a38d3a59ce5708e695
// will have the first callchain entry be the interrupted IP, while in older
// kernels it will be the sampled IP. If PEBS is off, the first callchain
// entry will be the interrupted IP. Either way, skip the first non-marker
// entry.
if (!skipped_dup) {
skipped_dup = true;
continue;
}
if (frame.mapping == nullptr) {
continue;
}
// Why <=? Because this is a return address, which should be
// preceded by a call (the "real" context.) If we're at the edge
// of the mapping, we're really off its edge.
if (frame.ip <= frame.mapping->start) {
continue;
}
// Subtract one so we point to the call instead of the return addr.
sample_key.stack.push_back(
AddOrGetLocation(event_pid, frame.ip - 1, frame.mapping, builder));
}
for (const auto& frame : sample.branch_stack) {
// branch_stack entries are pairs of <from, to> locations corresponding to
// addresses of call instructions and target addresses of those calls.
// We need only the addresses of the function call instructions, stored in
// the 'from' field, to recover the call chains.
if (frame.from.mapping == nullptr) {
continue;
}
// An LBR entry includes the address of the call instruction, so we don't
// have to do any adjustments.
if (frame.from.ip < frame.from.mapping->start) {
continue;
}
sample_key.stack.push_back(AddOrGetLocation(event_pid, frame.from.ip,
frame.from.mapping, builder));
}
AddOrUpdateSample(sample, event_pid, sample_key, builder);
}
ProcessProfiles PerfDataConverter::Profiles() {
ProcessProfiles pps;
for (size_t i = 0; i < builders_.size(); i++) {
auto& b = builders_[i];
b.Finalize();
auto pp = process_metas_[i].makeProcessProfile(b.mutable_profile());
pps.push_back(std::move(pp));
}
return pps;
}
} // namespace
ProcessProfiles PerfDataProtoToProfiles(
const quipper::PerfDataProto* perf_data, const uint32 sample_labels,
const uint32 options, const std::map<Tid, string>& thread_types) {
PerfDataConverter converter(*perf_data, sample_labels, options, thread_types);
PerfDataHandler::Process(*perf_data, &converter);
return converter.Profiles();
}
ProcessProfiles RawPerfDataToProfiles(
const void* raw, const int raw_size,
const std::map<string, string>& build_ids, const uint32 sample_labels,
const uint32 options, const std::map<Tid, string>& thread_types) {
quipper::PerfReader reader;
if (!reader.ReadFromPointer(reinterpret_cast<const char*>(raw), raw_size)) {
LOG(ERROR) << "Could not read input perf.data";
return ProcessProfiles();
}
reader.InjectBuildIDs(build_ids);
// Perf populates info about the kernel using multiple pathways,
// which don't actually all match up how they name kernel data; in
// particular, buildids are reported by a different name than the
// actual "mmap" info. Normalize these names so our ProcessProfiles
// will match kernel mappings to a buildid.
reader.LocalizeUsingFilenames({
{"[kernel.kallsyms]_text", "[kernel.kallsyms]"},
{"[kernel.kallsyms]_stext", "[kernel.kallsyms]"},
});
// Use PerfParser to modify reader's events to have magic done to them such
// as hugepage deduction and sorting events based on time, if timestamps are
// present.
quipper::PerfParserOptions opts;
opts.sort_events_by_time = true;
opts.deduce_huge_page_mappings = true;
opts.combine_mappings = true;
opts.allow_unaligned_jit_mappings = options & kAllowUnalignedJitMappings;
quipper::PerfParser parser(&reader, opts);
if (!parser.ParseRawEvents()) {
LOG(ERROR) << "Could not parse perf events.";
return ProcessProfiles();
}
return PerfDataProtoToProfiles(&reader.proto(), sample_labels, options,
thread_types);
}
} // namespace perftools
| 30,478 | 9,704 |
#include "../hook/responsive_hooks.h"
#include "radio_check_button_control_group.h"
cwin::control::radio_group::radio_group(){
insert_object<hook::contain>(nullptr);
}
cwin::control::radio_group::radio_group(tree &parent)
: radio_group(parent, static_cast<std::size_t>(-1)){}
cwin::control::radio_group::radio_group(tree &parent, std::size_t index)
: radio_group(){
index_ = index;
if (&parent.get_thread() == &thread_)
set_parent_(parent);
else//Error
throw thread::exception::context_mismatch();
}
cwin::control::radio_group::~radio_group(){
force_destroy_();
}
bool cwin::control::radio_group::inserting_child_(ui::object &child){
return (dynamic_cast<check_button *>(&child) != nullptr || dynamic_cast<hook::object *>(&child) != nullptr);
}
void cwin::control::radio_group::create_(){
creation_state_ = true;
}
void cwin::control::radio_group::destroy_(){
creation_state_ = false;
}
bool cwin::control::radio_group::is_created_() const{
return creation_state_;
}
| 991 | 360 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <boost/test/auto_unit_test.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <climits>
#include <vector>
#include <thrift/concurrency/Monitor.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/transport/THttpServer.h>
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSocket.h>
#include <memory>
#include <thrift/transport/TBufferTransports.h>
#include "gen-cpp/OneWayService.h"
BOOST_AUTO_TEST_SUITE(OneWayHTTPTest)
using namespace apache::thrift;
using apache::thrift::protocol::TProtocol;
using apache::thrift::protocol::TBinaryProtocol;
using apache::thrift::protocol::TBinaryProtocolFactory;
using apache::thrift::protocol::TJSONProtocol;
using apache::thrift::protocol::TJSONProtocolFactory;
using apache::thrift::server::TThreadedServer;
using apache::thrift::server::TServerEventHandler;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::THttpServer;
using apache::thrift::transport::THttpServerTransportFactory;
using apache::thrift::transport::THttpClient;
using apache::thrift::transport::TBufferedTransport;
using apache::thrift::transport::TBufferedTransportFactory;
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::transport::TServerSocket;
using apache::thrift::transport::TSocket;
using apache::thrift::transport::TTransportException;
using std::shared_ptr;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
namespace utf = boost::unit_test;
// Define this env var to enable some logging (in case you need to debug)
#undef ENABLE_STDERR_LOGGING
class OneWayServiceHandler : public onewaytest::OneWayServiceIf {
public:
OneWayServiceHandler() {}
void roundTripRPC() override {
#ifdef ENABLE_STDERR_LOGGING
cerr << "roundTripRPC()" << endl;
#endif
}
void oneWayRPC() {
#ifdef ENABLE_STDERR_LOGGING
cerr << "oneWayRPC()" << std::endl ;
#endif
}
};
class OneWayServiceCloneFactory : virtual public onewaytest::OneWayServiceIfFactory {
public:
virtual ~OneWayServiceCloneFactory() {}
virtual onewaytest::OneWayServiceIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo)
{
(void)connInfo ;
return new OneWayServiceHandler;
}
virtual void releaseHandler( onewaytest::OneWayServiceIf* handler) {
delete handler;
}
};
class RPC0ThreadClass {
public:
RPC0ThreadClass(TThreadedServer& server) : server_(server) { } // Constructor
~RPC0ThreadClass() { } // Destructor
void Run() {
server_.serve() ;
}
TThreadedServer& server_ ;
} ;
using apache::thrift::concurrency::Monitor;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::Synchronized;
// copied from IntegrationTest
class TServerReadyEventHandler : public TServerEventHandler, public Monitor {
public:
TServerReadyEventHandler() : isListening_(false), accepted_(0) {}
virtual ~TServerReadyEventHandler() {}
virtual void preServe() {
Synchronized sync(*this);
isListening_ = true;
notify();
}
virtual void* createContext(shared_ptr<TProtocol> input,
shared_ptr<TProtocol> output) {
Synchronized sync(*this);
++accepted_;
notify();
(void)input;
(void)output;
return NULL;
}
bool isListening() const { return isListening_; }
uint64_t acceptedCount() const { return accepted_; }
private:
bool isListening_;
uint64_t accepted_;
};
class TBlockableBufferedTransport : public TBufferedTransport {
public:
TBlockableBufferedTransport(std::shared_ptr<TTransport> transport)
: TBufferedTransport(transport, 10240),
blocked_(false) {
}
uint32_t write_buffer_length() {
uint32_t have_bytes = static_cast<uint32_t>(wBase_ - wBuf_.get());
return have_bytes ;
}
void block() {
blocked_ = true ;
#ifdef ENABLE_STDERR_LOGGING
cerr << "block flushing\n" ;
#endif
}
void unblock() {
blocked_ = false ;
#ifdef ENABLE_STDERR_LOGGING
cerr << "unblock flushing, buffer is\n<<" << std::string((char *)wBuf_.get(), write_buffer_length()) << ">>\n" ;
#endif
}
void flush() override {
if (blocked_) {
#ifdef ENABLE_STDERR_LOGGING
cerr << "flush was blocked\n" ;
#endif
return ;
}
TBufferedTransport::flush() ;
}
bool blocked_ ;
} ;
BOOST_AUTO_TEST_CASE( JSON_BufferedHTTP )
{
std::shared_ptr<TServerSocket> ss = std::make_shared<TServerSocket>(0) ;
TThreadedServer server(
std::make_shared<onewaytest::OneWayServiceProcessorFactory>(std::make_shared<OneWayServiceCloneFactory>()),
ss, //port
std::make_shared<THttpServerTransportFactory>(),
std::make_shared<TJSONProtocolFactory>());
std::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
#ifdef ENABLE_STDERR_LOGGING
cerr << "Starting the server...\n";
#endif
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
int port = ss->getPort() ;
#ifdef ENABLE_STDERR_LOGGING
cerr << "port " << port << endl ;
#endif
{
std::shared_ptr<TSocket> socket(new TSocket("localhost", port));
socket->setRecvTimeout(10000) ; // 1000msec should be enough
std::shared_ptr<TBlockableBufferedTransport> blockable_transport(new TBlockableBufferedTransport(socket));
std::shared_ptr<TTransport> transport(new THttpClient(blockable_transport, "localhost", "/service"));
std::shared_ptr<TProtocol> protocol(new TJSONProtocol(transport));
onewaytest::OneWayServiceClient client(protocol);
transport->open();
client.roundTripRPC();
blockable_transport->block() ;
uint32_t size0 = blockable_transport->write_buffer_length() ;
client.send_oneWayRPC() ;
uint32_t size1 = blockable_transport->write_buffer_length() ;
client.send_oneWayRPC() ;
uint32_t size2 = blockable_transport->write_buffer_length() ;
BOOST_CHECK((size1 - size0) == (size2 - size1)) ;
blockable_transport->unblock() ;
client.send_roundTripRPC() ;
blockable_transport->flush() ;
try {
client.recv_roundTripRPC() ;
} catch (const TTransportException &e) {
BOOST_ERROR( "we should not get a transport exception -- this means we failed: " + std::string(e.what()) ) ;
}
transport->close();
}
server.stop();
thread.join() ;
#ifdef ENABLE_STDERR_LOGGING
cerr << "finished.\n";
#endif
}
BOOST_AUTO_TEST_SUITE_END()
| 7,445 | 2,428 |
// Attached: HW_3a, 3b, 3c
// ===========================================================
// Project: HW_3b
// ===========================================================
// Programmer: Mark Norem
// Class: CMPR 131
// ===========================================================
#include "SortedList.h"
void showMenu();
char getChoice();
int main() {
SortedList list;
char runAgain;
do {
showMenu();
char choice = getChoice();
if (choice == 'A') {
std::cout << "Enter a number: ";
int number = 0;
std::cin >> number;
std::cout << std::endl;
if (!list.isFull()) {
list.insertItem(number);
std::cout << "Item was added to the list" << std::endl << std::endl;
}
else if (list.isFull()) {
std::cout << "Unable to add item to list, list was full." << std::endl << std::endl;
}
}
if (choice == 'B') {
std::cout << "Enter the number to be deleted: ";
int number = 0;
std::cin >> number;
if (!list.isEmpty()) {
list.deleteItem(number);
}
else {
std::cout << "Unable to delete item, the list was empty" << std::endl << std::endl;
}
}
std::cout << "Run again? Y/N";
runAgain = getChoice();
} while (runAgain == 'Y');
}
void showMenu()
{
std::cout << "a. Insert a number into the list." << std::endl
<< "b. Delete a number from the list." << std::endl << std::endl;
}
char getChoice()
{
char choice;
std::cout << std::endl << "Enter your choice: ";
std::cin >> choice;
std::cout << std::endl;
return toupper(choice);
}
| 1,509 | 570 |
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/operator/acc_tick_op.h"
namespace oneflow {
namespace {
Maybe<void> InferBlobDescs(const std::function<BlobDesc*(const std::string&)>& GetBlobDesc4BnInOp) {
*GetBlobDesc4BnInOp("acc") = *GetBlobDesc4BnInOp("one");
GetBlobDesc4BnInOp("acc")->mut_shape() = Shape({1LL});
return Maybe<void>::Ok();
}
} // namespace
Maybe<void> AccTickOp::InitFromOpConf() {
CHECK(op_conf().has_acc_tick_conf());
EnrollInputBn("one", false);
EnrollOutputBn("acc", false);
return Maybe<void>::Ok();
}
Maybe<void> AccTickOp::InferLogicalOutBlobDescs(
const std::function<BlobDesc*(const std::string&)>& BlobDesc4BnInOp,
const ParallelDesc& parallel_desc) const {
return InferBlobDescs(BlobDesc4BnInOp);
}
Maybe<void> AccTickOp::InferOutBlobDescs(
const std::function<BlobDesc*(const std::string&)>& GetBlobDesc4BnInOp,
const ParallelContext* parallel_ctx) const {
return InferBlobDescs(GetBlobDesc4BnInOp);
}
Maybe<void> AccTickOp::InferOpTimeShape(
const std::function<Maybe<const Shape>(const std::string&)>& GetTimeShape4BnInOp,
std::shared_ptr<const Shape>* time_shape) const {
const int32_t max_acc_num = op_conf().acc_tick_conf().max_acc_num();
std::shared_ptr<const Shape> in_shape = JUST(GetTimeShape4BnInOp("one"));
CHECK_EQ_OR_RETURN(in_shape->elem_cnt() % max_acc_num, 0);
DimVector in_dim_vec = in_shape->dim_vec();
std::shared_ptr<Shape> op_time_shape;
if (in_dim_vec.back() == max_acc_num) {
in_dim_vec.pop_back();
op_time_shape.reset(new Shape(in_dim_vec));
} else if (in_dim_vec.back() % max_acc_num == 0) {
in_dim_vec.back() /= max_acc_num;
op_time_shape.reset(new Shape(in_dim_vec));
} else {
op_time_shape.reset(new Shape({in_shape->elem_cnt() / max_acc_num}));
}
*time_shape = op_time_shape;
return Maybe<void>::Ok();
}
Maybe<void> AccTickOp::GetSbpSignatures(
const std::function<Maybe<const BlobDesc&>(const std::string&)>& LogicalBlobDesc4Ibn,
cfg::SbpSignatureList* sbp_sig_list) const {
return Maybe<void>::Ok();
}
REGISTER_OP(OperatorConf::kAccTickConf, AccTickOp);
REGISTER_TICK_TOCK_OP(OperatorConf::kAccTickConf);
} // namespace oneflow
| 2,762 | 1,042 |
/*
* Copyright (C) 2018 Microchip Technology Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "pages.h"
#include "settings.h"
#include "window.h"
#include <chrono>
using namespace egt;
using namespace std;
ThermostatWindow::ThermostatWindow()
{
auto hsizer = make_shared<BoxSizer>(Orientation::horizontal);
add(expand(hsizer));
notebook = make_shared<Notebook>();
m_pages["idle"] = make_shared<IdlePage>(*this, m_logic);
auto main_page = make_shared<MainPage>(*this, m_logic);
m_pages["main"] = main_page;
m_pages["menu"] = make_shared<MenuPage>(*this, m_logic);
m_pages["mode"] = make_shared<ModePage>(*this, m_logic);
m_pages["homecontent"] = make_shared<HomeContentPage>(*this, m_logic);
m_pages["idlesettings"] = make_shared<IdleSettingsPage>(*this, m_logic);
m_pages["fan"] = make_shared<FanPage>(*this, m_logic);
m_pages["screenbrightness"] = make_shared<ScreenBrightnessPage>(*this, m_logic);
m_pages["sensors"] = make_shared<SensorsPage>(*this, m_logic);
m_pages["schedule"] = make_shared<SchedulePage>(*this, m_logic);
m_pages["about"] = make_shared<AboutPage>(*this, m_logic);
for (auto& i : m_pages)
notebook->add(i.second);
hsizer->add(expand(notebook));
auto idle = m_pages["idle"];
idle->on_event([this, idle](Event&)
{
goto_page("main");
}, {EventId::raw_pointer_down});
goto_page("main");
m_screen_brightness_timer.on_timeout([]()
{
const auto brightness = settings().get("sleep_brightness");
Application::instance().screen()->brightness(std::stoi(brightness));
});
m_idle_timer.change_duration(std::chrono::seconds(std::stoi(settings().get("sleep_timeout"))));
m_idle_timer.on_timeout([this]()
{
this->idle();
m_screen_brightness_timer.start();
});
m_idle_timer.start();
// on any input, reset idle timer
m_handle = Input::global_input().on_event([this, main_page](Event & event)
{
m_screen_brightness_timer.cancel();
auto screen = Application::instance().screen();
screen->brightness(std::stoi(settings().get("normal_brightness")));
m_idle_timer.start();
}, {EventId::raw_pointer_down,
EventId::raw_pointer_up,
EventId::raw_pointer_move,
EventId::pointer_hold
});
m_logic.on_logic_change([this]()
{
if (settings().get("sql_logs") == "on")
settings().status_log(m_logic.current_status(), m_logic.current_fan_status());
});
m_logic.on_temperature_change([this]()
{
if (settings().get("sql_logs") == "on")
settings().temp_log(m_logic.current());
});
}
void ThermostatWindow::idle()
{
m_queue.clear();
notebook->selected(page_to_idx("idle"));
}
void ThermostatWindow::goto_page(const std::string& name)
{
m_queue.clear();
m_queue.push_back(name);
notebook->selected(page_to_idx(name));
}
void ThermostatWindow::push_page(const std::string& name)
{
m_queue.push_back(name);
notebook->selected(page_to_idx(name));
}
void ThermostatWindow::pop_page()
{
assert(!m_queue.empty());
m_queue.pop_back();
auto prev = m_queue.back();
notebook->selected(page_to_idx(prev));
}
int ThermostatWindow::page_to_idx(const std::string& name)
{
return std::distance(m_pages.begin(), m_pages.find(name));
}
ThermostatWindow::~ThermostatWindow()
{
Input::global_input().remove_handler(m_handle);
}
| 3,507 | 1,245 |
#include "processcreate.h"
#include "ui_processcreate.h"
#include <QDebug>
ProcessCreate::ProcessCreate(QWidget *parent) :
QWidget(parent),
ui(new Ui::ProcessCreate)
{
ui->setupUi(this);
this->setWindowTitle("创建进程 - PowerSimulator");
this->setFixedSize(this->width(),this->height());
this->setWindowFlag(Qt::FramelessWindowHint);
ui->titleBarGroup->setAlignment(Qt::AlignRight);
QBitmap bmp(this->size());
bmp.fill();
QPainter p(&bmp);
p.setRenderHint(QPainter::Antialiasing); // 反锯齿;
p.setPen(Qt::transparent);
p.setBrush(Qt::black);
p.drawRoundedRect(bmp.rect(), 15, 15);
setMask(bmp);
}
ProcessCreate::~ProcessCreate()
{
delete ui;
}
void ProcessCreate::on_pushButton_exit_clicked()
{
this->close();
delete this;
}
void ProcessCreate::on_pushButton_create_clicked()
{
qDebug()<< ui->lineEdit_pid->text().toInt();
PCB* newPCB = new PCB(ui->lineEdit_pid->text().toInt(),ui->lineEdit_neededtime->text().toInt(),ui->lineEdit_priority->text().toInt(),ui->lineEdit_neededLength->text().toInt());
emit transmitPCB(newPCB);
}
/*
* 以下代码段为隐藏标题栏之后,重写的鼠标事件
*/
void ProcessCreate::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_Drag = true;
m_DragPosition = event->globalPos() - this->pos();
event->accept();
}
QWidget::mousePressEvent(event);
}
void ProcessCreate::mouseMoveEvent(QMouseEvent *event)
{
if (m_Drag && (event->buttons() && static_cast<bool>(Qt::LeftButton)))
{
move(event->globalPos() - m_DragPosition);
event->accept();
emit mouseButtonMove(event->globalPos() - m_DragPosition);
emit signalMainWindowMove();
}
QWidget::mouseMoveEvent(event);
}
void ProcessCreate::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event);
m_Drag = false;
QWidget::mouseReleaseEvent(event);
}
//最小化这个窗口
void ProcessCreate::on_btn_min_clicked()
{
this->setWindowState(Qt::WindowMinimized);
}
//关闭这个窗口
void ProcessCreate::on_btn_close_clicked()
{
this->close();
delete this;
}
| 2,107 | 781 |
/// \file
/// \brief Contains definition of parallel_execution_policy.
///
#pragma once
#include <agency/detail/config.hpp>
#include <agency/execution/executor/parallel_executor.hpp>
#include <agency/execution/execution_agent.hpp>
#include <agency/execution/execution_policy/basic_execution_policy.hpp>
namespace agency
{
/// \brief Encapsulates requirements for creating groups of parallel execution agents.
/// \ingroup execution_policies
///
///
/// When used as a control structure parameter, `parallel_execution_policy` requires the creation of a group of execution agents which execute in parallel.
/// When agents in such a group execute on separate threads, they have no order. Otherwise, if agents in such a group execute on the same thread,
/// they execute in an unspecified order.
///
/// The type of execution agent `parallel_execution_policy` induces is `parallel_agent`, and the type of its associated executor is `parallel_executor`.
///
/// \see execution_policies
/// \see basic_execution_policy
/// \see par
/// \see parallel_agent
/// \see parallel_executor
/// \see parallel_execution_tag
class parallel_execution_policy : public basic_execution_policy<parallel_agent, parallel_executor, parallel_execution_policy>
{
private:
using super_t = basic_execution_policy<parallel_agent, parallel_executor, parallel_execution_policy>;
public:
using super_t::basic_execution_policy;
};
/// \brief The global variable `par` is the default `parallel_execution_policy`.
/// \ingroup execution_policies
const parallel_execution_policy par{};
/// \brief Encapsulates requirements for creating two-dimensional groups of parallel execution agents.
/// \ingroup execution_policies
///
///
/// When used as a control structure parameter, `parallel_execution_policy_2d` requires the creation of a two-dimensional group of execution agents which execute in parallel.
/// When agents in such a group execute on separate threads, they have no order. Otherwise, if agents in such a group execute on the same thread,
/// they execute in an unspecified order.
///
/// The type of execution agent `parallel_execution_policy_2d` induces is `parallel_agent_2d`, and the type of its associated executor is `parallel_executor`.
///
/// \see execution_policies
/// \see basic_execution_policy
/// \see par
/// \see parallel_agent_2d
/// \see parallel_executor
/// \see parallel_execution_tag
class parallel_execution_policy_2d : public basic_execution_policy<parallel_agent_2d, parallel_executor, parallel_execution_policy_2d>
{
private:
using super_t = basic_execution_policy<parallel_agent_2d, parallel_executor, parallel_execution_policy_2d>;
public:
using super_t::basic_execution_policy;
};
/// \brief The global variable `par2d` is the default `parallel_execution_policy_2d`.
/// \ingroup execution_policies
const parallel_execution_policy_2d par2d{};
/// \brief The function template `parnd` creates an n-dimensional parallel
/// execution policy that induces execution agents over the given domain.
/// \ingroup execution_policies
template<class Index>
__AGENCY_ANNOTATION
basic_execution_policy<
agency::detail::basic_execution_agent<agency::bulk_guarantee_t::parallel_t,Index>,
agency::parallel_executor
>
parnd(const agency::lattice<Index>& domain)
{
using policy_type = agency::basic_execution_policy<
agency::detail::basic_execution_agent<agency::bulk_guarantee_t::parallel_t,Index>,
agency::parallel_executor
>;
typename policy_type::param_type param(domain);
return policy_type{param};
}
/// \brief The function template `parnd` creates an n-dimensional parallel
/// execution policy that creates agent groups of the given shape.
/// \ingroup execution_policies
template<class Shape>
__AGENCY_ANNOTATION
basic_execution_policy<
agency::detail::basic_execution_agent<agency::bulk_guarantee_t::parallel_t,Shape>,
agency::parallel_executor
>
parnd(const Shape& shape)
{
return agency::parnd(agency::make_lattice(shape));
}
} // end agency
| 4,033 | 1,167 |
/**
* Copyright 2018-2019 Dynatrace LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "configuration/BeaconCacheConfiguration.h"
using namespace configuration;
///
/// The default @ref BeaconCacheConfiguration when user does not override it.
/// Default settings allow beacons which are max 2 hours old and unbounded memory limits.
///
const std::chrono::milliseconds BeaconCacheConfiguration::DEFAULT_MAX_RECORD_AGE_IN_MILLIS = std::chrono::minutes(105); // 1hour and 45 minutes
const int64_t BeaconCacheConfiguration::DEFAULT_UPPER_MEMORY_BOUNDARY_IN_BYTES = 100 * 1024 * 1024; // 100 MiB
const int64_t BeaconCacheConfiguration::DEFAULT_LOWER_MEMORY_BOUNDARY_IN_BYTES = 80 * 1024 * 1024; // 80 MiB
BeaconCacheConfiguration::BeaconCacheConfiguration(int64_t maxRecordAge, int64_t cacheSizeLowerBound, int64_t cacheSizeUpperBound)
: mMaxRecordAge(maxRecordAge)
, mCacheSizeLowerBound(cacheSizeLowerBound)
, mCacheSizeUpperBound(cacheSizeUpperBound)
{
}
int64_t BeaconCacheConfiguration::getMaxRecordAge() const
{
return mMaxRecordAge;
}
int64_t BeaconCacheConfiguration::getCacheSizeLowerBound() const
{
return mCacheSizeLowerBound;
}
int64_t BeaconCacheConfiguration::getCacheSizeUpperBound() const
{
return mCacheSizeUpperBound;
} | 1,762 | 588 |
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/ext/boost/mpl/list.hpp>
#include <boost/hana/assert.hpp>
#include <boost/hana/drop_front_exactly.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/front.hpp>
#include <boost/hana/is_empty.hpp>
#include <boost/hana/not.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
#include <laws/iterable.hpp>
#include <boost/mpl/list.hpp>
namespace hana = boost::hana;
namespace mpl = boost::mpl;
struct t1; struct t2; struct t3; struct t4;
int main() {
// front
{
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::front(mpl::list<t1>{}),
hana::type_c<t1>
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::front(mpl::list<t1, t2>{}),
hana::type_c<t1>
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::front(mpl::list<t1, t2, t3>{}),
hana::type_c<t1>
));
}
// drop_front_exactly
{
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::drop_front_exactly(mpl::list<t1>{}),
mpl::list<>{}
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::drop_front_exactly(mpl::list<t1, t2>{}),
mpl::list<t2>{}
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::drop_front_exactly(mpl::list<t1, t2, t3>{}),
mpl::list<t2, t3>{}
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::drop_front_exactly(mpl::list<t1, t2, t3>{}, hana::size_c<2>),
mpl::list<t3>{}
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::drop_front_exactly(mpl::list<t1, t2, t3, t4>{}, hana::size_c<2>),
mpl::list<t3, t4>{}
));
BOOST_HANA_CONSTANT_CHECK(hana::equal(
hana::drop_front_exactly(mpl::list<t1, t2, t3, t4>{}, hana::size_c<3>),
mpl::list<t4>{}
));
}
// is_empty
{
BOOST_HANA_CONSTANT_CHECK(hana::is_empty(mpl::list<>{}));
BOOST_HANA_CONSTANT_CHECK(hana::is_empty(mpl::list0<>{}));
BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::is_empty(mpl::list<t1>{})));
BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::is_empty(mpl::list1<t1>{})));
BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::is_empty(mpl::list<t1, t2>{})));
BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::is_empty(mpl::list2<t1, t2>{})));
}
// laws
auto lists = hana::make_tuple(
mpl::list<>{}
, mpl::list<t1>{}
, mpl::list<t1, t2>{}
, mpl::list<t1, t2, t3>{}
, mpl::list<t1, t2, t3, t4>{}
);
hana::test::TestIterable<hana::ext::boost::mpl::list_tag>{lists};
}
| 2,967 | 1,295 |
#include "msrating.h"
#include <npassert.h>
#include "array.h"
#include "msluglob.h"
#include "parselbl.h"
#include "debug.h"
#include <convtime.h>
#include <wininet.h>
extern BOOL LoadWinINet();
COptionsBase::COptionsBase()
{
m_cRef = 1;
m_timeUntil = 0xffffffff; /* as far in the future as possible */
m_fdwFlags = 0;
m_pszInvalidString = NULL;
m_pszURL = NULL;
}
void COptionsBase::AddRef()
{
m_cRef++;
}
void COptionsBase::Release()
{
if (!--m_cRef)
Delete();
}
void COptionsBase::Delete()
{
/* default does nothing when deleting reference */
}
BOOL COptionsBase::CheckUntil(DWORD timeUntil)
{
if (m_timeUntil <= timeUntil)
{
m_fdwFlags |= LBLOPT_EXPIRED;
return FALSE;
}
return TRUE;
}
/* AppendSlash forces pszString to end in a single slash if it doesn't
* already. This may produce a technically invalid URL (for example,
* "http://gregj/default.htm/", but we're only using the result for
* comparisons against other paths similarly mangled.
*/
void AppendSlash(LPSTR pszString)
{
LPSTR pszSlash = ::strrchrf(pszString, '/');
if (pszSlash == NULL || *(pszSlash + 1) != '\0')
::strcatf(pszString, "/");
}
extern BOOL (WINAPI *pfnInternetCrackUrl)(
IN LPCTSTR lpszUrl,
IN DWORD dwUrlLength,
IN DWORD dwFlags,
IN OUT LPURL_COMPONENTS lpUrlComponents
);
extern BOOL (WINAPI *pfnInternetCanonicalizeUrl)(
IN LPCSTR lpszUrl,
OUT LPSTR lpszBuffer,
IN OUT LPDWORD lpdwBufferLength,
IN DWORD dwFlags
);
BOOL DoURLsMatch(LPCSTR pszBaseURL, LPCSTR pszCheckURL, BOOL fGeneric)
{
/* Buffers to canonicalize URLs into */
LPSTR pszBaseCanon = new char[INTERNET_MAX_URL_LENGTH + 1];
LPSTR pszCheckCanon = new char[INTERNET_MAX_URL_LENGTH + 1];
if (pszBaseCanon != NULL && pszCheckCanon != NULL)
{
BOOL fCanonOK = FALSE;
DWORD cbBuffer = INTERNET_MAX_URL_LENGTH + 1;
if (pfnInternetCanonicalizeUrl(pszBaseURL, pszBaseCanon, &cbBuffer, ICU_ENCODE_SPACES_ONLY))
{
cbBuffer = INTERNET_MAX_URL_LENGTH + 1;
if (pfnInternetCanonicalizeUrl(pszCheckURL, pszCheckCanon, &cbBuffer, ICU_ENCODE_SPACES_ONLY))
{
fCanonOK = TRUE;
}
}
if (!fCanonOK)
{
delete pszBaseCanon;
pszBaseCanon = NULL;
delete pszCheckCanon;
pszCheckCanon = NULL;
return FALSE;
}
}
UINT cbBaseURL = strlenf(pszBaseCanon) + 1;
LPSTR pszBaseUrlPath = new char[cbBaseURL];
LPSTR pszBaseExtra = new char[cbBaseURL];
CHAR szBaseHostName[INTERNET_MAX_HOST_NAME_LENGTH];
CHAR szBaseUrlScheme[20]; // reasonable limit
UINT cbCheckURL = strlenf(pszCheckCanon) + 1;
LPSTR pszCheckUrlPath = new char[cbCheckURL];
LPSTR pszCheckExtra = new char[cbCheckURL];
CHAR szCheckHostName[INTERNET_MAX_HOST_NAME_LENGTH];
CHAR szCheckUrlScheme[20]; // reasonable limit
BOOL fOK = FALSE;
if (pszBaseUrlPath != NULL &&
pszBaseExtra != NULL &&
pszCheckUrlPath != NULL &&
pszCheckExtra != NULL)
{
URL_COMPONENTS ucBase, ucCheck;
memset(&ucBase, 0, sizeof(ucBase));
ucBase.dwStructSize = sizeof(ucBase);
ucBase.lpszScheme = szBaseUrlScheme;
ucBase.dwSchemeLength = sizeof(szBaseUrlScheme);
ucBase.lpszHostName = szBaseHostName;
ucBase.dwHostNameLength = sizeof(szBaseHostName);
ucBase.lpszUrlPath = pszBaseUrlPath;
ucBase.dwUrlPathLength = cbBaseURL;
ucBase.lpszExtraInfo = pszBaseExtra;
ucBase.dwExtraInfoLength = cbBaseURL;
memset(&ucCheck, 0, sizeof(ucCheck));
ucCheck.dwStructSize = sizeof(ucCheck);
ucCheck.lpszScheme = szCheckUrlScheme;
ucCheck.dwSchemeLength = sizeof(szCheckUrlScheme);
ucCheck.lpszHostName = szCheckHostName;
ucCheck.dwHostNameLength = sizeof(szCheckHostName);
ucCheck.lpszUrlPath = pszCheckUrlPath;
ucCheck.dwUrlPathLength = cbCheckURL;
ucCheck.lpszExtraInfo = pszCheckExtra;
ucCheck.dwExtraInfoLength = cbCheckURL;
if (pfnInternetCrackUrl(pszBaseCanon, 0, 0, &ucBase) &&
pfnInternetCrackUrl(pszCheckCanon, 0, 0, &ucCheck))
{
/* Scheme and host name must always match */
if (!stricmpf(ucBase.lpszScheme, ucCheck.lpszScheme) &&
!stricmpf(ucBase.lpszHostName, ucCheck.lpszHostName))
{
/* For extra info, just has to match exactly, even for a generic URL. */
if (!*ucBase.lpszExtraInfo ||
!stricmpf(ucBase.lpszExtraInfo, ucCheck.lpszExtraInfo))
{
AppendSlash(ucBase.lpszUrlPath);
AppendSlash(ucCheck.lpszUrlPath);
/* If not a generic label, path must match exactly too */
if (!fGeneric)
{
if (!stricmpf(ucBase.lpszUrlPath, ucCheck.lpszUrlPath))
{
fOK = TRUE;
}
}
else
{
UINT cbBasePath = strlenf(ucBase.lpszUrlPath);
if (!strnicmpf(ucBase.lpszUrlPath, ucCheck.lpszUrlPath, cbBasePath))
{
fOK = TRUE;
}
}
}
}
}
}
delete pszBaseUrlPath;
pszBaseUrlPath = NULL;
delete pszBaseExtra;
pszBaseExtra = NULL;
delete pszCheckUrlPath;
pszCheckUrlPath = NULL;
delete pszCheckExtra;
pszCheckExtra = NULL;
delete pszBaseCanon;
pszBaseCanon = NULL;
delete pszCheckCanon;
pszCheckCanon = NULL;
return fOK;
}
BOOL COptionsBase::CheckURL(LPCSTR pszURL)
{
if (!(m_fdwFlags & LBLOPT_URLCHECKED))
{
m_fdwFlags |= LBLOPT_URLCHECKED;
BOOL fInvalid = FALSE;
if (pszURL != NULL && m_pszURL != NULL)
{
if (LoadWinINet())
{
fInvalid = !DoURLsMatch(m_pszURL, pszURL, m_fdwFlags & LBLOPT_GENERIC);
}
}
if (fInvalid)
{
m_fdwFlags |= LBLOPT_WRONGURL;
}
}
return !(m_fdwFlags & LBLOPT_WRONGURL);
}
void CDynamicOptions::Delete()
{
delete this;
}
CParsedServiceInfo::CParsedServiceInfo()
{
m_pNext = NULL;
m_poptCurrent = &m_opt;
m_poptList = NULL;
m_pszServiceName = NULL;
m_pszErrorString = NULL;
m_fInstalled = TRUE; /* assume the best */
m_pszInvalidString = NULL;
m_pszCurrent = NULL;
}
void FreeOptionsList(CDynamicOptions *pList)
{
while (pList != NULL)
{
CDynamicOptions *pNext = pList->m_pNext;
delete pList;
pList = pNext;
}
}
CParsedServiceInfo::~CParsedServiceInfo()
{
FreeOptionsList(m_poptList);
}
void CParsedServiceInfo::Append(CParsedServiceInfo *pNew)
{
CParsedServiceInfo **ppNext = &m_pNext;
while (*ppNext != NULL)
{
ppNext = &((*ppNext)->m_pNext);
}
*ppNext = pNew;
pNew->m_pNext = NULL;
}
CParsedLabelList::CParsedLabelList()
{
m_pszList = NULL;
m_fRated = FALSE;
m_pszInvalidString = NULL;
m_pszURL = NULL;
m_pszOriginalLabel = NULL;
m_fDenied = FALSE;
m_fIsHelper = FALSE;
m_fNoRating = FALSE;
m_fIsCustomHelper = FALSE;
m_pszRatingName = NULL;
m_pszRatingReason = NULL;
}
CParsedLabelList::~CParsedLabelList()
{
delete m_pszList;
m_pszList = NULL;
CParsedServiceInfo *pInfo = m_ServiceInfo.Next();
while (pInfo != NULL)
{
CParsedServiceInfo *pNext = pInfo->Next();
delete pInfo;
pInfo = pNext;
}
delete m_pszURL;
m_pszURL = NULL;
delete m_pszOriginalLabel;
m_pszOriginalLabel = NULL;
delete [] m_pszRatingName;
m_pszRatingName = NULL;
delete [] m_pszRatingReason;
m_pszRatingReason = NULL;
}
/* SkipWhitespace(&pszString)
*
* advances pszString past whitespace characters
*/
void SkipWhitespace(LPSTR *ppsz)
{
UINT cchWhitespace = ::strspnf(*ppsz, szWhitespace);
*ppsz += cchWhitespace;
}
/* FindTokenEnd(pszStart)
*
* Returns a pointer to the end of a contiguous range of similarly-typed
* characters (whitespace, quote mark, punctuation, or alphanumerics).
*/
LPSTR FindTokenEnd(LPSTR pszStart)
{
LPSTR pszEnd = pszStart;
if (*pszEnd == '\0')
{
return pszEnd;
}
else if (strchrf(szSingleCharTokens, *pszEnd))
{
return ++pszEnd;
}
UINT cch;
cch = ::strspnf(pszEnd, szWhitespace);
if (cch > 0)
{
return pszEnd + cch;
}
cch = ::strspnf(pszEnd, szExtendedAlphaNum);
if (cch > 0)
{
return pszEnd + cch;
}
return pszEnd; /* unrecognized characters */
}
/* GetBool(LPSTR *ppszToken, BOOL *pfOut, PICSRulesBooleanSwitch PRBoolSwitch)
*
* t-markh 8/98 (
* added default parameter PRBoolSwitch=PR_BOOLEAN_TRUEFALSE
* this allows for no modification of existing code, and extension
* of the GetBool function from true/false to include pass/fail and
* yes/no. The enumerated type PICSRulesBooleanSwitch is defined
* in picsrule.h)
*
* Parses a boolean value at the given token and returns its value in *pfOut.
* Legal values are 't', 'f', 'true', and 'false'. If success, *ppszToken
* is advanced past the boolean token and any following whitespace. If failure,
* *ppszToken is not modified.
*
* pfOut may be NULL if the caller just wants to eat the token and doesn't
* care about its value.
*/
HRESULT GetBool(LPSTR *ppszToken, BOOL *pfOut, PICSRulesBooleanSwitch PRBoolSwitch)
{
BOOL bValue;
LPSTR pszTokenEnd = FindTokenEnd(*ppszToken);
switch(PRBoolSwitch)
{
case PR_BOOLEAN_TRUEFALSE:
{
if (IsEqualToken(*ppszToken, pszTokenEnd, szShortTrue) ||
IsEqualToken(*ppszToken, pszTokenEnd, szTrue))
{
bValue = TRUE;
}
else if (IsEqualToken(*ppszToken, pszTokenEnd, szShortFalse) ||
IsEqualToken(*ppszToken, pszTokenEnd, szFalse))
{
bValue = FALSE;
}
else
{
TraceMsg( TF_WARNING, "GetBool() - Failed True/False Token Parse at '%s'!", *ppszToken );
return ResultFromScode(MK_E_SYNTAX);
}
break;
}
case PR_BOOLEAN_PASSFAIL:
{
//szPRShortPass and szPRShortfail are not supported in the
//official PICSRules spec, but we'll catch them anyway
if (IsEqualToken(*ppszToken, pszTokenEnd, szPRShortPass) ||
IsEqualToken(*ppszToken, pszTokenEnd, szPRPass))
{
bValue = PR_PASSFAIL_PASS;
}
else if (IsEqualToken(*ppszToken, pszTokenEnd, szPRShortFail) ||
IsEqualToken(*ppszToken, pszTokenEnd, szPRFail))
{
bValue = PR_PASSFAIL_FAIL;
}
else
{
TraceMsg( TF_WARNING, "GetBool() - Failed Pass/Fail Token Parse at '%s'!", *ppszToken );
return ResultFromScode(MK_E_SYNTAX);
}
break;
}
case PR_BOOLEAN_YESNO:
{
if (IsEqualToken(*ppszToken, pszTokenEnd, szPRShortYes) ||
IsEqualToken(*ppszToken, pszTokenEnd, szPRYes))
{
bValue = PR_YESNO_YES;
}
else if (IsEqualToken(*ppszToken, pszTokenEnd, szPRShortNo) ||
IsEqualToken(*ppszToken, pszTokenEnd, szPRNo))
{
bValue = PR_YESNO_NO;
}
else
{
TraceMsg( TF_WARNING, "GetBool() - Failed Yes/No Token Parse at '%s'!", *ppszToken );
return ResultFromScode(MK_E_SYNTAX);
}
break;
}
default:
{
return(MK_E_UNAVAILABLE);
}
}
if (pfOut != NULL)
{
*pfOut = bValue;
}
*ppszToken = pszTokenEnd;
SkipWhitespace(ppszToken);
return NOERROR;
}
/* GetQuotedToken(&pszThisToken, &pszQuotedToken)
*
* Sets pszQuotedToken to point to the contents of the doublequotes.
* pszQuotedToken may be NULL if the caller just wants to eat the token.
* Sets pszThisToken to point to the first character after the closing
* doublequote.
* Fails if pszThisToken doesn't start with a doublequote or doesn't
* contain a closing doublequote.
* The closing doublequote is replaced with a null terminator, iff the
* function does not fail.
*/
HRESULT GetQuotedToken(LPSTR *ppszThisToken, LPSTR *ppszQuotedToken)
{
HRESULT hres = ResultFromScode(MK_E_SYNTAX);
LPSTR pszStart = *ppszThisToken;
if (*pszStart != '\"')
{
TraceMsg( TF_WARNING, "GetQuotedToken() - Failed to Find Start Quote at '%s'!", pszStart );
return hres;
}
pszStart++;
LPSTR pszEndQuote = strchrf(pszStart, '\"');
if (pszEndQuote == NULL)
{
TraceMsg( TF_WARNING, "GetQuotedToken() - Failed to Find End Quote at '%s'!", pszStart );
return hres;
}
*pszEndQuote = '\0';
if (ppszQuotedToken != NULL)
{
*ppszQuotedToken = pszStart;
}
*ppszThisToken = pszEndQuote+1;
return NOERROR;
}
BOOL IsEqualToken(LPCSTR pszTokenStart, LPCSTR pszTokenEnd, LPCSTR pszTokenToMatch)
{
UINT cbToken = strlenf(pszTokenToMatch);
if (cbToken != (UINT)(pszTokenEnd - pszTokenStart) || strnicmpf(pszTokenStart, pszTokenToMatch, cbToken))
{
return FALSE;
}
return TRUE;
}
/* ParseLiteralToken(ppsz, pszToken) tries to match *ppsz against pszToken.
* If they don't match, an error is returned. If they do match, then *ppsz
* is advanced past the token and any following whitespace.
*
* If ppszInvalid is NULL, then the function is non-destructive in the error
* path, so it's OK to call ParseLiteralToken just to see if a possible literal
* token is what's next; if the token isn't found, whatever was there didn't
* get eaten or anything.
*
* If ppszInvalid is not NULL, then if the token doesn't match, *ppszInvalid
* will be set to *ppsz.
*/
HRESULT ParseLiteralToken(LPSTR *ppsz, LPCSTR pszToken, LPCSTR *ppszInvalid)
{
LPSTR pszTokenEnd = FindTokenEnd(*ppsz);
if (!IsEqualToken(*ppsz, pszTokenEnd, pszToken))
{
if (ppszInvalid != NULL)
{
*ppszInvalid = *ppsz;
}
// TraceMsg( TF_WARNING, "ParseLiteralToken() - Token '%s' Not Found at '%s'!", pszToken, *ppsz );
return ResultFromScode(MK_E_SYNTAX);
}
*ppsz = pszTokenEnd;
SkipWhitespace(ppsz);
return NOERROR;
}
/* ParseServiceError parses a service-error construct, once it's been
* determined that such is the case. m_pszCurrent has been advanced past
* the 'error' keyword that indicates a service-error.
*
* We're pretty flexible about the contents of this stuff. We basically
* accept anything of the form:
*
* 'error' '(' <error string> [quoted explanations] ')' - or -
* 'error' <error string>
*
* without caring too much about what the error string actually is.
*
* A format with quoted explanations but without the parens would not be
* legal, we wouldn't be able to distinguish the explanations from the
* serviceID of the next service-info.
*/
HRESULT CParsedServiceInfo::ParseServiceError()
{
BOOL fParen = FALSE;
HRESULT hres = NOERROR;
if (SUCCEEDED(ParseLiteralToken(&m_pszCurrent, szLeftParen, NULL)))
{
fParen = TRUE;
}
LPSTR pszErrorEnd = FindTokenEnd(m_pszCurrent); /* find end of error string */
m_pszErrorString = m_pszCurrent; /* remember start of error string */
if (fParen)
{ /* need to eat explanations */
m_pszCurrent = pszErrorEnd; /* skip error string to get to explanations */
SkipWhitespace();
while (SUCCEEDED(hres))
{
hres = GetQuotedToken(&m_pszCurrent, NULL);
SkipWhitespace();
}
}
if (fParen)
{
hres = ParseLiteralToken(&m_pszCurrent, szRightParen, &m_pszInvalidString);
}
else
{
hres = NOERROR;
}
if (SUCCEEDED(hres))
{
*pszErrorEnd = '\0'; /* null-terminate the error string */
}
return hres;
}
/* ParseNumber parses a numeric token at the specified position. If the
* number makes sense, the pointer is advanced to the end of the number
* and past any following whitespace, and the numeric value is returned
* in *pnOut. Any non-numeric characters are considered to terminate the
* number without error; it is assumed that higher-level parsing code
* will eventually reject such characters if they're not supposed to be
* there.
*
* pnOut may be NULL if the caller doesn't care about the number being
* returned and just wants to eat it.
*
* Floating point numbers of the form nnn.nnn are rounded to the next
* higher integer and returned as such.
*/
//t-markh 8/98 - added fPICSRules for line counting support in PICSRules
HRESULT ParseNumber(LPSTR *ppszNumber, INT *pnOut,BOOL fPICSRules)
{
HRESULT hres = ResultFromScode(MK_E_SYNTAX);
BOOL fNegative = FALSE;
INT nAccum = 0;
BOOL fNonZeroDecimal = FALSE;
BOOL fInDecimal = FALSE;
BOOL fFoundDigits = FALSE;
LPSTR pszCurrent = *ppszNumber;
/* Handle one sign character. */
if (*pszCurrent == '+')
{
pszCurrent++;
}
else if (*pszCurrent == '-')
{
pszCurrent++;
fNegative = TRUE;
}
for (;;)
{
if (*pszCurrent == '.')
{
fInDecimal = TRUE;
}
else if (*pszCurrent >= '0' && *pszCurrent <= '9')
{
fFoundDigits = TRUE;
if (fInDecimal)
{
if (*pszCurrent > '0')
{
fNonZeroDecimal = TRUE;
}
}
else
{
nAccum = nAccum * 10 + (*pszCurrent - '0');
}
}
else
{
break;
}
pszCurrent++;
}
if (fFoundDigits)
{
hres = NOERROR;
if (fNonZeroDecimal)
{
nAccum++; /* round away from zero if decimal present */
}
if (fNegative)
{
nAccum = -nAccum;
}
}
if (SUCCEEDED(hres))
{
if (pnOut != NULL)
{
*pnOut = nAccum;
}
*ppszNumber = pszCurrent;
if ( fPICSRules == FALSE )
{
SkipWhitespace(ppszNumber);
}
}
else
{
TraceMsg( TF_WARNING, "ParseNumber() - Failed with hres=0x%x at '%s'!", hres, pszCurrent );
}
return hres;
}
/* ParseExtensionData just needs to get past whatever data was supplied
* for an extension. The PICS spec implies that it can be recursive, which
* complicates matters a bit:
*
* data :: quoted-ISO-date | quotedURL | number | quotedname | '(' data* ')'
*
* Use of recursion here is probably OK, we don't really expect complicated
* nested extensions all that often, and this function doesn't use a lot of
* stack or other resources...
*/
HRESULT CParsedServiceInfo::ParseExtensionData(COptionsBase *pOpt)
{
HRESULT hres;
if (SUCCEEDED(ParseLiteralToken(&m_pszCurrent, szLeftParen, NULL)))
{
hres = ParseExtensionData(pOpt);
if (FAILED(hres))
{
return hres;
}
return ParseLiteralToken(&m_pszCurrent, szRightParen, &m_pszInvalidString);
}
if (SUCCEEDED(GetQuotedToken(&m_pszCurrent, NULL)))
{
SkipWhitespace();
return NOERROR;
}
hres = ParseNumber(&m_pszCurrent, NULL);
if (FAILED(hres))
{
m_pszInvalidString = m_pszCurrent;
}
return hres;
}
/* ParseExtension parses an extension option. Syntax is:
*
* extension ( mandatory|optional "identifyingURL" data )
*
* Currently all extensions are parsed but ignored, although a mandatory
* extension causes the entire options structure and anything dependent
* on it to be invalidated.
*/
HRESULT CParsedServiceInfo::ParseExtension(COptionsBase *pOpt)
{
HRESULT hres;
hres = ParseLiteralToken(&m_pszCurrent, szLeftParen, &m_pszInvalidString);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseExtension() - Missing '(' at '%s'!", m_pszInvalidString );
return hres;
}
hres = ParseLiteralToken(&m_pszCurrent, szOptional, &m_pszInvalidString);
if (FAILED(hres))
{
hres = ParseLiteralToken(&m_pszCurrent, szMandatory, &m_pszInvalidString);
if (SUCCEEDED(hres))
{
pOpt->m_fdwFlags |= LBLOPT_INVALID;
}
}
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseExtension() - Failed ParseLiteralToken() with hres=0x%x at '%s'!", hres, m_pszInvalidString );
return hres; /* this causes us to lose our place -- OK? */
}
hres = GetQuotedToken(&m_pszCurrent, NULL);
if (FAILED(hres))
{
m_pszInvalidString = m_pszCurrent;
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseExtension() - Missing Quote at '%s'!", m_pszInvalidString );
return hres;
}
SkipWhitespace();
while (*m_pszCurrent != ')' && *m_pszCurrent != '\0')
{
hres = ParseExtensionData(pOpt);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseExtension() - Failed ParseExtensionData() with hres=0x%x!", hres );
return hres;
}
}
if (*m_pszCurrent != ')')
{
m_pszInvalidString = m_pszCurrent;
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseExtension() - Missing ')' at '%s'!", m_pszInvalidString );
return ResultFromScode(MK_E_SYNTAX);
}
m_pszCurrent++;
SkipWhitespace();
return NOERROR;
}
/* ParseTime parses a "quoted-ISO-date" as found in a label. This is required
* to have the following form, as quoted from the PICS spec:
*
* quoted-ISO-date :: YYYY'.'MM'.'DD'T'hh':'mmStz
* YYYY :: four-digit year
* MM :: two-digit month (01=January, etc.)
* DD :: two-digit day of month (01-31)
* hh :: two digits of hour (00-23)
* mm :: two digits of minute (00-59)
* S :: sign of time zone offset from UTC (+ or -)
* tz :: four digit amount of offset from UTC (e.g., 1512 means 15 hours 12 minutes)
*
* Example: "1994.11.05T08:15-0500" means Nov. 5, 1994, 8:15am, US EST.
*
* Time is parsed into NET format -- seconds since 1970 (easiest to adjust for
* time zones, and compare with). Returns an error if string is invalid.
*/
/* Template describing the string format. 'n' means a digit, '+' means a
* plus or minus sign, any other character must match that literal character.
*/
const char szTimeTemplate[] = "nnnn.nn.nnTnn:nn+nnnn";
const char szPICSRulesTimeTemplate[] = "nnnn-nn-nnTnn:nn+nnnn";
HRESULT ParseTime(LPSTR pszTime, DWORD *pOut, BOOL fPICSRules)
{
/* Copy the time string into a temporary buffer, since we're going to
* stomp on some separators. We preserve the original in case it turns
* out to be invalid and we have to show it to the user later.
*/
LPCSTR pszCurrTemplate;
char szTemp[sizeof(szTimeTemplate)];
if (::strlenf(pszTime) >= sizeof(szTemp))
{
TraceMsg( TF_WARNING, "ParseTime() - Time String Too Long (pszTime='%s', %d chars expected)!", pszTime, sizeof(szTemp) );
return ResultFromScode(MK_E_SYNTAX);
}
strcpyf(szTemp, pszTime);
LPSTR pszCurrent = szTemp;
if(fPICSRules)
{
pszCurrTemplate = szPICSRulesTimeTemplate;
}
else
{
pszCurrTemplate = szTimeTemplate;
}
/* First validate the format against the template. If that succeeds, then
* we get to make all sorts of assumptions later.
*
* We stomp all separators except the +/- for the timezone with spaces
* so that ParseNumber will (a) skip them for us, and (b) not interpret
* the '.' separators as decimal points.
*/
BOOL fOK = TRUE;
while (*pszCurrent && *pszCurrTemplate && fOK)
{
char chCurrent = *pszCurrent;
switch (*pszCurrTemplate)
{
case 'n':
if (chCurrent < '0' || chCurrent > '9')
{
fOK = FALSE;
}
break;
case '+':
if (chCurrent != '+' && chCurrent != '-')
{
fOK = FALSE;
}
break;
default:
if (chCurrent != *pszCurrTemplate)
{
fOK = FALSE;
}
else
{
*pszCurrent = ' ';
}
break;
}
pszCurrent++;
pszCurrTemplate++;
}
/* If invalid character, or didn't reach the ends of both strings
* simultaneously, fail.
*/
if (!fOK || *pszCurrent || *pszCurrTemplate)
{
TraceMsg( TF_WARNING, "ParseTime() - Invalid Character or Strings Mismatch (fOK=%d, pszCurrent='%s', pszCurrTemplate='%s')!", fOK, pszCurrent, pszCurrTemplate );
return ResultFromScode(MK_E_SYNTAX);
}
HRESULT hres;
int n;
SYSTEMTIME st;
/* We parse into SYSTEMTIME structure because it has separate fields for
* the different components. We then convert to net time (seconds since
* Jan 1 1970) to easily add the timezone bias and compare with other
* times.
*
* The sense of the bias sign is inverted because it indicates the direction
* of the bias FROM UTC. We want to use it to convert the specified time
* back TO UTC.
*/
int nBiasSign = -1;
int nBiasNumber;
pszCurrent = szTemp;
hres = ParseNumber(&pszCurrent, &n);
if (SUCCEEDED(hres) && n >= 1980)
{
st.wYear = (WORD)n;
hres = ParseNumber(&pszCurrent, &n);
if (SUCCEEDED(hres) && n <= 12)
{
st.wMonth = (WORD)n;
hres = ParseNumber(&pszCurrent, &n);
if (SUCCEEDED(hres) && n < 32)
{
st.wDay = (WORD)n;
hres = ParseNumber(&pszCurrent, &n);
if (SUCCEEDED(hres) && n <= 23)
{
st.wHour = (WORD)n;
hres = ParseNumber(&pszCurrent, &n);
if (SUCCEEDED(hres) && n <= 59)
{
st.wMinute = (WORD)n;
if (*(pszCurrent++) == '-')
{
nBiasSign = 1;
}
hres = ParseNumber(&pszCurrent, &nBiasNumber);
}
}
}
}
}
/* Seconds are used by the time converter, but are not specified in
* the label.
*/
st.wSecond = 0;
/* Other fields (wDayOfWeek, wMilliseconds) are ignored when converting
* to net time.
*/
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "ParseTime() - Failed to Parse Time where hres=0x%x!", hres );
return hres;
}
DWORD dwTime = SystemToNetDate(&st);
/* The bias number is 4 digits, but hours and minutes. Convert to
* a number of seconds.
*/
nBiasNumber = (((nBiasNumber / 100) * 60) + (nBiasNumber % 100)) * 60;
/* Adjust the time by the timezone bias, and return to the caller. */
*pOut = dwTime + (nBiasNumber * nBiasSign);
return hres;
}
/* ParseOptions parses through any label options that may be present at
* m_pszCurrent. pszTokenEnd initially points to the end of the token at
* m_pszCurrent, a small perf win since the caller has already calculated
* it. If ParseOptions is filling in the static options structure embedded
* in the serviceinfo, pOpt points to it and ppOptOut will be NULL. If pOpt
* is NULL, then ParseOptions will construct a new CDynamicOptions object
* and return it in *ppOptOut, iff any new options are found at the current
* token. pszOptionEndToken indicates the token which ends the list of
* options -- either "labels" or "ratings". A token consisting of just the
* first character of pszOptionEndToken will also terminate the list.
*
* ParseOptions fails iff it finds an option it doesn't recognize, or a
* syntax error in an option it does recognize. It succeeds if all options
* are syntactically correct or if there are no options to parse.
*
* The token which terminates the list of options is also consumed.
*
* FEATURE - how should we flag mandatory extensions, 'until' options that
* give an expired date, etc.? set a flag in the CParsedServiceInfo and
* keep parsing?
*/
enum OptionID {
OID_AT,
OID_BY,
OID_COMMENT,
OID_FULL,
OID_EXTENSION,
OID_GENERIC,
OID_FOR,
OID_MIC,
OID_ON,
OID_SIG,
OID_UNTIL
};
enum OptionContents {
OC_QUOTED,
OC_BOOL,
OC_SPECIAL
};
const struct {
LPCSTR pszToken;
OptionID oid;
OptionContents oc;
} aKnownOptions[] = {
{ szAtOption, OID_AT, OC_QUOTED },
{ szByOption, OID_BY, OC_QUOTED },
{ szCommentOption, OID_COMMENT, OC_QUOTED },
{ szCompleteLabelOption, OID_FULL, OC_QUOTED },
{ szFullOption, OID_FULL, OC_QUOTED },
{ szExtensionOption, OID_EXTENSION, OC_SPECIAL },
{ szGenericOption, OID_GENERIC, OC_BOOL },
{ szShortGenericOption, OID_GENERIC, OC_BOOL },
{ szForOption, OID_FOR, OC_QUOTED },
{ szMICOption, OID_MIC, OC_QUOTED },
{ szMD5Option, OID_MIC, OC_QUOTED },
{ szOnOption, OID_ON, OC_QUOTED },
{ szSigOption, OID_SIG, OC_QUOTED },
{ szUntilOption, OID_UNTIL, OC_QUOTED },
{ szExpOption, OID_UNTIL, OC_QUOTED }
};
const UINT cKnownOptions = sizeof(aKnownOptions) / sizeof(aKnownOptions[0]);
HRESULT CParsedServiceInfo::ParseOptions(LPSTR pszTokenEnd, COptionsBase *pOpt,
CDynamicOptions **ppOptOut, LPCSTR pszOptionEndToken)
{
HRESULT hres = NOERROR;
char szShortOptionEndToken[2];
szShortOptionEndToken[0] = *pszOptionEndToken;
szShortOptionEndToken[1] = '\0';
if (pszTokenEnd == NULL)
{
pszTokenEnd = FindTokenEnd(m_pszCurrent);
}
do
{
/* Have we hit the token that signals the end of the options? */
if (IsEqualToken(m_pszCurrent, pszTokenEnd, pszOptionEndToken) ||
IsEqualToken(m_pszCurrent, pszTokenEnd, szShortOptionEndToken))
{
m_pszCurrent = pszTokenEnd;
SkipWhitespace();
return NOERROR;
}
for (UINT i=0; i<cKnownOptions; i++)
{
if (IsEqualToken(m_pszCurrent, pszTokenEnd, aKnownOptions[i].pszToken))
{
break;
}
}
if (i == cKnownOptions)
{
m_pszInvalidString = m_pszCurrent;
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseOptions() - Unknown Token Encountered at '%s'!", m_pszInvalidString );
return ResultFromScode(MK_E_SYNTAX); /* unrecognized option */
}
m_pszCurrent = pszTokenEnd;
SkipWhitespace();
/* Now parse the stuff that comes after the option token. */
LPSTR pszQuotedString = NULL;
BOOL fBoolOpt = FALSE;
switch (aKnownOptions[i].oc)
{
case OC_QUOTED:
hres = GetQuotedToken(&m_pszCurrent, &pszQuotedString);
break;
case OC_BOOL:
hres = GetBool(&m_pszCurrent, &fBoolOpt);
break;
case OC_SPECIAL:
break; /* we'll handle this specially */
}
if (FAILED(hres))
{ /* incorrect stuff after the option token */
m_pszInvalidString = m_pszCurrent;
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseOptions() - Failed Option Contents Parse at '%s'!", m_pszInvalidString );
return hres;
}
if (pOpt == NULL)
{ /* need to allocate a new options structure */
CDynamicOptions *pNew = new CDynamicOptions;
if (pNew == NULL)
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseOptions() - Failed to Create CDynamicOptions Object!" );
return ResultFromScode(E_OUTOFMEMORY);
}
pOpt = pNew;
*ppOptOut = pNew; /* return new structure to caller */
}
/* Now actually do useful stuff based on which option it is. */
switch (aKnownOptions[i].oid)
{
case OID_UNTIL:
hres = ParseTime(pszQuotedString, &pOpt->m_timeUntil);
if (FAILED(hres))
{
m_pszInvalidString = pszQuotedString;
}
break;
case OID_FOR:
pOpt->m_pszURL = pszQuotedString;
break;
case OID_GENERIC:
if (fBoolOpt)
{
pOpt->m_fdwFlags |= LBLOPT_GENERIC;
}
else
{
pOpt->m_fdwFlags &= ~LBLOPT_GENERIC;
}
break;
case OID_EXTENSION:
hres = ParseExtension(pOpt);
break;
}
if ( FAILED(hres) )
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseOptions() - Failed Option ID Parse at '%s'!", m_pszCurrent );
}
SkipWhitespace();
pszTokenEnd = FindTokenEnd(m_pszCurrent);
} while (SUCCEEDED(hres));
return hres;
}
/* CParsedServiceInfo::ParseRating parses a single rating -- a transmit-name
* followed by either a number or a parenthesized list of multi-values. The
* corresponding rating is stored in the current list of ratings.
*/
HRESULT CParsedServiceInfo::ParseRating()
{
LPSTR pszTokenEnd = FindTokenEnd(m_pszCurrent);
if (*m_pszCurrent == '\0')
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseRating() - Empty String after FindTokenEnd()!" );
return ResultFromScode(MK_E_SYNTAX);
}
*(pszTokenEnd++) = '\0';
CParsedRating r;
r.pszTransmitName = m_pszCurrent;
m_pszCurrent = pszTokenEnd;
SkipWhitespace();
HRESULT hres = ParseNumber(&m_pszCurrent, &r.nValue);
if (FAILED(hres))
{
m_pszInvalidString = m_pszCurrent;
return hres;
}
r.pOptions = m_poptCurrent;
r.fFound = FALSE;
r.fFailed = FALSE;
return (aRatings.Append(r) ? NOERROR : ResultFromScode(E_OUTOFMEMORY));
}
/* CParsedServiceInfo::ParseSingleLabel starts parsing where a single-label
* should occur. A single-label may contain options (in which case a new
* options structure will be allocated), following by the keyword 'ratings'
* (or 'r') and a parenthesized list of ratings.
*/
HRESULT CParsedServiceInfo::ParseSingleLabel()
{
HRESULT hres;
CDynamicOptions *pOpt = NULL;
hres = ParseOptions(NULL, NULL, &pOpt, szRatings);
if (FAILED(hres))
{
if (pOpt != NULL)
{
pOpt->Release();
}
return hres;
}
if (pOpt != NULL)
{
pOpt->m_pNext = m_poptList;
m_poptList = pOpt;
m_poptCurrent = pOpt;
}
hres = ParseLiteralToken(&m_pszCurrent, szLeftParen, &m_pszInvalidString);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseSingleLabel() - ParseLiteralToken() Failed with hres=0x%x!", hres );
return hres;
}
do
{
hres = ParseRating();
} while (SUCCEEDED(hres) && *m_pszCurrent != ')' && *m_pszCurrent != '\0');
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseSingleLabel() - ParseRating() Failed with hres=0x%x!", hres );
return hres;
}
return ParseLiteralToken(&m_pszCurrent, szRightParen, &m_pszInvalidString);
}
/* CParsedServiceInfo::ParseLabels starts parsing just past the keyword
* 'labels' (or 'l'). It needs to handle a label-error, a single-label,
* or a parenthesized list of single-labels.
*/
HRESULT CParsedServiceInfo::ParseLabels()
{
HRESULT hres;
/* First deal with a label-error. It begins with the keyword 'error'. */
if (SUCCEEDED(ParseLiteralToken(&m_pszCurrent, szError, NULL)))
{
hres = ParseLiteralToken(&m_pszCurrent, szLeftParen, &m_pszInvalidString);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseLabels() - ParseLiteralToken() Failed with hres=0x%x!", hres );
return hres;
}
LPSTR pszTokenEnd = FindTokenEnd(m_pszCurrent);
m_pszErrorString = m_pszCurrent;
m_pszCurrent = pszTokenEnd;
SkipWhitespace();
while (*m_pszCurrent != ')')
{
hres = GetQuotedToken(&m_pszCurrent, NULL);
if (FAILED(hres))
{
m_pszInvalidString = m_pszCurrent;
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseLabels() - GetQuotedToken() Failed with hres=0x%x!", hres );
return hres;
}
}
return NOERROR;
}
BOOL fParenthesized = FALSE;
/* If we see a left paren, it's a parenthesized list of single-labels,
* which basically means we'll have to eat an extra parenthesis later.
*/
if (SUCCEEDED(ParseLiteralToken(&m_pszCurrent, szLeftParen, NULL)))
{
fParenthesized = TRUE;
}
for (;;)
{
/* Things which signify the end of the label list:
* - the close parenthesis checked for above
* - a quoted string, indicating the next service-info
* - the end of the string
* - a service-info saying "error (no-ratings <explanation>)"
*
* Check the easy ones first.
*/
if (*m_pszCurrent == ')' || *m_pszCurrent == '\"' || *m_pszCurrent == '\0')
{
break;
}
/* Now look for that tricky error-state service-info. */
LPSTR pszTemp = m_pszCurrent;
if (SUCCEEDED(ParseLiteralToken(&pszTemp, szError, NULL)) &&
SUCCEEDED(ParseLiteralToken(&pszTemp, szLeftParen, NULL)) &&
SUCCEEDED(ParseLiteralToken(&pszTemp, szNoRatings, NULL)))
{
break;
}
hres = ParseSingleLabel();
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedServiceInfo::ParseLabels() - ParseSingleLabel() Failed with hres=0x%x!", hres );
return hres;
}
}
if (fParenthesized)
{
return ParseLiteralToken(&m_pszCurrent, szRightParen, &m_pszInvalidString);
}
return NOERROR;
}
/* Parse is passed a pointer to a pointer to something which should
* be a service-info string (i.e., not the close paren for the labellist, and
* not the end of the string). The caller's string pointer is advanced to the
* end of the service-info string.
*/
HRESULT CParsedServiceInfo::Parse(LPSTR *ppszServiceInfo)
{
/* NOTE: Do not return out of this function without copying m_pszCurrent
* back into *ppszServiceInfo! Always store your return code in hres and
* exit out the bottom of the function.
*/
HRESULT hres;
m_pszCurrent = *ppszServiceInfo;
hres = ParseLiteralToken(&m_pszCurrent, szError, NULL);
if (SUCCEEDED(hres))
{
/* Keyword is 'error'. Better be followed by '(', 'no-ratings',
* explanations, and a close-paren.
*/
hres = ParseLiteralToken(&m_pszCurrent, szLeftParen, &m_pszInvalidString);
if (SUCCEEDED(hres))
{
hres = ParseLiteralToken(&m_pszCurrent, szNoRatings, &m_pszInvalidString);
}
if (SUCCEEDED(hres))
{
m_pszErrorString = szNoRatings;
while (*m_pszCurrent != ')' && *m_pszCurrent != '\0')
{
hres = GetQuotedToken(&m_pszCurrent, NULL);
if (FAILED(hres))
{
m_pszInvalidString = m_pszCurrent;
break;
}
SkipWhitespace();
}
if (*m_pszCurrent == ')')
{
m_pszCurrent++;
SkipWhitespace();
}
}
}
else
{
/* Keyword is not 'error'. Better start with a serviceID --
* a quoted URL.
*/
LPSTR pszServiceID;
hres = GetQuotedToken(&m_pszCurrent, &pszServiceID);
if (SUCCEEDED(hres))
{
m_pszServiceName = pszServiceID;
SkipWhitespace();
/* Past the serviceID. Next either 'error' indicating a service-error,
* or we start options and then a labelword.
*/
LPSTR pszTokenEnd = FindTokenEnd(m_pszCurrent);
if (IsEqualToken(m_pszCurrent, pszTokenEnd, szError))
{
m_pszCurrent = pszTokenEnd;
SkipWhitespace();
hres = ParseServiceError();
}
else
{
hres = ParseOptions(pszTokenEnd, &m_opt, NULL, ::szLabelWord);
if (SUCCEEDED(hres))
{
hres = ParseLabels();
}
}
}
else
{
m_pszInvalidString = m_pszCurrent;
}
}
*ppszServiceInfo = m_pszCurrent;
return hres;
}
const char szPicsVersionLabel[] = "PICS-";
const UINT cchLabel = (sizeof(szPicsVersionLabel)-1) / sizeof(szPicsVersionLabel[0]);
HRESULT CParsedLabelList::Parse(LPSTR pszCopy)
{
m_pszList = pszCopy; /* we own the label list string now */
/* Make another copy, which we won't carve up during parsing, so that the
* access-denied dialog can compare literal labels.
*/
m_pszOriginalLabel = new char[::strlenf(pszCopy)+1];
if (m_pszOriginalLabel != NULL)
{
::strcpyf(m_pszOriginalLabel, pszCopy);
}
m_pszCurrent = m_pszList;
SkipWhitespace();
HRESULT hres;
hres = ParseLiteralToken(&m_pszCurrent, szLeftParen, &m_pszInvalidString);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedLabelList::Parse() - ParseLiteralToken() Failed with hres=0x%x!", hres );
return hres;
}
if (strnicmpf(m_pszCurrent, szPicsVersionLabel, cchLabel))
{
TraceMsg( TF_WARNING, "CParsedLabelList::Parse() - Pics Version Label Comparison Failed at '%s'!", m_pszCurrent );
return ResultFromScode(MK_E_SYNTAX);
}
m_pszCurrent += cchLabel;
INT nVersion;
hres = ParseNumber(&m_pszCurrent, &nVersion);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedLabelList::Parse() - ParseNumber() Failed with hres=0x%x!", hres );
return hres;
}
CParsedServiceInfo *psi = &m_ServiceInfo;
do
{
hres = psi->Parse(&m_pszCurrent);
if (FAILED(hres))
{
TraceMsg( TF_WARNING, "CParsedLabelList::Parse() - psi->Parse() Failed with hres=0x%x!", hres );
return hres;
}
if (*m_pszCurrent != ')' && *m_pszCurrent != '\0')
{
CParsedServiceInfo *pNew = new CParsedServiceInfo;
if (pNew == NULL)
{
TraceMsg( TF_WARNING, "CParsedLabelList::Parse() - Failed to Create CParsedServiceInfo!" );
return ResultFromScode(E_OUTOFMEMORY);
}
psi->Append(pNew);
psi = pNew;
}
} while (*m_pszCurrent != ')' && *m_pszCurrent != '\0');
return NOERROR;
}
HRESULT ParseLabelList(LPCSTR pszList, CParsedLabelList **ppParsed)
{
LPSTR pszCopy = new char[strlenf(pszList)+1];
if (pszCopy == NULL)
{
TraceMsg( TF_WARNING, "ParseLabelList() - Failed to Create pszCopy!" );
return ResultFromScode(E_OUTOFMEMORY);
}
::strcpyf(pszCopy, pszList);
*ppParsed = new CParsedLabelList;
if (*ppParsed == NULL)
{
TraceMsg( TF_WARNING, "ParseLabelList() - Failed to Create CParsedLabelList!" );
delete pszCopy;
pszCopy = NULL;
return ResultFromScode(E_OUTOFMEMORY);
}
return (*ppParsed)->Parse(pszCopy);
}
void FreeParsedLabelList(CParsedLabelList *pList)
{
delete pList;
pList = NULL;
}
| 46,311 | 15,574 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <deque>
#include <iostream>
#include "absl/memory/memory.h"
#include "absl/strings/str_format.h"
#include "tensorflow/core/grappler/graph_analyzer/gen_node.h"
#include "tensorflow/core/grappler/graph_analyzer/graph_analyzer.h"
#include "tensorflow/core/grappler/graph_analyzer/sig_node.h"
namespace tensorflow {
namespace grappler {
namespace graph_analyzer {
GraphAnalyzer::GraphAnalyzer(const GraphDef& graph, int subgraph_size)
: graph_(graph), subgraph_size_(subgraph_size) {}
GraphAnalyzer::~GraphAnalyzer() {}
Status GraphAnalyzer::Run() {
// The signature computation code would detect this too, but better
// to report it up front than spend time computing all the graphs first.
if (subgraph_size_ > Signature::kMaxGraphSize) {
return Status(error::INVALID_ARGUMENT,
absl::StrFormat("Subgraphs of %d nodes are not supported, "
"the maximal supported node count is %d.",
subgraph_size_, Signature::kMaxGraphSize));
}
Status st = BuildMap();
if (!st.ok()) {
return st;
}
FindSubgraphs();
DropInvalidSubgraphs();
st = CollateResult();
if (!st.ok()) {
return st;
}
return Status::OK();
}
Status GraphAnalyzer::BuildMap() {
nodes_.clear();
return GenNode::BuildGraphInMap(graph_, &nodes_);
}
void GraphAnalyzer::FindSubgraphs() {
result_.clear();
if (subgraph_size_ < 1) {
return;
}
partial_.clear();
todo_.clear(); // Just in case.
// Start with all subgraphs of size 1.
const Subgraph::Identity empty_parent;
for (const auto& node : nodes_) {
if (subgraph_size_ == 1) {
result_.ExtendParent(empty_parent, node.second.get());
} else {
// At this point ExtendParent() is guaranteed to not return nullptr.
todo_.push_back(partial_.ExtendParent(empty_parent, node.second.get()));
}
}
// Then extend the subgraphs until no more extensions are possible.
while (!todo_.empty()) {
ExtendSubgraph(todo_.front());
todo_.pop_front();
}
partial_.clear();
}
void GraphAnalyzer::ExtendSubgraph(Subgraph* parent) {
bool will_complete = (parent->id().size() + 1 == subgraph_size_);
SubgraphPtrSet& sg_set = will_complete ? result_ : partial_;
const GenNode* last_all_or_none_node = nullptr;
for (SubgraphIterator sit(parent); !sit.AtEnd(); sit.Next()) {
const GenNode* node = sit.GetNode();
GenNode::Port port = sit.GetPort();
const GenNode::LinkTarget& neighbor = sit.GetNeighbor();
if (node->AllInputsOrNone() && port.IsInbound() && !port.IsControl()) {
if (node != last_all_or_none_node) {
ExtendSubgraphAllOrNone(parent, node);
last_all_or_none_node = node;
}
sit.SkipPort();
} else if (neighbor.node->AllInputsOrNone() && !port.IsInbound() &&
!port.IsControl()) {
if (parent->id().find(neighbor.node) == parent->id().end()) {
// Not added yet.
ExtendSubgraphAllOrNone(parent, neighbor.node);
}
} else if (node->IsMultiInput(port)) {
ExtendSubgraphPortAllOrNone(parent, node, port);
sit.SkipPort();
} else if (neighbor.node->IsMultiInput(neighbor.port)) {
// Would need to add all inputs of the neighbor node at this port at
// once.
if (parent->id().find(neighbor.node) != parent->id().end()) {
continue; // Already added.
}
ExtendSubgraphPortAllOrNone(parent, neighbor.node, neighbor.port);
} else {
Subgraph* sg = sg_set.ExtendParent(parent->id(), neighbor.node);
if (!will_complete && sg != nullptr) {
todo_.push_back(sg);
}
}
}
}
void GraphAnalyzer::ExtendSubgraphAllOrNone(Subgraph* parent,
const GenNode* node) {
Subgraph::Identity id = parent->id();
id.insert(node);
auto range_end = node->links().end();
for (auto nbit = node->links().begin(); nbit != range_end; ++nbit) {
auto port = nbit->first;
if (!port.IsInbound() || port.IsControl()) {
continue;
}
// Since there might be multiple links to the same nodes,
// have to add all links one-by-one to check whether the subgraph
// would grow too large. But if it does grow too large, there is no
// point in growing it more, can just skip over the rest of the links.
for (const auto& link : nbit->second) {
id.insert(link.node);
if (id.size() > subgraph_size_) {
return; // Too big.
}
}
}
AddExtendedSubgraph(parent, id);
}
void GraphAnalyzer::ExtendSubgraphPortAllOrNone(Subgraph* parent,
const GenNode* node,
GenNode::Port port) {
auto nbit = node->links().find(port);
if (nbit == node->links().end()) {
return; // Should never happen.
}
Subgraph::Identity id = parent->id();
id.insert(node);
// Since there might be multiple links to the same nodes,
// have to add all links one-by-one to check whether the subgraph
// would grow too large. But if it does grow too large, there is no
// point in growing it more, can just skip over the rest of the links.
for (const auto& link : nbit->second) {
id.insert(link.node);
if (id.size() > subgraph_size_) {
return; // Too big.
}
}
AddExtendedSubgraph(parent, id);
}
void GraphAnalyzer::AddExtendedSubgraph(Subgraph* parent,
const Subgraph::Identity& id) {
if (id.size() == parent->id().size()) {
return; // Nothing new was added.
}
auto sg = absl::make_unique<Subgraph>(id);
SubgraphPtrSet& spec_sg_set =
(id.size() == subgraph_size_) ? result_ : partial_;
if (spec_sg_set.find(sg) != spec_sg_set.end()) {
// This subgraph was already found by extending from a different path.
return;
}
if (id.size() != subgraph_size_) {
todo_.push_back(sg.get());
}
spec_sg_set.insert(std::move(sg));
}
void GraphAnalyzer::DropInvalidSubgraphs() {
auto resit = result_.begin();
while (resit != result_.end()) {
if (HasInvalidMultiInputs(resit->get())) {
auto delit = resit;
++resit;
result_.erase(delit);
} else {
++resit;
}
}
}
bool GraphAnalyzer::HasInvalidMultiInputs(Subgraph* sg) {
// Do the all-or-none-input nodes.
for (auto const& node : sg->id()) {
if (!node->AllInputsOrNone()) {
continue;
}
bool anyIn = false;
bool anyOut = false;
auto range_end = node->links().end();
for (auto nbit = node->links().begin(); nbit != range_end; ++nbit) {
auto port = nbit->first;
if (!port.IsInbound() || port.IsControl()) {
continue;
}
// Since there might be multiple links to the same nodes,
// have to add all links one-by-one to check whether the subgraph
// would grow too large. But if it does grow too large, there is no
// point in growing it more, can just skip over the rest of the links.
for (const auto& link : nbit->second) {
if (sg->id().find(link.node) == sg->id().end()) {
anyOut = true;
} else {
anyIn = true;
}
}
}
if (anyIn && anyOut) {
return true;
}
}
// Do the multi-input ports.
for (SubgraphIterator sit(sg); !sit.AtEnd(); sit.Next()) {
if (sit.GetNode()->IsMultiInput(sit.GetPort())) {
bool anyIn = false;
bool anyOut = false;
do {
GenNode* peer = sit.GetNeighbor().node;
if (sg->id().find(peer) == sg->id().end()) {
anyOut = true;
} else {
anyIn = true;
}
} while (sit.NextIfSamePort());
if (anyIn && anyOut) {
return true;
}
}
}
return false;
}
Status GraphAnalyzer::CollateResult() {
ordered_collation_.clear();
collation_map_.clear();
// Collate by the signatures of the graphs.
for (const auto& it : result_) {
auto sig = absl::make_unique<Signature>();
it->ExtractForSignature(&sig->map);
Status status = sig->Compute();
if (!status.ok()) {
return status;
}
auto& coll_entry = collation_map_[sig.get()];
if (coll_entry.sig == nullptr) {
coll_entry.sig = std::move(sig);
}
++coll_entry.count;
}
// Then order them by the count.
for (auto& entry : collation_map_) {
ordered_collation_.insert(&entry.second);
}
result_.clear(); // Not needed after collation.
return Status::OK();
}
std::vector<string> GraphAnalyzer::DumpRawSubgraphs() {
std::vector<string> result;
for (const auto& it : result_) {
result.emplace_back(it->Dump());
}
return result;
}
std::vector<string> GraphAnalyzer::DumpSubgraphs() {
std::vector<string> result;
for (auto ptr : ordered_collation_) {
result.emplace_back(
absl::StrFormat("%d %s", ptr->count, ptr->sig->ToString()));
}
return result;
}
Status GraphAnalyzer::OutputSubgraphs() {
size_t total = 0;
for (auto ptr : ordered_collation_) {
std::cout << ptr->count << ' ' << ptr->sig->ToString() << '\n';
total += ptr->count;
}
std::cout << "Total: " << total << '\n';
if (std::cout.fail()) {
return Status(error::DATA_LOSS, "Failed to write to stdout");
} else {
return Status::OK();
}
}
} // end namespace graph_analyzer
} // end namespace grappler
} // end namespace tensorflow
| 10,048 | 3,268 |
// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "Script.h"
#include "IScriptInstance.h"
#include "ScriptAsset.h"
#include "AssetAPI.h"
#include "Framework.h"
#include "IAttribute.h"
#include "AttributeMetadata.h"
#include "IAssetTransfer.h"
#include "Entity.h"
#include "AssetRefListener.h"
#include "LoggingFunctions.h"
namespace Tundra
{
Script::~Script()
{
// If we have a classname, empty it to trigger deletion of the script object
if (!className.Get().Trimmed().Empty())
className.Set("", AttributeChange::LocalOnly);
if (scriptInstance_)
scriptInstance_->Unload();
scriptInstance_.Reset();
}
void Script::SetScriptInstance(IScriptInstance *instance)
{
// If we already have a script instance, unload and delete it.
if (scriptInstance_)
{
scriptInstance_->Unload();
scriptInstance_.Reset();
}
scriptInstance_ = instance;
}
void Script::SetScriptApplication(Script* app)
{
if (app)
scriptApplication_ = app;
else
scriptApplication_.Reset();
}
Script* Script::ScriptApplication() const
{
return dynamic_cast<Script*>(scriptApplication_.Get());
}
bool Script::ShouldRun() const
{
int mode = runMode.Get();
if (mode == RunOnBoth)
return true;
if (mode == RunOnClient && isClient_)
return true;
if (mode == RunOnServer && isServer_)
return true;
return false;
}
void Script::SetIsClientIsServer(bool isClient, bool isServer)
{
isClient_ = isClient;
isServer_ = isServer;
}
void Script::Run(const String &name)
{
if (!ShouldRun())
{
LogWarning("Run explicitly called, but RunMode does not match");
return;
}
// This function (Script::Run) is invoked on the Entity Action RunScript(scriptName). To
// allow the user to differentiate between multiple instances of Script in the same entity, the first
// parameter of RunScript allows the user to specify which Script to run. So, first check
// if this Run message is meant for us.
if (!name.Empty() && name != Name())
return; // Not our RunScript invocation - ignore it.
if (!scriptInstance_)
{
LogError("Run: No script instance set");
return;
}
scriptInstance_->Run();
}
/// Invoked on the Entity Action UnloadScript(scriptName).
void Script::Unload(const String &name)
{
if (!name.Empty() && name != Name())
return; // Not our RunScript invocation - ignore it.
if (!scriptInstance_)
{
LogError("Unload: Cannot perform, no script instance set");
return;
}
scriptInstance_->Unload();
}
Script::Script(Urho3D::Context* context, Scene* scene):
IComponent(context, scene),
INIT_ATTRIBUTE_VALUE(scriptRef, "Script ref", AssetReferenceList("Script")),
INIT_ATTRIBUTE_VALUE(runOnLoad, "Run on load", false),
INIT_ATTRIBUTE_VALUE(runMode, "Run mode", RunOnBoth),
INIT_ATTRIBUTE(applicationName, "Script application name"),
INIT_ATTRIBUTE(className, "Script class name"),
scriptInstance_(0),
isClient_(false),
isServer_(false)
{
static AttributeMetadata scriptRefData;
static AttributeMetadata runModeData;
static bool metadataInitialized = false;
if (!metadataInitialized)
{
AttributeMetadata::ButtonInfoList scriptRefButtons;
scriptRefData.buttons = scriptRefButtons;
scriptRefData.elementType = "AssetReference";
runModeData.enums[RunOnBoth] = "Both";
runModeData.enums[RunOnClient] = "Client";
runModeData.enums[RunOnServer] = "Server";
metadataInitialized = true;
}
scriptRef.SetMetadata(&scriptRefData);
runMode.SetMetadata(&runModeData);
AttributeChanged.Connect(this, &Script::HandleAttributeChanged);
ParentEntitySet.Connect(this, &Script::RegisterActions);
}
void Script::HandleAttributeChanged(IAttribute* attribute, AttributeChange::Type /*change*/)
{
if (!framework)
return;
if (attribute == &scriptRef)
{
// Do not even fetch the assets if we should not run
if (!ShouldRun())
return;
AssetReferenceList scripts = scriptRef.Get();
// Purge empty script refs
scripts.RemoveEmpty();
if (scripts.Size())
scriptAssets->HandleChange(scripts);
else // If there are no non-empty script refs, we unload the script instance.
SetScriptInstance(0);
}
else if (attribute == &applicationName)
{
ApplicationNameChanged.Emit(this, applicationName.Get());
}
else if (attribute == &className)
{
ClassNameChanged.Emit(this, className.Get());
}
else if (attribute == &runMode)
{
// If we had not loaded script assets previously because of runmode not allowing, load them now
if (ShouldRun())
{
if (scriptAssets->Assets().Empty())
HandleAttributeChanged(&scriptRef, AttributeChange::Default);
}
else // If runmode is changed and shouldn't run, unload script assets and script instance
{
scriptAssets->HandleChange(AssetReferenceList());
SetScriptInstance(0);
}
}
else if (attribute == &runOnLoad)
{
// If RunOnLoad changes, is true, and we don't have a script instance yet, emit ScriptAssetsChanged to start up the script.
if (runOnLoad.Get() && scriptAssets->Assets().Size() && (!scriptInstance_ || !scriptInstance_->IsEvaluated()))
OnScriptAssetLoaded(0, AssetPtr()); // The asset ptr can be null, it is not used.
}
}
void Script::OnScriptAssetLoaded(uint /*index*/, AssetPtr /*asset_*/)
{
// If all asset ref listeners have valid, loaded script assets, it's time to fire up the script engine
Vector<ScriptAssetPtr> loadedScriptAssets;
Vector<AssetPtr> allAssets = scriptAssets->Assets();
for (uint i = 0; i < allAssets.Size(); ++i)
{
if (allAssets[i])
{
ScriptAssetPtr asset = Urho3D::DynamicCast<ScriptAsset>(allAssets[i]);
if (!asset)
{
LogError("Script::ScriptAssetLoaded: Loaded asset of type other than ScriptAsset!");
continue;
}
if (asset->IsLoaded())
loadedScriptAssets.Push(asset);
}
}
if (loadedScriptAssets.Size() == allAssets.Size())
ScriptAssetsChanged.Emit(this, loadedScriptAssets);
}
void Script::RegisterActions()
{
Entity *entity = ParentEntity();
assert(entity);
if (entity)
{
entity->Action("RunScript")->Triggered.Connect(this, &Script::RunTriggered);
entity->Action("UnloadScript")->Triggered.Connect(this, &Script::UnloadTriggered);
}
scriptAssets = new AssetRefListListener(framework->Asset());
scriptAssets->Loaded.Connect(this, &Script::OnScriptAssetLoaded);
}
void Script::RunTriggered(const StringVector& params)
{
if (params.Size())
Run(params[0]);
}
void Script::UnloadTriggered(const StringVector& params)
{
if (params.Size())
Unload(params[0]);
}
}
| 7,196 | 2,068 |
/*/////////////////////////////////////////////////////////////////////////////////
/// An
/// ___ ____ ___ _____ ___ ____
/// / _ \ / ___|_ _|_ _/ _ \| _ \
/// | | | | | _ | | | || | | | |_) |
/// | |_| | |_| || | | || |_| | _ <
/// \___/ \____|___| |_| \___/|_| \_\
/// File
///
/// Copyright (c) 2008-2016 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team
///
/// The MIT License
///
/// 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 "OgitorsPrerequisites.h"
#include "BaseEditor.h"
#include "OgitorsRoot.h"
#include "OgitorsSystem.h"
#include "CameraEditor.h"
#include "ViewportEditor.h"
#include "PGInstanceManager.h"
#include "PGInstanceEditor.h"
#include "OgitorsUndoManager.h"
#include "tinyxml.h"
#include "ofs.h"
#include "PagedGeometry.h"
#include "BatchPage.h"
#include "ImpostorPage.h"
#include "TreeLoader3D.h"
using namespace Ogitors;
using namespace Forests;
//-----------------------------------------------------------------------------------------
namespace Ogitors
{
class AddInstanceUndo : public OgitorsUndoBase
{
public:
AddInstanceUndo(unsigned int objectID, int index) : mObjectID(objectID), mIndex(index) {};
virtual bool apply();
protected:
unsigned int mObjectID;
int mIndex;
};
//-----------------------------------------------------------------------------------------
class RemoveInstanceUndo : public OgitorsUndoBase
{
public:
RemoveInstanceUndo(unsigned int objectID, Ogre::Vector3 pos, Ogre::Real scale, Ogre::Real yaw) : mObjectID(objectID), mPos(pos), mScale(scale), mYaw(yaw) {};
virtual bool apply();
protected:
unsigned int mObjectID;
Ogre::Vector3 mPos;
Ogre::Real mScale;
Ogre::Real mYaw;
};
}
//-----------------------------------------------------------------------------------------
bool AddInstanceUndo::apply()
{
CPGInstanceManager *man = static_cast<CPGInstanceManager*>(OgitorsRoot::getSingletonPtr()->FindObject(mObjectID));
if(man)
{
PGInstanceInfo info = man->getInstanceInfo(mIndex);
man->_deleteChildEditor(mIndex);
man->removeInstance(mIndex);
OgitorsUndoManager::getSingletonPtr()->AddUndo(OGRE_NEW RemoveInstanceUndo(mObjectID, info.pos, info.scale, info.yaw));
}
return true;
}
//-----------------------------------------------------------------------------------------
bool RemoveInstanceUndo::apply()
{
CPGInstanceManager *man = static_cast<CPGInstanceManager *>(OgitorsRoot::getSingletonPtr()->FindObject(mObjectID));
if(man)
{
int index = man->addInstance(mPos, mScale, mYaw);
man->_createChildEditor(index , mPos, mScale, mYaw);
OgitorsUndoManager::getSingletonPtr()->AddUndo(OGRE_NEW AddInstanceUndo(mObjectID, index));
}
return true;
}
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
CPGInstanceManager::CPGInstanceManager(CBaseEditorFactory *factory) : CBaseEditor(factory),
mHandle(0), mPGHandle(0), mEntityHandle(0), mPlacementMode(false), mNextInstanceIndex(0)
{
mHelper = 0;
mHideChildrenInProgress = false;
mLastFileName = "";
mUsingPlaceHolderMesh = false;
mTempFileName = "";
mShowChildren = false;
}
//-----------------------------------------------------------------------------------------
CPGInstanceManager::~CPGInstanceManager()
{
}
//-----------------------------------------------------------------------------------------
Ogre::AxisAlignedBox CPGInstanceManager::getAABB()
{
if(mEntityHandle)
return mEntityHandle->getBoundingBox();
else
return Ogre::AxisAlignedBox::BOX_NULL;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::update(float timePassed)
{
if(mPGHandle)
mPGHandle->update();
return false;
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::showBoundingBox(bool bShow)
{
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::setLayerImpl(unsigned int newlayer)
{
if(mEntityHandle)
mEntityHandle->setVisibilityFlags(1 << newlayer);
if(mLoaded->get())
{
unLoad();
load();
}
return true;
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::setSelectedImpl(bool bSelected)
{
if(!bSelected)
{
mPlacementMode = false;
mOgitorsRoot->ReleaseMouse();
}
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::_save(Ogre::String filename)
{
std::stringstream stream;
PGInstanceList::iterator it = mInstanceList.begin();
while(it != mInstanceList.end())
{
stream << Ogre::StringConverter::toString(it->first).c_str();
stream << ";";
stream << Ogre::StringConverter::toString(it->second.pos).c_str();
stream << ";";
stream << Ogre::StringConverter::toString(it->second.scale).c_str();
stream << ";";
stream << Ogre::StringConverter::toString(it->second.yaw).c_str();
stream << "\n";
it++;
}
OgitorsUtils::SaveStreamOfs(stream, filename);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::onSave(bool forced)
{
Ogre::String dir = "/PGInstances/";
OFS::OfsPtr& mFile = mOgitorsRoot->GetProjectFile();
mFile->createDirectory(dir.c_str());
Ogre::String name = mName->get();
std::replace(name.begin(), name.end(), '<', ' ');
std::replace(name.begin(), name.end(), '>', ' ');
std::replace(name.begin(), name.end(), '#', ' ');
if(!mLastFileName.empty())
mFile->deleteFile(mLastFileName.c_str());
if(!mTempFileName.empty())
mFile->deleteFile(mTempFileName.c_str());
Ogre::String filename = dir + Ogre::StringConverter::toString(mObjectID->get()) + "_" + name + ".instance";
mLastFileName = filename;
_save(filename);
mTempModified->set(false);
mTempFileName = "";
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::_onLoad()
{
Ogre::String filename;
if(mTempModified->get())
{
if(mTempFileName.empty())
mTempFileName = "/Temp/tmp" + Ogre::StringConverter::toString(mObjectID->get()) + ".instance";
filename = mTempFileName;
}
else
{
Ogre::String name = mName->get();
std::replace(name.begin(), name.end(), '<', ' ');
std::replace(name.begin(), name.end(), '>', ' ');
std::replace(name.begin(), name.end(), '#', ' ');
filename = "/PGInstances/" + Ogre::StringConverter::toString(mObjectID->get()) + "_" + name + ".instance";
}
OFS::OFSHANDLE handle;
OFS::OfsPtr& mFile = mOgitorsRoot->GetProjectFile();
OFS::OfsResult ret = mFile->openFile(handle, filename.c_str());
if(ret != OFS::OFS_OK)
return;
OFS::ofs64 file_size = 0;
mFile->getFileSize(handle, file_size);
if(file_size == 0)
{
mFile->closeFile(handle);
return;
}
char *buffer = new char[(unsigned int)file_size];
mFile->read(handle, buffer, (unsigned int)file_size);
std::stringstream stream;
stream << buffer;
delete [] buffer;
if(!mTempModified->get())
mLastFileName = filename;
Ogre::StringVector list;
char res[128];
while(!stream.eof())
{
stream.getline(res, 128);
Ogre::String resStr(res);
OgitorsUtils::ParseStringVector(resStr, list);
if(list.size() == 3)
{
PGInstanceInfo info;
info.pos = Ogre::StringConverter::parseVector3(list[0]);
info.scale = Ogre::StringConverter::parseReal(list[1]);
info.yaw = Ogre::StringConverter::parseReal(list[2]);
mInstanceList[mNextInstanceIndex++] = info;
}
else if(list.size() == 4)
{
PGInstanceInfo info;
int index = Ogre::StringConverter::parseInt(list[0]);
info.pos = Ogre::StringConverter::parseVector3(list[1]);
info.scale = Ogre::StringConverter::parseReal(list[2]);
info.yaw = Ogre::StringConverter::parseReal(list[3]);
info.instance = 0;
mInstanceList[index] = info;
if(index >= mNextInstanceIndex)
mNextInstanceIndex = index + 1;
}
}
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::getObjectContextMenu(UTFStringVector &menuitems)
{
menuitems.clear();
if(!mEntityHandle)
return false;
if(mPlacementMode)
menuitems.push_back(OTR("Stop Placement"));
else
menuitems.push_back(OTR("Start Placement"));
if(mInstanceList.size())
{
if(mShowChildren)
menuitems.push_back(OTR("Hide Children"));
else
menuitems.push_back(OTR("Show Children"));
}
return true;
}
//-------------------------------------------------------------------------------
void CPGInstanceManager::onObjectContextMenu(int menuresult)
{
if(menuresult == 0)
{
mPlacementMode = !mPlacementMode;
if(mPlacementMode)
mOgitorsRoot->CaptureMouse(this);
else
mOgitorsRoot->ReleaseMouse();
}
else if(menuresult == 1)
{
if(mShowChildren)
{
mHideChildrenInProgress = true;
NameObjectPairList::iterator i, iend;
iend = mChildren.end();
for (i = mChildren.begin(); i != iend; ++i)
{
mSystem->DeleteTreeItem(i->second);
i->second->destroy();
}
mChildren.clear();
mHideChildrenInProgress = false;
mShowChildren = false;
}
else
{
mShowChildren = true;
PGInstanceList::iterator it = mInstanceList.begin();
while(it != mInstanceList.end())
{
_createChildEditor(it->first, it->second.pos, it->second.scale, it->second.yaw);
it++;
}
}
}
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::createProperties(OgitorsPropertyValueMap ¶ms)
{
PROPERTY_PTR(mModel , "model" , Ogre::String , "" , 0, SETTER(Ogre::String, CPGInstanceManager, _setModel));
PROPERTY_PTR(mPageSize , "pagesize" , int , 75 , 0, SETTER(int, CPGInstanceManager, _setPageSize));
PROPERTY_PTR(mBatchDistance , "batchdistance" , int , 75 , 0, SETTER(int, CPGInstanceManager, _setBatchDistance));
PROPERTY_PTR(mImpostorDistance, "impostordistance", int , 1000, 0, SETTER(int, CPGInstanceManager, _setImpostorDistance));
PROPERTY_PTR(mBounds , "bounds" , Ogre::Vector4, Ogre::Vector4(-10000,-10000,10000,10000), 0, SETTER(Ogre::Vector4, CPGInstanceManager, _setBounds));
PROPERTY_PTR(mCastShadows , "castshadows" , bool ,false,0, SETTER(bool, CPGInstanceManager, _setCastShadows));
PROPERTY_PTR(mTempModified , "tempmodified" , bool ,false,0, 0);
PROPERTY_PTR(mMinScale , "randomizer::minscale", Ogre::Real,1.0f,0, 0);
PROPERTY_PTR(mMaxScale , "randomizer::maxscale", Ogre::Real,1.0f,0, 0);
PROPERTY_PTR(mMinYaw , "randomizer::minyaw", Ogre::Real , 0.0f,0, 0);
PROPERTY_PTR(mMaxYaw , "randomizer::maxyaw", Ogre::Real , 0.0f,0, 0);
mProperties.initValueMap(params);
}
//-----------------------------------------------------------------------------------------
TiXmlElement* CPGInstanceManager::exportDotScene(TiXmlElement *pParent)
{
Ogre::String name = mName->get();
std::replace(name.begin(), name.end(), '<', ' ');
std::replace(name.begin(), name.end(), '>', ' ');
std::replace(name.begin(), name.end(), '#', ' ');
name = Ogre::StringConverter::toString(mObjectID->get()) + "_" + name;
Ogre::String filename = "PGInstances/" + name + ".instance";
TiXmlElement *pNode = pParent->InsertEndChild(TiXmlElement("node"))->ToElement();
// node properties
pNode->SetAttribute("name", mName->get().c_str());
pNode->SetAttribute("id", Ogre::StringConverter::toString(mObjectID->get()).c_str());
// position
TiXmlElement *pPosition = pNode->InsertEndChild(TiXmlElement("position"))->ToElement();
pPosition->SetAttribute("x", "0");
pPosition->SetAttribute("y", "0");
pPosition->SetAttribute("z", "0");
// rotation
TiXmlElement *pRotation = pNode->InsertEndChild(TiXmlElement("rotation"))->ToElement();
pRotation->SetAttribute("qw", "1");
pRotation->SetAttribute("qx", "0");
pRotation->SetAttribute("qy", "0");
pRotation->SetAttribute("qz", "0");
// scale
TiXmlElement *pScale = pNode->InsertEndChild(TiXmlElement("scale"))->ToElement();
pScale->SetAttribute("x", "1");
pScale->SetAttribute("y", "1");
pScale->SetAttribute("z", "1");
TiXmlElement *pPG = pNode->InsertEndChild(TiXmlElement("pagedgeometry"))->ToElement();
pPG->SetAttribute("fileName", filename.c_str());
pPG->SetAttribute("model", mModel->get().c_str());
pPG->SetAttribute("pageSize", Ogre::StringConverter::toString(mPageSize->get()).c_str());
pPG->SetAttribute("batchDistance", Ogre::StringConverter::toString(mBatchDistance->get()).c_str());
pPG->SetAttribute("impostorDistance", Ogre::StringConverter::toString(mImpostorDistance->get()).c_str());
pPG->SetAttribute("bounds", Ogre::StringConverter::toString(mBounds->get()).c_str());
pPG->SetAttribute("castShadows", Ogre::StringConverter::toString(mCastShadows->get()).c_str());
return pPG;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::load(bool async)
{
if(mLoaded->get())
return true;
Ogre::String tmpDir = OgitorsUtils::QualifyPath(mOgitorsRoot->GetProjectOptions()->ProjectDir + "/Temp") + "/";
mPGHandle = new PagedGeometry();
mPGHandle->setCamera(mOgitorsRoot->GetViewport()->getCameraEditor()->getCamera());
mPGHandle->setPageSize(mPageSize->get());
mPGHandle->setInfinite();
mPGHandle->setTempDir(tmpDir);
mPGHandle->addDetailLevel<BatchPage>(mBatchDistance->get(),0);
mPGHandle->addDetailLevel<ImpostorPage>(mImpostorDistance->get(),0);
Ogre::Vector4 bounds = mBounds->get();
mHandle = new Forests::TreeLoader3D(mPGHandle, Forests::TBounds(bounds.x, bounds.y, bounds.z, bounds.w));
mPGHandle->setPageLoader(mHandle);
if(mInstanceList.size() == 0)
_onLoad();
if(mModel->get() != "")
{
try
{
mEntityHandle = mOgitorsRoot->GetSceneManager()->createEntity(mName->get(), mModel->get() + ".mesh", PROJECT_RESOURCE_GROUP);
mUsingPlaceHolderMesh = false;
}
catch(...)
{
mUsingPlaceHolderMesh = true;
mEntityHandle = mOgitorsRoot->GetSceneManager()->createEntity(mName->get(), "missing_mesh.mesh");
mEntityHandle->setMaterialName("MAT_GIZMO_X_L");
}
mEntityHandle->setQueryFlags(0);
mEntityHandle->setVisibilityFlags(1 << mLayer->get());
mEntityHandle->setCastShadows(mCastShadows->get());
PGInstanceList::iterator it = mInstanceList.begin();
while(it != mInstanceList.end())
{
mHandle->addTree(mEntityHandle, it->second.pos, Ogre::Degree(it->second.yaw), it->second.scale);
it++;
}
}
registerForUpdates();
mLoaded->set(true);
return true;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::unLoad()
{
if(!mLoaded->get())
return true;
if(mOgitorsRoot->GetLoadState() != LS_UNLOADED)
{
if(mTempFileName.empty())
{
mTempFileName = "/Temp/tmp" + Ogre::StringConverter::toString(mObjectID->get()) + ".instance";
}
_save(mTempFileName);
mTempModified->set(true);
}
unRegisterForUpdates();
if(mHandle)
delete mHandle;
if(mPGHandle)
delete mPGHandle;
if(mEntityHandle)
mOgitorsRoot->GetSceneManager()->destroyEntity(mEntityHandle);
mHandle = 0;
mPGHandle = 0;
mEntityHandle = 0;
if(mPlacementMode)
mOgitorsRoot->ReleaseMouse();
mPlacementMode = false;
mLoaded->set(false);
return true;
}
//-----------------------------------------------------------------------------------------
PGInstanceInfo CPGInstanceManager::getInstanceInfo(int index)
{
PGInstanceList::iterator it = mInstanceList.find(index);
if(it != mInstanceList.end())
{
return it->second;
}
return PGInstanceInfo();
}
//-----------------------------------------------------------------------------------------
int CPGInstanceManager::addInstance(const Ogre::Vector3& pos, const Ogre::Real& scale, const Ogre::Real& yaw)
{
if(!mEntityHandle || !mHandle)
return -1;
mHandle->addTree(mEntityHandle, pos, Ogre::Degree(yaw), scale);
PGInstanceInfo instance;
instance.pos = pos;
instance.scale = scale;
instance.yaw = yaw;
instance.instance = 0;
int result = mNextInstanceIndex++;
mInstanceList.insert(PGInstanceList::value_type(result, instance));
return result;
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::removeInstance(int index)
{
if(!mLoaded->get() || index == -1)
return;
PGInstanceList::iterator it = mInstanceList.find(index);
if(it != mInstanceList.end())
{
it->second.instance = 0;
if(!mHideChildrenInProgress)
{
mHandle->deleteTrees(it->second.pos, 0.01f, mEntityHandle);
mInstanceList.erase(it);
}
}
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::modifyInstancePosition(int index, const Ogre::Vector3& pos)
{
if(!mHandle || index == -1)
return;
PGInstanceList::iterator it = mInstanceList.find(index);
if(it != mInstanceList.end())
{
if(mEntityHandle)
{
mHandle->deleteTrees(it->second.pos, 0.01f, mEntityHandle);
mHandle->addTree(mEntityHandle, pos, Ogre::Degree(it->second.yaw), it->second.scale);
}
it->second.pos = pos;
}
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::modifyInstanceScale(int index, Ogre::Real scale)
{
if(!mHandle || index == -1)
return;
PGInstanceList::iterator it = mInstanceList.find(index);
if(it != mInstanceList.end())
{
it->second.scale = scale;
if(mEntityHandle)
{
mHandle->deleteTrees(it->second.pos, 0.01f, mEntityHandle);
mHandle->addTree(mEntityHandle, it->second.pos, Ogre::Degree(it->second.yaw), it->second.scale);
}
}
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::modifyInstanceYaw(int index, Ogre::Real yaw)
{
if(!mHandle || index == -1)
return;
PGInstanceList::iterator it = mInstanceList.find(index);
if(it != mInstanceList.end())
{
it->second.yaw = yaw;
if(mEntityHandle)
{
mHandle->deleteTrees(it->second.pos, 0.01f, mEntityHandle);
mHandle->addTree(mEntityHandle, it->second.pos, Ogre::Degree(it->second.yaw), it->second.scale);
}
}
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::_setModel(OgitorsPropertyBase* property, const Ogre::String& value)
{
Ogre::String newname = "PGInstance<" + value + ">";
newname += mOgitorsRoot->CreateUniqueID(newname,"");
if(mPlacementMode)
{
mPlacementMode = false;
mOgitorsRoot->ReleaseMouse();
}
mModel->init(value);
mName->set(newname);
return true;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::_setPageSize(OgitorsPropertyBase* property, const int& value)
{
if(value < 10)
return false;
if(mLoaded->get())
{
unLoad();
load();
}
return true;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::_setBatchDistance(OgitorsPropertyBase* property, const int& value)
{
if(value < 50)
return false;
if(mLoaded->get())
{
unLoad();
load();
}
return true;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::_setImpostorDistance(OgitorsPropertyBase* property, const int& value)
{
if(value < (mBatchDistance->get() + 50))
return false;
if(mLoaded->get())
{
unLoad();
load();
}
return true;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::_setBounds(OgitorsPropertyBase* property, const Ogre::Vector4& value)
{
if(mLoaded->get())
{
unLoad();
load();
}
return true;
}
//-----------------------------------------------------------------------------------------
bool CPGInstanceManager::_setCastShadows(OgitorsPropertyBase* property, const bool& value)
{
if(mEntityHandle)
{
mEntityHandle->setCastShadows(value);
}
if(mPGHandle)
mPGHandle->reloadGeometry();
return true;
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::_createChildEditor(int index, Ogre::Vector3 pos, Ogre::Real scale, Ogre::Real yaw)
{
if(index == -1 || !mShowChildren)
return;
//We do not want an UNDO to be created for creation of children
OgitorsUndoManager::getSingletonPtr()->BeginCollection("Eat Creation");
OgitorsPropertyValueMap params;
params["init"] = OgitorsPropertyValue(PROP_STRING, Ogre::Any(Ogre::String("")));
params["position"] = OgitorsPropertyValue(PROP_VECTOR3, Ogre::Any(pos));
params["index"] = OgitorsPropertyValue(PROP_INT, Ogre::Any(index));
params["scale"] = OgitorsPropertyValue(PROP_VECTOR3, Ogre::Any(Ogre::Vector3(scale, scale, scale)));
params["uniformscale"] = OgitorsPropertyValue(PROP_REAL, Ogre::Any(scale));
params["yaw"] = OgitorsPropertyValue(PROP_REAL, Ogre::Any(yaw));
Ogre::Quaternion q1;
q1.FromAngleAxis(Ogre::Degree(yaw), Ogre::Vector3::UNIT_Y);
params["orientation"] = OgitorsPropertyValue(PROP_QUATERNION, Ogre::Any(q1));
mInstanceList[index].instance = static_cast<CPGInstanceEditor*>(mOgitorsRoot->CreateEditorObject(this, "PGInstance", params, true, false));
OgitorsUndoManager::getSingletonPtr()->EndCollection(false, true);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::_deleteChildEditor(int index)
{
if(index == -1 || !mShowChildren)
return;
//We do not want an UNDO to be created for deletion of children
OgitorsUndoManager::getSingletonPtr()->BeginCollection("Eat Deletion");
PGInstanceList::iterator it = mInstanceList.find(index);
if(it != mInstanceList.end())
{
mHideChildrenInProgress = true;
if(it->second.instance)
{
mSystem->DeleteTreeItem(it->second.instance);
it->second.instance->destroy(true);
it->second.instance = 0;
}
mHideChildrenInProgress = false;
}
OgitorsUndoManager::getSingletonPtr()->EndCollection(false, true);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseLeftUp (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseLeftDown (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
Ogre::Camera *cam = viewport->getCameraEditor()->getCamera();
Ogre::Viewport *vp = static_cast<Ogre::Viewport*>(viewport->getHandle());
float width = vp->getActualWidth();
float height = vp->getActualHeight();
Ogre::Ray mRay = cam->getCameraToViewportRay(point.x / width, point.y / height);
Ogre::Vector3 vPos;
if(viewport->GetHitPosition(mRay, vPos))
{
float yaw = (mMaxYaw->get() - mMinYaw->get()) * Ogre::Math::UnitRandom() + mMinYaw->get();
float scale = (mMaxScale->get() - mMinScale->get()) * Ogre::Math::UnitRandom() + mMinScale->get();
int index = addInstance(vPos, scale, yaw);
OgitorsUndoManager::getSingletonPtr()->BeginCollection("Add Instance");
_createChildEditor(index , vPos, scale, yaw);
OgitorsUndoManager::getSingletonPtr()->AddUndo(OGRE_NEW AddInstanceUndo(mObjectID->get(), index));
OgitorsUndoManager::getSingletonPtr()->EndCollection(true);
}
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseMove (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
viewport->OnMouseMove(point, buttons & ~OMB_LEFT);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseLeave (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
viewport->OnMouseLeave(point, buttons);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseRightDown (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
viewport->OnMouseRightDown(point, buttons);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseRightUp (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
viewport->OnMouseRightUp(point, buttons);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseMiddleDown (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
viewport->OnMouseMiddleDown(point, buttons);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseMiddleUp (CViewportEditor *viewport, Ogre::Vector2 point, unsigned int buttons)
{
viewport->OnMouseMiddleUp(point, buttons);
}
//-----------------------------------------------------------------------------------------
void CPGInstanceManager::OnMouseWheel (CViewportEditor *viewport, Ogre::Vector2 point, float delta, unsigned int buttons)
{
viewport->OnMouseWheel(point, delta, buttons);
}
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
//------CMATERIALEDITORFACTORY-----------------------------------------------------------------
//-----------------------------------------------------------------------------------------
CPGInstanceManagerFactory::CPGInstanceManagerFactory(OgitorsView *view) : CBaseEditorFactory(view)
{
mTypeName = "PGInstance Manager";
mEditorType = ETYPE_CUSTOM_MANAGER;
mAddToObjectList = true;
mRequirePlacement = false;
mIcon = "pagedgeometry.svg";
mCapabilities = CAN_UNDO | CAN_DELETE;
mUsesGizmos = false;
mUsesHelper = false;
OgitorsPropertyDef *definition = AddPropertyDefinition("model", "Model", "The model to be used.", PROP_STRING);
definition->setOptions(OgitorsRoot::getSingletonPtr()->GetModelNames());
AddPropertyDefinition("pagesize", "Page Size", "Size of batch pages.",PROP_INT);
AddPropertyDefinition("batchdistance", "Batch Distance", "Batch Distance.",PROP_INT);
AddPropertyDefinition("impostordistance", "Impostor Distance", "Impostor Distance.",PROP_INT);
definition = AddPropertyDefinition("bounds", "Bounds", "The dimensions of the bounding area.",PROP_VECTOR4);
definition->setFieldNames("X1","Z1","X2","Z2");
AddPropertyDefinition("castshadows","Cast Shadows","Do the instances cast shadows?",PROP_BOOL);
AddPropertyDefinition("tempmodified", "", "Is it temporarily modified.", PROP_BOOL);
AddPropertyDefinition("randomizer::minscale", "Randomizer::Min. Scale", "Minimum Scale of new objects.",PROP_REAL);
AddPropertyDefinition("randomizer::maxscale", "Randomizer::Max. Scale", "Maximum Scale of new objects.",PROP_REAL);
AddPropertyDefinition("randomizer::minyaw", "Randomizer::Min. Yaw", "Minimum Yaw of new objects.",PROP_REAL);
AddPropertyDefinition("randomizer::maxyaw", "Randomizer::Max. Yaw", "Maximum Yaw of new objects.",PROP_REAL);
OgitorsPropertyDefMap::iterator it = mPropertyDefs.find("name");
it->second.setAccess(true, false);
}
//-----------------------------------------------------------------------------------------
CBaseEditorFactory *CPGInstanceManagerFactory::duplicate(OgitorsView *view)
{
CBaseEditorFactory *ret = new CPGInstanceManagerFactory(view);
ret->mTypeID = mTypeID;
return ret;
}
//-----------------------------------------------------------------------------------------
CBaseEditor *CPGInstanceManagerFactory::CreateObject(CBaseEditor **parent, OgitorsPropertyValueMap ¶ms)
{
CPGInstanceManager *object = new CPGInstanceManager(this);
OgitorsPropertyValueMap::iterator ni;
if((ni = params.find("init")) != params.end())
{
OgitorsPropertyValue value = EMPTY_PROPERTY_VALUE;
value.val = Ogre::Any(CreateUniqueID("PGInstance<>"));
params["name"] = value;
params.erase(ni);
}
object->createProperties(params);
object->mParentEditor->init(*parent);
mInstanceCount++;
return object;
}
//-----------------------------------------------------------------------------------------
| 31,907 | 9,370 |
/* Copyright 2019 Axel Huebl, Benjamin Worpitz
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#ifdef _OPENMP
# include <alpaka/core/Common.hpp>
# include <alpaka/core/Unused.hpp>
# include <alpaka/time/Traits.hpp>
# include <omp.h>
namespace alpaka
{
//#############################################################################
//! The OpenMP accelerator time implementation.
class TimeOmp : public concepts::Implements<ConceptTime, TimeOmp>
{
public:
//-----------------------------------------------------------------------------
TimeOmp() = default;
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST TimeOmp(TimeOmp const&) = delete;
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST TimeOmp(TimeOmp&&) = delete;
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST auto operator=(TimeOmp const&) -> TimeOmp& = delete;
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST auto operator=(TimeOmp&&) -> TimeOmp& = delete;
//-----------------------------------------------------------------------------
/*virtual*/ ~TimeOmp() = default;
};
namespace traits
{
//#############################################################################
//! The OpenMP accelerator clock operation.
template<>
struct Clock<TimeOmp>
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST static auto clock(TimeOmp const& time) -> std::uint64_t
{
alpaka::ignore_unused(time);
// NOTE: We compute the number of clock ticks by dividing the following durations:
// - omp_get_wtime returns the elapsed wall clock time in seconds.
// - omp_get_wtick gets the timer precision, i.e., the number of seconds between two successive clock
// ticks.
return static_cast<std::uint64_t>(omp_get_wtime() / omp_get_wtick());
}
};
} // namespace traits
} // namespace alpaka
#endif
| 2,518 | 645 |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
#include "common/Common.hpp"
#include "common/MockILogManagerInternal.hpp"
#include "modules/filter/CompliantByDefaultEventFilterModule.hpp"
using namespace MAT;
using namespace testing;
class CompliantByDefaultEventFilterModuleTests : public CompliantByDefaultEventFilterModule, public ::testing::Test
{
public:
CompliantByDefaultEventFilterModuleTests() noexcept
: m_logManager(m_logConfiguration, static_cast<bool>(nullptr)) { }
ILogConfiguration m_logConfiguration;
LogManagerImpl m_logManager;
using CompliantByDefaultEventFilterModule::m_parent;
using CompliantByDefaultEventFilterModule::m_allowedLevels;
virtual void SetUp() override
{
Initialize(&m_logManager);
}
};
TEST_F(CompliantByDefaultEventFilterModuleTests, Initialize_ParentValid_SetsParentMember)
{
ASSERT_EQ(&m_logManager, m_parent);
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Initialize_AllowedLevelsSizeOne)
{
ASSERT_EQ(m_allowedLevels.GetSize(), size_t { 1 });
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Initialize_AllowedLevelValueIsRequired)
{
ASSERT_TRUE(m_allowedLevels.IsLevelInCollection(DIAG_LEVEL_REQUIRED));
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Initialize_HooksIsNotNullptr)
{
ASSERT_TRUE(m_hooks != nullptr);
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Initialize_HooksSizeSet)
{
#ifdef HAVE_MAT_DEFAULT_FILTER
constexpr const size_t expected = 2; // This, and the default filter initialized by LogManager.
#else
constexpr const size_t expected = 1; // Just this hook.
#endif // HAVE_MAT_DEFAULT_FILTER
ASSERT_EQ(m_hooks->GetSize(), expected);
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Initialize_ThisPointerIsInHooksCollection)
{
ASSERT_TRUE(m_hooks->IsModuleInCollection(this));
}
TEST_F(CompliantByDefaultEventFilterModuleTests, UpdateAllowedLevels_UpdatesSetOfAllowedLevels)
{
UpdateAllowedLevels({ DIAG_LEVEL_OPTIONAL });
ASSERT_TRUE(m_allowedLevels.IsLevelInCollection(DIAG_LEVEL_OPTIONAL));
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Teardown_HooksIsNullptr)
{
Teardown();
ASSERT_EQ(m_hooks, nullptr);
}
TEST_F(CompliantByDefaultEventFilterModuleTests, Teardown_ParentIsNullptr)
{
Teardown();
ASSERT_EQ(m_parent, nullptr);
}
| 2,397 | 816 |
/*
* Realsense Segmentation Sample
*
* Contributing Authors: Tome Vang <tome.vang@intel.com>
*
*
*/
#include <iostream>
#include <vector>
#include <time.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <librealsense2/rs.hpp>
#include <inference_engine.hpp>
// window name
#define WINDOW_NAME "Realsense Segmentation - NCS2/OpenVINO - press q to quit"
// label file
#define segmentationNetworkLabelsFile "../seg_labels.txt"
#define DEVICE "MYRIAD"
// window height and width 4:3 ratio
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define CAP_FPS 30
const unsigned int MAX_PATH = 256;
using namespace InferenceEngine;
// Location of the segmentation network xml/bin file
const std::string SEG_XML_PATH = "../semantic-segmentation-adas-0001.xml";
const std::string SEG_BIN_PATH = "../semantic-segmentation-adas-0001.bin";
// OpenCV display constants
const int FONT = cv::FONT_HERSHEY_PLAIN;
const float FONT_SCALE = 1.5;
const int FONT_LINE_THICKNESS = 1;
const cv::Scalar RED = cv::Scalar(0, 0, 255, 255);
const cv::Scalar BLUE = cv::Scalar(255, 0, 0, 255);
const cv::Scalar GREEN = cv::Scalar(0, 255, 0, 255);
const cv::Scalar GRAY = cv::Scalar(50, 50, 50, 255);
const cv::Scalar BLACK = cv::Scalar(0, 0, 0, 255);
const float canvasSize = 120;
const float canvasTop = (canvasSize * 0.80);
const float canvasMidTop = (canvasSize * 0.60);
const float canvasMidBottom = (canvasSize * 0.40);
const float canvasBottom = (canvasSize * 0.20);
const float alpha = 0.5;
const float beta = 1.0 - alpha;
bool videoPauseFlag = false;
float depthMap[WINDOW_WIDTH][WINDOW_HEIGHT];
// Segmentation network variables
std::vector<long unsigned int> segmentationNetworkInputDims;
std::vector<long unsigned int> segmentationNetworkOutputDims;
InferenceEngine::InferRequest::Ptr segmentationNetworkInferenceRequest;
std::string segmentationNetworkInputLayerName;
std::string segmentationNetworkOutputLayerName;
std::vector <std::string> segmentationNetworkLabels;
cv::Mat finalResultMat;
cv::Mat segmentationColorMat;
// Segmentation class color values. Each set of BGR values correspond to a class.
// Visit https://docs.openvinotoolkit.org/latest/_models_intel_semantic_segmentation_adas_0001_description_semantic_segmentation_adas_0001.html for more information.
std::vector<cv::Vec3b> colors = {
{128, 64, 128}, // background
{232, 35, 244}, // road
{70, 70, 70}, // sidewalk
{156, 102, 102}, // building
{153, 153, 190}, // wall
{153, 153, 153}, // fence
{30, 170, 250}, // pole
{0, 220, 220}, // traffic light
{35, 142, 107}, // traffic sign
{152, 251, 152}, // vegetation
{180, 130, 70}, // terrain
{60, 20, 220}, // sky
{0, 0, 255}, // person
{142, 0, 0}, // rider
{70, 0, 0}, // car
{100, 60, 0}, // truck
{90, 0, 0}, // bus
{230, 0, 0}, // train
{32, 11, 119}, // motorcycle
{0, 74, 111}, // bicycle
{81, 0, 81} // ego-vehicle
};
/*
* read network labels from file
*/
void getNetworkLabels(std::string labelsDir, std::vector<std::string>* labelsVector)
{
char filename[MAX_PATH];
strncpy(filename, labelsDir.c_str(), MAX_PATH);
FILE* catFile = fopen(filename, "r");
if (catFile == nullptr) {
std::cerr << "Could not find Category file." << std::endl;
exit(1);
}
char catLine[255];
while (fgets(catLine , 255 , catFile) != NULL) {
if (catLine[strlen(catLine) - 1] == '\n')
catLine[strlen(catLine) - 1] = '\0';
labelsVector->push_back(std::string(catLine));
}
fclose (catFile);
}
/*
* get the distance map for all pixels in the image using Intel Realsense camera
*/
void getDistanceMap(rs2::depth_frame RSDepthFrame, float depthMap[WINDOW_WIDTH][WINDOW_HEIGHT])
{
// Check all points and record the closest distance
for (int horizontalDepthCheck = 0; horizontalDepthCheck < WINDOW_WIDTH; horizontalDepthCheck++)
{
for (int verticalDepthCheck = 0; verticalDepthCheck < WINDOW_HEIGHT; verticalDepthCheck++)
{
// Get the distance of a point using the depth sensor
depthMap[horizontalDepthCheck][verticalDepthCheck] = RSDepthFrame.get_distance(horizontalDepthCheck, verticalDepthCheck);
}
}
}
/*
* places text in a canvas section on a OpenCV mat
*/
void placeText(std::string text, const float canvasPosition, cv::Mat &mat)
{
// calculate text size
cv::Size textSize = cv::getTextSize(text, FONT, FONT_SCALE, FONT_LINE_THICKNESS, 0);
// display centered text
cv::putText(mat, text, cv::Point2f((mat.cols - textSize.width)/2, mat.rows - canvasPosition + (textSize.height/2)), FONT, FONT_SCALE, GREEN, FONT_LINE_THICKNESS);
}
/*
* clears a canvas section (top, midtop, midbottom, bottom)
*/
void clearCanvasSection(const float canvasPosition, cv::Mat &mat)
{
// calculate text size
std::string text = "some sample text";
cv::Size textSize = cv::getTextSize(text, FONT, FONT_SCALE, FONT_LINE_THICKNESS, 0);
// clear out a section
cv::rectangle(mat, cv::Point(0, mat.rows - canvasPosition-textSize.height), cv::Point(mat.cols, mat.rows - canvasPosition + (textSize.height/2)+2), GRAY, -1);
}
/*
* add a canvas for displaying text to an OpenCV mat
*/
void addCanvasToMat(cv::Mat ¤tMat)
{
cv::Mat canvas = cv::Mat(canvasSize, currentMat.cols, CV_8UC3);
canvas = canvas.setTo(GRAY);
currentMat.push_back(canvas);
}
/*
* make an inference using the semantic segmentation network
*/
void segmentationInference(cv::Mat &cameraColorMat)
{
// Get segmentation network input dimensions
unsigned int segmentationInputChannelsNumber = segmentationNetworkInputDims.at(1);
unsigned int segmentationInputHeight = segmentationNetworkInputDims.at(2);
unsigned int segmentationInputWidth = segmentationNetworkInputDims.at(3);
// Get segmentation network output dimensions
unsigned int segmentationOutputHeight = segmentationNetworkOutputDims.at(2);
unsigned int segmentationOutputWidth = segmentationNetworkOutputDims.at(3);
// ----------Image preprocessing----------
cv::Mat imgInput;
// Resize the input to fit the segmentation network
cv::resize(cameraColorMat, imgInput, cv::Size(segmentationInputWidth, segmentationInputHeight));
// Set the input blob for the inference request using the segmentation input layer name
auto segmentationInputBlob = segmentationNetworkInferenceRequest->GetBlob(segmentationNetworkInputLayerName);
// Set up a 8-bit unsigned int buffer to be filled with input data
auto segmentationInputData = segmentationInputBlob->buffer().as<PrecisionTrait<Precision::U8>::value_type*>();
// Set the input data for the segmentation network and fills buffer with input from the openCV color mat
size_t segmentationImageSize = segmentationInputHeight * segmentationInputWidth;
for (size_t pid = 0; pid < segmentationImageSize; ++pid)
{
for (size_t ch = 0; ch < segmentationInputChannelsNumber; ++ch)
{
segmentationInputData[ch * segmentationImageSize + pid] = imgInput.at<cv::Vec3b>(pid)[ch];
}
}
// ----------Run the inference for the segmentation network----------
segmentationNetworkInferenceRequest->Infer();
// ----------Output Postprocessing for the segmentation network----------
// Get the results from the inference
auto segmentationOutput = segmentationNetworkInferenceRequest->GetBlob(segmentationNetworkOutputLayerName);
const float *classDetections = segmentationOutput->buffer().as<float*>();
// Create a opencv mat based on the output of the segmentation network
// Start off with a blank opencv mat
cv::Mat blankMat = cv::Mat(segmentationOutputHeight, segmentationOutputWidth, CV_8UC3, cv::Scalar(0,0,0));
// Visit each of the pixels for the blank opencv Mat and determine the color values that should be there.
// The color values are based on the inference results from classDetections.
for(unsigned int y = 0; y < segmentationOutputHeight; y++)
{
for(unsigned int x = 0; x < segmentationOutputWidth; x++)
{
// Get the class index from classDetections for a specific coorindate
int classIndexFromDetections = classDetections[y * segmentationOutputWidth + x];
// Set the color for the blank opencv mat
blankMat.at<cv::Vec3b>(cv::Point(x,y)) = colors.at(classIndexFromDetections);
}
}
// Resize the segmentation color mat
cv::resize(blankMat, segmentationColorMat, cv::Size(WINDOW_WIDTH, WINDOW_HEIGHT));
// Blend both the segmentation color mat and the camera color mat together
addWeighted(cameraColorMat, alpha, segmentationColorMat, beta, 0.0, finalResultMat);
// Add canvas to the final result mat
addCanvasToMat(finalResultMat);
}
/*
* handle mouse events for when the video is paused
*/
void mouseCallBackFunctionPaused(int mouseEvent, int mouseXCoordinate, int mouseYCoordinate, int flags, void* userParam)
{
// Unpause if video is paused and the left mouse button is pressed
if (mouseEvent == cv::EVENT_LBUTTONDOWN && videoPauseFlag == true)
{
videoPauseFlag = false;
}
// Handles mouse cursor move events while the video stream is paused. Reports object distance and object classification when mouse cursor moves.
else if (mouseEvent == cv::EVENT_MOUSEMOVE && videoPauseFlag == true)
{
// First we wil clear the top and upper middle sections of the canvas
clearCanvasSection(canvasTop, finalResultMat);
clearCanvasSection(canvasMidTop, finalResultMat);
// Next, we determine the distance at the mouse cursor then place the distance text on the canvas
std::string distanceText = "Distance is ";
if (mouseYCoordinate < WINDOW_HEIGHT)
distanceText = distanceText + cv::format("%2.2f", depthMap[mouseXCoordinate][mouseYCoordinate]) + " meters.";
placeText(distanceText, canvasMidTop, finalResultMat);
// Finally, we will determine the object at the mouse cursor then place the object text on the canvas.
// To do this, we will look at the color image created from the segmentation results.
// We will attempt to match the color values at the mouse cursor from the segmentation color image to
// the ones in the colors vector (defined on line 92).
// The indexes of the colors vector correspond to the index of a class label for the network and we can determine
// the object at the mouse cursor by doing this color comparision.
std::string objectText = "Object is ";
// Get the current color values at the current mouse coordinate
cv::Vec3b currentColor = segmentationColorMat.at<cv::Vec3b>(mouseYCoordinate, mouseXCoordinate);
// Create an iterator so we can iterate through our colors vector and see if there is a match
std::vector<cv::Vec3b>::iterator vectorIterator;
vectorIterator = std::find(colors.begin(), colors.end(), currentColor);
// Check to see if we found a color match and determine the object label
if (vectorIterator != colors.end())
{
objectText = objectText + segmentationNetworkLabels[vectorIterator - colors.begin() + 1];
}
placeText(objectText, canvasTop, finalResultMat);
imshow(WINDOW_NAME, finalResultMat);
cv::waitKey(1);
}
}
/*
* handle mouse events for when the video is playing
*/
void mouseCallBackFunctionPlay(int mouseEvent, int mouseXCoordinate, int mouseYCoordinate, int flags, void* cameraColorMatPtr)
{
char key;
// Convert the user parameter (OpenCV camera color mat) from void pointer to openCV mat
cv::Mat cameraColorMat = *((cv::Mat*)cameraColorMatPtr);
// Make a copy of the camera color mat and add a canvas to it
cv::Mat cameraColorMatWithCanvas = cameraColorMat;
addCanvasToMat(cameraColorMatWithCanvas);
// This if-block handles left mouse-button clicks. Will "pause" the video feed.
if (mouseEvent == cv::EVENT_LBUTTONDOWN && videoPauseFlag == false)
{
// Clear a section of the canvas and show loading text on the canvas
clearCanvasSection(canvasMidTop, cameraColorMatWithCanvas);
std::string loadingText = "Loading...";
placeText(loadingText, canvasMidTop, cameraColorMatWithCanvas);
imshow(WINDOW_NAME, cameraColorMatWithCanvas);
cv::waitKey(1);
videoPauseFlag = true;
// Perform the inference for the segmentation network
segmentationInference(cameraColorMat);
// Show some text on the canvas
std::string pauseText = "Paused - Move mouse around to explore.";
placeText(pauseText, canvasMidBottom, finalResultMat);
std::string helpText = "Click the screen to continue.";
placeText(helpText, canvasBottom, finalResultMat);
imshow(WINDOW_NAME, finalResultMat);
// This loop will show depth and object label when the user moves their mouse.
while(videoPauseFlag == true)
{
key = cv::waitKey(1);
if (tolower(key) == 'q')
break;
// Handle mouse events while paused
cv::setMouseCallback(WINDOW_NAME, mouseCallBackFunctionPaused, NULL);
}
}
}
/*
* perform some network initialization then start the Realsense camera
*/
void initializationThenStartCamera(rs2::pipeline RSpipe)
{
char key;
cv::Mat cameraColorMat;
// ----------------------------------Segmentation Network Setup----------------------------------
getNetworkLabels(segmentationNetworkLabelsFile, &segmentationNetworkLabels);
// Create the inference engine object
Core ie;
// Create a network object by reading the XML and BIN files
CNNNetwork networkObj = ie.ReadNetwork(SEG_XML_PATH, SEG_BIN_PATH);
// Get the input layer nodes and check to see if there are multiple inputs and outputs.
// This sample only supports networks with 1 input and 1 output
InputsDataMap netInputDataMap(networkObj.getInputsInfo());
OutputsDataMap netOutputDataMap(networkObj.getOutputsInfo());
if (netInputDataMap.size() != 1 && netOutputDataMap.size() != 1)
std::cout << "This sample only supports segmentation networks with 1 input and 1 output" << '\n';
// ----------Prepare input blobs----------
// Get the network input information, set the precision to 8 bit unsigned int, get the network input node name
InputInfo::Ptr& netInputInfo = netInputDataMap.begin()->second;
netInputInfo->setPrecision(Precision::U8);
segmentationNetworkInputLayerName = netInputDataMap.begin()->first;
// ----------Prepare output blobs----------
// Get the network output information, set the precision to FP32, get the output node name
auto netOutputInfo = netOutputDataMap.begin()->second;
netOutputInfo->setPrecision(Precision::FP32);
segmentationNetworkOutputLayerName = netOutputDataMap.begin()->first;
// ----------Loading network to the plugin----------
// Create executable network object by loading the network and specifying the NCS device
auto execNetwork = ie.LoadNetwork(networkObj, DEVICE);
// ----------Create inference request and prep network input blob----------
// Create inference request for the network
segmentationNetworkInferenceRequest = execNetwork.CreateInferRequestPtr();
// Get pointers to the input and output dimensions for the network
segmentationNetworkInputDims = segmentationNetworkInferenceRequest->GetBlob(segmentationNetworkInputLayerName)->getTensorDesc().getDims();
segmentationNetworkOutputDims = segmentationNetworkInferenceRequest->GetBlob(segmentationNetworkOutputLayerName)->getTensorDesc().getDims();
std::cout << "\nStarting Realsense distance detection app...\n";
std::cout << "\nPress q or Q to quit.\n";
// ----------Main loop----------
while (cv::getWindowProperty(WINDOW_NAME, cv::WND_PROP_AUTOSIZE) >= 0)
{
// Wait for frames from Realsense camera
rs2::frameset RSdata = RSpipe.wait_for_frames();
// Get a Realsense color frame from the frame data
auto RSColorFrame = RSdata.get_color_frame();
auto RSDepthFrame = RSdata.get_depth_frame();
// First we get the distance map for the current frame using the RS depth frame
getDistanceMap(RSDepthFrame, depthMap);
// Convert the Realsense color frame to an OpenCV color mat
cameraColorMat = cv::Mat(cv::Size(WINDOW_WIDTH, WINDOW_HEIGHT), CV_8UC3, (void*)RSColorFrame.get_data(), cv::Mat::AUTO_STEP);
cv::Mat cameraColorMatWithCanvas = cameraColorMat;
// Add an empty "canvas" area to the OpenCV mat for displaying text
addCanvasToMat(cameraColorMatWithCanvas);
// Place some text in the canvas
std::string playText = "Click anywhere to create snapshot.";
placeText(playText, canvasTop, cameraColorMatWithCanvas);
// Place some text in the canvas
std::string quitText = "Press q to quit.";
placeText(quitText, canvasMidTop, cameraColorMatWithCanvas);
// Handle mouse events (this is where the inferences will happen)
cv::setMouseCallback(WINDOW_NAME, mouseCallBackFunctionPlay, &cameraColorMat);
// Show the OpenCV camera color mat
cv::imshow(WINDOW_NAME, cameraColorMatWithCanvas);
// Handle key press events
key = cv::waitKey(1);
if (tolower(key) == 'q')
break;
}
}
/*
* Start.
*/
int main (int argc, char** argv)
{
// Set up the openCV display window
cv::namedWindow(WINDOW_NAME, cv::WINDOW_NORMAL);
cv::resizeWindow(WINDOW_NAME, WINDOW_WIDTH, WINDOW_HEIGHT + canvasSize);
cv::setWindowProperty(WINDOW_NAME, cv::WND_PROP_ASPECT_RATIO, cv::WINDOW_KEEPRATIO);
cv::moveWindow(WINDOW_NAME, 0, 0);
// ----------Realsense setup----------
// Create Realsense pipeline and config
rs2::pipeline RSpipe;
rs2::config RSconfig;
// Enable both color and depth streams in the configuration
RSconfig.enable_stream(RS2_STREAM_COLOR, WINDOW_WIDTH, WINDOW_HEIGHT, RS2_FORMAT_BGR8, CAP_FPS);
RSconfig.enable_stream(RS2_STREAM_DEPTH, WINDOW_WIDTH, WINDOW_HEIGHT, RS2_FORMAT_Z16, CAP_FPS);
// Start pipeline with config settings
RSpipe.start(RSconfig);
// start the camera and inferences
initializationThenStartCamera(RSpipe);
// Close all windows
cv::destroyAllWindows();
std::cout << "\nFinished." << std::endl;
return 0;
}
| 19,082 | 5,815 |
/*
* event_identity.hpp
*
* Created on: Dec 20, 2016
* Author: zmij
*/
#ifndef AFSM_DETAIL_EVENT_IDENTITY_HPP_
#define AFSM_DETAIL_EVENT_IDENTITY_HPP_
#include <type_traits>
#include <set>
#include <pushkin/meta/type_tuple.hpp>
namespace afsm {
namespace detail {
struct event_base {
struct id_type {};
};
template < typename T >
struct event : event_base {
static constexpr id_type id{};
};
template < typename T >
constexpr event_base::id_type event<T>::id;
template < typename T >
struct event_identity {
using event_type = typename ::std::decay<T>::type;
using type = event<event_type>;
};
using event_set = ::std::set< event_base::id_type const* >;
template < typename ... T >
event_set
make_event_set( ::psst::meta::type_tuple<T...> const& )
{
return event_set{
&event_identity<T>::type::id...
};
}
} /* namespace detail */
} /* namespace afsm */
#endif /* AFSM_DETAIL_EVENT_IDENTITY_HPP_ */
| 976 | 370 |
////////////////////////////////////////////////////////////
// Door Motor - Open / close coop door by cycling a relay
////////////////////////////////////////////////////////////
#include <Arduino.h>
#include <GPSParser.h>
#include <SaveController.h>
#include "ICommInterface.h"
#include "TelemetryTags.h"
#include "Telemetry.h"
#include "MilliTimer.h"
#include "Pins.h"
#include "SunCalc.h"
#include "DoorController.h"
#include "LightController.h"
#include "BeepController.h"
#include "GaryCooper.h"
#include "DoorMotor_GarageDoor.h"
typedef enum
{
doorSwitchOpen = 1 << 0,
doorSwitchClosed = 1 << 1,
} doorSwitchMaskE;
////////////////////////////////////////////////////////////
// Implementation of a chicken coop door controller that
// treats the door as a garage door style system with a
// button to open / close the door. This is broken out
// of the door controller so that other types of door
// motor (such as stepper motors) can be used with minimal
// change to the other software, especially the CDoorController class.
////////////////////////////////////////////////////////////
IDoorMotor *getDoorMotor()
{
static CDoorMotor_GarageDoor s_doorMotor;
return &s_doorMotor;
}
CDoorMotor_GarageDoor::CDoorMotor_GarageDoor()
{
m_seekingKnownState = true;
m_state = doorState_unknown;
m_lastCommand = (doorCommandE) - 1;
}
CDoorMotor_GarageDoor::~CDoorMotor_GarageDoor()
{
}
void CDoorMotor_GarageDoor::setup()
{
// Setup the door relay
pinMode(PIN_DOOR_RELAY, OUTPUT);
digitalWrite(PIN_DOOR_RELAY, RELAY_OFF);
// Setup the door position switch sensor inputs
pinMode(PIN_DOOR_OPEN_SWITCH, INPUT_PULLUP);
pinMode(PIN_DOOR_CLOSED_SWITCH, INPUT_PULLUP);
}
telemetrycommandResponseE CDoorMotor_GarageDoor::command(doorCommandE _command)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.print(F("CDoorMotor_GarageDoor - command door: "));
DEBUG_SERIAL.println((_command == doorCommand_open) ? F("open.") :
(_command == doorCommand_close) ? F("close.") :
F("*** INVALID ***"));
#endif
if((_command != doorCommand_open) && (_command != doorCommand_close))
return telemetry_cmd_response_nak_invalid_value;
// Very special case at startup when coop door should be open
if(m_seekingKnownState)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - received command while seeking known state. Command delayed."));
#endif
m_lastCommand = _command;
return telemetry_cmd_response_ack;
}
// Only accept commands when I am in a stable state
if((m_state != doorState_closed) && (m_state != doorState_open))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - commmand() info:"));
#endif
return telemetry_cmd_response_nak_not_ready;
}
// Well, act on the command
if( ((m_state == doorState_closed) && (_command == doorCommand_open)) ||
((m_state == doorState_open) && (_command == doorCommand_close)))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - cycling relay."));
#endif
// Remember my last valid command
m_lastCommand = _command;
// Start the relay on timer
m_relayTimer.start(CDoorMotor_GarageDoor_relayMS);
digitalWrite(PIN_DOOR_RELAY, RELAY_ON);
// Set door state to moving and start the stuck timer
m_state = doorState_moving;
m_stuckDoorTimer.start(CDoorMotor_GarageDoor_stuck_door_delayMS);
return telemetry_cmd_response_ack;
}
else
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - not commanded to opposite state, ignoring."));
#endif
return telemetry_cmd_response_ack;
}
return telemetry_cmd_response_nak_internal_error;
}
doorStateE CDoorMotor_GarageDoor::getDoorState()
{
if(uglySwitches())
return doorState_unknown;
return m_state;
}
void CDoorMotor_GarageDoor::tick()
{
// Don't do anything if the switches are in an ugly state
if(uglySwitches())
{
digitalWrite(PIN_DOOR_RELAY, RELAY_OFF);
return;
}
// Monitor the relay and turn it off
// when the timer hits zero
// First "running" test returns to keep the door switch debounce
// logic from messing with the relay timing
if(m_relayTimer.getState() == CMilliTimer::running)
return;
if(m_relayTimer.getState() == CMilliTimer::expired)
{
m_relayTimer.reset();
digitalWrite(PIN_DOOR_RELAY, RELAY_OFF);
}
///////////////////////////////////////////////////////////////////////
// If I have not checked my initial state then do it now.
if(m_seekingKnownState)
{
// I just started. This is my first tick. If I don't know
// where the door is then toggle the relay to get it to
// go somewhere!
if((getSwitches() == 0) && (m_seekKnownStateRelayCommandIssued == false))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - Started in unknown state, seeking a switch."));
#endif
// Start the relay on timer
m_relayTimer.start( CDoorMotor_GarageDoor_relayMS);
digitalWrite(PIN_DOOR_RELAY, RELAY_ON);
// And a delay to see if we ever get there
m_state = doorState_unknown;
m_stuckDoorTimer.start(CDoorMotor_GarageDoor_stuck_door_delayMS);
m_seekKnownStateRelayCommandIssued = true;
}
// I'm waiting for a known state - good or bad.
if(getSwitches() == doorSwitchOpen)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - found open-switch, now in known state."));
#endif
m_state = doorState_open;
m_seekingKnownState = false;
m_stuckDoorTimer.reset();
}
else if(getSwitches() == doorSwitchClosed)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - found closed-switch, now in known state."));
#endif
m_state = doorState_closed;
m_seekingKnownState = false;
m_stuckDoorTimer.reset();
}
else if(m_stuckDoorTimer.getState() == CMilliTimer::expired)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - time is up, entering unknown state."));
#endif
m_state = doorState_unknown;
m_seekingKnownState = false;
m_stuckDoorTimer.reset();
}
return;
}
///////////////////////////////////////////////////////////////////////
// We have passed the m_seekingKnownState startup phase. This is normal
// operation
switch(m_state)
{
case doorState_moving:
if((m_lastCommand == doorCommand_open) && (getSwitches() == doorSwitchOpen))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - reached command state: open"));
#endif
m_state = doorState_open;
m_stuckDoorTimer.reset();
}
else if((m_lastCommand == doorCommand_close) && (getSwitches() == doorSwitchClosed))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - reached command state: closed"));
#endif
m_state = doorState_closed;
m_stuckDoorTimer.reset();
}
else if(m_stuckDoorTimer.getState() == CMilliTimer::expired)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - *** Timed out waiting for commanded state. ***"));
#endif
m_state = doorState_unknown;
m_stuckDoorTimer.reset();
}
return;
case doorState_open:
// Closed from the open state
if((m_state == doorState_open) && (getSwitches() == doorSwitchClosed))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - spontaneous change to: closed"));
#endif
m_state = doorState_closed;
}
break;
case doorState_closed:
// Open from the closed state
if((m_state == doorState_closed) && (getSwitches() == doorSwitchOpen))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - spontaneous change to: open"));
#endif
m_state = doorState_open;
}
break;
case doorState_unknown:
if(getSwitches() == doorSwitchOpen)
m_state = doorState_open;
if(getSwitches() == doorSwitchClosed)
m_state = doorState_closed;
break;
default:
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - *** UNKNOWN STATE VALUE ***"));
#endif
return;
}
////////////////////////////////////////////
// We are not moving, so we should be in the open or closed state.
// Now we monitor for spontaneous changes in the door switches
// Loss of door switches
if(getSwitches() == 0)
{
// The switches went to 0. Someone might be out there
// opening the door, so wait until we know for sure.
if(m_lostSwitchesTimer.getState() == CMilliTimer::notSet)
{
m_lostSwitchesTimer.start(CDoorMotor_GarageDoor_stuck_door_delayMS);
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - both door switches open. Is the door moving?"));
#endif
}
else if(m_lostSwitchesTimer.getState() == CMilliTimer::expired)
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - spontaneous change to: * UNKNOWN *"));
#endif
m_lostSwitchesTimer.reset();
m_state = doorState_unknown;
}
}
else
{
#ifdef DEBUG_DOOR_MOTOR
if(m_lostSwitchesTimer.getState() == CMilliTimer::running)
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - switches recovered before timeout to unknown state."));
#endif
m_lostSwitchesTimer.reset();
}
}
static unsigned int rawSwitchRead()
{
unsigned int mask = 0;
// NOTE, Inputs are active LOW, so a zero means that
// the switch is closed and the door is in that position
if(digitalRead(PIN_DOOR_OPEN_SWITCH) == 0)
mask |= doorSwitchOpen;
if(digitalRead(PIN_DOOR_CLOSED_SWITCH) == 0)
mask |= doorSwitchClosed;
return mask;
}
unsigned int CDoorMotor_GarageDoor::getSwitches()
{
unsigned int mask1 = 0;
unsigned int mask2 = 0;
// Make sure the switches are not bouncing
// and producing false readings.
do
{
mask1 = rawSwitchRead();
delay(2);
mask2 = rawSwitchRead();
delay(2);
}
while(mask1 != mask2);
return mask2;
}
bool CDoorMotor_GarageDoor::uglySwitches()
{
if((getSwitches() & doorSwitchOpen) && (getSwitches() & doorSwitchClosed))
{
#ifdef DEBUG_DOOR_MOTOR
DEBUG_SERIAL.println(F("CDoorMotor_GarageDoor - *** Ugly switches ***"));
#endif
return true;
}
return false;
}
| 9,954 | 3,916 |
#include "ValidRequest.h"
#include "dllexport.h"
using TLMUtilities::E_XactorType ;
template<unsigned A, unsigned D, unsigned U>
unsigned ValidRequest<A,D,U>::isValid (TLMUtilities::E_XactorType xtype
, const TLMRequest<A,D,U> &req
, TLMUtilities::ErrorList_t &errs) {
ValidRequest<A,D,U> checker( xtype, req, errs);
return checker.errCount();
}
template<unsigned A, unsigned D, unsigned U>
ValidRequest<A,D,U>::ValidRequest ( TLMUtilities::E_XactorType xtype
, const TLMRequest<A,D,U> &req
, TLMUtilities::ErrorList_t &errs)
: m_type(xtype)
, m_request(req)
, m_errors(errs)
, m_errCnt(0)
{
check();
}
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::check() {
checkLock();
switch (m_type) {
case TLMUtilities::e_UNKNOWN: break;
case TLMUtilities::e_AHB: checkAhb(); break;
case TLMUtilities::e_APB: checkApb(); break;
case TLMUtilities::e_AXI3: checkAxi3(); break;
case TLMUtilities::e_AXI4: checkAxi4(); break;
}
}
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::checkAddressAligned() {
unsigned zeros = TLMUtilities::lsbZeros (m_request.m_header.m_b_size);
long long addr = (long long) m_request.m_address;
long long mask = ~((-1LL) << zeros);
if ((mask & addr) != 0) {
errorAddressAlignment();
}
}
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::checkBurstCross(unsigned boundary) {
long long baseAddr = (long long) m_request.m_address;
// only incr burst can cross boundary
if (m_request.m_header.m_burst_mode == TLMBurstMode::e_INCR) {
unsigned bursts = (unsigned) m_request.m_b_length ;
unsigned a_incr = TLMUtilities::addrIncr (m_request.m_header.m_b_size) * bursts ;
long long topAddr = baseAddr + (long long) a_incr ;
long long mask = (boundary - 1);
if ((baseAddr & ~mask) != (topAddr & ~mask)) {
errorBurstCrossing (boundary);
}
}
}
/// \brief Check that burst lenght is valid. wrap must be a power of 2 (-1)
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::checkBurstLenght() {
if (m_request.m_header.m_burst_mode == TLMBurstMode::e_WRAP) {
unsigned blen = (unsigned) m_request.m_b_length;
if (!isPowerOfTwo (blen)) {
errorBurstLength();
}
}
}
/// \brief Check that that exclusive access restrictions are met for AXI transactions
///
/// Address must be aligned withe total byte transfered
/// number of byte must be power of 2 upto 128
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::checkExclusizeAccessRestrictions( ){
bool ok = true;
if (m_request.m_header.m_lock == TLMLock::e_EXCLUSIVE) {
unsigned blen = (unsigned) m_request.m_b_length;
unsigned oneXferBytes = TLMUtilities::addrIncr (m_request.m_header.m_b_size);
unsigned totalBytes = blen * oneXferBytes;
if ( !isPowerOfTwo (totalBytes) ) {
errorExclusiveSize(totalBytes);
ok = false;
}
if ((totalBytes > 128) ) {
errorExclusiveTooBig(totalBytes);
ok = false;
}
if (ok) {
// This will error if the above condition is false
unsigned zeros = TLMUtilities::lsbZeros(TLMUtilities::getBSize(totalBytes*8));
long long addr = (long long) m_request.m_address;
long long mask = ~((-1LL) << zeros);
if ((mask & addr) != 0) {
errorExclusiveUnaligned(totalBytes);
}
}
}
}
/// \brief Check that the lock field is supported for the xtype
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::checkLock() {
bool err = false;
switch (m_type) {
case TLMUtilities::e_UNKNOWN:
break;
case TLMUtilities::e_AHB:
err = (m_request.m_header.m_lock != TLMLock::e_NORMAL);
break;
case TLMUtilities::e_APB:
err = (m_request.m_header.m_lock != TLMLock::e_NORMAL);
break;
case TLMUtilities::e_AXI3:
err = (m_request.m_header.m_lock == TLMLock::e_RESERVED);
break;
case TLMUtilities::e_AXI4:
err = ( (m_request.m_header.m_lock != TLMLock::e_NORMAL) &&
(m_request.m_header.m_lock != TLMLock::e_EXCLUSIVE) ) ;
break;
}
if (err) {
errorWrongLockMode ();
}
}
template<unsigned A, unsigned D, unsigned U>
void ValidRequest<A,D,U>::checkBurstSize(unsigned maxb) {
unsigned bursts = (unsigned) m_request.m_b_length ;
if (bursts > maxb) {
errorBurstSize(maxb);
}
}
template class DLLEXPORT ValidRequest<32,8,0>;
template class DLLEXPORT ValidRequest<32,16,0>;
template class DLLEXPORT ValidRequest<32,32,0>;
template class DLLEXPORT ValidRequest<32,64,0>;
template class DLLEXPORT ValidRequest<32,128,0>;
template class DLLEXPORT ValidRequest<32,256,0>;
template class DLLEXPORT ValidRequest<32,512,0>;
template class DLLEXPORT ValidRequest<32,1024,0>;
template class DLLEXPORT ValidRequest<64,8,0>;
template class DLLEXPORT ValidRequest<64,16,0>;
template class DLLEXPORT ValidRequest<64,32,0>;
template class DLLEXPORT ValidRequest<64,64,0>;
template class DLLEXPORT ValidRequest<64,128,0>;
template class DLLEXPORT ValidRequest<64,256,0>;
template class DLLEXPORT ValidRequest<64,512,0>;
template class DLLEXPORT ValidRequest<64,1024,0>;
template class DLLEXPORT ValidRequest<32,8,32>;
template class DLLEXPORT ValidRequest<32,16,32>;
template class DLLEXPORT ValidRequest<32,32,32>;
template class DLLEXPORT ValidRequest<32,64,32>;
template class DLLEXPORT ValidRequest<32,128,32>;
template class DLLEXPORT ValidRequest<32,256,32>;
template class DLLEXPORT ValidRequest<32,512,32>;
template class DLLEXPORT ValidRequest<32,1024,32>;
template class DLLEXPORT ValidRequest<64,8,32>;
template class DLLEXPORT ValidRequest<64,16,32>;
template class DLLEXPORT ValidRequest<64,32,32>;
template class DLLEXPORT ValidRequest<64,64,32>;
template class DLLEXPORT ValidRequest<64,128,32>;
template class DLLEXPORT ValidRequest<64,256,32>;
template class DLLEXPORT ValidRequest<64,512,32>;
template class DLLEXPORT ValidRequest<64,1024,32>;
template class DLLEXPORT ValidRequest<32,8,64>;
template class DLLEXPORT ValidRequest<32,16,64>;
template class DLLEXPORT ValidRequest<32,32,64>;
template class DLLEXPORT ValidRequest<32,64,64>;
template class DLLEXPORT ValidRequest<32,128,64>;
template class DLLEXPORT ValidRequest<32,256,64>;
template class DLLEXPORT ValidRequest<32,512,64>;
template class DLLEXPORT ValidRequest<32,1024,64>;
template class DLLEXPORT ValidRequest<64,8,64>;
template class DLLEXPORT ValidRequest<64,16,64>;
template class DLLEXPORT ValidRequest<64,32,64>;
template class DLLEXPORT ValidRequest<64,64,64>;
template class DLLEXPORT ValidRequest<64,128,64>;
template class DLLEXPORT ValidRequest<64,256,64>;
template class DLLEXPORT ValidRequest<64,512,64>;
template class DLLEXPORT ValidRequest<64,1024,64>;
| 6,873 | 2,651 |
#include "QtScriptBindingsHelpers.h"
void ToExistingScriptValue_Circle(QScriptEngine *engine, const Circle &value, QScriptValue obj)
{
obj.setProperty("pos", qScriptValueFromValue(engine, value.pos), QScriptValue::Undeletable);
obj.setProperty("normal", qScriptValueFromValue(engine, value.normal), QScriptValue::Undeletable);
obj.setProperty("r", qScriptValueFromValue(engine, value.r), QScriptValue::Undeletable);
}
static QScriptValue Circle_Circle(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Circle_Circle in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle ret;
memset(&ret, 0, sizeof ret);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_Circle_float3_float3_float(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 3) { printf("Error! Invalid number of arguments passed to function Circle_Circle_float3_float3_float in file %s, line %d!\nExpected 3, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
float3 center = qscriptvalue_cast<float3>(context->argument(0));
float3 normal = qscriptvalue_cast<float3>(context->argument(1));
float radius = qscriptvalue_cast<float>(context->argument(2));
Circle ret(center, normal, radius);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_BasisU_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Circle_BasisU_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 ret = This.BasisU();
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_BasisV_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Circle_BasisV_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 ret = This.BasisV();
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_GetPoint_float_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_GetPoint_float_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float angleRadians = qscriptvalue_cast<float>(context->argument(0));
float3 ret = This.GetPoint(angleRadians);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_GetPoint_float_float_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Circle_GetPoint_float_float_const in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float angleRadians = qscriptvalue_cast<float>(context->argument(0));
float d = qscriptvalue_cast<float>(context->argument(1));
float3 ret = This.GetPoint(angleRadians, d);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_CenterPoint_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Circle_CenterPoint_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 ret = This.CenterPoint();
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_Centroid_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Circle_Centroid_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 ret = This.Centroid();
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_ExtremePoint_float3_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_ExtremePoint_float3_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 direction = qscriptvalue_cast<float3>(context->argument(0));
float3 ret = This.ExtremePoint(direction);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_ContainingPlane_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Circle_ContainingPlane_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
Plane ret = This.ContainingPlane();
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_Translate_float3(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_Translate_float3 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 offset = qscriptvalue_cast<float3>(context->argument(0));
This.Translate(offset);
ToExistingScriptValue_Circle(engine, This, context->thisObject());
return QScriptValue();
}
static QScriptValue Circle_Transform_float3x3(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_Transform_float3x3 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3x3 transform = qscriptvalue_cast<float3x3>(context->argument(0));
This.Transform(transform);
ToExistingScriptValue_Circle(engine, This, context->thisObject());
return QScriptValue();
}
static QScriptValue Circle_Transform_float3x4(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_Transform_float3x4 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3x4 transform = qscriptvalue_cast<float3x4>(context->argument(0));
This.Transform(transform);
ToExistingScriptValue_Circle(engine, This, context->thisObject());
return QScriptValue();
}
static QScriptValue Circle_Transform_float4x4(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_Transform_float4x4 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float4x4 transform = qscriptvalue_cast<float4x4>(context->argument(0));
This.Transform(transform);
ToExistingScriptValue_Circle(engine, This, context->thisObject());
return QScriptValue();
}
static QScriptValue Circle_Transform_Quat(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_Transform_Quat in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
Quat transform = qscriptvalue_cast<Quat>(context->argument(0));
This.Transform(transform);
ToExistingScriptValue_Circle(engine, This, context->thisObject());
return QScriptValue();
}
static QScriptValue Circle_EdgeContains_float3_float_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Circle_EdgeContains_float3_float_const in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 point = qscriptvalue_cast<float3>(context->argument(0));
float maxDistance = qscriptvalue_cast<float>(context->argument(1));
bool ret = This.EdgeContains(point, maxDistance);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_DistanceToEdge_float3_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_DistanceToEdge_float3_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 point = qscriptvalue_cast<float3>(context->argument(0));
float ret = This.DistanceToEdge(point);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_DistanceToDisc_float3_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_DistanceToDisc_float3_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 point = qscriptvalue_cast<float3>(context->argument(0));
float ret = This.DistanceToDisc(point);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_ClosestPointToEdge_float3_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_ClosestPointToEdge_float3_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 point = qscriptvalue_cast<float3>(context->argument(0));
float3 ret = This.ClosestPointToEdge(point);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_ClosestPointToDisc_float3_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_ClosestPointToDisc_float3_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
float3 point = qscriptvalue_cast<float3>(context->argument(0));
float3 ret = This.ClosestPointToDisc(point);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_Intersects_Plane_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_Intersects_Plane_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
Plane plane = qscriptvalue_cast<Plane>(context->argument(0));
int ret = This.Intersects(plane);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_IntersectsDisc_Line_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_IntersectsDisc_Line_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
Line line = qscriptvalue_cast<Line>(context->argument(0));
bool ret = This.IntersectsDisc(line);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_IntersectsDisc_LineSegment_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_IntersectsDisc_LineSegment_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
LineSegment lineSegment = qscriptvalue_cast<LineSegment>(context->argument(0));
bool ret = This.IntersectsDisc(lineSegment);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_IntersectsDisc_Ray_const(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_IntersectsDisc_Ray_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
Ray ray = qscriptvalue_cast<Ray>(context->argument(0));
bool ret = This.IntersectsDisc(ray);
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_toString_const(QScriptContext *context, QScriptEngine *engine)
{
Circle This;
if (context->argumentCount() > 0) This = qscriptvalue_cast<Circle>(context->argument(0)); // Qt oddity (bug?): Sometimes the built-in toString() function doesn't give us this from thisObject, but as the first argument.
else This = qscriptvalue_cast<Circle>(context->thisObject());
QString ret = This.toString();
return qScriptValueFromValue(engine, ret);
}
static QScriptValue Circle_IntersectsFaces_manual(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Circle_IntersectsDisc_Ray_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); }
Circle This = qscriptvalue_cast<Circle>(context->thisObject());
OBB obb = qscriptvalue_cast<OBB>(context->argument(0));
std::vector<float3> ret = This.IntersectsFaces(obb);
QScriptValue retObj = engine->newArray((uint)ret.size());
for(size_t i = 0; i < ret.size(); ++i)
retObj.setProperty((quint32)i, qScriptValueFromValue(engine, ret[i]));
return retObj;
}
static QScriptValue Circle_ctor(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() == 0)
return Circle_Circle(context, engine);
if (context->argumentCount() == 3 && QSVIsOfType<float3>(context->argument(0)) && QSVIsOfType<float3>(context->argument(1)) && QSVIsOfType<float>(context->argument(2)))
return Circle_Circle_float3_float3_float(context, engine);
printf("Circle_ctor failed to choose the right function to call! Did you use 'var x = Circle();' instead of 'var x = new Circle();'?\n"); PrintCallStack(context->backtrace()); return QScriptValue();
}
static QScriptValue Circle_GetPoint_selector(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() == 1 && QSVIsOfType<float>(context->argument(0)))
return Circle_GetPoint_float_const(context, engine);
if (context->argumentCount() == 2 && QSVIsOfType<float>(context->argument(0)) && QSVIsOfType<float>(context->argument(1)))
return Circle_GetPoint_float_float_const(context, engine);
printf("Circle_GetPoint_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue();
}
static QScriptValue Circle_Transform_selector(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() == 1 && QSVIsOfType<float3x3>(context->argument(0)))
return Circle_Transform_float3x3(context, engine);
if (context->argumentCount() == 1 && QSVIsOfType<float3x4>(context->argument(0)))
return Circle_Transform_float3x4(context, engine);
if (context->argumentCount() == 1 && QSVIsOfType<float4x4>(context->argument(0)))
return Circle_Transform_float4x4(context, engine);
if (context->argumentCount() == 1 && QSVIsOfType<Quat>(context->argument(0)))
return Circle_Transform_Quat(context, engine);
printf("Circle_Transform_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue();
}
static QScriptValue Circle_IntersectsDisc_selector(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() == 1 && QSVIsOfType<Line>(context->argument(0)))
return Circle_IntersectsDisc_Line_const(context, engine);
if (context->argumentCount() == 1 && QSVIsOfType<LineSegment>(context->argument(0)))
return Circle_IntersectsDisc_LineSegment_const(context, engine);
if (context->argumentCount() == 1 && QSVIsOfType<Ray>(context->argument(0)))
return Circle_IntersectsDisc_Ray_const(context, engine);
printf("Circle_IntersectsDisc_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue();
}
void FromScriptValue_Circle(const QScriptValue &obj, Circle &value)
{
value.pos = qScriptValueToValue<float3>(obj.property("pos"));
value.normal = qScriptValueToValue<float3>(obj.property("normal"));
value.r = qScriptValueToValue<float>(obj.property("r"));
}
QScriptValue ToScriptValue_Circle(QScriptEngine *engine, const Circle &value)
{
QScriptValue obj = engine->newVariant(QVariant::fromValue(value)); // The contents of this variant are NOT used. The real data lies in the data() pointer of this QScriptValue. This only exists to enable overload resolution to work for QObject slots.
ToExistingScriptValue_Circle(engine, value, obj);
return obj;
}
QScriptValue ToScriptValue_const_Circle(QScriptEngine *engine, const Circle &value)
{
QScriptValue obj = engine->newVariant(QVariant::fromValue(value)); // The contents of this variant are NOT used. The real data lies in the data() pointer of this QScriptValue. This only exists to enable overload resolution to work for QObject slots.
obj.setPrototype(engine->defaultPrototype(qMetaTypeId<Circle>()));
obj.setProperty("pos", ToScriptValue_const_float3(engine, value.pos), QScriptValue::Undeletable | QScriptValue::ReadOnly);
obj.setProperty("normal", ToScriptValue_const_float3(engine, value.normal), QScriptValue::Undeletable | QScriptValue::ReadOnly);
obj.setProperty("r", qScriptValueFromValue(engine, value.r), QScriptValue::Undeletable | QScriptValue::ReadOnly);
return obj;
}
QScriptValue register_Circle_prototype(QScriptEngine *engine)
{
QScriptValue proto = engine->newObject();
proto.setProperty("BasisU", engine->newFunction(Circle_BasisU_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("BasisV", engine->newFunction(Circle_BasisV_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("GetPoint", engine->newFunction(Circle_GetPoint_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("GetPoint", engine->newFunction(Circle_GetPoint_selector, 2), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("CenterPoint", engine->newFunction(Circle_CenterPoint_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("Centroid", engine->newFunction(Circle_Centroid_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("ExtremePoint", engine->newFunction(Circle_ExtremePoint_float3_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("ContainingPlane", engine->newFunction(Circle_ContainingPlane_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("Translate", engine->newFunction(Circle_Translate_float3, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("Transform", engine->newFunction(Circle_Transform_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("EdgeContains", engine->newFunction(Circle_EdgeContains_float3_float_const, 2), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("DistanceToEdge", engine->newFunction(Circle_DistanceToEdge_float3_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("DistanceToDisc", engine->newFunction(Circle_DistanceToDisc_float3_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("ClosestPointToEdge", engine->newFunction(Circle_ClosestPointToEdge_float3_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("ClosestPointToDisc", engine->newFunction(Circle_ClosestPointToDisc_float3_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("Intersects", engine->newFunction(Circle_Intersects_Plane_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("IntersectsDisc", engine->newFunction(Circle_IntersectsDisc_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("toString", engine->newFunction(Circle_toString_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("IntersectsFaces", engine->newFunction(Circle_IntersectsFaces_manual, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
proto.setProperty("metaTypeId", engine->toScriptValue<qint32>((qint32)qMetaTypeId<Circle>()));
engine->setDefaultPrototype(qMetaTypeId<Circle>(), proto);
engine->setDefaultPrototype(qMetaTypeId<Circle*>(), proto);
qScriptRegisterMetaType(engine, ToScriptValue_Circle, FromScriptValue_Circle, proto);
QScriptValue ctor = engine->newFunction(Circle_ctor, proto, 3);
engine->globalObject().setProperty("Circle", ctor, QScriptValue::Undeletable | QScriptValue::ReadOnly);
return ctor;
}
| 24,260 | 7,266 |
/**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/delegate/npu/op/resize_npu.h"
#include <memory>
#include "src/delegate/npu/npu_converter_utils.h"
namespace mindspore {
int ResizeNPUOp::IsSupport(const schema::Primitive *primitive, const std::vector<tensor::MSTensor *> &in_tensors,
const std::vector<tensor::MSTensor *> &out_tensors) {
auto resize_prim = primitive->value_as_Resize();
if (resize_prim == nullptr) {
MS_LOG(ERROR) << "Get null primitive value for op ." << name_;
return RET_ERROR;
}
resize_method_ = resize_prim->method();
if (resize_method_ != schema::ResizeMethod_LINEAR && resize_method_ != schema::ResizeMethod_NEAREST) {
MS_LOG(WARNING) << "Unsupported resize method type: " << resize_method_;
return RET_NOT_SUPPORT;
}
if (in_tensors[0]->shape()[1] > out_tensors[0]->shape()[1] ||
in_tensors[0]->shape()[2] > out_tensors[0]->shape()[2]) {
MS_LOG(WARNING) << "Npu resize does not support reduction.";
return RET_NOT_SUPPORT;
}
return RET_OK;
}
int ResizeNPUOp::Init(const schema::Primitive *primitive, const std::vector<tensor::MSTensor *> &in_tensors,
const std::vector<tensor::MSTensor *> &out_tensors) {
auto resize_prim = primitive->value_as_Resize();
if (resize_prim == nullptr) {
MS_LOG(ERROR) << "Get null primitive value for op ." << name_;
return RET_ERROR;
}
if (in_tensors.size() == 1) {
new_height_ = resize_prim->new_height();
new_width_ = resize_prim->new_width();
} else if (in_tensors.size() == 2) {
auto out_size = in_tensors.at(1)->data();
if (out_size == nullptr) {
MS_LOG(ERROR) << "Out size is not assigned";
return RET_ERROR;
}
new_height_ = out_tensors.at(0)->shape().at(1);
new_width_ = out_tensors.at(0)->shape().at(2);
} else {
MS_LOG(ERROR) << "Get resize op new_height and new_width error.";
return RET_ERROR;
}
ge::TensorDesc sizeTensorDesc(ge::Shape({2}), ge::FORMAT_NCHW, ge::DT_INT32);
ge::TensorPtr sizeTensor = std::make_shared<hiai::Tensor>(sizeTensorDesc);
vector<int32_t> dataValue = {static_cast<int32_t>(new_height_), static_cast<int32_t>(new_width_)};
sizeTensor->SetData(reinterpret_cast<uint8_t *>(dataValue.data()), 2 * sizeof(int32_t));
out_size_ = new (std::nothrow) hiai::op::Const(name_ + "_size");
out_size_->set_attr_value(sizeTensor);
if (resize_method_ == schema::ResizeMethod_LINEAR) {
auto resize_bilinear = new (std::nothrow) hiai::op::ResizeBilinearV2(name_);
if (resize_bilinear == nullptr) {
MS_LOG(ERROR) << " resize_ is nullptr.";
return RET_ERROR;
}
resize_bilinear->set_attr_align_corners(resize_prim->coordinate_transform_mode() ==
schema::CoordinateTransformMode_ALIGN_CORNERS);
resize_bilinear->set_input_size(*out_size_);
resize_bilinear->set_attr_half_pixel_centers(resize_prim->preserve_aspect_ratio());
resize_ = resize_bilinear;
} else if (resize_method_ == schema::ResizeMethod_NEAREST) {
auto resize_nearest = new (std::nothrow) hiai::op::ResizeNearestNeighborV2(name_);
if (resize_nearest == nullptr) {
MS_LOG(ERROR) << " resize_ is nullptr.";
return RET_ERROR;
}
resize_nearest->set_attr_align_corners(resize_prim->coordinate_transform_mode() ==
schema::CoordinateTransformMode_ALIGN_CORNERS);
resize_nearest->set_input_size(*out_size_);
} else {
MS_LOG(WARNING) << "Unsupported resize method type:" << resize_method_;
return RET_ERROR;
}
return RET_OK;
}
int ResizeNPUOp::SetNPUInputs(const std::vector<tensor::MSTensor *> &in_tensors,
const std::vector<tensor::MSTensor *> &out_tensors,
const std::vector<ge::Operator *> &npu_inputs) {
if (resize_method_ == schema::ResizeMethod_LINEAR) {
auto resize_bilinear = reinterpret_cast<hiai::op::ResizeBilinearV2 *>(resize_);
resize_bilinear->set_input_x(*npu_inputs[0]);
} else if (resize_method_ == schema::ResizeMethod_NEAREST) {
auto resize_nearest = reinterpret_cast<hiai::op::ResizeNearestNeighborV2 *>(resize_);
resize_nearest->set_input_x(*npu_inputs[0]);
} else {
MS_LOG(WARNING) << "Unsupported resize method type:" << resize_method_;
return RET_ERROR;
}
return RET_OK;
}
ge::Operator *ResizeNPUOp::GetNPUOp() { return this->resize_; }
ResizeNPUOp::~ResizeNPUOp() {
if (resize_ != nullptr) {
delete resize_;
resize_ = nullptr;
}
if (out_size_ != nullptr) {
delete out_size_;
out_size_ = nullptr;
}
}
} // namespace mindspore
| 5,237 | 1,873 |
// Copyright (c) 2012 The Chromium 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 "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/protector/mock_setting_change.h"
#include "chrome/browser/protector/protector_service.h"
#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/browser/protector/settings_change_global_error.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error.h"
#include "chrome/browser/ui/global_error_bubble_view_base.h"
#include "chrome/browser/ui/global_error_service.h"
#include "chrome/browser/ui/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
using ::testing::InvokeWithoutArgs;
using ::testing::NiceMock;
using ::testing::Return;
namespace protector {
class ProtectorServiceTest : public InProcessBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
// Make sure protector is enabled.
command_line->AppendSwitch(switches::kProtector);
}
virtual void SetUpOnMainThread() OVERRIDE {
protector_service_ =
ProtectorServiceFactory::GetForProfile(browser()->profile());
// ProtectService will own this change instance.
mock_change_ = new NiceMock<MockSettingChange>();
}
protected:
GlobalError* GetGlobalError(BaseSettingChange* change) {
for (ProtectorService::Items::iterator item =
protector_service_->items_.begin();
item != protector_service_->items_.end(); item++) {
if (item->change.get() == change)
return item->error.get();
}
return NULL;
}
// Checks that |protector_service_| has an error instance corresponding to
// |change| and that GlobalErrorService knows about it.
bool IsGlobalErrorActive(BaseSettingChange* change) {
GlobalError* error = GetGlobalError(change);
if (!error)
return false;
if (!GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
GetGlobalErrorByMenuItemCommandID(error->MenuItemCommandID())) {
return false;
}
return protector_service_->IsShowingChange();
}
ProtectorService* protector_service_;
MockSettingChange* mock_change_;
};
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ChangeInitError) {
// Init fails and causes the change to be ignored.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(false));
protector_service_->ShowChange(mock_change_);
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(protector_service_->GetLastChange());
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDismiss) {
// Show the change and immediately dismiss it.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
protector_service_->DismissChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(protector_service_->GetLastChange());
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndApply) {
// Show the change and apply it.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_CALL(*mock_change_, Apply(browser()));
protector_service_->ApplyChange(mock_change_, browser());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
}
// ProtectorServiceTest.ShowAndApplyManually is timing out frequently on Win
// bots. http://crbug.com/130590
#if defined(OS_WIN)
#define MAYBE_ShowAndApplyManually DISABLED_ShowAndApplyManually
#else
#define MAYBE_ShowAndApplyManually ShowAndApplyManually
#endif
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, MAYBE_ShowAndApplyManually) {
// Show the change and apply it, mimicking a button click.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_CALL(*mock_change_, Apply(browser()));
// Pressing Cancel applies the change.
GlobalError* error = GetGlobalError(mock_change_);
ASSERT_TRUE(error);
error->BubbleViewCancelButtonPressed(browser());
error->GetBubbleView()->CloseBubbleView();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDiscard) {
// Show the change and discard it.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_CALL(*mock_change_, Discard(browser()));
protector_service_->DiscardChange(mock_change_, browser());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDiscardManually) {
// Show the change and discard it, mimicking a button click.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_CALL(*mock_change_, Discard(browser()));
// Pressing Apply discards the change.
GlobalError* error = GetGlobalError(mock_change_);
ASSERT_TRUE(error);
error->BubbleViewAcceptButtonPressed(browser());
error->GetBubbleView()->CloseBubbleView();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, BubbleClosedInsideApply) {
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
GlobalError* error = GetGlobalError(mock_change_);
ASSERT_TRUE(error);
GlobalErrorBubbleViewBase* bubble_view = error->GetBubbleView();
ASSERT_TRUE(bubble_view);
EXPECT_CALL(*mock_change_, Apply(browser())).WillOnce(InvokeWithoutArgs(
bubble_view, &GlobalErrorBubbleViewBase::CloseBubbleView));
// Pressing Cancel applies the change.
error->BubbleViewCancelButtonPressed(browser());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleChangesAndApply) {
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
EXPECT_EQ(mock_change2, protector_service_->GetLastChange());
// Apply the first change, the second should still be active.
EXPECT_CALL(*mock_change_, Apply(browser()));
protector_service_->ApplyChange(mock_change_, browser());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
EXPECT_EQ(mock_change2, protector_service_->GetLastChange());
// Finally apply the second change.
EXPECT_CALL(*mock_change2, Apply(browser()));
protector_service_->ApplyChange(mock_change2, browser());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
EXPECT_FALSE(protector_service_->GetLastChange());
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest,
ShowMultipleChangesDismissAndApply) {
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
// Dismiss the first change, the second should still be active.
protector_service_->DismissChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
// Finally apply the second change.
EXPECT_CALL(*mock_change2, Apply(browser()));
protector_service_->ApplyChange(mock_change2, browser());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest,
ShowMultipleChangesAndApplyManually) {
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
// The first bubble view has been displayed.
GlobalError* error = GetGlobalError(mock_change_);
ASSERT_TRUE(error);
ASSERT_TRUE(error->HasShownBubbleView());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
// The second bubble view hasn't been displayed because the first is still
// shown.
GlobalError* error2 = GetGlobalError(mock_change2);
ASSERT_TRUE(error2);
EXPECT_FALSE(error2->HasShownBubbleView());
// Apply the first change, mimicking a button click; the second should still
// be active.
EXPECT_CALL(*mock_change_, Apply(browser()));
error->BubbleViewCancelButtonPressed(browser());
error->GetBubbleView()->CloseBubbleView();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
// Now the second bubble view should be shown.
ASSERT_TRUE(error2->HasShownBubbleView());
// Finally apply the second change.
EXPECT_CALL(*mock_change2, Apply(browser()));
error2->BubbleViewCancelButtonPressed(browser());
error2->GetBubbleView()->CloseBubbleView();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest,
ShowMultipleChangesAndApplyManuallyBeforeOther) {
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
// The first bubble view has been displayed.
GlobalError* error = GetGlobalError(mock_change_);
ASSERT_TRUE(error);
ASSERT_TRUE(error->HasShownBubbleView());
// Apply the first change, mimicking a button click.
EXPECT_CALL(*mock_change_, Apply(browser()));
error->BubbleViewCancelButtonPressed(browser());
error->GetBubbleView()->CloseBubbleView();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
// The second bubble view has been displayed.
GlobalError* error2 = GetGlobalError(mock_change2);
ASSERT_TRUE(error2);
ASSERT_TRUE(error2->HasShownBubbleView());
// Finally apply the second change.
EXPECT_CALL(*mock_change2, Apply(browser()));
error2->BubbleViewCancelButtonPressed(browser());
error2->GetBubbleView()->CloseBubbleView();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleDifferentURLs) {
GURL url1("http://example.com/");
GURL url2("http://example.net/");
// Show the first change with some non-empty URL.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change with another non-empty URL.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
// Both changes are shown separately, not composited.
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
EXPECT_EQ(mock_change2, protector_service_->GetLastChange());
protector_service_->DismissChange(mock_change_);
protector_service_->DismissChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(protector_service_->GetLastChange());
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndDismiss) {
GURL url1("http://example.com/");
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// The first bubble view has been displayed.
GlobalError* error = GetGlobalError(mock_change_);
ASSERT_TRUE(error);
EXPECT_TRUE(error->HasShownBubbleView());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
// Now ProtectorService should be showing a single composite change.
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
BaseSettingChange* composite_change = protector_service_->GetLastChange();
ASSERT_TRUE(composite_change);
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
// The second (composite) bubble view has been displayed.
GlobalError* error2 = GetGlobalError(composite_change);
ASSERT_TRUE(error2);
EXPECT_TRUE(error2->HasShownBubbleView());
protector_service_->DismissChange(composite_change);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(composite_change));
EXPECT_FALSE(protector_service_->GetLastChange());
// Show the third change.
MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>();
EXPECT_CALL(*mock_change3, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change3);
ui_test_utils::RunAllPendingInMessageLoop();
// The third change should not be composed with the previous.
EXPECT_TRUE(IsGlobalErrorActive(mock_change3));
EXPECT_EQ(mock_change3, protector_service_->GetLastChange());
protector_service_->DismissChange(mock_change3);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change3));
EXPECT_FALSE(protector_service_->GetLastChange());
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndOther) {
GURL url1("http://example.com/");
GURL url2("http://example.net/");
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
// Now ProtectorService should be showing a single composite change.
BaseSettingChange* composite_change = protector_service_->GetLastChange();
ASSERT_TRUE(composite_change);
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
// Show the third change, with the same URL as 1st and 2nd.
MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>();
EXPECT_CALL(*mock_change3, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change3);
ui_test_utils::RunAllPendingInMessageLoop();
// The third change should be composed with the previous.
EXPECT_FALSE(IsGlobalErrorActive(mock_change3));
EXPECT_EQ(composite_change, protector_service_->GetLastChange());
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
// Show the 4th change, now with a different URL.
MockSettingChange* mock_change4 = new NiceMock<MockSettingChange>();
EXPECT_CALL(*mock_change4, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change4, GetNewSettingURL()).WillRepeatedly(Return(url2));
EXPECT_CALL(*mock_change4, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change4);
ui_test_utils::RunAllPendingInMessageLoop();
// The 4th change is shown independently.
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
EXPECT_TRUE(IsGlobalErrorActive(mock_change4));
EXPECT_EQ(mock_change4, protector_service_->GetLastChange());
protector_service_->DismissChange(composite_change);
protector_service_->DismissChange(mock_change4);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(composite_change));
EXPECT_FALSE(IsGlobalErrorActive(mock_change4));
EXPECT_FALSE(protector_service_->GetLastChange());
}
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndDismissSingle) {
GURL url1("http://example.com/");
GURL url2("http://example.net/");
// Show the first change.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
// Now ProtectorService should be showing a single composite change.
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
BaseSettingChange* composite_change = protector_service_->GetLastChange();
ASSERT_TRUE(composite_change);
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
// Show the third change with a different URL.
MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>();
EXPECT_CALL(*mock_change3, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url2));
EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change3);
ui_test_utils::RunAllPendingInMessageLoop();
// The third change should not be composed with the previous.
EXPECT_TRUE(IsGlobalErrorActive(mock_change3));
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
EXPECT_EQ(mock_change3, protector_service_->GetLastChange());
// Now dismiss the first change.
protector_service_->DismissChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
// This should effectively dismiss the whole composite change.
EXPECT_FALSE(IsGlobalErrorActive(composite_change));
EXPECT_TRUE(IsGlobalErrorActive(mock_change3));
EXPECT_EQ(mock_change3, protector_service_->GetLastChange());
protector_service_->DismissChange(mock_change3);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(mock_change3));
EXPECT_FALSE(protector_service_->GetLastChange());
}
// Verifies that changes with different URLs but same domain are merged.
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, SameDomainDifferentURLs) {
GURL url1("http://www.example.com/abc");
GURL url2("http://example.com/def");
// Show the first change with some non-empty URL.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change with another non-empty URL having same domain.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
// Changes should be merged.
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
BaseSettingChange* composite_change = protector_service_->GetLastChange();
ASSERT_TRUE(composite_change);
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
protector_service_->DismissChange(composite_change);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(composite_change));
EXPECT_FALSE(protector_service_->GetLastChange());
}
// Verifies that changes with different Google URLs are merged.
IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, DifferentGoogleDomains) {
GURL url1("http://www.google.com/search?q=");
GURL url2("http://google.ru/search?q=");
// Show the first change with some non-empty URL.
EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change_);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
// ProtectService will own this change instance as well.
MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
// Show the second change with another non-empty URL having same domain.
EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
WillOnce(Return(true));
EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2));
EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
protector_service_->ShowChange(mock_change2);
ui_test_utils::RunAllPendingInMessageLoop();
// Changes should be merged.
EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
BaseSettingChange* composite_change = protector_service_->GetLastChange();
ASSERT_TRUE(composite_change);
EXPECT_TRUE(IsGlobalErrorActive(composite_change));
protector_service_->DismissChange(composite_change);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(IsGlobalErrorActive(composite_change));
EXPECT_FALSE(protector_service_->GetLastChange());
}
// TODO(ivankr): Timeout test.
} // namespace protector
| 28,125 | 9,350 |
//
// Created by Siddhant on 2019-11-15.
//
#include "iostream"
#include "vector"
#include "string"
using namespace std;
vector<string> map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> s;
vector<string> old;
for (int i = 0; i < digits.size(); i++) {
int digit = digits[i] - '0';
if (s.empty()) {
for (int j = 0; j < map[digit].size(); j++) {
string character(1,map[digit][j]);
s.push_back(character);
}
old = s;
continue;
}
s = {};
for (int j = 0; j < map[digit].size(); j++) {
for (int k = 0; k < old.size(); k++) {
s.push_back(old[k] + map[digit][j]);
}
}
old = s;
}
return s;
}
int main() {
letterCombinations("23");
cout << "hello";
return 0;
} | 968 | 355 |
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_MissionRace_Interface_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass MissionRace_Interface.MissionRace_Interface_C
// 0x0000 (0x0028 - 0x0028)
class UMissionRace_Interface_C : public UInterface
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass MissionRace_Interface.MissionRace_Interface_C");
return ptr;
}
void GetPlayerRanking(int PlayerIndex, int* Ranking);
void GetRaceData(TArray<struct FRacePlayerData>* RaceData);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 840 | 291 |
#include "Settings.h"
Settings::Settings() {
uint8_t tempMAC[6];
defaultMacAP.set(WiFi.softAPmacAddress(tempMAC));
if(!defaultMacAP.valid()) defaultMacAP.randomize();
}
void Settings::syncMacInterface(){
if(debug) Serial.println("Trying to sync the MAC addr with settings");
if(isSettingsLoaded){
Mac macToSync;
if(isMacAPRand){
macToSync.randomize();
wifi_set_macaddr(SOFTAP_IF, macToSync._get());
if(debug) Serial.println("Synced with a random mac addr : " + macToSync.toString());
}else if(macAP.valid()){
macToSync = macAP;
wifi_set_macaddr(SOFTAP_IF, macToSync._get());
if(debug) Serial.println("Synced with saved mac addr : " + macToSync.toString());
}else{
if(debug) Serial.println("Could not sync because of invalid settings !");
}
}else{
if(debug) Serial.println("Could not sync because settings are not loaded !");
}
}
void Settings::setLedPin(int newLedPin){
prevLedPin = ledPin;
if(newLedPin > 0 && newLedPin != prevLedPin){
ledPin = newLedPin;
pinMode(ledPin, OUTPUT);
if(!prevLedPin == 0){
digitalWrite(ledPin, digitalRead(prevLedPin));
digitalWrite(prevLedPin, pinStateOff);
pinMode(prevLedPin, INPUT);
}else{
digitalWrite(ledPin, pinStateOff);
}
}
}
void Settings::load() {
if (EEPROM.read(checkNumAdr) != checkNum) {
reset();
return;
}
ssidLen = EEPROM.read(ssidLenAdr);
passwordLen = EEPROM.read(passwordLenAdr);
if (ssidLen < 1 || ssidLen > 32 || passwordLen < 8 && passwordLen != 0 || passwordLen > 32) {
reset();
return;
}
ssid = "";
password = "";
for (int i = 0; i < ssidLen; i++) ssid += (char)EEPROM.read(ssidAdr + i);
for (int i = 0; i < passwordLen; i++) password += (char)EEPROM.read(passwordAdr + i);
ssidHidden = (bool)EEPROM.read(ssidHiddenAdr);
if ((int)EEPROM.read(apChannelAdr) >= 1 && (int)EEPROM.read(apChannelAdr) <= 14) {
apChannel = (int)EEPROM.read(apChannelAdr);
} else {
apChannel = 1;
}
for(int i=0; i<6; i++){
macAP.setAt((uint8_t)EEPROM.read(macAPAdr+i),i);
}
if(!macAP.valid()) macAP.set(defaultMacAP);
isMacAPRand = (bool)EEPROM.read(isMacAPRandAdr);
apScanHidden = (bool)EEPROM.read(apScanHiddenAdr);
deauthReason = EEPROM.read(deauthReasonAdr);
attackTimeout = eepromReadInt(attackTimeoutAdr);
attackPacketRate = EEPROM.read(attackPacketRateAdr);
clientScanTime = EEPROM.read(clientScanTimeAdr);
useLed = (bool)EEPROM.read(useLedAdr);
channelHop = (bool)EEPROM.read(channelHopAdr);
multiAPs = (bool)EEPROM.read(multiAPsAdr);
multiAttacks = (bool)EEPROM.read(multiAttacksAdr);
macInterval = eepromReadInt(macIntervalAdr);
beaconInterval = (bool)EEPROM.read(beaconIntervalAdr);
setLedPin((int)EEPROM.read(ledPinAdr));
isSettingsLoaded = 1;
}
void Settings::reset() {
if (debug) Serial.print("reset settings...");
ssid = "MZY7 WIFI MT1";
password = "mzy7tech"; //must have at least 8 characters
ssidHidden = false;
apChannel = 9;
ssidLen = ssid.length();
passwordLen = password.length();
macAP = defaultMacAP;
isMacAPRand = 0;
apScanHidden = true;
deauthReason = 0x01;
attackTimeout = 5 * 60;
attackPacketRate = 10;
clientScanTime = 15;
useLed = true;
channelHop = false;
multiAPs = false;
multiAttacks = false;
macInterval = 4;
beaconInterval = false;
ledPin = 2;
if (debug) Serial.println("done");
save();
}
void Settings::save() {
ssidLen = ssid.length();
passwordLen = password.length();
EEPROM.write(ssidLenAdr, ssidLen);
EEPROM.write(passwordLenAdr, passwordLen);
for (int i = 0; i < ssidLen; i++) EEPROM.write(ssidAdr + i, ssid[i]);
for (int i = 0; i < passwordLen; i++) EEPROM.write(passwordAdr + i, password[i]);
EEPROM.write(ssidHiddenAdr, ssidHidden);
EEPROM.write(apChannelAdr, apChannel);
EEPROM.write(isMacAPRandAdr, isMacAPRand);
for(int i=0; i<6; i++){
EEPROM.write(macAPAdr+i, macAP._get(i));
}
EEPROM.write(apScanHiddenAdr, apScanHidden);
EEPROM.write(deauthReasonAdr, deauthReason);
eepromWriteInt(attackTimeoutAdr, attackTimeout);
EEPROM.write(attackPacketRateAdr, attackPacketRate);
EEPROM.write(clientScanTimeAdr, clientScanTime);
EEPROM.write(useLedAdr, useLed);
EEPROM.write(channelHopAdr, channelHop);
EEPROM.write(multiAPsAdr, multiAPs);
EEPROM.write(multiAttacksAdr, multiAttacks);
EEPROM.write(checkNumAdr, checkNum);
eepromWriteInt(macIntervalAdr, macInterval);
EEPROM.write(beaconIntervalAdr, beaconInterval);
EEPROM.write(ledPinAdr, ledPin);
EEPROM.commit();
if (debug) {
info();
Serial.println("settings saved");
}
}
void Settings::info() {
Serial.println("Settings:");
Serial.println("SSID: " + ssid);
Serial.println("SSID length: " + (String)ssidLen);
Serial.println("SSID hidden: " + (String)ssidHidden);
Serial.println("password: " + password);
Serial.println("password length: " + (String)passwordLen);
Serial.println("channel: " + (String)apChannel);
Serial.println("Default MAC AP: " + defaultMacAP.toString());
Serial.println("Saved MAC AP: " + macAP.toString());
Serial.println("MAC AP random: " + (String)isMacAPRand);
Serial.println("Scan hidden APs: " + (String)apScanHidden);
Serial.println("deauth reson: " + (String)(int)deauthReason);
Serial.println("attack timeout: " + (String)attackTimeout);
Serial.println("attack packet rate: " + (String)attackPacketRate);
Serial.println("client scan time: " + (String)clientScanTime);
Serial.println("use built-in LED: " + (String)useLed);
Serial.println("channel hopping: " + (String)channelHop);
Serial.println("multiple APs: " + (String)multiAPs);
Serial.println("multiple Attacks: " + (String)multiAttacks);
Serial.println("mac change interval: " + (String)macInterval);
Serial.println("1s beacon interval: " + (String)beaconInterval);
Serial.println("LED Pin: " + (String)ledPin);
}
size_t Settings::getSize() {
String json = "{";
size_t jsonSize = 0;
json += "\"ssid\":\"" + ssid + "\",";
json += "\"ssidHidden\":" + (String)ssidHidden + ",";
json += "\"password\":\"" + password + "\",";
json += "\"apChannel\":" + (String)apChannel + ",";
json += "\"macAp\":\"" + macAP.toString() + "\",";
json += "\"randMacAp\":" + (String)isMacAPRand + ",";
json += "\"apScanHidden\":" + (String)apScanHidden + ",";
json += "\"deauthReason\":" + (String)(int)deauthReason + ",";
json += "\"attackTimeout\":" + (String)attackTimeout + ",";
json += "\"attackPacketRate\":" + (String)attackPacketRate + ",";
json += "\"clientScanTime\":" + (String)clientScanTime + ",";
json += "\"useLed\":" + (String)useLed + ",";
json += "\"channelHop\":" + (String)channelHop + ",";
json += "\"multiAPs\":" + (String)multiAPs + ",";
json += "\"multiAttacks\":" + (String)multiAttacks + ",";
json += "\"macInterval\":" + (String)macInterval + ",";
json += "\"beaconInterval\":" + (String)beaconInterval + ",";
json += "\"ledPin\":" + (String)ledPin + "}";
jsonSize += json.length();
return jsonSize;
}
void Settings::send() {
if (debug) Serial.println("getting settings json");
sendHeader(200, "text/json", getSize());
String json = "{";
json += "\"ssid\":\"" + ssid + "\",";
json += "\"ssidHidden\":" + (String)ssidHidden + ",";
json += "\"password\":\"" + password + "\",";
json += "\"apChannel\":" + (String)apChannel + ",";
json += "\"macAp\":\"" + macAP.toString() + "\",";
json += "\"randMacAp\":" + (String)isMacAPRand + ",";
json += "\"apScanHidden\":" + (String)apScanHidden + ",";
json += "\"deauthReason\":" + (String)(int)deauthReason + ",";
json += "\"attackTimeout\":" + (String)attackTimeout + ",";
json += "\"attackPacketRate\":" + (String)attackPacketRate + ",";
json += "\"clientScanTime\":" + (String)clientScanTime + ",";
json += "\"useLed\":" + (String)useLed + ",";
json += "\"channelHop\":" + (String)channelHop + ",";
json += "\"multiAPs\":" + (String)multiAPs + ",";
json += "\"multiAttacks\":" + (String)multiAttacks + ",";
json += "\"macInterval\":" + (String)macInterval + ",";
json += "\"beaconInterval\":" + (String)beaconInterval + ",";
json += "\"ledPin\":" + (String)ledPin + "}";
sendToBuffer(json);
sendBuffer();
if (debug) Serial.println("\ndone");
}
| 8,305 | 3,161 |
//------------------------------------------------------------------------------------------
//
//
// Created on: 2/1/2015
// Author: Nghia Truong
//
//------------------------------------------------------------------------------------------
#include <iostream>
#include <cmath>
#include <core/helper_math.h>
#include "scene.h"
#include "core/cutil_math_ext.h"
#include "core/monitor.h"
#include "cyTriMesh.h"
//------------------------------------------------------------------------------------------
Scene::Scene(SimulationParameters& simParams,
RunningParameters& runningParams,
ParticleArrangement _arrangement):
simParams_(simParams),
runningParams_(runningParams),
arrangement_(_arrangement)
{
if(simParams_.num_pd_particle == 0)
{
return;
}
cyTriMesh triMesh;
triMesh.LoadFromFileObj(runningParams_.obj_file);
triMesh.ComputeBoundingBox();
cyPoint3f box_min = triMesh.GetBoundMin();
cyPoint3f box_max = triMesh.GetBoundMax();
cyPoint3f diff = box_max - box_min;
double maxDiff = fmaxf(fmaxf(fabs(diff.x), fabs(diff.y)), fabs(diff.z));
double scale = fminf(fminf(simParams_.boundary_max_x - simParams_.boundary_min_x,
simParams_.boundary_max_y - simParams_.boundary_min_y),
simParams_.boundary_max_z - simParams_.boundary_min_z) * 0.9 / maxDiff;
// how small the mesh object will be:
scale *= 0.5f;
// scale /= simParams_.scaleFactor;
// scale = fmin(scale*0.9, 1.0);
box_min.x *= scale;
box_min.y *= scale;
box_min.z *= scale;
box_max.x *= scale;
box_max.y *= scale;
box_max.z *= scale;
// translate the object if needed
double shift_x = simParams_.boundary_min_x - box_min.x;
double shift_y = simParams_.boundary_min_y - box_min.y;
double shift_z = simParams_.boundary_min_z - box_min.z;
box_min.x += shift_x;
box_max.x += shift_x;
box_min.y += shift_y;
box_max.y += shift_y;
box_min.z += shift_z;
box_max.z += shift_z;
std::cout << Monitor::PADDING << "Bounding box for mesh object: [" << box_min.x << ", " <<
box_min.y << ", " << box_min.z << "] -> [" << box_max.x << ", " << box_max.y << ", "
<< box_max.z << "]" << std::endl;
int grid3d[3];
createPeridynamicsGrid(box_min, box_max, grid3d);
int max_num_pd_particles = grid3d[0] * grid3d[1] * grid3d[2];
double* vertices = new double[triMesh.NV() * 3];
int* faces = new int[triMesh.NF() * 3];
for(int i = 0; i < triMesh.NV(); ++i)
{
cyPoint3f vertex = triMesh.V(i);
vertices[i * 3] = (double) vertex[0] * scale + shift_x;
vertices[i * 3 + 1] = (double) vertex[1] * scale + shift_y;
vertices[i * 3 + 2] = (double) vertex[2] * scale + shift_z;
}
for(int i = 0; i < triMesh.NF(); ++i)
{
cyTriMesh::cyTriFace face = triMesh.F(i);
faces[i * 3] = (int) face.v[0];
faces[i * 3 + 1] = (int) face.v[1];
faces[i * 3 + 2] = (int) face.v[2];
}
MeshObject* meshObject = construct_mesh_object(triMesh.NV(), vertices, triMesh.NF(),
faces);
pd_position_cache_ = new real4_t[max_num_pd_particles];
real_t jitter;
real_t margin;
real_t spacing;
if(arrangement_ == Scene::REGULAR_GRID)
{
jitter = 0.0f;
}
else
{
jitter = JITTER * simParams_.pd_particle_radius;
}
margin = simParams_.pd_particle_radius;
spacing = 2 * simParams_.pd_particle_radius;
simParams_.num_pd_particle = fillParticlesToMesh(meshObject, box_min, box_max,
pd_position_cache_, grid3d, spacing,
jitter, max_num_pd_particles);
simParams_.num_total_particle = simParams_.num_sph_particle + simParams_.num_pd_particle;
simParams_.num_clists = simParams_.num_pd_particle;
while(simParams_.num_clists % 8 != 0)
{
simParams_.num_clists++;
}
// else
// {
// simParams_.num_clists = (int) (floor(simParams_.num_pd_particle / 8.0) + 1) * 8;
// }
std::cout << Monitor::PADDING << "Num. clist: " << simParams_.num_clists << std::endl;
}
//------------------------------------------------------------------------------------------
void Scene::initSPHParticles(int* sph_activity, real4_t* sph_position,
real4_t* sph_velocity)
{
if(simParams_.num_sph_particle == 0)
{
return;
}
real_t jitter;
real_t margin3d[3];
real_t spacing, border;
if(arrangement_ == Scene::REGULAR_GRID)
{
jitter = 0.0f;
}
else
{
jitter = JITTER * simParams_.sph_particle_radius;
}
margin3d[0] = simParams_.sph_particle_radius;
margin3d[1] = simParams_.sph_particle_radius;
margin3d[2] = simParams_.sph_particle_radius;
spacing = 2 * simParams_.sph_particle_radius;
border = simParams_.sph_particle_radius;
int grid3d[3];
createSPHGrid(grid3d);
srand(1546);
fillParticles(sph_position, grid3d, margin3d, border,
spacing, jitter,
simParams_.num_sph_particle, true);
// set the activity and velocity
for(int i = 0; i < simParams_.num_sph_particle; ++i)
{
sph_activity[i] = ACTIVE;
sph_velocity[i] = MAKE_REAL4(0, 0, runningParams_.sph_initial_velocity, 0);
}
}
//------------------------------------------------------------------------------------------
inline double kernel_poly6(const real_t t)
{
double val = 0.0;
if(t >= 1.0)
{
return val;
}
const double tmp = 1.0 - t;
val = tmp * tmp * tmp;
return val;
}
void Scene::initSPHBoundaryParticles(real4_t* sph_boundary_pos)
{
if(simParams_.num_sph_particle == 0)
{
return;
}
int plane_size = simParams_.boundaryPlaneSize;
real_t spacing = 2 * simParams_.sph_particle_radius;
int index = 0;
int num_plane_particles = (plane_size + 2) * (plane_size + 2);
simParams_.boundaryPlaneBottomIndex = index;
simParams_.boundaryPlaneBottomSize = num_plane_particles;
simParams_.boundaryPlaneTopIndex = index + num_plane_particles;
simParams_.boundaryPlaneTopSize = num_plane_particles;
real_t px, py, pz;
// The top and bottom planes have size (size+2)^2
for (int x = 0; x < plane_size + 2; x++)
{
for (int z = 0; z < plane_size + 2; z++)
{
// Bottom plane
px = spacing * x + simParams_.boundary_min_x - simParams_.sph_particle_radius;
py = simParams_.boundary_min_y - simParams_.sph_particle_radius;
pz = spacing * z + simParams_.boundary_min_z - simParams_.sph_particle_radius;
sph_boundary_pos[index] = MAKE_REAL4(px, py, pz, 0.0f);
// Top plane
px = spacing * x + simParams_.boundary_min_x - simParams_.sph_particle_radius;
py = simParams_.boundary_min_y + simParams_.sph_particle_radius;
pz = spacing * z + simParams_.boundary_min_z - simParams_.sph_particle_radius;
sph_boundary_pos[index + num_plane_particles] = MAKE_REAL4(px, py, pz, 0.0f);
index++;
}
}
index += num_plane_particles;
num_plane_particles = (plane_size + 1) * plane_size;
simParams_.boundaryPlaneFrontIndex = index;
simParams_.boundaryPlaneFrontSize = num_plane_particles;
simParams_.boundaryPlaneBackIndex = index + num_plane_particles;
simParams_.boundaryPlaneBackSize = num_plane_particles;
// Front and back plane have size (size+1)*size
for (int x = 0; x < plane_size + 1; x++)
{
for (int y = 0; y < plane_size; y++)
{
// Front plane
px = spacing * x + simParams_.boundary_min_x + simParams_.sph_particle_radius;
py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius;
pz = simParams_.boundary_max_z + simParams_.sph_particle_radius;
sph_boundary_pos[index] = MAKE_REAL4(px, py, pz, 0.0f);
// Back plane
px = spacing * x + simParams_.boundary_min_x - simParams_.sph_particle_radius;
py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius;
pz = simParams_.boundary_min_z - simParams_.sph_particle_radius;
sph_boundary_pos[index + num_plane_particles] = MAKE_REAL4(px, py, pz, 0.0f);
index++;
}
}
index += num_plane_particles;
simParams_.boundaryPlaneLeftSideIndex = index;
simParams_.boundaryPlaneLeftSideSize = num_plane_particles;
simParams_.boundaryPlaneRightSideIndex = index + num_plane_particles;
simParams_.boundaryPlaneRightSideSize = num_plane_particles;
for (int y = 0; y < plane_size; y++)
{
for (int z = 0; z < plane_size + 1; z++)
{
// Left side plane
px = simParams_.boundary_min_x - simParams_.sph_particle_radius;
py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius;
pz = spacing * z + simParams_.boundary_min_z + simParams_.sph_particle_radius;
sph_boundary_pos[index] = MAKE_REAL4(px, py, pz, 0.0f);
// Right side plane
px = simParams_.boundary_max_x + simParams_.sph_particle_radius;
py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius;
pz = spacing * z + simParams_.boundary_min_z - simParams_.sph_particle_radius;
sph_boundary_pos[index + num_plane_particles] = MAKE_REAL4(px, py, pz, 0.0f);
index++;
}
}
std::cout << Monitor::PADDING << "Boundary planes size: " << plane_size <<
std::endl;
std::cout << Monitor::PADDING << Monitor::PADDING << "Bottom plane index: " <<
simParams_.boundaryPlaneBottomIndex << ", size: " << simParams_.boundaryPlaneBottomSize <<
std::endl;
std::cout << Monitor::PADDING << Monitor::PADDING << "Top plane index: " <<
simParams_.boundaryPlaneTopIndex << ", size: " << simParams_.boundaryPlaneTopSize <<
std::endl;
std::cout << Monitor::PADDING << Monitor::PADDING << "Front plane index: " <<
simParams_.boundaryPlaneFrontIndex << ", size: " << simParams_.boundaryPlaneFrontSize <<
std::endl;
std::cout << Monitor::PADDING << Monitor::PADDING << "Back plane index: " <<
simParams_.boundaryPlaneBackIndex << ", size: " << simParams_.boundaryPlaneBackSize <<
std::endl;
std::cout << Monitor::PADDING << Monitor::PADDING << "Left plane index: " <<
simParams_.boundaryPlaneLeftSideIndex << ", size; " <<
simParams_.boundaryPlaneLeftSideSize <<
std::endl;
std::cout << Monitor::PADDING << Monitor::PADDING << "Right plane index: " <<
simParams_.boundaryPlaneRightSideIndex << ", size: " <<
simParams_.boundaryPlaneRightSideSize <<
std::endl;
/////////////////////////////////////////////////////////////////
// calculate rest density
real_t dist_sq;
double sumW = 0;
int span = (int)ceil(simParams_.sph_kernel_coeff / 2);
for (int z = -span; z <= span; ++z)
{
for (int y = -span; y <= span; ++y)
{
for (int x = -span; x <= span; ++x)
{
px = 2 * x * simParams_.sph_particle_radius;
py = 2 * y * simParams_.sph_particle_radius;
pz = 2 * z * simParams_.sph_particle_radius;
dist_sq = px * px + py * py + pz * pz;
sumW += kernel_poly6(dist_sq / simParams_.sph_kernel_smooth_length_squared);
}
}
}
simParams_.sph_rest_density = (real_t) sumW * simParams_.sph_particle_mass *
simParams_.sph_kernel_poly6;
std::cout << Monitor::PADDING << "SPH rest density: " << simParams_.sph_rest_density <<
std::endl;
}
//------------------------------------------------------------------------------------------
void Scene::initPeridynamicsParticles(int* pd_activity,
real4_t* pd_position,
real4_t *pd_velocity)
{
if(simParams_.num_pd_particle == 0)
{
return;
}
memcpy(pd_position, pd_position_cache_, sizeof(real4_t)*simParams_.num_pd_particle);
real4_t translation = MAKE_REAL4(runningParams_.mesh_translation_x /
simParams_.scaleFactor,
runningParams_.mesh_translation_y / simParams_.scaleFactor,
runningParams_.mesh_translation_z / simParams_.scaleFactor,
0.0f);
real4_t rotation = MAKE_REAL4(0.0, 0.0f, 0.0f, 0.0f);
// real4_t rotation = MAKE_REAL4(0.0, M_PI / 6.0f, 0.0f, 0.0f);
std::cout << Monitor::PADDING << "PD particles translated by: " <<
translation.x << ", " << translation.y << ", " << translation.z << std::endl;
std::cout << Monitor::PADDING << "PD particles rotated by: " <<
rotation.x << " degree around axis: " <<
rotation.y << ", " << rotation.z << ", " << rotation.w << std::endl;
transformParticles(pd_position, translation, rotation, simParams_.num_pd_particle);
// set the activity
for(int i = 0; i < simParams_.num_pd_particle; ++i)
{
pd_activity[i] = ACTIVE;
pd_velocity[i] = MAKE_REAL4_FROM_REAL(runningParams_.pd_initial_velocity);
}
}
//------------------------------------------------------------------------------------------
void Scene::fillParticles(real4_t* particles, int* grid3d, real_t* margin3d,
real_t border,
real_t spacing, real_t jitter, int num_particles, bool position_correction)
{
real_t pX, pY, pZ;
for (int z = 0; z < grid3d[2]; z++)
{
for (int y = 0; y < grid3d[1]; y++)
{
for (int x = 0; x < grid3d[0]; x++)
{
int i = (z * grid3d[1] * grid3d[0]) + (y * grid3d[0]) + x;
if (i >= num_particles)
{
continue;
}
pX = simParams_.boundary_min_x + margin3d[0] + x * spacing
+ (frand() * 2.0f - 1.0f) * jitter;
pY = simParams_.boundary_min_y + margin3d[1] + y * spacing
+ (frand() * 2.0f - 1.0f) * jitter;
pZ = simParams_.boundary_min_z + margin3d[2] + z * spacing
+ (frand() * 2.0f - 1.0f) * jitter;
// Correction of position
if(position_correction)
{
if(pX > simParams_.boundary_min_x)
{
if(pX < simParams_.boundary_min_x + border)
{
pX = simParams_.boundary_min_x + border;
}
}
else
{
if(pX > simParams_.boundary_min_x - border)
{
pX = simParams_.boundary_min_x - border;
}
}
if(pX < simParams_.boundary_max_x)
{
if(pX > simParams_.boundary_max_x - border)
{
pX = simParams_.boundary_max_x - border;
}
}
else
{
if(pX < simParams_.boundary_max_x + border)
{
pX = simParams_.boundary_max_x + border;
}
}
if(pY > simParams_.boundary_min_y)
{
if(pY < simParams_.boundary_min_y + border)
{
pY = simParams_.boundary_min_y + border;
}
}
else
{
if(pY > simParams_.boundary_min_y - border)
{
pY = simParams_.boundary_min_y - border;
}
}
if(pY < simParams_.boundary_max_y)
{
if(pY > simParams_.boundary_max_y - border)
{
pY = simParams_.boundary_max_y - border;
}
}
else
{
if(pY < simParams_.boundary_max_y + border)
{
pY = simParams_.boundary_max_y + border;
}
}
if(pZ > simParams_.boundary_min_z)
{
if(pZ < simParams_.boundary_min_z + border)
{
pZ = simParams_.boundary_min_z + border;
}
}
else
{
if(pZ > simParams_.boundary_min_z - border)
{
pZ = simParams_.boundary_min_z - border;
}
}
if(pZ < simParams_.boundary_max_z)
{
if(pZ > simParams_.boundary_max_z - border)
{
pZ = simParams_.boundary_max_z - border;
}
}
else
{
if(pZ < simParams_.boundary_max_z + border)
{
pZ = simParams_.boundary_max_z + border;
}
}
}
particles[i] = MAKE_REAL4(pX, pY, pZ, 0.0f);
// printf("p: %d, %f, %f, %f\n", i, pX, pY, pZ);
}
}
}
}
//------------------------------------------------------------------------------------------
int Scene::fillParticlesToMesh(MeshObject* meshObject, cyPoint3f box_min,
cyPoint3f box_max, real4_t* particles, int* grid3d, real_t spacing, real_t jitter,
int max_num_particles)
{
real_t pX, pY, pZ;
int num_particles = 0;
double point[3];
// bool y0=false;
for (int z = 0; z < grid3d[2]; z++)
{
for (int y = 0; y < grid3d[1]; y++)
{
for (int x = 0; x < grid3d[0]; x++)
{
int i = (z * grid3d[1] * grid3d[0]) + (y * grid3d[0]) + x;
if (i >= max_num_particles)
{
continue;
}
// if(y0 && y==1)
// continue;
// if(count == 3)
// continue;
pX = box_min.x + x * spacing
+ (frand() * 2.0f - 1.0f) * jitter;
pY = box_min.y + y * spacing
+ (frand() * 2.0f - 1.0f) * jitter;
pZ = box_min.z + z * spacing
+ (frand() * 2.0f - 1.0f) * jitter;
point[0] = (double)pX;
point[1] = (double)pY;
point[2] = (double)pZ;
if(point_inside_mesh(point, meshObject))
{
// Correction of position
pX = (pX < box_min.x) ? box_min.x : pX;
pX = (pX > box_max.x) ? box_max.x : pX;
pY = (pY < box_min.y) ? box_min.y : pY;
pY = (pY > box_max.y) ? box_max.y : pY;
pZ = (pZ < box_min.z) ? box_min.z : pZ;
pZ = (pZ > box_max.z) ? box_max.z : pZ;
//if(!y0 && y==1) y0 = true;
//printf("P: %d, %d, %d, %f, %f, %f\n", x, y, z, pX, pY, pZ);
particles[num_particles] = MAKE_REAL4(pX, pY, pZ, 0.0);
++num_particles;
}
}
}
}
std::cout << Monitor::PADDING << "Total filled Peridynamics particles: " << num_particles
<<
std::endl;
return num_particles;
}
//------------------------------------------------------------------------------------------
void Scene::fillTubeParticles(real4_t* particles, int tube_radius, real3_t base_center,
int* up_direction, real_t spacing, real_t jitter, int num_particles)
{
}
//------------------------------------------------------------------------------------------
void Scene::createSPHGrid(int* grid3d)
{
grid3d[0] = (int) floor((simParams_.boundary_max_x - simParams_.boundary_min_x) /
(2.0f * simParams_.sph_particle_radius)) - 10;
grid3d[1] = (int) floor((simParams_.boundary_max_y - simParams_.boundary_min_y) /
(2.0f * simParams_.sph_particle_radius)) - 3;
grid3d[2] = (int) floor((simParams_.boundary_max_z - simParams_.boundary_min_z) /
(2.0f * simParams_.sph_particle_radius));
std::cout << Monitor::PADDING << "Maximum SPH grid: " << grid3d[0] << "x" << grid3d[1] <<
"x" << grid3d[2] << std::endl;
}
//------------------------------------------------------------------------------------------
void Scene::createPeridynamicsGrid(int* grid3d)
{
grid3d[0] = (int) floor((simParams_.boundary_max_x - simParams_.boundary_min_x) /
(2.0f * simParams_.pd_particle_radius));
grid3d[1] = (int) floor((simParams_.boundary_max_y - simParams_.boundary_min_y) /
(2.0f * simParams_.pd_particle_radius));
grid3d[2] = (int) floor((simParams_.boundary_max_z - simParams_.boundary_min_z) /
(2.0f * simParams_.pd_particle_radius));
std::cout << Monitor::PADDING << "Maximum Peridynamics grid: " << grid3d[0] << "x" <<
grid3d[1] << "x" << grid3d[2] << std::endl;
}
//------------------------------------------------------------------------------------------
void Scene::createPeridynamicsGrid(cyPoint3f box_min, cyPoint3f box_max, int* grid3d)
{
grid3d[0] = (int) ceil((box_max.x - box_min.x) /
(2.0f * simParams_.pd_particle_radius)) + 1;
grid3d[1] = (int) ceil((box_max.y - box_min.y) /
(2.0f * simParams_.pd_particle_radius)) + 1;
grid3d[2] = (int) ceil((box_max.z - box_min.z) /
(2.0f * simParams_.pd_particle_radius)) + 1;
std::cout << Monitor::PADDING << "Maximum Peridynamics grid: " << grid3d[0] << "x" <<
grid3d[1] << "x" << grid3d[2] << std::endl;
}
//------------------------------------------------------------------------------------------
inline double dot3(double a[3], real4_t b)
{
return (a[0] * b.x + a[1] * b.y + a[2] * b.z);
}
void Scene::transformParticles(real4_t* particles, real4_t translation, real4_t rotation,
int num_particles)
{
int i, j;
double azimuth = rotation.x;
double elevation = rotation.y;
double roll = rotation.z;
double sinA, cosA, sinE, cosE, sinR, cosR;
double R[3][3];
double tmp[4];
sinA = std::sin(azimuth);
cosA = std::cos(azimuth);
sinE = std::sin(elevation);
cosE = std::cos(elevation);
sinR = std::sin(roll);
cosR = std::cos(roll);
R[0][0] = cosR * cosA - sinR * sinA * sinE;
R[0][1] = sinR * cosA + cosR * sinA * sinE;
R[0][2] = -sinA * cosE;
R[1][0] = -sinR * cosE;
R[1][1] = cosR * cosE;
R[1][2] = sinE;
R[2][0] = cosR * sinA + sinR * cosA * sinE;
R[2][1] = sinR * sinA - cosR * cosA * sinE;
R[2][2] = cosA * cosE;
for (i = 0; i < num_particles; ++i)
{
for (j = 0; j < 3; ++j)
{
tmp[j] = dot3(R[j], particles[i]);
}
particles[i] = MAKE_REAL4(tmp[0] + translation.x, tmp[1] + translation.y,
tmp[2] + translation.z, 0.0f);
}
}
| 24,500 | 8,168 |
#pragma once
#include <bunsan/error.hpp>
namespace bunsan::utility {
struct error : virtual bunsan::error {
error() = default;
explicit error(const std::string &message_);
};
} // namespace bunsan::utility
| 215 | 74 |
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include "myalloc11.hpp"
#include <vector>
#include <map>
#include <string>
#include <functional>
int main() {
// a vector with special allocator
std::vector<int, MyAlloc<int>> v;
// an int/float map with special allocator
std::map<int, float, std::less<int>,
MyAlloc<std::pair<const int, float>>> m;
// a string with special allocator
std::basic_string<char, std::char_traits<char>, MyAlloc<char>> s;
// special string type that uses special allocator
typedef std::basic_string<char, std::char_traits<char>,
MyAlloc<char>> MyString;
// special string/string map type that uses special allocator
typedef std::map <MyString, MyString, std::less<MyString>,
MyAlloc<std::pair<const MyString, MyString>>> MyMap;
// create object of this type
MyMap mymap;
//...
}
| 1,338 | 416 |
// s_only.cpp
/* Copyright 2009 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding
#include "mongo/platform/basic.h"
#include <tuple>
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_manager_global.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/service_context.h"
#include "mongo/db/stats/counters.h"
#include "mongo/rpc/metadata.h"
#include "mongo/rpc/reply_builder_interface.h"
#include "mongo/rpc/request_interface.h"
#include "mongo/s/cluster_last_error_info.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/concurrency/thread_name.h"
#include "mongo/util/log.h"
namespace mongo {
using std::string;
using std::stringstream;
bool isMongos() {
return true;
}
/** When this callback is run, we record a shard that we've used for useful work
* in an operation to be read later by getLastError()
*/
void usingAShardConnection(const std::string& addr) {
ClusterLastErrorInfo::get(cc()).addShardHost(addr);
}
// called into by the web server. For now we just translate the parameters
// to their old style equivalents.
void Command::execCommand(OperationContext* txn,
Command* command,
const rpc::RequestInterface& request,
rpc::ReplyBuilderInterface* replyBuilder) {
int queryFlags = 0;
BSONObj cmdObj;
std::tie(cmdObj, queryFlags) = uassertStatusOK(
rpc::downconvertRequestMetadata(request.getCommandArgs(), request.getMetadata()));
std::string db = request.getDatabase().rawData();
BSONObjBuilder result;
execCommandClientBasic(txn,
command,
*txn->getClient(),
queryFlags,
request.getDatabase().rawData(),
cmdObj,
result);
replyBuilder->setCommandReply(result.done()).setMetadata(rpc::makeEmptyMetadata());
}
void Command::execCommandClientBasic(OperationContext* txn,
Command* c,
ClientBasic& client,
int queryOptions,
const char* ns,
BSONObj& cmdObj,
BSONObjBuilder& result) {
std::string dbname = nsToDatabase(ns);
if (cmdObj.getBoolField("help")) {
stringstream help;
help << "help for: " << c->name << " ";
c->help(help);
result.append("help", help.str());
result.append("lockType", c->isWriteCommandForConfigServer() ? 1 : 0);
appendCommandStatus(result, true, "");
return;
}
Status status = checkAuthorization(c, txn, dbname, cmdObj);
if (!status.isOK()) {
appendCommandStatus(result, status);
return;
}
c->_commandsExecuted.increment();
if (c->shouldAffectCommandCounter()) {
globalOpCounters.gotCommand();
}
std::string errmsg;
bool ok = false;
try {
ok = c->run(txn, dbname, cmdObj, queryOptions, errmsg, result);
} catch (const DBException& e) {
result.resetToEmpty();
const int code = e.getCode();
// Codes for StaleConfigException
if (code == ErrorCodes::RecvStaleConfig || code == ErrorCodes::SendStaleConfig) {
throw;
}
errmsg = e.what();
result.append("code", code);
}
if (!ok) {
c->_commandsFailed.increment();
}
appendCommandStatus(result, ok, errmsg);
}
void Command::runAgainstRegistered(OperationContext* txn,
const char* ns,
BSONObj& jsobj,
BSONObjBuilder& anObjBuilder,
int queryOptions) {
// It should be impossible for this uassert to fail since there should be no way to get
// into this function with any other collection name.
uassert(16618,
"Illegal attempt to run a command against a namespace other than $cmd.",
nsToCollectionSubstring(ns) == "$cmd");
BSONElement e = jsobj.firstElement();
std::string commandName = e.fieldName();
Command* c = e.type() ? Command::findCommand(commandName) : NULL;
if (!c) {
Command::appendCommandStatus(
anObjBuilder, false, str::stream() << "no such cmd: " << commandName);
anObjBuilder.append("code", ErrorCodes::CommandNotFound);
Command::unknownCommands.increment();
return;
}
execCommandClientBasic(txn, c, cc(), queryOptions, ns, jsobj, anObjBuilder);
}
void Command::registerError(OperationContext* txn, const DBException& exception) {}
} // namespace mongo
| 6,381 | 1,802 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "stdafx.h"
#ifdef _WIN32
HANDLE JITProcessManager::s_rpcServerProcessHandle = 0; // 0 is the "invalid handle" value for process handles
UUID JITProcessManager::s_connectionId = GUID_NULL;
HRESULT JITProcessManager::StartRpcServer(int argc, __in_ecount(argc) LPWSTR argv[])
{
HRESULT hr = S_OK;
JITProcessManager::RemoveArg(_u("-dynamicprofilecache:"), &argc, &argv);
JITProcessManager::RemoveArg(_u("-dpc:"), &argc, &argv);
JITProcessManager::RemoveArg(_u("-dynamicprofileinput:"), &argc, &argv);
if (IsEqualGUID(s_connectionId, GUID_NULL))
{
RPC_STATUS status = UuidCreate(&s_connectionId);
if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
{
hr = CreateServerProcess(argc, argv);
}
else
{
hr = HRESULT_FROM_WIN32(status);
}
}
return hr;
}
/* static */
void
JITProcessManager::RemoveArg(LPCWSTR flag, int * argc, __in_ecount(*argc) LPWSTR * argv[])
{
size_t flagLen = wcslen(flag);
int flagIndex;
while ((flagIndex = HostConfigFlags::FindArg(*argc, *argv, flag, flagLen)) >= 0)
{
HostConfigFlags::RemoveArg(*argc, *argv, flagIndex);
}
}
HRESULT JITProcessManager::CreateServerProcess(int argc, __in_ecount(argc) LPWSTR argv[])
{
HRESULT hr;
PROCESS_INFORMATION processInfo = { 0 };
STARTUPINFOW si = { 0 };
// overallocate constant cmd line (jshost -jitserver:<guid>)
size_t cmdLineSize = (MAX_PATH + (size_t)argc) * sizeof(WCHAR);
for (int i = 0; i < argc; ++i)
{
// calculate space requirement for each arg
cmdLineSize += wcslen(argv[i]) * sizeof(WCHAR);
}
WCHAR* cmdLine = (WCHAR*)malloc(cmdLineSize);
if (cmdLine == nullptr)
{
return E_OUTOFMEMORY;
}
RPC_WSTR connectionUuidString = NULL;
#pragma warning(suppress: 6386) // buffer overrun
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
hr = StringCchCopyW(cmdLine, cmdLineSize, _u("ch.exe -OOPCFGRegistration- -CheckOpHelpers -jitserver:"));
#else
hr = StringCchCopyW(cmdLine, cmdLineSize, _u("ch.exe -jitserver:"));
#endif
if (FAILED(hr))
{
return hr;
}
RPC_STATUS status = UuidToStringW(&s_connectionId, &connectionUuidString);
if (status != S_OK)
{
return HRESULT_FROM_WIN32(status);
}
hr = StringCchCatW(cmdLine, cmdLineSize, (WCHAR*)connectionUuidString);
if (FAILED(hr))
{
return hr;
}
for (int i = 1; i < argc; ++i)
{
hr = StringCchCatW(cmdLine, cmdLineSize, _u(" "));
if (FAILED(hr))
{
return hr;
}
hr = StringCchCatW(cmdLine, cmdLineSize, argv[i]);
if (FAILED(hr))
{
return hr;
}
}
if (!CreateProcessW(
NULL,
cmdLine,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
&si,
&processInfo))
{
return HRESULT_FROM_WIN32(GetLastError());
}
free(cmdLine);
CloseHandle(processInfo.hThread);
s_rpcServerProcessHandle = processInfo.hProcess;
if (HostConfigFlags::flags.EnsureCloseJITServer)
{
// create job object so if parent ch gets killed, server is killed as well
// under a flag because it's preferable to let server close naturally
// only useful in scenarios where ch is expected to be force terminated
HANDLE jobObject = CreateJobObject(nullptr, nullptr);
if (jobObject == nullptr)
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (!AssignProcessToJobObject(jobObject, s_rpcServerProcessHandle))
{
return HRESULT_FROM_WIN32(GetLastError());
}
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo = { 0 };
jobInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (!SetInformationJobObject(jobObject, JobObjectExtendedLimitInformation, &jobInfo, sizeof(jobInfo)))
{
return HRESULT_FROM_WIN32(GetLastError());
}
}
return NOERROR;
}
void
JITProcessManager::TerminateJITServer()
{
if (s_rpcServerProcessHandle)
{
TerminateProcess(s_rpcServerProcessHandle, 1);
CloseHandle(s_rpcServerProcessHandle);
s_rpcServerProcessHandle = NULL;
}
}
HANDLE JITProcessManager::GetRpcProccessHandle()
{
return s_rpcServerProcessHandle;
}
UUID JITProcessManager::GetRpcConnectionId()
{
return s_connectionId;
}
#endif
| 4,882 | 1,622 |
/* economyPhase.cpp */
#include <iostream>
#include <string>
#include "basicHeader.hpp"
using std::cout;
using std::endl;
/* ========================================================================= */
void Game::economyPhase(PlayerPtr pl) {
printF ("Economy Phase Started !" , 1 , YEL , FILL);
printF ("Press ENTER to continue . . ." , 1);
std::cin.clear();
std::cin.sync();
std::cin.get();
printF ("Player : " , 0 , MAG , BOLD);
cout << pl->getUserName();
printF (" can now buy Provinces!" , 1 , MAG , BOLD);
printF ("Printing " , 0 , MAG);
cout << pl->getUserName();
printF ("'s Provinces : " , 1 , MAG);
pl->printProvinces();
printF ("Type 'Y' (YES) or '<any other key>' (NO) after each card's \
appearance, to proceed to purchase. " , 1 , MAG , BOLD);
/* Buy provinces */
for (auto i : *(pl->getProvinces())) /* For every province */
{
if (i->checkBroken() == false && i->getCard()->checkRevealed() == true)
{
if (pl->getCurrMoney() == 0)
{
cout << "No money left !" << endl;
return;
}
else if (pl->getCurrMoney() < i->getCard()->getCost())
continue;
else
{
cout << pl->getUserName();
printF ("'s Current balance: " , 0 , YEL , BOLD);
cout << pl->getCurrMoney() << endl;
}
i->print(); /* If it is revealed and not broken */
cout << endl << pl->getUserName();
printF (" , do you want to proceed to purchase ?\n> Your answer: " , 0 , YEL , BOLD);
std::string answer;
std::getline(std::cin, answer);
cout << endl;
if ((answer == "Y")||(answer == "y")) /* Attempt to make the purchase */
{
if (pl->makePurchase(i->getCard()->getCost()) == true)
{
printF ("Purchase Completed ! " , 1 , YEL , BOLD);
i->getCard()->setTapped(); /* Can't be used for this round */
i->getCard()->attachToPlayer(pl);
if (pl->getDynastyDeck()->empty() == false)
i->setCard( pl->drawBlackCard() ); /* Replace the card bought */
else
{
printF ("Dynasty deck is empty! No more Black Cards for player \'" , 0 , MAG , BOLD);
cout << pl->getUserName();
printF ("\' !" , 1 , MAG , BOLD);
}
}
else
printF ("You don't have enough money to buy this province!" , 1 , MAG , BOLD);
}
}
}
printF ("Economy Phase Ended !" , 1 , YEL , FILL);
}
/* ========================================================================= */ | 2,606 | 869 |
// Copyright 2006-2009 Daniel James.
// 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 <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include "../helpers/test.hpp"
namespace unnecessary_copy_tests
{
struct count_copies
{
static int copies;
static int moves;
count_copies() : tag_(0) { ++copies; }
explicit count_copies(int tag) : tag_(tag) { ++copies; }
// This bizarre constructor is an attempt to confuse emplace.
//
// unordered_map<count_copies, count_copies> x:
// x.emplace(count_copies(1), count_copies(2));
// x.emplace(count_copies(1), count_copies(2), count_copies(3));
//
// The first emplace should use the single argument constructor twice.
// The second emplace should use the single argument contructor for
// the key, and this constructor for the value.
count_copies(count_copies const&, count_copies const& x)
: tag_(x.tag_) { ++copies; }
count_copies(count_copies const& x) : tag_(x.tag_) { ++copies; }
#if defined(BOOST_HAS_RVALUE_REFS)
count_copies(count_copies&& x) : tag_(x.tag_) {
x.tag_ = -1; ++moves;
}
#endif
int tag_;
private:
count_copies& operator=(count_copies const&);
};
bool operator==(count_copies const& x, count_copies const& y) {
return x.tag_ == y.tag_;
}
template <class T>
T source() {
return T();
}
void reset() {
count_copies::copies = 0;
count_copies::moves = 0;
}
}
#if defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP)
namespace boost
#else
namespace unnecessary_copy_tests
#endif
{
std::size_t hash_value(unnecessary_copy_tests::count_copies const& x) {
return x.tag_;
}
}
#define COPY_COUNT(n) \
if(count_copies::copies != n) { \
BOOST_ERROR("Wrong number of copies."); \
std::cerr<<"Number of copies: "<<count_copies::copies<<" expecting: "<<n<<std::endl; \
}
#define MOVE_COUNT(n) \
if(count_copies::moves != n) { \
BOOST_ERROR("Wrong number of moves."); \
std::cerr<<"Number of moves: "<<count_copies::moves<<" expecting: "<<n<<std::endl; \
}
#define COPY_COUNT_RANGE(a, b) \
if(count_copies::copies < a || count_copies::copies > b) { \
BOOST_ERROR("Wrong number of copies."); \
std::cerr<<"Number of copies: "<<count_copies::copies<<" expecting: ["<<a<<", "<<b<<"]"<<std::endl; \
}
#define MOVE_COUNT_RANGE(a, b) \
if(count_copies::moves < a || count_copies::moves > b) { \
BOOST_ERROR("Wrong number of moves."); \
std::cerr<<"Number of moves: "<<count_copies::copies<<" expecting: ["<<a<<", "<<b<<"]"<<std::endl; \
}
namespace unnecessary_copy_tests
{
int count_copies::copies;
int count_copies::moves;
template <class T>
void unnecessary_copy_insert_test(T*)
{
T x;
BOOST_DEDUCED_TYPENAME T::value_type a;
reset();
x.insert(a);
COPY_COUNT(1);
}
boost::unordered_set<count_copies>* set;
boost::unordered_multiset<count_copies>* multiset;
boost::unordered_map<int, count_copies>* map;
boost::unordered_multimap<int, count_copies>* multimap;
UNORDERED_TEST(unnecessary_copy_insert_test,
((set)(multiset)(map)(multimap)))
template <class T>
void unnecessary_copy_emplace_test(T*)
{
reset();
T x;
BOOST_DEDUCED_TYPENAME T::value_type a;
COPY_COUNT(1);
x.emplace(a);
COPY_COUNT(2);
}
template <class T>
void unnecessary_copy_emplace_rvalue_test(T*)
{
reset();
T x;
x.emplace(source<BOOST_DEDUCED_TYPENAME T::value_type>());
#if defined(BOOST_HAS_RVALUE_REFS) && defined(BOOST_HAS_VARIADIC_TMPL)
COPY_COUNT(1);
#else
COPY_COUNT(2);
#endif
}
UNORDERED_TEST(unnecessary_copy_emplace_test,
((set)(multiset)(map)(multimap)))
UNORDERED_TEST(unnecessary_copy_emplace_rvalue_test,
((set)(multiset)(map)(multimap)))
#if defined(BOOST_HAS_RVALUE_REFS) && defined(BOOST_HAS_VARIADIC_TMPL)
template <class T>
void unnecessary_copy_emplace_move_test(T*)
{
reset();
T x;
BOOST_DEDUCED_TYPENAME T::value_type a;
COPY_COUNT(1); MOVE_COUNT(0);
x.emplace(std::move(a));
COPY_COUNT(1); MOVE_COUNT(1);
}
UNORDERED_TEST(unnecessary_copy_emplace_move_test,
((set)(multiset)(map)(multimap)))
#endif
UNORDERED_AUTO_TEST(unnecessary_copy_emplace_set_test)
{
reset();
boost::unordered_set<count_copies> x;
count_copies a;
x.insert(a);
COPY_COUNT(2); MOVE_COUNT(0);
//
// 0 arguments
//
// The container will have to create a copy in order to compare with
// the existing element.
reset();
x.emplace();
COPY_COUNT(1); MOVE_COUNT(0);
//
// 1 argument
//
// Emplace should be able to tell that there already is an element
// without creating a new one.
reset();
x.emplace(a);
COPY_COUNT(0); MOVE_COUNT(0);
// A new object is created by source, but it shouldn't be moved or
// copied.
reset();
x.emplace(source<count_copies>());
COPY_COUNT(1); MOVE_COUNT(0);
#if defined(BOOST_HAS_RVALUE_REFS)
// No move should take place.
reset();
x.emplace(std::move(a));
COPY_COUNT(0); MOVE_COUNT(0);
#endif
// Just in case a did get moved...
count_copies b;
// The container will have to create a copy in order to compare with
// the existing element.
reset();
x.emplace(b.tag_);
COPY_COUNT(1); MOVE_COUNT(0);
//
// 2 arguments
//
// The container will have to create b copy in order to compare with
// the existing element.
//
// Note to self: If copy_count == 0 it's an error not an optimization.
// TODO: Devise a better test.
reset();
x.emplace(b, b);
COPY_COUNT(1); MOVE_COUNT(0);
}
UNORDERED_AUTO_TEST(unnecessary_copy_emplace_map_test)
{
reset();
boost::unordered_map<count_copies, count_copies> x;
// TODO: Run tests for pairs without const etc.
std::pair<count_copies const, count_copies> a;
x.emplace(a);
COPY_COUNT(4); MOVE_COUNT(0);
//
// 0 arguments
//
// COPY_COUNT(1) would be okay here.
reset();
x.emplace();
COPY_COUNT(2); MOVE_COUNT(0);
//
// 1 argument
//
reset();
x.emplace(a);
COPY_COUNT(0); MOVE_COUNT(0);
// A new object is created by source, but it shouldn't be moved or
// copied.
reset();
x.emplace(source<std::pair<count_copies, count_copies> >());
COPY_COUNT(2); MOVE_COUNT(0);
// TODO: This doesn't work on older versions of gcc.
//count_copies part;
std::pair<count_copies const, count_copies> b;
//reset();
//std::pair<count_copies const&, count_copies const&> a_ref(part, part);
//x.emplace(a_ref);
//COPY_COUNT(0); MOVE_COUNT(0);
#if defined(BOOST_HAS_RVALUE_REFS)
// No move should take place.
// (since a is already in the container)
reset();
x.emplace(std::move(a));
COPY_COUNT(0); MOVE_COUNT(0);
#endif
//
// 2 arguments
//
reset();
x.emplace(b.first, b.second);
COPY_COUNT(0); MOVE_COUNT(0);
reset();
x.emplace(source<count_copies>(), source<count_copies>());
COPY_COUNT(2); MOVE_COUNT(0);
// source<count_copies> creates a single copy.
reset();
x.emplace(b.first, source<count_copies>());
COPY_COUNT(1); MOVE_COUNT(0);
reset();
x.emplace(count_copies(b.first.tag_), count_copies(b.second.tag_));
COPY_COUNT(2); MOVE_COUNT(0);
}
}
RUN_TESTS()
| 8,279 | 2,932 |
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include "common_test_utils/test_common.hpp"
#include <string>
#include <sstream>
#include <fstream>
#include <memory>
#include <map>
#include <ngraph/function.hpp>
#include <ngraph/op/constant.hpp>
#include <ngraph_ops/convolution_ie.hpp>
#include <ngraph/pass/constant_folding.hpp>
#include <legacy/transformations/convert_opset1_to_legacy/reshape_1d_ops.hpp>
#include <transformations/init_node_info.hpp>
#include <ngraph/opsets/opset1.hpp>
#include <ngraph/pass/manager.hpp>
#include "common_test_utils/ngraph_test_utils.hpp"
using namespace testing;
using namespace ngraph;
TEST(TransformationTests, ConvReshapeTest1) {
auto input = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{1, 3, 64}, {1});
auto w = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6, 3, 3/*OIW*/}, {1});
std::shared_ptr<ngraph::Function> f(nullptr);
{
ngraph::Strides strides{1}, dilations{1};
ngraph::CoordinateDiff pads_begin{0}, pads_end{0};
ngraph::Shape output_shape{1, 6, 62};
auto conv = std::make_shared<ngraph::op::ConvolutionIE>(input, w, strides, dilations, pads_begin, pads_end, ngraph::element::f32, 1);
f = std::make_shared<ngraph::Function>(ngraph::NodeVector{conv}, ngraph::ParameterVector{});
ngraph::pass::InitNodeInfo().run_on_function(f);
ngraph::pass::Reshape1DOps().run_on_function(f);
ASSERT_NO_THROW(check_rt_info(f));
ngraph::pass::ConstantFolding().run_on_function(f);
}
std::vector<size_t> ref_shape{1, 6, 1, 62};
ngraph::Strides ref_strides{1, 1};
ngraph::CoordinateDiff ref_pads_begin{0, 0}, ref_pads_end{0, 0};
for (auto op : f->get_ops()) {
if (auto conv = ngraph::as_type_ptr<ngraph::op::ConvolutionIE>(op)) {
ASSERT_EQ(conv->get_shape(), ref_shape);
ASSERT_EQ(conv->get_strides(), ref_strides);
ASSERT_EQ(conv->get_dilations(), ref_strides);
ASSERT_EQ(conv->get_pads_begin(), ref_pads_begin);
ASSERT_EQ(conv->get_pads_end(), ref_pads_end);
}
}
}
TEST(TransformationTests, ConvBiasReshapeTest1) {
auto input = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{1, 3, 64}, {1});
auto w = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6, 3, 3/*OIW*/}, {1});
auto b = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6}, {1});
std::shared_ptr<ngraph::Function> f(nullptr);
{
ngraph::Strides strides{1}, dilations{1};
ngraph::CoordinateDiff pads_begin{0}, pads_end{0};
ngraph::Shape output_shape{1, 6, 62};
auto conv = std::make_shared<ngraph::op::ConvolutionIE>(input, w, b, strides, dilations, pads_begin, pads_end, ngraph::element::f32, 1);
f = std::make_shared<ngraph::Function>(ngraph::NodeVector{conv}, ngraph::ParameterVector{});
ngraph::pass::InitNodeInfo().run_on_function(f);
ngraph::pass::Reshape1DOps().run_on_function(f);
ASSERT_NO_THROW(check_rt_info(f));
ngraph::pass::ConstantFolding().run_on_function(f);
}
std::vector<size_t> ref_shape{1, 6, 1, 62};
ngraph::Strides ref_strides{1, 1};
ngraph::CoordinateDiff ref_pads_begin{0, 0}, ref_pads_end{0, 0};
for (auto op : f->get_ops()) {
if (auto conv = ngraph::as_type_ptr<ngraph::op::ConvolutionIE>(op)) {
ASSERT_EQ(conv->get_shape(), ref_shape);
ASSERT_EQ(conv->get_strides(), ref_strides);
ASSERT_EQ(conv->get_dilations(), ref_strides);
ASSERT_EQ(conv->get_pads_begin(), ref_pads_begin);
ASSERT_EQ(conv->get_pads_end(), ref_pads_end);
}
}
}
TEST(TransformationTests, MaxPoolReshapeTest1) {
std::shared_ptr<ngraph::Function> f(nullptr), f_ref(nullptr);
{
auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64});
ngraph::Strides strides{1};
ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3};
auto pool = std::make_shared<ngraph::opset1::MaxPool>(input, strides, pads_begin, pads_end, kernel, ngraph::op::RoundingType::FLOOR);
f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input});
ngraph::pass::InitNodeInfo().run_on_function(f);
ngraph::pass::Reshape1DOps().run_on_function(f);
ASSERT_NO_THROW(check_rt_info(f));
}
{
auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64});
auto reshape_begin = std::make_shared<opset1::Reshape>(input, opset1::Constant::create(element::i64, Shape{4}, {1, 3, 1, 64}), true);
ngraph::Strides strides{1, 1};
ngraph::Shape pads_begin{0, 0}, pads_end{0, 0}, kernel{1, 3};
auto pool = std::make_shared<ngraph::opset1::MaxPool>(reshape_begin, strides, pads_begin, pads_end, kernel, ngraph::op::RoundingType::FLOOR);
auto reshape_end = std::make_shared<opset1::Reshape>(pool, opset1::Constant::create(element::i64, Shape{3}, {1, 3, 62}), true);
f_ref = std::make_shared<ngraph::Function>(ngraph::NodeVector{reshape_end}, ngraph::ParameterVector{input});
}
auto res = compare_functions(f, f_ref);
ASSERT_TRUE(res.first) << res.second;
}
TEST(TransformationTests, AvgPoolReshapeTest1) {
std::shared_ptr<ngraph::Function> f(nullptr), f_ref(nullptr);
{
auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64});
ngraph::Strides strides{1};
ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3};
auto pool = std::make_shared<ngraph::opset1::AvgPool>(input, strides, pads_begin, pads_end, kernel, false, ngraph::op::RoundingType::FLOOR);
f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input});
ngraph::pass::InitNodeInfo().run_on_function(f);
ngraph::pass::Reshape1DOps().run_on_function(f);
ASSERT_NO_THROW(check_rt_info(f));
}
{
auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64});
auto reshape_begin = std::make_shared<opset1::Reshape>(input, opset1::Constant::create(element::i64, Shape{4}, {1, 3, 1, 64}), true);
ngraph::Strides strides{1, 1};
ngraph::Shape pads_begin{0, 0}, pads_end{0, 0}, kernel{1, 3};
auto pool = std::make_shared<ngraph::opset1::AvgPool>(reshape_begin, strides, pads_begin, pads_end, kernel, false, ngraph::op::RoundingType::FLOOR);
auto reshape_end = std::make_shared<opset1::Reshape>(pool, opset1::Constant::create(element::i64, Shape{3}, {1, 3, 62}), true);
f_ref = std::make_shared<ngraph::Function>(ngraph::NodeVector{reshape_end}, ngraph::ParameterVector{input});
}
auto res = compare_functions(f, f_ref);
ASSERT_TRUE(res.first) << res.second;
}
TEST(TransformationTests, ReshapeDynamicTest1) {
{
auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::PartialShape::dynamic());
ngraph::Strides strides{1};
ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3};
auto pool = std::make_shared<ngraph::opset1::AvgPool>(input, strides, pads_begin, pads_end, kernel, false, ngraph::op::RoundingType::FLOOR);
auto f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input});
pass::Manager manager;
manager.register_pass<ngraph::pass::Reshape1DOps>();
ASSERT_NO_THROW(manager.run_passes(f));
}
{
auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64});
ngraph::Strides strides{1};
ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3};
auto pool = std::make_shared<ngraph::opset1::MaxPool>(input, strides, pads_begin, pads_end, kernel, ngraph::op::RoundingType::FLOOR);
auto f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input});
pass::Manager manager;
manager.register_pass<ngraph::pass::Reshape1DOps>();
ASSERT_NO_THROW(manager.run_passes(f));
}
{
auto input = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{1, 3, 64}, {1});
auto w = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6, 3, 3/*OIW*/}, {1});
auto b = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6}, {1});
ngraph::Strides strides{1}, dilations{1};
ngraph::CoordinateDiff pads_begin{0}, pads_end{0};
ngraph::Shape output_shape{1, 6, 62};
auto conv = std::make_shared<ngraph::op::ConvolutionIE>(input, w, b, strides, dilations, pads_begin, pads_end, 1);
auto f = std::make_shared<ngraph::Function>(ngraph::NodeVector{conv}, ngraph::ParameterVector{});
pass::Manager manager;
manager.register_pass<ngraph::pass::Reshape1DOps>();
ASSERT_NO_THROW(manager.run_passes(f));
}
} | 9,141 | 3,430 |
/*
* Copyright 2019-2020 Douglas Kaip
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* getvkDebugUtilsMessengerCallbackDataEXT.cpp
*
* Created on: Apr 30, 2019
* Author: Douglas Kaip
*/
#include <stdlib.h>
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getvkDebugUtilsMessengerCallbackDataEXT(
JNIEnv *env,
const jobject jVkDebugUtilsMessengerCallbackDataEXTObject,
VkDebugUtilsMessengerCallbackDataEXT *vkDebugUtilsMessengerCallbackDataEXT,
std::vector<void *> *memoryToFree)
{
jclass vkDebugUtilsMessengerCallbackDataEXTClass = env->GetObjectClass(jVkDebugUtilsMessengerCallbackDataEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to GetObjectClass for jVkDebugUtilsMessengerCallbackDataEXTObject");
return;
}
////////////////////////////////////////////////////////////////////////
VkStructureType sTypeValue = getSType(env, jVkDebugUtilsMessengerCallbackDataEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to getSType");
return;
}
////////////////////////////////////////////////////////////////////////
jobject pNextObject = getpNextObject(env, jVkDebugUtilsMessengerCallbackDataEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNext failed.");
return;
}
if (pNextObject != nullptr)
{
LOGERROR(env, "%s", "pNext must be null.");
return;
}
void *pNext = nullptr;
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getFlags", "()Ljava/util/EnumSet;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getFlags methodId");
return;
}
jobject flagsObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
VkDebugUtilsMessengerCallbackDataFlagsEXT flags = getEnumSetValue(
env,
flagsObject,
"com/CIMthetics/jvulkan/VulkanExtensions/Enums/VkDebugUtilsMessengerCallbackDataFlagBitsEXT");
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getMessageIdName", "()Ljava/lang/String;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getMessageIdName methodId");
return;
}
jstring jMessageIdName = (jstring)env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod for getMessageIdName");
return;
}
char *theMessageIdName = nullptr;
if (jMessageIdName != nullptr)
{
const char *tempString1 = env->GetStringUTFChars(jMessageIdName, 0);
theMessageIdName = (char *)calloc(1, strlen(tempString1) + 1);
memoryToFree->push_back(theMessageIdName);
strcpy(theMessageIdName, tempString1);
env->ReleaseStringUTFChars(jMessageIdName, tempString1);
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getMessageIdNumber", "()I");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getMessageIdNumber methodId");
return;
}
jint messageIdNumber = env->CallIntMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallIntMethod for getMessageIdNumber");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getMessage", "()Ljava/lang/String;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getMessage methodId");
return;
}
jstring jMessage = (jstring)env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod for getMessage");
return;
}
char *message = nullptr;
if (jMessage != nullptr)
{
const char *tempString2 = env->GetStringUTFChars(jMessage, 0);
message = (char *)calloc(1, strlen(tempString2) + 1);
memoryToFree->push_back(message);
strcpy(message, tempString2);
env->ReleaseStringUTFChars(jMessage, tempString2);
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getQueueLabels", "()Ljava/util/Collection;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getQueueLabels methodId");
return;
}
jobject jVkDebugUtilsLabelEXTCollectionObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod for getQueueLabels");
return;
}
int numberOfQLabels = 0;
VkDebugUtilsLabelEXT *queueLabels = nullptr;
if (jVkDebugUtilsLabelEXTCollectionObject != nullptr)
{
jvulkan::getVkDebugUtilsLabelEXTCollection(
env,
jVkDebugUtilsLabelEXTCollectionObject,
&queueLabels,
&numberOfQLabels,
memoryToFree);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getVkDebugUtilsLabelEXTCollection failed");
return;
}
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getCmdBufLabels", "()Ljava/util/Collection;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getCmdBufLabels methodId");
return;
}
jVkDebugUtilsLabelEXTCollectionObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod for getCmdBufLabels");
return;
}
int numberOfCmdBufLabels = 0;
VkDebugUtilsLabelEXT *cmdBufLabels = nullptr;
if (jVkDebugUtilsLabelEXTCollectionObject != nullptr)
{
jvulkan::getVkDebugUtilsLabelEXTCollection(
env,
jVkDebugUtilsLabelEXTCollectionObject,
&cmdBufLabels,
&numberOfCmdBufLabels,
memoryToFree);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getVkDebugUtilsLabelEXTCollection failed");
return;
}
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getObjects", "()Ljava/util/Collection;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get getObjects methodId");
return;
}
jobject jVkDebugUtilsObjectNameInfoEXTCollectionObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod for getObjects");
return;
}
int numberOfObjects = 0;
VkDebugUtilsObjectNameInfoEXT *objects = nullptr;
if (jVkDebugUtilsObjectNameInfoEXTCollectionObject != nullptr)
{
jvulkan::getVkDebugUtilsObjectNameInfoEXTCollection(
env,
jVkDebugUtilsObjectNameInfoEXTCollectionObject,
&objects,
&numberOfObjects,
memoryToFree);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getVkDebugUtilsLabelEXTCollection failed");
return;
}
}
vkDebugUtilsMessengerCallbackDataEXT->sType = sTypeValue;
vkDebugUtilsMessengerCallbackDataEXT->pNext = (void *)pNext;
vkDebugUtilsMessengerCallbackDataEXT->flags = flags;
vkDebugUtilsMessengerCallbackDataEXT->pMessageIdName = theMessageIdName;
vkDebugUtilsMessengerCallbackDataEXT->messageIdNumber = messageIdNumber;
vkDebugUtilsMessengerCallbackDataEXT->pMessage = message;
vkDebugUtilsMessengerCallbackDataEXT->queueLabelCount = numberOfQLabels;
vkDebugUtilsMessengerCallbackDataEXT->pQueueLabels = queueLabels;
vkDebugUtilsMessengerCallbackDataEXT->cmdBufLabelCount = numberOfCmdBufLabels;
vkDebugUtilsMessengerCallbackDataEXT->pCmdBufLabels = cmdBufLabels;
vkDebugUtilsMessengerCallbackDataEXT->objectCount = numberOfObjects;
vkDebugUtilsMessengerCallbackDataEXT->pObjects = objects;
}
}
| 10,099 | 2,882 |
//============================================================================
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#include "VNState.hpp"
#include <QDebug>
#include <QImage>
#include <QImageReader>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include "VNode.hpp"
#include "ServerHandler.hpp"
#include "Submittable.hpp"
#include "UserMessage.hpp"
#include "VConfigLoader.hpp"
#include "VProperty.hpp"
std::map<std::string,VNState*> VNState::items_;
static std::map<NState::State,VNState*> stateMap_;
static std::map<unsigned char,VNState*> idMap_;
static VNState unSt("unknown",NState::UNKNOWN);
static VNState compSt("complete",NState::COMPLETE);
static VNState queuedSt("queued",NState::QUEUED);
static VNState abortedSt("aborted",NState::ABORTED);
static VNState submittedSt("submitted",NState::SUBMITTED);
static VNState activeSt("active",NState::ACTIVE);
static VNState suspendedSt("suspended");
static unsigned char ucIdCnt=0;
VNState::VNState(const std::string& name,NState::State nstate) :
VParam(name),
ucId_(ucIdCnt++)
{
items_[name]=this;
stateMap_[nstate]=this;
idMap_[ucId_]=this;
}
VNState::VNState(const std::string& name) :
VParam(name)
{
items_[name]=this;
}
//===============================================================
//
// Static methods
//
//===============================================================
std::vector<VParam*> VNState::filterItems()
{
std::vector<VParam*> v;
for(std::map<std::string,VNState*>::const_iterator it=items_.begin(); it != items_.end(); ++it)
{
v.push_back(it->second);
}
return v;
}
VNState* VNState::toState(const VNode *n)
{
if(!n || !n->node().get())
return nullptr;
node_ptr node=n->node();
if(node->isSuspended())
return items_["suspended"];
else
{
std::map<NState::State,VNState*>::const_iterator it=stateMap_.find(node->state());
if(it != stateMap_.end())
return it->second;
}
return nullptr;
}
VNState* VNState::toRealState(const VNode *n)
{
if(!n || !n->node().get())
return nullptr;
node_ptr node=n->node();
std::map<NState::State,VNState*>::const_iterator it=stateMap_.find(node->state());
if(it != stateMap_.end())
return it->second;
return nullptr;
}
VNState* VNState::toDefaultState(const VNode *n)
{
if(!n || !n->node())
return nullptr;
node_ptr node=n->node();
const char *dStateName=DState::toString(node->defStatus());
assert(dStateName);
std::string dsn(dStateName);
return find(dsn);
}
VNState* VNState::find(const std::string& name)
{
std::map<std::string,VNState*>::const_iterator it=items_.find(name);
if(it != items_.end())
return it->second;
return nullptr;
}
VNState* VNState::find(unsigned char ucId)
{
std::map<unsigned char,VNState*>::const_iterator it=idMap_.find(ucId);
if(it != idMap_.end())
return it->second;
return nullptr;
}
//
//Has to be very quick!!
//
QColor VNState::toColour(const VNode *n)
{
VNState *obj=VNState::toState(n);
return (obj)?(obj->colour()):QColor();
}
QColor VNState::toRealColour(const VNode *n)
{
VNState *obj=VNState::toRealState(n);
return (obj)?(obj->colour()):QColor();
}
QColor VNState::toFontColour(const VNode *n)
{
VNState *obj=VNState::toState(n);
return (obj)?(obj->fontColour()):QColor();
}
QColor VNState::toTypeColour(const VNode *n)
{
VNState *obj=VNState::toState(n);
return (obj)?(obj->typeColour()):QColor();
}
QString VNState::toName(const VNode *n)
{
VNState *obj=VNState::toState(n);
return (obj)?(obj->name()):QString();
}
QString VNState::toDefaultStateName(const VNode *n)
{
VNState *obj=VNState::toDefaultState(n);
return (obj)?(obj->name()):QString();
}
QString VNState::toRealStateName(const VNode *n)
{
VNState *obj=VNState::toRealState(n);
return (obj)?(obj->name()):QString();
}
bool VNState::isActive(unsigned char ucId)
{
VNState *obj=VNState::find(ucId);
return (obj)?(obj->name() == "active"):false;
}
bool VNState::isComplete(unsigned char ucId)
{
VNState *obj=VNState::find(ucId);
return (obj)?(obj->name() == "complete"):false;
}
bool VNState::isSubmitted(unsigned char ucId)
{
VNState *obj=VNState::find(ucId);
return (obj)?(obj->name() == "submitted"):false;
}
//==================================================
// Server state
//==================================================
VNState* VNState::toState(ServerHandler *s)
{
if(!s)
return nullptr;
bool susp=false;
NState::State ns=s->state(susp);
if(susp)
return items_["suspended"];
else
{
std::map<NState::State,VNState*>::const_iterator it=stateMap_.find(ns);
if(it != stateMap_.end())
return it->second;
}
return nullptr;
}
QString VNState::toName(ServerHandler *s)
{
VNState *obj=VNState::toState(s);
return (obj)?(obj->name()):QString();
}
QColor VNState::toColour(ServerHandler *s)
{
VNState *obj=VNState::toState(s);
return (obj)?(obj->colour()):QColor();
}
QColor VNState::toFontColour(ServerHandler *s)
{
VNState *obj=VNState::toState(s);
return (obj)?(obj->fontColour()):QColor();
}
void VNState::load(VProperty* group)
{
Q_FOREACH(VProperty* p,group->children())
{
if(VNState* obj=VNState::find(p->strName()))
{
obj->setProperty(p);
}
}
}
static SimpleLoader<VNState> loader("nstate");
| 5,778 | 2,205 |
/*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "gpu/ocl/gemm_matmul.hpp"
#include "gpu/ocl/gemm/ocl_gemm_utils.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
namespace ocl {
status_t gemm_matmul_t::execute(const exec_ctx_t &ctx) const {
using namespace gemm_utils;
const auto src_d = ctx.memory_mdw(DNNL_ARG_SRC);
const auto weights_d = ctx.memory_mdw(DNNL_ARG_WEIGHTS);
const auto dst_d = ctx.memory_mdw(DNNL_ARG_DST);
const auto bia_d = ctx.memory_mdw(DNNL_ARG_BIAS);
memory_storage_t *scales = &CTX_IN_STORAGE(DNNL_ARG_ATTR_OUTPUT_SCALES);
memory_storage_t *a0
= &CTX_IN_STORAGE(DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_SRC);
memory_storage_t *b0
= &CTX_IN_STORAGE(DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS);
memory_storage_t *c0
= &CTX_IN_STORAGE(DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_DST);
const bool is_batched = src_d.ndims() == 3;
const dim_t MB = is_batched ? dst_d.dims()[0] : 1;
const dim_t M = dst_d.dims()[is_batched + 0];
const dim_t N = dst_d.dims()[is_batched + 1];
const dim_t K = src_d.dims()[is_batched + 1];
const auto &dst_bd = dst_d.blocking_desc();
const auto &src_strides = &src_d.blocking_desc().strides[0];
const auto &weights_strides = &weights_d.blocking_desc().strides[0];
const auto &dst_strides = &dst_d.blocking_desc().strides[0];
int bias_mask = 0;
if (is_batched) bias_mask |= (bia_d.dims()[0] > 1) ? 1 << 0 : 0;
for (int d = is_batched; d < bia_d.ndims(); ++d) {
bias_mask |= (bia_d.dims()[d] > 1) ? 1 << (bia_d.ndims() - d) : 0;
}
const transpose_t transA = src_strides[is_batched + 1] == 1
&& src_d.dims()[is_batched + 0] > 1
? transpose::notrans
: transpose::trans;
const transpose_t transB = weights_strides[is_batched + 1] == 1
&& weights_d.dims()[is_batched + 0] > 1
? transpose::notrans
: transpose::trans;
const int lda = (int)
src_strides[is_batched + (transA == transpose::notrans ? 0 : 1)];
const int ldb = (int)weights_strides[is_batched
+ (transB == transpose::notrans ? 0 : 1)];
const int ldc = (int)dst_bd.strides[is_batched + 0];
const auto d = pd()->desc();
const auto src_dt = d->src_desc.data_type;
const auto wei_dt = d->weights_desc.data_type;
const auto bia_dt = d->bias_desc.data_type;
const auto dst_dt = d->dst_desc.data_type;
const auto acc_dt = d->accum_data_type;
const int stride_a = (int)src_strides[0];
const int stride_b = (int)weights_strides[0];
const int stride_c = (int)dst_strides[0];
gemm_exec_args_t gemm_args;
gemm_args.a = &CTX_IN_STORAGE(DNNL_ARG_WEIGHTS);
gemm_args.b = &CTX_IN_STORAGE(DNNL_ARG_SRC);
gemm_args.c = &CTX_OUT_STORAGE(DNNL_ARG_DST);
gemm_args.bias = &CTX_IN_STORAGE(DNNL_ARG_BIAS);
gemm_args.a_zero_point = b0;
gemm_args.b_zero_point = a0;
gemm_args.c_zero_point = c0;
gemm_args.output_scales = scales;
gemm_desc_t gemm_desc;
gemm_desc.transa = transB;
gemm_desc.transb = transA;
gemm_desc.batch = MB;
gemm_desc.m = N;
gemm_desc.n = M;
gemm_desc.k = K;
gemm_desc.stride_a = stride_b;
gemm_desc.stride_b = stride_a;
gemm_desc.stride_c = stride_c;
gemm_desc.lda = ldb;
gemm_desc.ldb = lda;
gemm_desc.ldc = ldc;
gemm_desc.bias_mask = bias_mask;
gemm_desc.a_type = wei_dt;
gemm_desc.b_type = src_dt;
gemm_desc.c_type = dst_dt;
gemm_desc.acc_type = acc_dt;
gemm_desc.bias_type = bia_dt;
gemm_exec_ctx_t gemm_ctx(ctx.stream(), gemm_args, &gemm_desc);
status_t gemm_status = gemm_impl(gemm_)->execute(gemm_ctx);
if (gemm_status != status::success) return gemm_status;
return status::success;
}
} // namespace ocl
} // namespace gpu
} // namespace impl
} // namespace dnnl
| 4,617 | 1,895 |
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "ros2_bdi_skills/bdi_action_executor.hpp"
#include "example_interfaces/msg/string.hpp"
#include "webots_ros2_simulations_interfaces/msg/move_status.hpp"
using std::string;
using example_interfaces::msg::String;
using webots_ros2_simulations_interfaces::msg::MoveStatus;
typedef enum {LOW, CLOSE, HIGH} PickupStatus;
class GripperPickup : public BDIActionExecutor
{
public:
GripperPickup()
: BDIActionExecutor("gripper_pickup", 3)
{
robot_name_ = this->get_parameter("agent_id").as_string();
gripper_pose_cmd_publisher_ = this->create_publisher<String>("/"+robot_name_+"/cmd_gripper_pose", rclcpp::QoS(1).keep_all());
gripper_status_cmd_publisher_ = this->create_publisher<String>("/"+robot_name_+"/cmd_gripper_status", rclcpp::QoS(1).keep_all());
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
on_activate(const rclcpp_lifecycle::State & previous_state)
{
action_status_ = LOW;
repeat_ = 0;
gripper_pose_cmd_publisher_->on_activate();
gripper_status_cmd_publisher_->on_activate();
return BDIActionExecutor::on_activate(previous_state);
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
on_deactivate(const rclcpp_lifecycle::State & previous_state)
{
gripper_pose_cmd_publisher_->on_deactivate();
gripper_status_cmd_publisher_->on_deactivate();
return BDIActionExecutor::on_deactivate(previous_state);
}
float advanceWork()
{
auto msg = String();
msg.data = (action_status_ == LOW)? "low" :
(
(action_status_ == CLOSE)? "close" :
"high"
);
if(action_status_ == CLOSE)
{
gripper_status_cmd_publisher_->publish(msg);
}
else
{
gripper_pose_cmd_publisher_->publish(msg);
}
repeat_++;
if(repeat_ == 3)
{
//publish same cmd for three action steps then switch to new status
repeat_ = 0;
action_status_ = (action_status_ == LOW)? CLOSE : HIGH;
}
return 0.112f;
}
private:
PickupStatus action_status_;
uint8_t repeat_;
rclcpp_lifecycle::LifecyclePublisher<String>::SharedPtr gripper_pose_cmd_publisher_;
rclcpp_lifecycle::LifecyclePublisher<String>::SharedPtr gripper_status_cmd_publisher_;
rclcpp::Subscription<MoveStatus>::SharedPtr gripper_move_status_subscriber_;
string robot_name_;
};
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
auto actionNode = std::make_shared<GripperPickup>();
rclcpp::spin(actionNode->get_node_base_interface());
rclcpp::shutdown();
return 0;
}
| 3,121 | 990 |
// Copyright (c) 2009 The Chromium 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 "base/file_util.h"
#include "chrome/installer/util/create_dir_work_item.h"
#include "chrome/installer/util/logging_installer.h"
CreateDirWorkItem::~CreateDirWorkItem() {
}
CreateDirWorkItem::CreateDirWorkItem(const FilePath& path)
: path_(path),
rollback_needed_(false) {
}
void CreateDirWorkItem::GetTopDirToCreate() {
if (file_util::PathExists(path_)) {
top_path_ = FilePath();
return;
}
FilePath parent_dir(path_);
do {
top_path_ = parent_dir;
parent_dir = parent_dir.DirName();
} while ((parent_dir != top_path_) && !file_util::PathExists(parent_dir));
return;
}
bool CreateDirWorkItem::Do() {
LOG(INFO) << "creating directory " << path_.value();
GetTopDirToCreate();
if (top_path_.empty())
return true;
LOG(INFO) << "top directory that needs to be created: " \
<< top_path_.value();
bool result = file_util::CreateDirectory(path_);
LOG(INFO) << "directory creation result: " << result;
rollback_needed_ = true;
return result;
}
void CreateDirWorkItem::Rollback() {
if (!rollback_needed_)
return;
// Delete all the directories we created to rollback.
// Note we can not recusively delete top_path_ since we don't want to
// delete non-empty directory. (We may have created a shared directory).
// Instead we walk through path_ to top_path_ and delete directories
// along the way.
FilePath path_to_delete(path_);
while (1) {
if (file_util::PathExists(path_to_delete)) {
if (!RemoveDirectory(path_to_delete.value().c_str()))
break;
}
if (path_to_delete == top_path_)
break;
path_to_delete = path_to_delete.DirName();
}
return;
}
| 1,853 | 625 |
#pragma once
#include <ros/ros.h>
#include <string>
#include "msg_adaptor/MeshGeometryStampedCustom.hpp"
// Placing all lib elements into a sel_map namespace, partly in case this is extended upon later, partly to reduce pollution.
namespace sel_map::publisher{
template <typename MeshAdaptorType>
class TriangularMeshPublisher{
ros::NodeHandle node_handle;
ros::Publisher mesh_publisher;
sel_map::msg_adaptor::MeshGeometryStampedCustom cached_message;
public:
MeshAdaptorType mesh_adaptor;
TriangularMeshPublisher(const MeshAdaptorType& mesh_adaptor, std::string uuid, std::string frame_id, std::string mesh_topic);
bool pubAlive();
void publishMesh();
unsigned int getSingleClassifications(int* buffer, unsigned int length);
};
}
| 834 | 259 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "T3D/containerQuery.h"
#include "scene/sceneObject.h"
#include "environment/waterObject.h"
#include "T3D/physicalZone.h"
void findRouter( SceneObject *obj, void *key )
{
if (obj->getTypeMask() & WaterObjectType)
waterFind(obj, key);
else if (obj->getTypeMask() & PhysicalZoneObjectType)
physicalZoneFind(obj, key);
else {
AssertFatal(false, "Error, must be either water or physical zone here!");
}
}
void waterFind( SceneObject *obj, void *key )
{
PROFILE_SCOPE( waterFind );
// This is called for each WaterObject the ShapeBase object is overlapping.
ContainerQueryInfo *info = static_cast<ContainerQueryInfo*>(key);
WaterObject *water = dynamic_cast<WaterObject*>(obj);
AssertFatal( water != NULL, "containerQuery - waterFind(), passed object was not of class WaterObject!");
// Get point at the bottom/center of the box.
Point3F testPnt = info->box.getCenter();
testPnt.z = info->box.minExtents.z;
F32 coverage = water->getWaterCoverage(info->box);
// Since a WaterObject can have global bounds we may get this call
// even though we have zero coverage. If so we want to early out and
// not save the water properties.
if ( coverage == 0.0f )
return;
// Add in flow force. Would be appropriate to try scaling it by coverage
// thought. Or perhaps have getFlow do that internally and take
// the box parameter.
info->appliedForce += water->getFlow( testPnt );
// Only save the following properties for the WaterObject with the
// greatest water coverage for this ShapeBase object.
if ( coverage < info->waterCoverage )
return;
info->waterCoverage = coverage;
info->liquidType = water->getLiquidType();
info->waterViscosity = water->getViscosity();
info->waterDensity = water->getDensity();
info->waterHeight = water->getSurfaceHeight( Point2F(testPnt.x,testPnt.y) );
info->waterObject = water;
}
void physicalZoneFind(SceneObject* obj, void *key)
{
PROFILE_SCOPE( physicalZoneFind );
ContainerQueryInfo *info = static_cast<ContainerQueryInfo*>(key);
PhysicalZone* pz = dynamic_cast<PhysicalZone*>(obj);
AssertFatal(pz != NULL, "Error, not a physical zone!");
if (pz == NULL || pz->testBox(info->box) == false)
return;
if (pz->isActive()) {
info->gravityScale *= pz->getGravityMod();
info->airResistanceScale *= pz->getAirResistanceMod();
info->appliedForce += pz->getForce();
}
}
| 3,804 | 1,183 |
// Copyright 2019 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 "src/connectivity/bluetooth/core/bt-host/l2cap/channel_configuration.h"
#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h"
#include "src/connectivity/bluetooth/core/bt-host/common/log.h"
// Prevent "undefined symbol: __zircon_driver_rec__" error.
BT_DECLARE_FAKE_DRIVER();
namespace bt {
namespace l2cap {
namespace internal {
void fuzz(const uint8_t* data, size_t size) {
DynamicByteBuffer buf(size);
memcpy(buf.mutable_data(), data, size);
ChannelConfiguration config;
bool _result = config.ReadOptions(buf);
// unused.
(void)_result;
}
} // namespace internal
} // namespace l2cap
} // namespace bt
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
bt::l2cap::internal::fuzz(data, size);
return 0;
}
| 947 | 340 |
#include "DxDeviceMt.h"
IDWriteFactory *DxDeviceMt::GetDwriteFactory() const {
return this->dwriteFactory.Get();
}
ID2D1Factory1 *DxDeviceMt::GetD2DFactory() const {
return this->d2dFactory.Get();
}
ID3D11Device *DxDeviceMt::GetD3DDevice() const {
return this->d3dDev.Get();
}
ID2D1Device *DxDeviceMt::GetD2DDevice() const {
return this->d2dDevice.Get();
}
D2DCtxMt *DxDeviceMt::GetD2DCtxMt() const {
// TODO try to find better approach than const_cast
D2DCtxMt *tmp = const_cast<D2DCtxMt *>(&this->d2dCtxMt);
return tmp;
}
Microsoft::WRL::ComPtr<IDWriteFactory> DxDeviceMt::GetDwriteFactoryCPtr() const {
return this->dwriteFactory;
}
Microsoft::WRL::ComPtr<ID2D1Factory1> DxDeviceMt::GetD2DFactoryCPtr() const {
return this->d2dFactory;
}
Microsoft::WRL::ComPtr<ID3D11Device> DxDeviceMt::GetD3DDeviceCPtr() const {
return this->d3dDev;
}
Microsoft::WRL::ComPtr<ID2D1Device> DxDeviceMt::GetD2DDeviceCPtr() const {
return this->d2dDevice;
} | 960 | 407 |
#include "water.h"
Water::Water(): TaticalMovingObject()
{
}
Water::Water
(
const Coordinates& position,
const Vector& velocity,
unsigned int initialTime,
unsigned int lifeTime,
const Vector &acceleration
): TaticalMovingObject(position, velocity, initialTime, lifeTime, acceleration, ObjectCategory::NavalShip)
{
}
void Water::setMaxDepth(double value)
{
this->maxDepth = value;
}
double Water::getMaxDepth() const
{
return this->maxDepth;
}
void Water::setMinDepth(double value)
{
this->minDepth = value;
}
double Water::getMinDepth() const
{
return this->minDepth;
}
| 614 | 210 |
#if !defined WATER_UTILITY_MATHS_INCLUDED
#define WATER_UTILITY_MATHS_INCLUDED
// STL headers.
#include <cmath>
#include <type_traits>
// Utility namespace.
namespace util
{
/////////////////////
/// Miscellaneous ///
/////////////////////
/// <summary> Checks if two float values are relatively equal to each other. </summary>
/// <param name="margin"> The absolute margin of error between the two floats. Must be a positive value. </param>
inline bool roughlyEquals (const float lhs, const float rhs, const float margin = 0.1f)
{
// Test the upper and lower limits.
return std::abs (lhs - rhs) <= margin;
}
///////////////////
/// Comparisons ///
///////////////////
/// <summary> Returns the minimum value, passed by value for arithmetic types. </summary>
template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type min (const T a, const T b)
{
return a < b ? a : b;
}
/// <summary> Returns the maximum value, passed by value for arithmetic types. </summary>
template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type max (const T a, const T b)
{
return a > b ? a : b;
}
/// <summary> Returns the minimum value, passed by reference for non-arithmetic types. </summary>
template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T>::type& min (const T& a, const T& b)
{
return a < b ? a : b;
}
/// <summary> Returns the maximum value, passed by reference for non-arithmetic types. </summary>
template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T>::type& max (const T& a, const T& b)
{
return a > b ? a : b;
}
/// <summary> Clamps a value between a given minimum and maximum value. Arithmetic types are passed by value. </summary>
/// <param name="value"> The value to clamp. </param>
template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type clamp (const T value, const T min, const T max)
{
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return value;
}
/// <summary> Clamps a value between a given minimum and maximum value. Non-arithmetic types are passed by reference. </summary>
/// <param name="value"> The value to clamp. </param>
template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T>::type clamp (const T& value, const T& min, const T& max)
{
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return value;
}
}
#endif
| 2,789 | 853 |
#include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
typedef long long ll;
typedef pair<int,int> pii;
// head
const int N = 105;
char s[105];
char dig[15][15] = {
"zero", "one", "two", "three",
"four", "five", "six",
"seven", "eight", "nine"
};
int main() {
while (scanf("%s", s) == 1) {
int n = strlen(s);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += s[i] - '0';
}
sprintf(s, "%d", sum);
n = strlen(s);
for (int i = 0; i < n; i++) {
printf("%s%c", dig[s[i]-'0'], i==n-1 ? '\n' : ' ');
}
}
return 0;
}
| 634 | 299 |
/**
* This file is part of the CernVM File System.
*/
#include "swissknife_lease_curl.h"
#include "cvmfs_config.h"
#include "gateway_util.h"
#include "hash.h"
#include "json_document.h"
#include "logging.h"
#include "util/pointer.h"
#include "util/string.h"
namespace {
CURL* PrepareCurl(const std::string& method) {
const char* user_agent_string = "cvmfs/" VERSION;
CURL* h_curl = curl_easy_init();
if (h_curl) {
curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string);
curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method.c_str());
}
return h_curl;
}
size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {
CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp);
if (size * nmemb < 1) {
return 0;
}
my_buffer->data = static_cast<char*>(buffer);
return my_buffer->data.size();
}
} // namespace
bool MakeAcquireRequest(const std::string& key_id, const std::string& secret,
const std::string& repo_path,
const std::string& repo_service_url,
CurlBuffer* buffer) {
CURLcode ret = static_cast<CURLcode>(0);
CURL* h_curl = PrepareCurl("POST");
if (!h_curl) {
return false;
}
const std::string payload = "{\"path\" : \"" + repo_path +
"\", \"api_version\" : \"" +
StringifyInt(gateway::APIVersion()) + "\"}";
shash::Any hmac(shash::kSha1);
shash::HmacString(secret, payload, &hmac);
const std::string header_str = std::string("Authorization: ") + key_id + " " +
Base64(hmac.ToString(false));
struct curl_slist* auth_header = NULL;
auth_header = curl_slist_append(auth_header, header_str.c_str());
curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header);
// Make request to acquire lease from repo services
curl_easy_setopt(h_curl, CURLOPT_URL, (repo_service_url + "/leases").c_str());
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
static_cast<curl_off_t>(payload.length()));
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, payload.c_str());
curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);
ret = curl_easy_perform(h_curl);
if (ret) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Make lease acquire request failed: %d. Reply: %s", ret,
buffer->data.c_str());
}
curl_easy_cleanup(h_curl);
h_curl = NULL;
return !ret;
}
bool MakeEndRequest(const std::string& method, const std::string& key_id,
const std::string& secret, const std::string& session_token,
const std::string& repo_service_url,
const std::string& request_payload, CurlBuffer* reply) {
CURLcode ret = static_cast<CURLcode>(0);
CURL* h_curl = PrepareCurl(method);
if (!h_curl) {
return false;
}
shash::Any hmac(shash::kSha1);
shash::HmacString(secret, session_token, &hmac);
const std::string header_str = std::string("Authorization: ") + key_id + " " +
Base64(hmac.ToString(false));
struct curl_slist* auth_header = NULL;
auth_header = curl_slist_append(auth_header, header_str.c_str());
curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header);
curl_easy_setopt(h_curl, CURLOPT_URL,
(repo_service_url + "/leases/" + session_token).c_str());
if (request_payload != "") {
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
static_cast<curl_off_t>(request_payload.length()));
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, request_payload.c_str());
} else {
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
static_cast<curl_off_t>(0));
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL);
}
curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, reply);
ret = curl_easy_perform(h_curl);
if (ret) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Lease end request - curl_easy_perform failed: %d", ret);
}
UniquePtr<JsonDocument> reply_json(JsonDocument::Create(reply->data));
const JSON *reply_status =
JsonDocument::SearchInObject(reply_json->root(), "status", JSON_STRING);
const bool ok = (reply_status != NULL &&
std::string(reply_status->string_value) == "ok");
if (!ok) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Lease end request - error reply: %s",
reply->data.c_str());
}
curl_easy_cleanup(h_curl);
h_curl = NULL;
return ok && !ret;
}
| 4,765 | 1,714 |
// algparam.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "algparam.h"
NAMESPACE_BEGIN(CryptoPP)
PAssignIntToInteger g_pAssignIntToInteger = NULL;
bool CombinedNameValuePairs::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
if (strcmp(name, "ValueNames") == 0)
return m_pairs1.GetVoidValue(name, valueType, pValue) && m_pairs2.GetVoidValue(name, valueType, pValue);
else
return m_pairs1.GetVoidValue(name, valueType, pValue) || m_pairs2.GetVoidValue(name, valueType, pValue);
}
void AlgorithmParametersBase::operator=(const AlgorithmParametersBase& rhs)
{
assert(false);
}
bool AlgorithmParametersBase::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
if (strcmp(name, "ValueNames") == 0)
{
NameValuePairs::ThrowIfTypeMismatch(name, typeid(std::string), valueType);
if (m_next.get())
m_next->GetVoidValue(name, valueType, pValue);
(*reinterpret_cast<std::string *>(pValue) += m_name) += ";";
return true;
}
else if (strcmp(name, m_name) == 0)
{
AssignValue(name, valueType, pValue);
m_used = true;
return true;
}
else if (m_next.get())
return m_next->GetVoidValue(name, valueType, pValue);
else
return false;
}
AlgorithmParameters::AlgorithmParameters()
: m_defaultThrowIfNotUsed(true)
{
}
AlgorithmParameters::AlgorithmParameters(const AlgorithmParameters &x)
: m_defaultThrowIfNotUsed(x.m_defaultThrowIfNotUsed)
{
m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release());
}
AlgorithmParameters & AlgorithmParameters::operator=(const AlgorithmParameters &x)
{
m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release());
return *this;
}
bool AlgorithmParameters::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
if (m_next.get())
return m_next->GetVoidValue(name, valueType, pValue);
else
return false;
}
NAMESPACE_END
#endif
| 1,987 | 741 |
#include "Player.h"
#include <SystemResources.h>
#include "TextureManager.h"
#include "CollisionHandler.h"
#include "Contact.h"
#include "Input.h"
#include "GameManager.h"
#include "Bullet.h"
namespace diva
{
/*
*/
Player::Player(int x, int y, int w, int h) : GameObject(), position(x, y), collider(position, w, h, "Player")
{
setTag("Player");
// laddar in spriten som ska användas samt sätter ett ID så att man kan hämta texuren från en map. sätter även en renderare.
TextureManager::getInstance()->load((resPath + "images/PlayerSprite/RBS.png").c_str(), tag, system.renderer);
rb.setGravity(0); // Eftersom spelet är topdown och vi fortfarande vill använda våran ridigbody klass så sätter vi gravity till 0.
shootCounter = shootTime;
counter = damageTimer;
}
void Player::gameObjectUpdate(float dt)
{
rb.resetForce();
//[Uträkning för vilken grad som spriten ska titta på]
getAngle();
// Kolla imputs för att röra spelaren.
if (InputHandler::getInstance()->getKeyDown(KEYS::A))
{
rb.applyForceX(-6.0f);
}
if (InputHandler::getInstance()->getKeyDown(KEYS::D))
{
rb.applyForceX(6.0f);
}
if (InputHandler::getInstance()->getKeyDown(KEYS::W))
{
rb.applyForceY(-6.0f);
}
if (InputHandler::getInstance()->getKeyDown(KEYS::S))
{
rb.applyForceY(6.0f);
}
shootCounter -= (dt / 100);
if (InputHandler::getInstance()->getMouseButton(MOUSEBUTTON::LMB))
{
shoot(shootCounter);
}
// När spelaren sjukter så ska den instanziera en annan klass som är av typ "Skott" eller liknande
cf = int(((SDL_GetTicks() / 100) % 2));
rb.updatePhysics(dt);
position += rb.getRbPosition();
if (rb.getVelocity().x != 0 || rb.getVelocity().y != 0)
{
isWalking = true;
}
else
{
isWalking = false;
}
collider.updateCollider();
if (isDamaged)
{
counter -= (dt / 100);
}
if (counter <= 0)
{
hp--;
counter = damageTimer;
isDamaged = false;
}
if (hp <= 0)
{
GameManager::getInstance()->remove(this);
GameManager::getInstance()->removeCollider(collider);
}
}
void Player::updateCollision(BoxCollider2D collision)
{
Contact c;
if (CollisionHandler::collisionDetection(collider, collision, c))
{
if (collision.getObjectTag() == "Enemy")
{
isDamaged = true;
}
if (collision.getObjectTag() == "Wall")
{
position += CollisionHandler::collisionResolution(collider, c);
}
}
}
void Player::draw() const
{
// OM player Velocity == 0
TextureManager::getInstance()->draw(tag, (int)position.x, (int)position.y, 57, 43, system.renderer, degrees, Spriteflip::HORIZONTALFLIP);
if (isWalking)
TextureManager::getInstance()->drawFrame(tag, (int)position.x, (int)position.y, 57, 43, cr, cf, system.renderer, degrees, Spriteflip::HORIZONTALFLIP);
}
void Player::getAngle()
{
float distX = collider.getCenterPoint().x - InputHandler::getInstance()->mousePos.x;
float distY = InputHandler::getInstance()->mousePos.y - collider.getCenterPoint().y;
float radians = (atan2(distY, distX));
degrees = -radians * (180 / 3.14);
}
void Player::shoot(float &sTime)
{
//Bullet *bull = nullptr;
if (sTime >= 0)
{
return;
}
Vector2D v{(float)InputHandler::getInstance()->mousePos.x, (float)InputHandler::getInstance()->mousePos.y};
Bullet *bull = new Bullet(position, v);
sTime = shootTime;
bull = nullptr;
}
Player::~Player()
{
}
}
| 4,087 | 1,339 |
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-716457
//
// All rights reserved.
//
// This file is part of Ascent.
//
// For details, see: http://ascent.readthedocs.io/.
//
// Please also read ascent/LICENSE
//
// 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 disclaimer below.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, THE U.S. DEPARTMENT OF ENERGY 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: ascent_mfem_data_adapter.hpp
///
//-----------------------------------------------------------------------------
#ifndef ASCENT_MFEM_DATA_ADAPTER_HPP
#define ASCENT_MFEM_DATA_ADAPTER_HPP
// conduit includes
#include <conduit.hpp>
#include <mfem.hpp>
//-----------------------------------------------------------------------------
// -- begin ascent:: --
//-----------------------------------------------------------------------------
namespace ascent
{
class MFEMDataSet
{
public:
using FieldMap = std::map<std::string, mfem::GridFunction*>;
MFEMDataSet();
~MFEMDataSet();
MFEMDataSet(mfem::Mesh *mesh);
void set_mesh(mfem::Mesh *mesh);
mfem::Mesh* get_mesh();
void add_field(mfem::GridFunction *field, const std::string &name);
bool has_field(const std::string &field_name);
mfem::GridFunction* get_field(const std::string &field_name);
int num_fields();
FieldMap get_field_map();
protected:
FieldMap m_fields;
mfem::Mesh *m_mesh;
};
struct MFEMDomains
{
std::vector<MFEMDataSet*> m_data_sets;
std::vector<int> m_domain_ids;
~MFEMDomains()
{
for(int i = 0; i < m_data_sets.size(); ++i)
{
delete m_data_sets[i];
}
}
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Class that Handles Blueprint to mfem
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class MFEMDataAdapter
{
public:
// convert blueprint mfem data to a mfem data set
// assumes "n" conforms to the mesh blueprint
//
// conduit::blueprint::mesh::verify(n,info) == true
//
static MFEMDomains* BlueprintToMFEMDataSet(const conduit::Node &n,
const std::string &topo_name="");
static bool IsHighOrder(const conduit::Node &n);
static void Linearize(MFEMDomains *ho_domains, conduit::Node &output, const int refinement);
static void GridFunctionToBlueprintField(mfem::GridFunction *gf,
conduit::Node &out,
const std::string &main_topology_name = "main");
static void MeshToBlueprintMesh(mfem::Mesh *m,
conduit::Node &out,
const std::string &coordset_name = "coords",
const std::string &main_topology_name = "main",
const std::string &boundary_topology_name = "boundary");
static std::string ElementTypeToShapeName(mfem::Element::Type element_type);
};
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent:: --
//-----------------------------------------------------------------------------
#endif
//-----------------------------------------------------------------------------
// -- end header ifdef guard
//-----------------------------------------------------------------------------
| 5,332 | 1,562 |
/*
* Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org>
* Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
* Copyright (C) 2018 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "SVGClipPathElement.h"
#include "Document.h"
#include "ImageBuffer.h"
#include "RenderSVGResourceClipper.h"
#include "SVGNames.h"
#include "StyleResolver.h"
#include <wtf/IsoMallocInlines.h>
#include <wtf/NeverDestroyed.h>
namespace WebCore {
WTF_MAKE_ISO_ALLOCATED_IMPL(SVGClipPathElement);
inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document& document)
: SVGGraphicsElement(tagName, document)
{
ASSERT(hasTagName(SVGNames::clipPathTag));
static std::once_flag onceFlag;
std::call_once(onceFlag, [] {
PropertyRegistry::registerProperty<SVGNames::clipPathUnitsAttr, SVGUnitTypes::SVGUnitType, &SVGClipPathElement::m_clipPathUnits>();
});}
Ref<SVGClipPathElement> SVGClipPathElement::create(const QualifiedName& tagName, Document& document)
{
return adoptRef(*new SVGClipPathElement(tagName, document));
}
void SVGClipPathElement::parseAttribute(const QualifiedName& name, const AtomString& value)
{
if (name == SVGNames::clipPathUnitsAttr) {
auto propertyValue = SVGPropertyTraits<SVGUnitTypes::SVGUnitType>::fromString(value);
if (propertyValue > 0)
m_clipPathUnits->setBaseValInternal<SVGUnitTypes::SVGUnitType>(propertyValue);
return;
}
SVGGraphicsElement::parseAttribute(name, value);
}
void SVGClipPathElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (PropertyRegistry::isKnownAttribute(attrName)) {
InstanceInvalidationGuard guard(*this);
if (RenderObject* object = renderer())
object->setNeedsLayout();
return;
}
SVGGraphicsElement::svgAttributeChanged(attrName);
}
void SVGClipPathElement::childrenChanged(const ChildChange& change)
{
SVGGraphicsElement::childrenChanged(change);
if (change.source == ChildChangeSource::Parser)
return;
if (RenderObject* object = renderer())
object->setNeedsLayout();
}
RenderPtr<RenderElement> SVGClipPathElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
{
return createRenderer<RenderSVGResourceClipper>(*this, WTFMove(style));
}
}
| 3,221 | 1,047 |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_PPC_VMX_SIMD_FUNCTION_RSQRT_HPP_INCLUDED
#define BOOST_SIMD_ARCH_PPC_VMX_SIMD_FUNCTION_RSQRT_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/half.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/fma.hpp>
#include <boost/simd/function/sqr.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bd = boost::dispatch;
namespace bs = boost::simd;
BOOST_DISPATCH_OVERLOAD( rsqrt_
, (typename A0)
, bs::vmx_
, bs::pack_< bd::single_<A0>, bs::vmx_>
)
{
BOOST_FORCEINLINE A0 operator()(const A0& a0) const BOOST_NOEXCEPT
{
A0 o = One<A0>();
A0 estimate = fast_(rsqrt)(a0);
A0 se = sqr(estimate);
A0 he = estimate*Half<A0>();
A0 st = vec_nmsub(a0.storage(),se.storage(),o.storage());
return fma(st, he, estimate);
}
};
BOOST_DISPATCH_OVERLOAD( rsqrt_
, (typename A0)
, bs::vmx_
, bs::fast_tag
, bs::pack_< bd::single_<A0>, bs::vmx_>
)
{
BOOST_FORCEINLINE A0 operator()(bs::fast_tag const&, const A0& a0) const BOOST_NOEXCEPT
{
return vec_rsqrte( a0.storage() );
}
};
} } }
#endif
| 1,856 | 633 |
/*+**************************************************************************/
/*** ***/
/*** Copyright (C) by Dierk Ohlerich ***/
/*** all rights reserverd ***/
/*** ***/
/*** To license this software, please contact the copyright holder. ***/
/*** ***/
/**************************************************************************+*/
#ifndef FILE_WERKKZEUG4_BUILD_HPP
#define FILE_WERKKZEUG4_BUILD_HPP
#ifndef __GNUC__
#pragma once
#endif
#include "base/types2.hpp"
#include "doc.hpp"
class ScriptCompiler;
class ScriptContext;
/****************************************************************************/
struct wNode
{
wOp *Op; // each node has to represent an op.
wOp *ScriptOp; // copy script from this op. Used for subroutine argumtent injection
wNode **Inputs;
wType *OutType; // real output type. Some ops specify "AnyType" as output.
sInt InputCount;
sInt FakeInputCount; // parameter only inputs
sInt CycleCheck;
sInt CallId; // this node is part of a subroutine call
sPoolString LoopName; // for injecting loop counters with a fake op
sF32 LoopValue;
sInt LoopFlag; // inside call or loop (possibly multiple different results for the same op)
sInt OutputCount; // used internally to find out good cache points
sU8 StoreCache; // while execution, store cache
sU8 LoadCache; // do no execute op, just load cache
sU8 Visited; // used during recursion (OptimizeCacheR)
wCommand *StoreCacheDone; // use the store cache!
};
struct wBuilderPush
{
wNode *CallInputs;
wOp *CallOp;
sArray<wNode *> FakeInputs; // for call and loop
sInt CurrentCallId;
sInt LoopFlag;
void GetFrom(wBuilder *);
void PutTo(wBuilder *);
};
class wBuilder
{
friend struct wBuilderPush;
sMemoryPool *Pool;
wNode *Root;
wNode *MakeNode(sInt ic,sInt fc=0);
const sChar *MakeString(const sChar *str1,const sChar *str2=0,const sChar *str3=0);
wNode *ParseR(wOp *op,sInt recursion);
void OptimizeCacheR(wNode **node);
wCommand *OutputR(wExecutive &,wNode *node);
wNode *SkipToSlowR(wNode *node);
wCommand *MakeCommand(wExecutive &exe,wOp *op,wCommand **inputs,sInt inputcount,wOp *scriptop,wOp *d0,const sChar *d1,sInt callid,sInt fakeinputcount);
void Error(wOp *op,const sChar *text);
sInt Errors;
void rssall(wNode *node,sInt flag);
wNode *CallInputs;
wOp *CallOp;
sArray<wNode *> FakeInputs; // for call and loop
sInt CallId;
sInt CurrentCallId;
sInt TypeCheckOnly;
sInt LoopFlag;
struct RecursionData_
{
sArray<wOp *> inputs;
sEndlessArray<sInt> inputloop;
RecursionData_() : inputloop(-1) {}
};
sEndlessArray<RecursionData_ *> RecursionData; // the new and delete in the recursion are very costly, especially with debug runtime. We can reuse the arrays!
public:
wBuilder();
~wBuilder();
sBool Parse(wOp *root);
sBool Optimize(sBool Cache);
sBool TypeCheck();
sBool Output(wExecutive &);
void SkipToSlow(sBool honorslow);
sBool Check(wOp *root);
sBool Depend(wExecutive &exe,wOp *root);
wObject *Execute(wExecutive &,wOp *root,sBool honorslow,sBool progress);
wObject *FindCache(wOp *root);
sArray<wNode *> AllNodes;
};
/****************************************************************************/
#endif // FILE_WERKKZEUG4_BUILD_HPP
| 3,756 | 1,169 |
#if defined(Hiro_VerticalSlider)
namespace hiro {
static auto VerticalSlider_change(GtkRange* gtkRange, pVerticalSlider* p) -> void {
auto position = (uint)gtk_range_get_value(gtkRange);
if(p->state().position == position) return;
p->state().position = position;
if(!p->locked()) p->self().doChange();
}
auto pVerticalSlider::construct() -> void {
#if HIRO_GTK==2
gtkWidget = gtk_vscale_new_with_range(0, 100, 1);
#elif HIRO_GTK==3
gtkWidget = gtk_scale_new_with_range(GTK_ORIENTATION_VERTICAL, 0, 100, 1);
#endif
gtk_scale_set_draw_value(GTK_SCALE(gtkWidget), false);
setLength(state().length);
setPosition(state().position);
g_signal_connect(G_OBJECT(gtkWidget), "value-changed", G_CALLBACK(VerticalSlider_change), (gpointer)this);
pWidget::construct();
}
auto pVerticalSlider::destruct() -> void {
gtk_widget_destroy(gtkWidget);
}
auto pVerticalSlider::minimumSize() const -> Size {
return {20, 3};
}
auto pVerticalSlider::setLength(uint length) -> void {
length += length == 0;
gtk_range_set_range(GTK_RANGE(gtkWidget), 0, max(1u, length - 1));
gtk_range_set_increments(GTK_RANGE(gtkWidget), 1, length >> 3);
}
auto pVerticalSlider::setPosition(uint position) -> void {
gtk_range_set_value(GTK_RANGE(gtkWidget), position);
}
}
#endif
| 1,290 | 516 |
// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "pathauditor/libc/logging.h"
#include <fcntl.h>
#include <syslog.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "absl/debugging/stacktrace.h"
#include "absl/debugging/symbolize.h"
#include "absl/strings/str_format.h"
namespace {
static const size_t kCmdlineMax = 1024;
static const size_t kMaxStackFrames = 20;
static const size_t kMaxSymbolLen = 64;
static const std::string &GetCmdline() {
static std::string cmdline;
if (!cmdline.empty()) {
return cmdline;
}
int fd = syscall(SYS_open, "/proc/self/cmdline", O_RDONLY);
if (fd == -1) {
cmdline = "(unknown)";
return cmdline;
}
char cmdline_buf[kCmdlineMax];
ssize_t bytes = read(fd, cmdline_buf, sizeof(cmdline_buf) - 1);
close(fd);
if (bytes == -1) {
cmdline = "(unknown)";
return cmdline;
}
cmdline_buf[bytes] = 0;
// /proc/self/cmdline separates arguments with null bytes. Turn them into
// spaces.
for (ssize_t i = 0; i < bytes - 1; i++) {
if (cmdline_buf[i] == '\x00') {
cmdline_buf[i] = ' ';
}
}
cmdline = cmdline_buf;
return cmdline;
}
static int GetUid() { return syscall(SYS_getuid); }
static std::string CurrentStackTrace() {
void *stack_trace[kMaxStackFrames];
int frame_cnt = absl::GetStackTrace(stack_trace, kMaxStackFrames, 2);
std::vector<std::string> stack_trace_lines;
for (int i = 0; i < frame_cnt; i++) {
char tmp[kMaxSymbolLen] = "";
const char *symbol = "(unknown)";
if (absl::Symbolize(stack_trace[i], tmp, sizeof(tmp))) {
symbol = tmp;
}
stack_trace_lines.push_back(absl::StrCat(
" ", absl::Hex(stack_trace[i], absl::kZeroPad12), " ", symbol));
}
return absl::StrJoin(stack_trace_lines, "\n");
}
} // namespace
namespace pathauditor {
void LogInsecureAccess(const FileEvent &event, const char *function_name) {
// for testing that functions get audited
const char *env_p = std::getenv("PATHAUDITOR_TEST");
if (env_p) {
std::cerr << "AUDITING:" << function_name << std::endl;
return;
}
openlog("pathauditor", LOG_PID, 0);
std::string args = absl::StrJoin(event.args, ", ");
std::string path_args = absl::StrJoin(event.path_args, ", ");
std::string event_info = absl::StrFormat(
"function %s, cmdline %s, syscall_nr %d, args %s, path args %s, uid %d, "
"stack trace:\n%s",
function_name, GetCmdline(), event.syscall_nr, args, path_args, GetUid(),
CurrentStackTrace());
syslog(LOG_WARNING, "InsecureAccess: %s", event_info.c_str());
}
void LogError(const absl::Status &status) {
openlog("pathauditor", LOG_PID, 0);
syslog(LOG_WARNING, "Cannot audit: %s",
std::string(status.message()).c_str());
}
} // namespace pathauditor
| 3,404 | 1,243 |
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// 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 "console/console.h"
#include "core/stream/fileStream.h"
#include "core/strings/unicode.h"
#include "core/util/journal/process.h"
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11CardProfiler.h"
#include "gfx/D3D11/gfxD3D11VertexBuffer.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "gfx/D3D11/gfxD3D11QueryFence.h"
#include "gfx/D3D11/gfxD3D11OcclusionQuery.h"
#include "gfx/D3D11/gfxD3D11Shader.h"
#include "gfx/D3D11/gfxD3D11Target.h"
#include "platformWin32/platformWin32.h"
#include "windowManager/win32/win32Window.h"
#include "windowManager/platformWindow.h"
#include "gfx/D3D11/screenshotD3D11.h"
#include "materials/shaderData.h"
#ifdef TORQUE_DEBUG
#include "d3d11sdklayers.h"
#endif
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
GFXAdapter::CreateDeviceInstanceDelegate GFXD3D11Device::mCreateDeviceInstance(GFXD3D11Device::createInstance);
GFXDevice *GFXD3D11Device::createInstance(U32 adapterIndex)
{
GFXD3D11Device* dev = new GFXD3D11Device(adapterIndex);
return dev;
}
GFXFormat GFXD3D11Device::selectSupportedFormat(GFXTextureProfile *profile, const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter)
{
U32 features = 0;
if(texture)
features |= D3D11_FORMAT_SUPPORT_TEXTURE2D;
if(mustblend)
features |= D3D11_FORMAT_SUPPORT_BLENDABLE;
if(mustfilter)
features |= D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;
for(U32 i = 0; i < formats.size(); i++)
{
if(GFXD3D11TextureFormat[formats[i]] == DXGI_FORMAT_UNKNOWN)
continue;
U32 supportFlag = 0;
mD3DDevice->CheckFormatSupport(GFXD3D11TextureFormat[formats[i]],&supportFlag);
if(supportFlag & features)
return formats[i];
}
return GFXFormatR8G8B8A8;
}
DXGI_SWAP_CHAIN_DESC GFXD3D11Device::setupPresentParams(const GFXVideoMode &mode, const HWND &hwnd)
{
DXGI_SWAP_CHAIN_DESC d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
DXGI_SAMPLE_DESC sampleDesc;
sampleDesc.Count = 1;
sampleDesc.Quality = 0;
mMultisampleDesc = sampleDesc;
d3dpp.BufferCount = !smDisableVSync ? 2 : 1; // triple buffering when vsync is on.
d3dpp.BufferDesc.Width = mode.resolution.x;
d3dpp.BufferDesc.Height = mode.resolution.y;
d3dpp.BufferDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8];
d3dpp.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
d3dpp.OutputWindow = hwnd;
d3dpp.SampleDesc = sampleDesc;
d3dpp.Windowed = !mode.fullScreen;
d3dpp.BufferDesc.RefreshRate.Numerator = mode.refreshRate;
d3dpp.BufferDesc.RefreshRate.Denominator = 1;
d3dpp.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
if (mode.fullScreen)
{
d3dpp.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
d3dpp.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
d3dpp.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
}
return d3dpp;
}
void GFXD3D11Device::enumerateAdapters(Vector<GFXAdapter*> &adapterList)
{
IDXGIAdapter1* EnumAdapter;
IDXGIFactory1* DXGIFactory;
CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
{
GFXAdapter *toAdd = new GFXAdapter;
toAdd->mType = Direct3D11;
toAdd->mIndex = adapterIndex;
toAdd->mCreateDeviceInstanceDelegate = mCreateDeviceInstance;
toAdd->mShaderModel = 5.0f;
DXGI_ADAPTER_DESC1 desc;
EnumAdapter->GetDesc1(&desc);
// LUID identifies adapter for oculus rift
dMemcpy(&toAdd->mLUID, &desc.AdapterLuid, sizeof(toAdd->mLUID));
size_t size=wcslen(desc.Description);
char *str = new char[size+1];
wcstombs(str, desc.Description,size);
str[size]='\0';
String Description=str;
SAFE_DELETE_ARRAY(str);
dStrncpy(toAdd->mName, Description.c_str(), GFXAdapter::MaxAdapterNameLen);
dStrncat(toAdd->mName, " (D3D11)", GFXAdapter::MaxAdapterNameLen);
IDXGIOutput* pOutput = NULL;
HRESULT hr;
hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
if(hr == DXGI_ERROR_NOT_FOUND)
{
SAFE_RELEASE(EnumAdapter);
break;
}
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> EnumOutputs call failure");
UINT numModes = 0;
DXGI_MODE_DESC* displayModes = NULL;
DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM;
// Get the number of elements
hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
displayModes = new DXGI_MODE_DESC[numModes];
// Get the list
hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
for(U32 numMode = 0; numMode < numModes; ++numMode)
{
GFXVideoMode vmAdd;
vmAdd.fullScreen = true;
vmAdd.bitDepth = 32;
vmAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
vmAdd.resolution.x = displayModes[numMode].Width;
vmAdd.resolution.y = displayModes[numMode].Height;
toAdd->mAvailableModes.push_back(vmAdd);
}
delete[] displayModes;
SAFE_RELEASE(pOutput);
SAFE_RELEASE(EnumAdapter);
adapterList.push_back(toAdd);
}
SAFE_RELEASE(DXGIFactory);
}
void GFXD3D11Device::enumerateVideoModes()
{
mVideoModes.clear();
IDXGIAdapter1* EnumAdapter;
IDXGIFactory1* DXGIFactory;
HRESULT hr;
hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
if (FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> CreateDXGIFactory1 call failure");
for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
{
IDXGIOutput* pOutput = NULL;
hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
if(hr == DXGI_ERROR_NOT_FOUND)
{
SAFE_RELEASE(EnumAdapter);
break;
}
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> EnumOutputs call failure");
UINT numModes = 0;
DXGI_MODE_DESC* displayModes = NULL;
DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8];
// Get the number of elements
hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
displayModes = new DXGI_MODE_DESC[numModes];
// Get the list
hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
for(U32 numMode = 0; numMode < numModes; ++numMode)
{
GFXVideoMode toAdd;
toAdd.fullScreen = false;
toAdd.bitDepth = 32;
toAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
toAdd.resolution.x = displayModes[numMode].Width;
toAdd.resolution.y = displayModes[numMode].Height;
mVideoModes.push_back(toAdd);
}
delete[] displayModes;
SAFE_RELEASE(pOutput);
SAFE_RELEASE(EnumAdapter);
}
SAFE_RELEASE(DXGIFactory);
}
IDXGISwapChain* GFXD3D11Device::getSwapChain()
{
return mSwapChain;
}
void GFXD3D11Device::init(const GFXVideoMode &mode, PlatformWindow *window)
{
AssertFatal(window, "GFXD3D11Device::init - must specify a window!");
HWND winHwnd = (HWND)window->getSystemWindow( PlatformWindow::WindowSystem_Windows );
UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef TORQUE_DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
mDebugLayers = true;
#endif
DXGI_SWAP_CHAIN_DESC d3dpp = setupPresentParams(mode, winHwnd);
D3D_FEATURE_LEVEL deviceFeature;
D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_HARDWARE;// use D3D_DRIVER_TYPE_REFERENCE for reference device
// create a device, device context and swap chain using the information in the d3dpp struct
HRESULT hres = D3D11CreateDeviceAndSwapChain(NULL,
driverType,
NULL,
createDeviceFlags,
NULL,
0,
D3D11_SDK_VERSION,
&d3dpp,
&mSwapChain,
&mD3DDevice,
&deviceFeature,
&mD3DDeviceContext);
if(FAILED(hres))
{
#ifdef TORQUE_DEBUG
//try again without debug device layer enabled
createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
HRESULT hres = D3D11CreateDeviceAndSwapChain(NULL, driverType,NULL,createDeviceFlags,NULL, 0,
D3D11_SDK_VERSION,
&d3dpp,
&mSwapChain,
&mD3DDevice,
&deviceFeature,
&mD3DDeviceContext);
//if we failed again than we definitely have a problem
if (FAILED(hres))
AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
Con::warnf("GFXD3D11Device::init - Debug layers not detected!");
mDebugLayers = false;
#else
AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
#endif
}
//set the fullscreen state here if we need to
if(mode.fullScreen)
{
hres = mSwapChain->SetFullscreenState(TRUE, NULL);
if(FAILED(hres))
{
AssertFatal(false, "GFXD3D11Device::init- Failed to set fullscreen state!");
}
}
mTextureManager = new GFXD3D11TextureManager();
// Now reacquire all the resources we trashed earlier
reacquireDefaultPoolResources();
//TODO implement feature levels?
if (deviceFeature >= D3D_FEATURE_LEVEL_11_0)
mPixVersion = 5.0f;
else
AssertFatal(false, "GFXD3D11Device::init - We don't support anything below feature level 11.");
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
ID3D11Query *testQuery = NULL;
// detect occlusion query support
if (SUCCEEDED(mD3DDevice->CreateQuery(&queryDesc, &testQuery))) mOcclusionQuerySupported = true;
SAFE_RELEASE(testQuery);
Con::printf("Hardware occlusion query detected: %s", mOcclusionQuerySupported ? "Yes" : "No");
mCardProfiler = new GFXD3D11CardProfiler();
mCardProfiler->init();
D3D11_TEXTURE2D_DESC desc;
desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
desc.CPUAccessFlags = 0;
desc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.Width = mode.resolution.x;
desc.Height = mode.resolution.y;
desc.SampleDesc.Count =1;
desc.SampleDesc.Quality =0;
desc.MiscFlags = 0;
HRESULT hr = mD3DDevice->CreateTexture2D(&desc, NULL, &mDeviceDepthStencil);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Device::init - couldn't create device's depth-stencil surface.");
}
D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc;
depthDesc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
depthDesc.Flags =0 ;
depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthDesc.Texture2D.MipSlice = 0;
hr = mD3DDevice->CreateDepthStencilView(mDeviceDepthStencil, &depthDesc, &mDeviceDepthStencilView);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Device::init - couldn't create depth stencil view");
}
hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mDeviceBackbuffer);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::init - coudln't retrieve backbuffer ref");
//create back buffer view
D3D11_RENDER_TARGET_VIEW_DESC RTDesc;
RTDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
RTDesc.Texture2D.MipSlice = 0;
RTDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
hr = mD3DDevice->CreateRenderTargetView(mDeviceBackbuffer, &RTDesc, &mDeviceBackBufferView);
if(FAILED(hr))
AssertFatal(false, "GFXD3D11Device::init - couldn't create back buffer target view");
#ifdef TORQUE_DEBUG
String backBufferName = "MainBackBuffer";
String depthSteniclName = "MainDepthStencil";
String backBuffViewName = "MainBackBuffView";
String depthStencViewName = "MainDepthView";
mDeviceBackbuffer->SetPrivateData(WKPDID_D3DDebugObjectName, backBufferName.size(), backBufferName.c_str());
mDeviceDepthStencil->SetPrivateData(WKPDID_D3DDebugObjectName, depthSteniclName.size(), depthSteniclName.c_str());
mDeviceDepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, depthStencViewName.size(), depthStencViewName.c_str());
mDeviceBackBufferView->SetPrivateData(WKPDID_D3DDebugObjectName, backBuffViewName.size(), backBuffViewName.c_str());
_suppressDebugMessages();
#endif
gScreenShot = new ScreenShotD3D11;
mInitialized = true;
deviceInited();
}
// Supress any debug layer messages we don't want to see
void GFXD3D11Device::_suppressDebugMessages()
{
if (mDebugLayers)
{
ID3D11Debug *pDebug = NULL;
if (SUCCEEDED(mD3DDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&pDebug)))
{
ID3D11InfoQueue *pInfoQueue = NULL;
if (SUCCEEDED(pDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&pInfoQueue)))
{
//Disable breaking on error or corruption, this can be handy when using VS graphics debugging
pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, false);
pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, false);
D3D11_MESSAGE_ID hide[] =
{
//this is harmless and no need to spam the console
D3D11_MESSAGE_ID_QUERY_BEGIN_ABANDONING_PREVIOUS_RESULTS
};
D3D11_INFO_QUEUE_FILTER filter;
memset(&filter, 0, sizeof(filter));
filter.DenyList.NumIDs = _countof(hide);
filter.DenyList.pIDList = hide;
pInfoQueue->AddStorageFilterEntries(&filter);
SAFE_RELEASE(pInfoQueue);
}
SAFE_RELEASE(pDebug);
}
}
}
bool GFXD3D11Device::beginSceneInternal()
{
mCanCurrentlyRender = true;
return mCanCurrentlyRender;
}
GFXWindowTarget * GFXD3D11Device::allocWindowTarget(PlatformWindow *window)
{
AssertFatal(window,"GFXD3D11Device::allocWindowTarget - no window provided!");
// Allocate the device.
init(window->getVideoMode(), window);
// Set up a new window target...
GFXD3D11WindowTarget *gdwt = new GFXD3D11WindowTarget();
gdwt->mWindow = window;
gdwt->mSize = window->getClientExtent();
gdwt->initPresentationParams();
gdwt->registerResourceWithDevice(this);
return gdwt;
}
GFXTextureTarget* GFXD3D11Device::allocRenderToTextureTarget()
{
GFXD3D11TextureTarget *targ = new GFXD3D11TextureTarget();
targ->registerResourceWithDevice(this);
return targ;
}
void GFXD3D11Device::reset(DXGI_SWAP_CHAIN_DESC &d3dpp)
{
if (!mD3DDevice)
return;
mInitialized = false;
// Clean up some commonly dangling state. This helps prevents issues with
// items that are destroyed by the texture manager callbacks and recreated
// later, but still left bound.
setVertexBuffer(NULL);
setPrimitiveBuffer(NULL);
for (S32 i = 0; i<getNumSamplers(); i++)
setTexture(i, NULL);
mD3DDeviceContext->ClearState();
DXGI_MODE_DESC displayModes;
displayModes.Format = d3dpp.BufferDesc.Format;
displayModes.Height = d3dpp.BufferDesc.Height;
displayModes.Width = d3dpp.BufferDesc.Width;
displayModes.RefreshRate = d3dpp.BufferDesc.RefreshRate;
displayModes.Scaling = d3dpp.BufferDesc.Scaling;
displayModes.ScanlineOrdering = d3dpp.BufferDesc.ScanlineOrdering;
HRESULT hr;
if (!d3dpp.Windowed)
{
hr = mSwapChain->ResizeTarget(&displayModes);
if (FAILED(hr))
{
AssertFatal(false, "D3D11Device::reset - failed to resize target!");
}
}
// First release all the stuff we allocated from D3DPOOL_DEFAULT
releaseDefaultPoolResources();
//release the backbuffer, depthstencil, and their views
SAFE_RELEASE(mDeviceBackBufferView);
SAFE_RELEASE(mDeviceBackbuffer);
SAFE_RELEASE(mDeviceDepthStencilView);
SAFE_RELEASE(mDeviceDepthStencil);
hr = mSwapChain->ResizeBuffers(d3dpp.BufferCount, d3dpp.BufferDesc.Width, d3dpp.BufferDesc.Height, d3dpp.BufferDesc.Format, d3dpp.Windowed ? 0 : DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
if (FAILED(hr))
{
AssertFatal(false, "D3D11Device::reset - failed to resize back buffer!");
}
//recreate backbuffer view. depth stencil view and texture
D3D11_TEXTURE2D_DESC desc;
desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
desc.CPUAccessFlags = 0;
desc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.Width = d3dpp.BufferDesc.Width;
desc.Height = d3dpp.BufferDesc.Height;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.MiscFlags = 0;
hr = mD3DDevice->CreateTexture2D(&desc, NULL, &mDeviceDepthStencil);
if (FAILED(hr))
{
AssertFatal(false, "GFXD3D11Device::reset - couldn't create device's depth-stencil surface.");
}
D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc;
depthDesc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
depthDesc.Flags = 0;
depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthDesc.Texture2D.MipSlice = 0;
hr = mD3DDevice->CreateDepthStencilView(mDeviceDepthStencil, &depthDesc, &mDeviceDepthStencilView);
if (FAILED(hr))
{
AssertFatal(false, "GFXD3D11Device::reset - couldn't create depth stencil view");
}
hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mDeviceBackbuffer);
if (FAILED(hr))
AssertFatal(false, "GFXD3D11Device::reset - coudln't retrieve backbuffer ref");
//create back buffer view
D3D11_RENDER_TARGET_VIEW_DESC RTDesc;
RTDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
RTDesc.Texture2D.MipSlice = 0;
RTDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
hr = mD3DDevice->CreateRenderTargetView(mDeviceBackbuffer, &RTDesc, &mDeviceBackBufferView);
if (FAILED(hr))
AssertFatal(false, "GFXD3D11Device::reset - couldn't create back buffer target view");
mD3DDeviceContext->OMSetRenderTargets(1, &mDeviceBackBufferView, mDeviceDepthStencilView);
hr = mSwapChain->SetFullscreenState(!d3dpp.Windowed, NULL);
if (FAILED(hr))
{
AssertFatal(false, "D3D11Device::reset - failed to change screen states!");
}
//Microsoft recommend this, see DXGI documentation
if (!d3dpp.Windowed)
{
displayModes.RefreshRate.Numerator = 0;
displayModes.RefreshRate.Denominator = 0;
hr = mSwapChain->ResizeTarget(&displayModes);
if (FAILED(hr))
{
AssertFatal(false, "D3D11Device::reset - failed to resize target!");
}
}
mInitialized = true;
// Now re aquire all the resources we trashed earlier
reacquireDefaultPoolResources();
// Mark everything dirty and flush to card, for sanity.
updateStates(true);
}
class GFXPCD3D11RegisterDevice
{
public:
GFXPCD3D11RegisterDevice()
{
GFXInit::getRegisterDeviceSignal().notify(&GFXD3D11Device::enumerateAdapters);
}
};
static GFXPCD3D11RegisterDevice pPCD3D11RegisterDevice;
//-----------------------------------------------------------------------------
/// Parse command line arguments for window creation
//-----------------------------------------------------------------------------
static void sgPCD3D11DeviceHandleCommandLine(S32 argc, const char **argv)
{
// useful to pass parameters by command line for d3d (e.g. -dx9 -dx11)
for (U32 i = 1; i < argc; i++)
{
argv[i];
}
}
// Register the command line parsing hook
static ProcessRegisterCommandLine sgCommandLine( sgPCD3D11DeviceHandleCommandLine );
GFXD3D11Device::GFXD3D11Device(U32 index)
{
mDeviceSwizzle32 = &Swizzles::bgra;
GFXVertexColor::setSwizzle( mDeviceSwizzle32 );
mDeviceSwizzle24 = &Swizzles::bgr;
mAdapterIndex = index;
mD3DDevice = NULL;
mVolatileVB = NULL;
mCurrentPB = NULL;
mDynamicPB = NULL;
mLastVertShader = NULL;
mLastPixShader = NULL;
mCanCurrentlyRender = false;
mTextureManager = NULL;
mCurrentStateBlock = NULL;
mResourceListHead = NULL;
mPixVersion = 0.0;
mDrawInstancesCount = 0;
mCardProfiler = NULL;
mDeviceDepthStencil = NULL;
mDeviceBackbuffer = NULL;
mDeviceBackBufferView = NULL;
mDeviceDepthStencilView = NULL;
mCreateFenceType = -1; // Unknown, test on first allocate
mCurrentConstBuffer = NULL;
mOcclusionQuerySupported = false;
mDebugLayers = false;
for(U32 i = 0; i < GS_COUNT; ++i)
mModelViewProjSC[i] = NULL;
// Set up the Enum translation tables
GFXD3D11EnumTranslate::init();
}
GFXD3D11Device::~GFXD3D11Device()
{
// Release our refcount on the current stateblock object
mCurrentStateBlock = NULL;
releaseDefaultPoolResources();
mD3DDeviceContext->ClearState();
mD3DDeviceContext->Flush();
// Free the vertex declarations.
VertexDeclMap::Iterator iter = mVertexDecls.begin();
for ( ; iter != mVertexDecls.end(); iter++ )
delete iter->value;
// Forcibly clean up the pools
mVolatileVBList.setSize(0);
mDynamicPB = NULL;
// And release our D3D resources.
SAFE_RELEASE(mDeviceDepthStencilView);
SAFE_RELEASE(mDeviceBackBufferView);
SAFE_RELEASE(mDeviceDepthStencil);
SAFE_RELEASE(mDeviceBackbuffer);
SAFE_RELEASE(mD3DDeviceContext);
SAFE_DELETE(mCardProfiler);
SAFE_DELETE(gScreenShot);
#ifdef TORQUE_DEBUG
if (mDebugLayers)
{
ID3D11Debug *pDebug = NULL;
mD3DDevice->QueryInterface(IID_PPV_ARGS(&pDebug));
AssertFatal(pDebug, "~GFXD3D11Device- Failed to get debug layer");
pDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
SAFE_RELEASE(pDebug);
}
#endif
SAFE_RELEASE(mSwapChain);
SAFE_RELEASE(mD3DDevice);
}
void GFXD3D11Device::setupGenericShaders(GenericShaderType type)
{
AssertFatal(type != GSTargetRestore, ""); //not used
if(mGenericShader[GSColor] == NULL)
{
ShaderData *shaderData;
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/colorV.hlsl");
shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/colorP.hlsl");
shaderData->setField("pixVersion", "5.0");
shaderData->registerObject();
mGenericShader[GSColor] = shaderData->getShader();
mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/modColorTextureV.hlsl");
shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/modColorTextureP.hlsl");
shaderData->setField("pixVersion", "5.0");
shaderData->registerObject();
mGenericShader[GSModColorTexture] = shaderData->getShader();
mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/addColorTextureV.hlsl");
shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/addColorTextureP.hlsl");
shaderData->setField("pixVersion", "5.0");
shaderData->registerObject();
mGenericShader[GSAddColorTexture] = shaderData->getShader();
mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/textureV.hlsl");
shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/textureP.hlsl");
shaderData->setField("pixVersion", "5.0");
shaderData->registerObject();
mGenericShader[GSTexture] = shaderData->getShader();
mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle("$modelView");
Sim::getRootGroup()->addObject(shaderData);
//Force an update
mViewportDirty = true;
_updateRenderTargets();
}
MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
setShader(mGenericShader[type]);
setShaderConstBuffer(mGenericShaderBuffer[type]);
}
//-----------------------------------------------------------------------------
/// Creates a state block object based on the desc passed in. This object
/// represents an immutable state.
GFXStateBlockRef GFXD3D11Device::createStateBlockInternal(const GFXStateBlockDesc& desc)
{
return GFXStateBlockRef(new GFXD3D11StateBlock(desc));
}
/// Activates a stateblock
void GFXD3D11Device::setStateBlockInternal(GFXStateBlock* block, bool force)
{
AssertFatal(static_cast<GFXD3D11StateBlock*>(block), "Incorrect stateblock type for this device!");
GFXD3D11StateBlock* d3dBlock = static_cast<GFXD3D11StateBlock*>(block);
GFXD3D11StateBlock* d3dCurrent = static_cast<GFXD3D11StateBlock*>(mCurrentStateBlock.getPointer());
if (force)
d3dCurrent = NULL;
d3dBlock->activate(d3dCurrent);
}
/// Called by base GFXDevice to actually set a const buffer
void GFXD3D11Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
{
if (buffer)
{
PROFILE_SCOPE(GFXD3D11Device_setShaderConstBufferInternal);
AssertFatal(static_cast<GFXD3D11ShaderConstBuffer*>(buffer), "Incorrect shader const buffer type for this device!");
GFXD3D11ShaderConstBuffer* d3dBuffer = static_cast<GFXD3D11ShaderConstBuffer*>(buffer);
d3dBuffer->activate(mCurrentConstBuffer);
mCurrentConstBuffer = d3dBuffer;
}
else
{
mCurrentConstBuffer = NULL;
}
}
//-----------------------------------------------------------------------------
void GFXD3D11Device::clear(U32 flags, ColorI color, F32 z, U32 stencil)
{
// Make sure we have flushed our render target state.
_updateRenderTargets();
UINT depthstencilFlag = 0;
ID3D11RenderTargetView* rtView = NULL;
ID3D11DepthStencilView* dsView = NULL;
mD3DDeviceContext->OMGetRenderTargets(1, &rtView, &dsView);
const FLOAT clearColor[4] = {
static_cast<F32>(color.red) * (1.0f / 255.0f),
static_cast<F32>(color.green) * (1.0f / 255.0f),
static_cast<F32>(color.blue) * (1.0f / 255.0f),
static_cast<F32>(color.alpha) * (1.0f / 255.0f)
};
if (flags & GFXClearTarget && rtView)
mD3DDeviceContext->ClearRenderTargetView(rtView, clearColor);
if (flags & GFXClearZBuffer)
depthstencilFlag |= D3D11_CLEAR_DEPTH;
if (flags & GFXClearStencil)
depthstencilFlag |= D3D11_CLEAR_STENCIL;
if (depthstencilFlag && dsView)
mD3DDeviceContext->ClearDepthStencilView(dsView, depthstencilFlag, z, stencil);
SAFE_RELEASE(rtView);
SAFE_RELEASE(dsView);
}
void GFXD3D11Device::endSceneInternal()
{
mCanCurrentlyRender = false;
}
void GFXD3D11Device::_updateRenderTargets()
{
if (mRTDirty || (mCurrentRT && mCurrentRT->isPendingState()))
{
if (mRTDeactivate)
{
mRTDeactivate->deactivate();
mRTDeactivate = NULL;
}
// NOTE: The render target changes are not really accurate
// as the GFXTextureTarget supports MRT internally. So when
// we activate a GFXTarget it could result in multiple calls
// to SetRenderTarget on the actual device.
mDeviceStatistics.mRenderTargetChanges++;
mCurrentRT->activate();
mRTDirty = false;
}
if (mViewportDirty)
{
D3D11_VIEWPORT viewport;
viewport.TopLeftX = mViewport.point.x;
viewport.TopLeftY = mViewport.point.y;
viewport.Width = mViewport.extent.x;
viewport.Height = mViewport.extent.y;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
mD3DDeviceContext->RSSetViewports(1, &viewport);
mViewportDirty = false;
}
}
void GFXD3D11Device::releaseDefaultPoolResources()
{
// Release all the dynamic vertex buffer arrays
// Forcibly clean up the pools
for(U32 i=0; i<mVolatileVBList.size(); i++)
{
SAFE_RELEASE(mVolatileVBList[i]->vb);
mVolatileVBList[i] = NULL;
}
mVolatileVBList.setSize(0);
// We gotta clear the current const buffer else the next
// activate may erroneously think the device is still holding
// this state and fail to set it.
mCurrentConstBuffer = NULL;
// Set current VB to NULL and set state dirty
for (U32 i=0; i < VERTEX_STREAM_COUNT; i++)
{
mCurrentVertexBuffer[i] = NULL;
mVertexBufferDirty[i] = true;
mVertexBufferFrequency[i] = 0;
mVertexBufferFrequencyDirty[i] = true;
}
// Release dynamic index buffer
if(mDynamicPB != NULL)
{
SAFE_RELEASE(mDynamicPB->ib);
}
// Set current PB/IB to NULL and set state dirty
mCurrentPrimitiveBuffer = NULL;
mCurrentPB = NULL;
mPrimitiveBufferDirty = true;
// Zombify texture manager (for D3D this only modifies default pool textures)
if( mTextureManager )
mTextureManager->zombify();
// Set global dirty state so the IB/PB and VB get reset
mStateDirty = true;
// Walk the resource list and zombify everything.
GFXResource *walk = mResourceListHead;
while(walk)
{
walk->zombify();
walk = walk->getNextResource();
}
}
void GFXD3D11Device::reacquireDefaultPoolResources()
{
// Now do the dynamic index buffers
if( mDynamicPB == NULL )
mDynamicPB = new GFXD3D11PrimitiveBuffer(this, 0, 0, GFXBufferTypeDynamic);
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(U16) * MAX_DYNAMIC_INDICES;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &mDynamicPB->ib);
if(FAILED(hr))
{
AssertFatal(false, "Failed to allocate dynamic IB");
}
// Walk the resource list and zombify everything.
GFXResource *walk = mResourceListHead;
while(walk)
{
walk->resurrect();
walk = walk->getNextResource();
}
if(mTextureManager)
mTextureManager->resurrect();
}
GFXD3D11VertexBuffer* GFXD3D11Device::findVBPool( const GFXVertexFormat *vertexFormat, U32 vertsNeeded )
{
PROFILE_SCOPE( GFXD3D11Device_findVBPool );
for( U32 i=0; i<mVolatileVBList.size(); i++ )
if( mVolatileVBList[i]->mVertexFormat.isEqual( *vertexFormat ) )
return mVolatileVBList[i];
return NULL;
}
GFXD3D11VertexBuffer * GFXD3D11Device::createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize )
{
PROFILE_SCOPE( GFXD3D11Device_createVBPool );
// this is a bit funky, but it will avoid problems with (lack of) copy constructors
// with a push_back() situation
mVolatileVBList.increment();
StrongRefPtr<GFXD3D11VertexBuffer> newBuff;
mVolatileVBList.last() = new GFXD3D11VertexBuffer();
newBuff = mVolatileVBList.last();
newBuff->mNumVerts = 0;
newBuff->mBufferType = GFXBufferTypeVolatile;
newBuff->mVertexFormat.copy( *vertexFormat );
newBuff->mVertexSize = vertSize;
newBuff->mDevice = this;
// Requesting it will allocate it.
vertexFormat->getDecl();
D3D11_BUFFER_DESC desc;
desc.ByteWidth = vertSize * MAX_DYNAMIC_VERTS;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &newBuff->vb);
if(FAILED(hr))
{
AssertFatal(false, "Failed to allocate dynamic VB");
}
return newBuff;
}
//-----------------------------------------------------------------------------
void GFXD3D11Device::setClipRect( const RectI &inRect )
{
// We transform the incoming rect by the view
// matrix first, so that it can be used to pan
// and scale the clip rect.
//
// This is currently used to take tiled screenshots.
Point3F pos( inRect.point.x, inRect.point.y, 0.0f );
Point3F extent( inRect.extent.x, inRect.extent.y, 0.0f );
getViewMatrix().mulP( pos );
getViewMatrix().mulV( extent );
RectI rect( pos.x, pos.y, extent.x, extent.y );
// Clip the rect against the renderable size.
Point2I size = mCurrentRT->getSize();
RectI maxRect(Point2I(0,0), size);
rect.intersect(maxRect);
mClipRect = rect;
F32 l = F32( mClipRect.point.x );
F32 r = F32( mClipRect.point.x + mClipRect.extent.x );
F32 b = F32( mClipRect.point.y + mClipRect.extent.y );
F32 t = F32( mClipRect.point.y );
// Set up projection matrix,
static Point4F pt;
pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f);
mTempMatrix.setColumn(0, pt);
pt.set(0.0f, 2.0f/(t - b), 0.0f, 0.0f);
mTempMatrix.setColumn(1, pt);
pt.set(0.0f, 0.0f, 1.0f, 0.0f);
mTempMatrix.setColumn(2, pt);
pt.set((l+r)/(l-r), (t+b)/(b-t), 1.0f, 1.0f);
mTempMatrix.setColumn(3, pt);
setProjectionMatrix( mTempMatrix );
// Set up world/view matrix
mTempMatrix.identity();
setWorldMatrix( mTempMatrix );
setViewport( mClipRect );
}
void GFXD3D11Device::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
{
GFXD3D11VertexBuffer *d3dBuffer = static_cast<GFXD3D11VertexBuffer*>( buffer );
if ( stream == 0 )
{
// Set the volatile buffer which is used to
// offset the start index when doing draw calls.
if ( d3dBuffer && d3dBuffer->mVolatileStart > 0 )
mVolatileVB = d3dBuffer;
else
mVolatileVB = NULL;
}
// NOTE: We do not use the stream offset here for stream 0
// as that feature is *supposedly* not as well supported as
// using the start index in drawPrimitive.
//
// If we can verify that this is not the case then we should
// start using this method exclusively for all streams.
U32 strides[1] = { d3dBuffer ? d3dBuffer->mVertexSize : 0 };
U32 offset = d3dBuffer && stream != 0 ? d3dBuffer->mVolatileStart * d3dBuffer->mVertexSize : 0;
ID3D11Buffer* buff = d3dBuffer ? d3dBuffer->vb : NULL;
getDeviceContext()->IASetVertexBuffers(stream, 1, &buff, strides, &offset);
}
void GFXD3D11Device::setVertexStreamFrequency( U32 stream, U32 frequency )
{
if (stream == 0)
mDrawInstancesCount = frequency; // instances count
}
void GFXD3D11Device::_setPrimitiveBuffer( GFXPrimitiveBuffer *buffer )
{
mCurrentPB = static_cast<GFXD3D11PrimitiveBuffer *>( buffer );
mD3DDeviceContext->IASetIndexBuffer(mCurrentPB->ib, DXGI_FORMAT_R16_UINT, 0);
}
U32 GFXD3D11Device::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
{
switch (primType)
{
case GFXPointList:
return primitiveCount;
break;
case GFXLineList:
return primitiveCount * 2;
break;
case GFXLineStrip:
return primitiveCount + 1;
break;
case GFXTriangleList:
return primitiveCount * 3;
break;
case GFXTriangleStrip:
return 2 + primitiveCount;
break;
default:
AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
break;
}
return 0;
}
void GFXD3D11Device::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
{
// This is done to avoid the function call overhead if possible
if( mStateDirty )
updateStates();
if (mCurrentShaderConstBuffer)
setShaderConstBufferInternal(mCurrentShaderConstBuffer);
if ( mVolatileVB )
vertexStart += mVolatileVB->mVolatileStart;
mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]);
if ( mDrawInstancesCount )
mD3DDeviceContext->DrawInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, vertexStart, 0);
else
mD3DDeviceContext->Draw(primCountToIndexCount(primType, primitiveCount), vertexStart);
mDeviceStatistics.mDrawCalls++;
if ( mVertexBufferFrequency[0] > 1 )
mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
else
mDeviceStatistics.mPolyCount += primitiveCount;
}
void GFXD3D11Device::drawIndexedPrimitive( GFXPrimitiveType primType,
U32 startVertex,
U32 minIndex,
U32 numVerts,
U32 startIndex,
U32 primitiveCount )
{
// This is done to avoid the function call overhead if possible
if( mStateDirty )
updateStates();
if (mCurrentShaderConstBuffer)
setShaderConstBufferInternal(mCurrentShaderConstBuffer);
AssertFatal( mCurrentPB != NULL, "Trying to call drawIndexedPrimitive with no current index buffer, call setIndexBuffer()" );
if ( mVolatileVB )
startVertex += mVolatileVB->mVolatileStart;
mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]);
if ( mDrawInstancesCount )
mD3DDeviceContext->DrawIndexedInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, mCurrentPB->mVolatileStart + startIndex, startVertex, 0);
else
mD3DDeviceContext->DrawIndexed(primCountToIndexCount(primType,primitiveCount), mCurrentPB->mVolatileStart + startIndex, startVertex);
mDeviceStatistics.mDrawCalls++;
if ( mVertexBufferFrequency[0] > 1 )
mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
else
mDeviceStatistics.mPolyCount += primitiveCount;
}
GFXShader* GFXD3D11Device::createShader()
{
GFXD3D11Shader* shader = new GFXD3D11Shader();
shader->registerResourceWithDevice( this );
return shader;
}
//-----------------------------------------------------------------------------
// Set shader - this function exists to make sure this is done in one place,
// and to make sure redundant shader states are not being
// sent to the card.
//-----------------------------------------------------------------------------
void GFXD3D11Device::setShader(GFXShader *shader, bool force)
{
if(shader)
{
GFXD3D11Shader *d3dShader = static_cast<GFXD3D11Shader*>(shader);
if (d3dShader->mPixShader != mLastPixShader || force)
{
mD3DDeviceContext->PSSetShader( d3dShader->mPixShader, NULL, 0);
mLastPixShader = d3dShader->mPixShader;
}
if (d3dShader->mVertShader != mLastVertShader || force)
{
mD3DDeviceContext->VSSetShader( d3dShader->mVertShader, NULL, 0);
mLastVertShader = d3dShader->mVertShader;
}
}
else
{
setupGenericShaders();
}
}
GFXPrimitiveBuffer * GFXD3D11Device::allocPrimitiveBuffer(U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void *data )
{
// Allocate a buffer to return
GFXD3D11PrimitiveBuffer * res = new GFXD3D11PrimitiveBuffer(this, numIndices, numPrimitives, bufferType);
// Determine usage flags
D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
// Assumptions:
// - static buffers are write once, use many
// - dynamic buffers are write many, use many
// - volatile buffers are write once, use once
// You may never read from a buffer.
//TODO: enable proper support for D3D11_USAGE_IMMUTABLE
switch(bufferType)
{
case GFXBufferTypeImmutable:
case GFXBufferTypeStatic:
usage = D3D11_USAGE_DEFAULT; //D3D11_USAGE_IMMUTABLE;
break;
case GFXBufferTypeDynamic:
case GFXBufferTypeVolatile:
usage = D3D11_USAGE_DYNAMIC;
break;
}
// Register resource
res->registerResourceWithDevice(this);
// Create d3d index buffer
if(bufferType == GFXBufferTypeVolatile)
{
// Get it from the pool if it's a volatile...
AssertFatal(numIndices < MAX_DYNAMIC_INDICES, "Cannot allocate that many indices in a volatile buffer, increase MAX_DYNAMIC_INDICES.");
res->ib = mDynamicPB->ib;
res->mVolatileBuffer = mDynamicPB;
}
else
{
// Otherwise, get it as a seperate buffer...
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(U16) * numIndices;
desc.Usage = usage;
if(bufferType == GFXBufferTypeDynamic)
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a primitive buffer.
else
desc.CPUAccessFlags = 0;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->ib);
if(FAILED(hr))
{
AssertFatal(false, "Failed to allocate an index buffer.");
}
}
if (data)
{
void* dest;
res->lock(0, numIndices, &dest);
dMemcpy(dest, data, sizeof(U16) * numIndices);
res->unlock();
}
return res;
}
GFXVertexBuffer * GFXD3D11Device::allocVertexBuffer(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize, GFXBufferType bufferType, void *data)
{
PROFILE_SCOPE( GFXD3D11Device_allocVertexBuffer );
GFXD3D11VertexBuffer *res = new GFXD3D11VertexBuffer( this,
numVerts,
vertexFormat,
vertSize,
bufferType );
// Determine usage flags
D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
res->mNumVerts = 0;
// Assumptions:
// - static buffers are write once, use many
// - dynamic buffers are write many, use many
// - volatile buffers are write once, use once
// You may never read from a buffer.
//TODO: enable proper support for D3D11_USAGE_IMMUTABLE
switch(bufferType)
{
case GFXBufferTypeImmutable:
case GFXBufferTypeStatic:
usage = D3D11_USAGE_DEFAULT;
break;
case GFXBufferTypeDynamic:
case GFXBufferTypeVolatile:
usage = D3D11_USAGE_DYNAMIC;
break;
}
// Register resource
res->registerResourceWithDevice(this);
// Create vertex buffer
if(bufferType == GFXBufferTypeVolatile)
{
// NOTE: Volatile VBs are pooled and will be allocated at lock time.
AssertFatal(numVerts <= MAX_DYNAMIC_VERTS, "GFXD3D11Device::allocVertexBuffer - Volatile vertex buffer is too big... see MAX_DYNAMIC_VERTS!");
}
else
{
// Requesting it will allocate it.
vertexFormat->getDecl(); //-ALEX disabled to postpone until after shader is actually set...
// Get a new buffer...
D3D11_BUFFER_DESC desc;
desc.ByteWidth = vertSize * numVerts;
desc.Usage = usage;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
if(bufferType == GFXBufferTypeDynamic)
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a vertex buffer.
else
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->vb);
if(FAILED(hr))
{
AssertFatal(false, "Failed to allocate VB");
}
}
res->mNumVerts = numVerts;
if (data)
{
void* dest;
res->lock(0, numVerts, &dest);
dMemcpy(dest, data, vertSize * numVerts);
res->unlock();
}
return res;
}
String GFXD3D11Device::_createTempShaderInternal(const GFXVertexFormat *vertexFormat)
{
U32 elemCount = vertexFormat->getElementCount();
//Input data
StringBuilder inputData;
inputData.append("struct VertIn {");
//Output data
StringBuilder outputData;
outputData.append("struct VertOut {");
// Shader main body data
StringBuilder mainBodyData;
//make shader
mainBodyData.append("VertOut main(VertIn IN){VertOut OUT;");
bool addedPadding = false;
for (U32 i = 0; i < elemCount; i++)
{
const GFXVertexElement &element = vertexFormat->getElement(i);
String semantic = element.getSemantic();
String semanticOut = semantic;
String type;
AssertFatal(!(addedPadding && !element.isSemantic(GFXSemantic::PADDING)), "Padding added before data");
if (element.isSemantic(GFXSemantic::POSITION))
{
semantic = "POSITION";
semanticOut = "SV_Position";
}
else if (element.isSemantic(GFXSemantic::NORMAL))
{
semantic = "NORMAL";
semanticOut = semantic;
}
else if (element.isSemantic(GFXSemantic::COLOR))
{
semantic = "COLOR";
semanticOut = semantic;
}
else if (element.isSemantic(GFXSemantic::TANGENT))
{
semantic = "TANGENT";
semanticOut = semantic;
}
else if (element.isSemantic(GFXSemantic::BINORMAL))
{
semantic = "BINORMAL";
semanticOut = semantic;
}
else if (element.isSemantic(GFXSemantic::BLENDINDICES))
{
semantic = String::ToString("BLENDINDICES%d", element.getSemanticIndex());
semanticOut = semantic;
}
else if (element.isSemantic(GFXSemantic::BLENDWEIGHT))
{
semantic = String::ToString("BLENDWEIGHT%d", element.getSemanticIndex());
semanticOut = semantic;
}
else if (element.isSemantic(GFXSemantic::PADDING))
{
addedPadding = true;
continue;
}
else
{
//Anything that falls thru to here will be a texture coord.
semantic = String::ToString("TEXCOORD%d", element.getSemanticIndex());
semanticOut = semantic;
}
switch (GFXD3D11DeclType[element.getType()])
{
case DXGI_FORMAT_R32_FLOAT:
type = "float";
break;
case DXGI_FORMAT_R32G32_FLOAT:
type = "float2";
break;
case DXGI_FORMAT_R32G32B32_FLOAT:
type = "float3";
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM:
type = "float4";
break;
case DXGI_FORMAT_R8G8B8A8_UINT:
type = "uint4";
break;
}
StringBuilder in;
in.format("%s %s%d : %s;", type.c_str(), "var", i, semantic.c_str());
inputData.append(in.data());
//SV_Position must be float4
if (semanticOut == String("SV_Position"))
{
StringBuilder out;
out.format("float4 %s%d : %s;", "var", i, semanticOut.c_str());
outputData.append(out.data());
StringBuilder body;
body.format("OUT.%s%d = float4(IN.%s%d.xyz,1);", "var", i, "var", i);
mainBodyData.append(body.data());
}
else
{
StringBuilder out;
out.format("%s %s%d : %s;", type.c_str(), "var", i, semanticOut.c_str());
outputData.append(out.data());
StringBuilder body;
body.format("OUT.%s%d = IN.%s%d;", "var", i, "var", i);
mainBodyData.append(body.data());
}
}
inputData.append("};");
outputData.append("};");
mainBodyData.append("return OUT;}");
//final data
StringBuilder finalData;
finalData.append(inputData.data());
finalData.append(outputData.data());
finalData.append(mainBodyData.data());
return String(finalData.data());
}
GFXVertexDecl* GFXD3D11Device::allocVertexDecl( const GFXVertexFormat *vertexFormat )
{
PROFILE_SCOPE( GFXD3D11Device_allocVertexDecl );
// First check the map... you shouldn't allocate VBs very often
// if you want performance. The map lookup should never become
// a performance bottleneck.
D3D11VertexDecl *decl = mVertexDecls[vertexFormat->getDescription()];
if ( decl )
return decl;
U32 elemCount = vertexFormat->getElementCount();
ID3DBlob* code = NULL;
// We have to generate a temporary shader here for now since the input layout creation
// expects a shader to be already compiled to verify the vertex layout structure. The problem
// is that most of the time the regular shaders are compiled AFTER allocVertexDecl is called.
if(!decl)
{
//TODO: Perhaps save/cache the ID3DBlob for later use on identical vertex formats,save creating/compiling the temp shader everytime
String shaderData = _createTempShaderInternal(vertexFormat);
#ifdef TORQUE_DEBUG
U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#else
U32 flags = D3DCOMPILE_ENABLE_STRICTNESS;
#endif
ID3DBlob *errorBlob = NULL;
HRESULT hr = D3DCompile(shaderData.c_str(), shaderData.length(), NULL, NULL, NULL, "main", "vs_5_0", flags, 0, &code, &errorBlob);
StringBuilder error;
if(errorBlob)
{
error.append((char*)errorBlob->GetBufferPointer(), errorBlob->GetBufferSize());
AssertFatal(hr, error.data());
}
SAFE_RELEASE(errorBlob);
}
AssertFatal(code, "D3D11Device::allocVertexDecl - compiled vert shader code missing!");
// Setup the declaration struct.
U32 stream;
D3D11_INPUT_ELEMENT_DESC *vd = new D3D11_INPUT_ELEMENT_DESC[ elemCount];
S32 elemIndex = 0;
for (S32 i = 0; i < elemCount; i++, elemIndex++)
{
const GFXVertexElement &element = vertexFormat->getElement(elemIndex);
stream = element.getStreamIndex();
vd[i].InputSlot = stream;
vd[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
vd[i].Format = GFXD3D11DeclType[element.getType()];
// If instancing is enabled, the per instance data is only used on stream 1.
if (vertexFormat->hasInstancing() && stream == 1)
{
vd[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
vd[i].InstanceDataStepRate = 1;
}
else
{
vd[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
vd[i].InstanceDataStepRate = 0;
}
// We force the usage index of 0 for everything but
// texture coords for now... this may change later.
vd[i].SemanticIndex = 0;
if (element.isSemantic(GFXSemantic::POSITION))
vd[i].SemanticName = "POSITION";
else if (element.isSemantic(GFXSemantic::NORMAL))
vd[i].SemanticName = "NORMAL";
else if (element.isSemantic(GFXSemantic::COLOR))
vd[i].SemanticName = "COLOR";
else if (element.isSemantic(GFXSemantic::TANGENT))
vd[i].SemanticName = "TANGENT";
else if (element.isSemantic(GFXSemantic::BINORMAL))
vd[i].SemanticName = "BINORMAL";
else if (element.isSemantic(GFXSemantic::BLENDWEIGHT))
{
vd[i].SemanticName = "BLENDWEIGHT";
vd[i].SemanticIndex = element.getSemanticIndex();
}
else if (element.isSemantic(GFXSemantic::BLENDINDICES))
{
vd[i].SemanticName = "BLENDINDICES";
vd[i].SemanticIndex = element.getSemanticIndex();
}
else if (element.isSemantic(GFXSemantic::PADDING))
{
i--;
elemCount--;
continue;
}
else
{
//Anything that falls thru to here will be a texture coord.
vd[i].SemanticName = "TEXCOORD";
vd[i].SemanticIndex = element.getSemanticIndex();
}
}
decl = new D3D11VertexDecl();
HRESULT hr = mD3DDevice->CreateInputLayout(vd, elemCount,code->GetBufferPointer(), code->GetBufferSize(), &decl->decl);
if (FAILED(hr))
{
AssertFatal(false, "GFXD3D11Device::allocVertexDecl - Failed to create vertex input layout!");
}
delete [] vd;
SAFE_RELEASE(code);
// Store it in the cache.
mVertexDecls[vertexFormat->getDescription()] = decl;
return decl;
}
void GFXD3D11Device::setVertexDecl( const GFXVertexDecl *decl )
{
ID3D11InputLayout *dx11Decl = NULL;
if (decl)
dx11Decl = static_cast<const D3D11VertexDecl*>(decl)->decl;
mD3DDeviceContext->IASetInputLayout(dx11Decl);
}
//-----------------------------------------------------------------------------
// This function should ONLY be called from GFXDevice::updateStates() !!!
//-----------------------------------------------------------------------------
void GFXD3D11Device::setTextureInternal( U32 textureUnit, const GFXTextureObject *texture)
{
if( texture == NULL )
{
ID3D11ShaderResourceView *pView = NULL;
mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, &pView);
return;
}
GFXD3D11TextureObject *tex = (GFXD3D11TextureObject*)(texture);
mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, tex->getSRViewPtr());
}
GFXFence *GFXD3D11Device::createFence()
{
// Figure out what fence type we should be making if we don't know
if( mCreateFenceType == -1 )
{
D3D11_QUERY_DESC desc;
desc.MiscFlags = 0;
desc.Query = D3D11_QUERY_EVENT;
ID3D11Query *testQuery = NULL;
HRESULT hRes = mD3DDevice->CreateQuery(&desc, &testQuery);
if(FAILED(hRes))
{
mCreateFenceType = true;
}
else
{
mCreateFenceType = false;
}
SAFE_RELEASE(testQuery);
}
// Cool, use queries
if(!mCreateFenceType)
{
GFXFence* fence = new GFXD3D11QueryFence( this );
fence->registerResourceWithDevice(this);
return fence;
}
// CodeReview: At some point I would like a specialized implementation of
// the method used by the general fence, only without the overhead incurred
// by using the GFX constructs. Primarily the lock() method on texture handles
// will do a data copy, and this method doesn't require a copy, just a lock
// [5/10/2007 Pat]
GFXFence* fence = new GFXGeneralFence( this );
fence->registerResourceWithDevice(this);
return fence;
}
GFXOcclusionQuery* GFXD3D11Device::createOcclusionQuery()
{
GFXOcclusionQuery *query;
if (mOcclusionQuerySupported)
query = new GFXD3D11OcclusionQuery( this );
else
return NULL;
query->registerResourceWithDevice(this);
return query;
}
GFXCubemap * GFXD3D11Device::createCubemap()
{
GFXD3D11Cubemap* cube = new GFXD3D11Cubemap();
cube->registerResourceWithDevice(this);
return cube;
} | 56,756 | 20,410 |
#ifndef __POOL_HPP__
#define __POOL_HPP__
#include <algorithm>
#include <deque>
#include "Mutex.hpp"
namespace osl {
template <typename T>
class Pool {
private:
Mutex _avail_lock;
Mutex _work_lock;
std::deque<T*> _avails;
std::deque<T*> _works;
size_t _size;
public:
Pool(size_t size) : _size(size) {
alloc();
}
virtual ~Pool() {
clear();
}
protected:
void alloc() {
for (size_t i = 0; i < _size; i++) {
T * t = new T;
_avails.push_back(t);
}
}
void clear() {
for (typename std::deque<T*>::iterator iter = _avails.begin(); iter != _avails.end(); iter++) {
delete *iter;
}
for (typename std::deque<T*>::iterator iter = _works.begin(); iter != _works.end(); iter++) {
delete *iter;
}
_avails.clear();
_works.clear();
}
public:
void lock_avail() {
_avail_lock.lock();
}
void unlock_avail() {
_avail_lock.unlock();
}
void lock_work() {
_work_lock.lock();
}
void unlock_work() {
_work_lock.unlock();
}
T * acquire() {
_avail_lock.lock();
T * item = _avails.size() > 0 ? _avails.front() : NULL;
if (item) {
_avails.pop_front();
}
_avail_lock.unlock();
return item;
}
void release(T * t) {
_avail_lock.lock();
if (std::find(_avails.begin(), _avails.end(), t) == _avails.end()) {
_avails.push_back(t);
}
_avail_lock.unlock();
}
void enqueue(T * t) {
_work_lock.lock();
if (std::find(_works.begin(), _works.end(), t) == _works.end()) {
_works.push_back(t);
}
_work_lock.unlock();
}
T * dequeue() {
_work_lock.lock();
T * item = _works.size() > 0 ? _works.front() : NULL;
if (item) {
_works.pop_front();
}
_work_lock.unlock();
return item;
}
void rest(T * t) {
_work_lock.lock();
for (typename std::deque<T*>::iterator iter = _works.begin(); iter != _works.end(); iter++) {
if (*iter == t) {
_works.erase(iter);
break;
}
}
_work_lock.unlock();
}
size_t available() const {
return _avails.size();
}
size_t busy() const {
return _works.size();
}
std::deque<T*> & avail_queue() {
return _avails;
}
std::deque<T*> & work_queue() {
return _works;
}
size_t size() const {
return _size;
}
};
}
#endif
| 2,304 | 1,000 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "stim/dem/detector_error_model.h"
#include <gtest/gtest.h>
#include "stim/test_util.test.h"
using namespace stim;
TEST(detector_error_model, init_equality) {
DetectorErrorModel model1;
DetectorErrorModel model2;
ASSERT_TRUE(model1 == model2);
ASSERT_TRUE(!(model1 != model2));
model1.append_shift_detectors_instruction({}, 5);
ASSERT_TRUE(model1 != model2);
ASSERT_TRUE(!(model1 == model2));
model2.append_shift_detectors_instruction({}, 4);
ASSERT_NE(model1, model2);
model1.clear();
model2.clear();
ASSERT_EQ(model1, model2);
model1.append_repeat_block(5, {});
model2.append_repeat_block(4, {});
ASSERT_NE(model1, model2);
model1.append_error_instruction(0.2, {});
model2.append_repeat_block(4, {});
ASSERT_NE(model1, model2);
}
TEST(detector_error_model, append_shift_detectors_instruction) {
DetectorErrorModel model;
ASSERT_EQ(model.instructions.size(), 0);
ASSERT_EQ(model.blocks.size(), 0);
std::vector<double> arg_data{1.5, 2.5};
ConstPointerRange<double> arg_data_ref = arg_data;
model.append_shift_detectors_instruction(arg_data_ref, 5);
ASSERT_EQ(model.instructions.size(), 1);
ASSERT_EQ(model.instructions[0].type, DEM_SHIFT_DETECTORS);
ASSERT_EQ(model.instructions[0].target_data.size(), 1);
ASSERT_EQ(model.instructions[0].target_data[0].data, 5);
ASSERT_EQ(model.instructions[0].arg_data, arg_data_ref);
ASSERT_EQ(model.blocks.size(), 0);
}
TEST(detector_error_model, append_detector_instruction) {
DetectorErrorModel model;
ASSERT_EQ(model.instructions.size(), 0);
ASSERT_EQ(model.blocks.size(), 0);
std::vector<double> arg_data{1.5, 2.5};
ConstPointerRange<double> arg_data_ref = arg_data;
model.append_detector_instruction(arg_data_ref, DemTarget::relative_detector_id(5));
ASSERT_EQ(model.instructions.size(), 1);
ASSERT_EQ(model.instructions[0].type, DEM_DETECTOR);
ASSERT_EQ(model.instructions[0].target_data.size(), 1);
ASSERT_EQ(model.instructions[0].target_data[0], DemTarget::relative_detector_id(5));
ASSERT_EQ(model.instructions[0].arg_data, arg_data_ref);
ASSERT_EQ(model.blocks.size(), 0);
ASSERT_THROW({ model.append_detector_instruction({}, DemTarget::separator()); }, std::invalid_argument);
ASSERT_THROW({ model.append_detector_instruction({}, DemTarget::observable_id(4)); }, std::invalid_argument);
model.append_detector_instruction({}, DemTarget::relative_detector_id(4));
}
TEST(detector_error_model, append_logical_observable_instruction) {
DetectorErrorModel model;
ASSERT_EQ(model.instructions.size(), 0);
ASSERT_EQ(model.blocks.size(), 0);
model.append_logical_observable_instruction(DemTarget::observable_id(5));
ASSERT_EQ(model.instructions.size(), 1);
ASSERT_EQ(model.instructions[0].type, DEM_LOGICAL_OBSERVABLE);
ASSERT_EQ(model.instructions[0].target_data.size(), 1);
ASSERT_EQ(model.instructions[0].target_data[0], DemTarget::observable_id(5));
ASSERT_EQ(model.instructions[0].arg_data.size(), 0);
ASSERT_EQ(model.blocks.size(), 0);
ASSERT_THROW({ model.append_logical_observable_instruction(DemTarget::separator()); }, std::invalid_argument);
ASSERT_THROW(
{ model.append_logical_observable_instruction(DemTarget::relative_detector_id(4)); }, std::invalid_argument);
model.append_logical_observable_instruction(DemTarget::observable_id(4));
}
TEST(detector_error_model, append_error_instruction) {
DetectorErrorModel model;
std::vector<DemTarget> symptoms;
symptoms.push_back(DemTarget::observable_id(3));
symptoms.push_back(DemTarget::relative_detector_id(4));
model.append_error_instruction(0.25, symptoms);
ASSERT_EQ(model.instructions.size(), 1);
ASSERT_EQ(model.blocks.size(), 0);
ASSERT_EQ(model.instructions[0].type, DEM_ERROR);
ASSERT_EQ(model.instructions[0].target_data, (PointerRange<DemTarget>)symptoms);
ASSERT_EQ(model.instructions[0].arg_data.size(), 1);
ASSERT_EQ(model.instructions[0].arg_data[0], 0.25);
model.clear();
ASSERT_EQ(model.instructions.size(), 0);
symptoms.push_back(DemTarget::separator());
symptoms.push_back(DemTarget::observable_id(4));
model.append_error_instruction(0.125, symptoms);
ASSERT_EQ(model.instructions.size(), 1);
ASSERT_EQ(model.blocks.size(), 0);
ASSERT_EQ(model.instructions[0].type, DEM_ERROR);
ASSERT_EQ(model.instructions[0].target_data, (PointerRange<DemTarget>)symptoms);
ASSERT_EQ(model.instructions[0].arg_data.size(), 1);
ASSERT_EQ(model.instructions[0].arg_data[0], 0.125);
ASSERT_THROW({ model.append_error_instruction(1.5, symptoms); }, std::invalid_argument);
ASSERT_THROW({ model.append_error_instruction(-0.5, symptoms); }, std::invalid_argument);
symptoms = {DemTarget::separator()};
ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument);
symptoms = {DemTarget::separator(), DemTarget::observable_id(0)};
ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument);
symptoms = {DemTarget::observable_id(0), DemTarget::separator()};
ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument);
symptoms = {
DemTarget::observable_id(0),
DemTarget::separator(),
DemTarget::separator(),
DemTarget::relative_detector_id(4)};
ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument);
symptoms = {DemTarget::observable_id(0), DemTarget::separator(), DemTarget::relative_detector_id(4)};
model.append_error_instruction(0.25, symptoms);
}
TEST(detector_error_model, append_block) {
DetectorErrorModel model;
DetectorErrorModel block;
block.append_shift_detectors_instruction({}, 3);
DetectorErrorModel block2 = block;
model.append_repeat_block(5, block);
block.append_shift_detectors_instruction({}, 4);
model.append_repeat_block(6, std::move(block));
model.append_repeat_block(20, block2);
ASSERT_EQ(model.instructions.size(), 3);
ASSERT_EQ(model.blocks.size(), 3);
ASSERT_EQ(model.instructions[0].type, DEM_REPEAT_BLOCK);
ASSERT_EQ(model.instructions[0].target_data[0].data, 5);
ASSERT_EQ(model.instructions[0].target_data[1].data, 0);
ASSERT_EQ(model.instructions[1].type, DEM_REPEAT_BLOCK);
ASSERT_EQ(model.instructions[1].target_data[0].data, 6);
ASSERT_EQ(model.instructions[1].target_data[1].data, 1);
ASSERT_EQ(model.instructions[2].type, DEM_REPEAT_BLOCK);
ASSERT_EQ(model.instructions[2].target_data[0].data, 20);
ASSERT_EQ(model.instructions[2].target_data[1].data, 2);
ASSERT_EQ(model.blocks[0], block2);
ASSERT_EQ(model.blocks[2], block2);
block2.append_shift_detectors_instruction({}, 4);
ASSERT_EQ(model.blocks[1], block2);
}
TEST(detector_error_model, round_trip_str) {
const char *t = R"MODEL(error(0.125) D0
repeat 100 {
repeat 200 {
error(0.25) D0 D1 L0 ^ D2
shift_detectors(1.5, 3) 10
detector(0.5) D0
detector D1
}
error(0.375) D0 D1
shift_detectors 20
logical_observable L0
})MODEL";
ASSERT_EQ(DetectorErrorModel(t).str(), std::string(t));
}
TEST(detector_error_model, parse) {
DetectorErrorModel expected;
ASSERT_EQ(DetectorErrorModel(""), expected);
expected.append_error_instruction(0.125, (std::vector<DemTarget>{DemTarget::relative_detector_id(0)}));
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
error(0.125) D0
)MODEL"),
expected);
expected.append_error_instruction(0.125, (std::vector<DemTarget>{DemTarget::relative_detector_id(5)}));
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
error(0.125) D0
error(0.125) D5
)MODEL"),
expected);
expected.append_error_instruction(
0.25,
(std::vector<DemTarget>{
DemTarget::relative_detector_id(5), DemTarget::separator(), DemTarget::observable_id(4)}));
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
error(0.125) D0
error(0.125) D5
error(0.25) D5 ^ L4
)MODEL"),
expected);
expected.append_shift_detectors_instruction(std::vector<double>{1.5, 2}, 60);
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
error(0.125) D0
error(0.125) D5
error(0.25) D5 ^ L4
shift_detectors(1.5, 2) 60
)MODEL"),
expected);
expected.append_repeat_block(100, expected);
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
error(0.125) D0
error(0.125) D5
error(0.25) D5 ^ L4
shift_detectors(1.5, 2) 60
repeat 100 {
error(0.125) D0
error(0.125) D5
error(0.25) D5 ^ L4
shift_detectors(1.5, 2) 60
}
)MODEL"),
expected);
}
TEST(detector_error_model, movement) {
const char *t = R"MODEL(
error(0.2) D0
REPEAT 100 {
REPEAT 200 {
error(0.1) D0 D1 L0 ^ D2
shift_detectors 10
}
error(0.1) D0 D2
shift_detectors 20
}
)MODEL";
DetectorErrorModel d1(t);
DetectorErrorModel d2(d1);
ASSERT_EQ(d1, d2);
ASSERT_EQ(d1, DetectorErrorModel(t));
DetectorErrorModel d3(std::move(d1));
ASSERT_EQ(d1, DetectorErrorModel());
ASSERT_EQ(d2, d3);
ASSERT_EQ(d2, DetectorErrorModel(t));
d1 = d3;
ASSERT_EQ(d1, d2);
ASSERT_EQ(d2, d3);
ASSERT_EQ(d2, DetectorErrorModel(t));
d1 = std::move(d2);
ASSERT_EQ(d1, d3);
ASSERT_EQ(d2, DetectorErrorModel());
ASSERT_EQ(d1, DetectorErrorModel(t));
}
TEST(dem_target, general) {
DemTarget d = DemTarget::relative_detector_id(3);
ASSERT_TRUE(d == DemTarget::relative_detector_id(3));
ASSERT_TRUE(!(d != DemTarget::relative_detector_id(3)));
ASSERT_TRUE(!(d == DemTarget::relative_detector_id(4)));
ASSERT_TRUE(d != DemTarget::relative_detector_id(4));
ASSERT_EQ(d, DemTarget::relative_detector_id(3));
ASSERT_NE(d, DemTarget::observable_id(5));
ASSERT_NE(d, DemTarget::separator());
DemTarget d3 = DemTarget::relative_detector_id(72);
DemTarget s = DemTarget::separator();
DemTarget o = DemTarget::observable_id(3);
ASSERT_EQ(d.str(), "D3");
ASSERT_EQ(d3.str(), "D72");
ASSERT_EQ(o.str(), "L3");
ASSERT_EQ(s.str(), "^");
ASSERT_TRUE(!o.is_separator());
ASSERT_TRUE(!d3.is_separator());
ASSERT_TRUE(s.is_separator());
ASSERT_TRUE(o.is_observable_id());
ASSERT_TRUE(!d3.is_observable_id());
ASSERT_TRUE(!s.is_observable_id());
ASSERT_TRUE(!o.is_relative_detector_id());
ASSERT_TRUE(d3.is_relative_detector_id());
ASSERT_TRUE(!s.is_relative_detector_id());
}
TEST(dem_instruction, general) {
std::vector<DemTarget> d1;
d1.push_back(DemTarget::observable_id(4));
d1.push_back(DemTarget::relative_detector_id(3));
std::vector<DemTarget> d2;
d2.push_back(DemTarget::observable_id(4));
std::vector<double> p125{0.125};
std::vector<double> p25{0.25};
std::vector<double> p126{0.126};
DemInstruction i1{p125, d1, DEM_ERROR};
DemInstruction i1a{p125, d1, DEM_ERROR};
DemInstruction i2{p125, d2, DEM_ERROR};
ASSERT_TRUE(i1 == i1a);
ASSERT_TRUE(!(i1 != i1a));
ASSERT_TRUE(!(i2 == i1a));
ASSERT_TRUE(i2 != i1a);
ASSERT_EQ(i1, (DemInstruction{p125, d1, DEM_ERROR}));
ASSERT_NE(i1, (DemInstruction{p125, d2, DEM_ERROR}));
ASSERT_NE(i1, (DemInstruction{p25, d1, DEM_ERROR}));
ASSERT_NE(((DemInstruction{{}, {}, DEM_DETECTOR})), (DemInstruction{{}, {}, DEM_LOGICAL_OBSERVABLE}));
ASSERT_TRUE(i1.approx_equals(DemInstruction{p125, d1, DEM_ERROR}, 0));
ASSERT_TRUE(!i1.approx_equals(DemInstruction{p126, d1, DEM_ERROR}, 0));
ASSERT_TRUE(i1.approx_equals(DemInstruction{p126, d1, DEM_ERROR}, 0.01));
ASSERT_TRUE(!i1.approx_equals(DemInstruction{p125, d2, DEM_ERROR}, 9999));
ASSERT_EQ(i1.str(), "error(0.125) L4 D3");
ASSERT_EQ(i2.str(), "error(0.125) L4");
d1.push_back(DemTarget::separator());
d1.push_back(DemTarget::observable_id(11));
ASSERT_EQ((DemInstruction{p25, d1, DEM_ERROR}).str(), "error(0.25) L4 D3 ^ L11");
}
TEST(detector_error_model, total_detector_shift) {
ASSERT_EQ(DetectorErrorModel("").total_detector_shift(), 0);
ASSERT_EQ(DetectorErrorModel("error(0.3) D2").total_detector_shift(), 0);
ASSERT_EQ(DetectorErrorModel("shift_detectors 5").total_detector_shift(), 5);
ASSERT_EQ(DetectorErrorModel("shift_detectors 5\nshift_detectors 4").total_detector_shift(), 9);
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
shift_detectors 5
repeat 1000 {
shift_detectors 4
}
)MODEL")
.total_detector_shift(),
4005);
}
TEST(detector_error_model, count_detectors) {
ASSERT_EQ(DetectorErrorModel("").count_detectors(), 0);
ASSERT_EQ(DetectorErrorModel("error(0.3) D2 L1000").count_detectors(), 3);
ASSERT_EQ(DetectorErrorModel("shift_detectors 5").count_detectors(), 0);
ASSERT_EQ(DetectorErrorModel("shift_detectors 5\ndetector D3").count_detectors(), 9);
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
shift_detectors 50
repeat 1000 {
detector D0
error(0.1) D0 D1
shift_detectors 4
}
)MODEL")
.count_detectors(),
4048);
}
TEST(detector_error_model, count_observables) {
ASSERT_EQ(DetectorErrorModel("").count_observables(), 0);
ASSERT_EQ(DetectorErrorModel("error(0.3) L2 D9999").count_observables(), 3);
ASSERT_EQ(DetectorErrorModel("shift_detectors 5\nlogical_observable L3").count_observables(), 4);
ASSERT_EQ(
DetectorErrorModel(R"MODEL(
shift_detectors 50
repeat 1000 {
logical_observable L5
error(0.1) D0 D1 L6
shift_detectors 4
}
)MODEL")
.count_observables(),
7);
}
TEST(detector_error_model, from_file) {
FILE *f = tmpfile();
const char *program = R"MODEL(
error(0.125) D1
REPEAT 99 {
error(0.25) D3 D4
shift_detectors 1
}
)MODEL";
fprintf(f, "%s", program);
rewind(f);
auto d = DetectorErrorModel::from_file(f);
ASSERT_EQ(d, DetectorErrorModel(program));
d.clear();
rewind(f);
d.append_from_file(f);
ASSERT_EQ(d, DetectorErrorModel(program));
d.clear();
rewind(f);
d.append_from_file(f, false);
ASSERT_EQ(d, DetectorErrorModel(program));
d.clear();
rewind(f);
d.append_from_file(f, true);
ASSERT_EQ(d, DetectorErrorModel("error(0.125) D1"));
d.append_from_file(f, true);
ASSERT_EQ(d, DetectorErrorModel(program));
}
TEST(detector_error_model, py_get_slice) {
DetectorErrorModel d(R"MODEL(
detector D2
logical_observable L1
error(0.125) D0 L1
REPEAT 100 {
shift_detectors(0.25) 5
REPEAT 20 {
}
}
error(0.125) D1 D2
REPEAT 999 {
}
)MODEL");
ASSERT_EQ(d.py_get_slice(0, 1, 6), d);
ASSERT_EQ(d.py_get_slice(0, 1, 4), DetectorErrorModel(R"MODEL(
detector D2
logical_observable L1
error(0.125) D0 L1
REPEAT 100 {
shift_detectors(0.25) 5
REPEAT 20 {
}
}
)MODEL"));
ASSERT_EQ(d.py_get_slice(2, 1, 3), DetectorErrorModel(R"MODEL(
error(0.125) D0 L1
REPEAT 100 {
shift_detectors(0.25) 5
REPEAT 20 {
}
}
error(0.125) D1 D2
)MODEL"));
ASSERT_EQ(d.py_get_slice(4, -1, 3), DetectorErrorModel(R"MODEL(
error(0.125) D1 D2
REPEAT 100 {
shift_detectors(0.25) 5
REPEAT 20 {
}
}
error(0.125) D0 L1
)MODEL"));
ASSERT_EQ(d.py_get_slice(5, -2, 3), DetectorErrorModel(R"MODEL(
REPEAT 999 {
}
REPEAT 100 {
shift_detectors(0.25) 5
REPEAT 20 {
}
}
logical_observable L1
)MODEL"));
DetectorErrorModel d2 = d;
DetectorErrorModel d3 = d2.py_get_slice(0, 1, 6);
d2.clear();
ASSERT_EQ(d, d3);
}
TEST(detector_error_model, mul) {
DetectorErrorModel original(R"MODEL(
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
)MODEL");
DetectorErrorModel d = original;
ASSERT_EQ(d * 3, DetectorErrorModel(R"MODEL(
REPEAT 3 {
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
}
)MODEL"));
ASSERT_EQ(d * 1, d);
ASSERT_EQ(d * 0, DetectorErrorModel());
ASSERT_EQ(d, original);
}
TEST(detector_error_model, imul) {
DetectorErrorModel original(R"MODEL(
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
)MODEL");
DetectorErrorModel d = original;
d *= 3;
ASSERT_EQ(d, DetectorErrorModel(R"MODEL(
REPEAT 3 {
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
}
)MODEL"));
d = original;
d *= 1;
ASSERT_EQ(d, original);
d = original;
d *= 0;
ASSERT_EQ(d, DetectorErrorModel());
}
TEST(detector_error_model, add) {
DetectorErrorModel a(R"MODEL(
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
)MODEL");
DetectorErrorModel b(R"MODEL(
error(0.125) D1
REPEAT 2 {
REPEAT 3 {
error(0.125) D1
}
}
)MODEL");
ASSERT_EQ(a + b, DetectorErrorModel(R"MODEL(
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
error(0.125) D1
REPEAT 2 {
REPEAT 3 {
error(0.125) D1
}
}
)MODEL"));
ASSERT_EQ(a + DetectorErrorModel(), a);
ASSERT_EQ(DetectorErrorModel() + a, a);
ASSERT_EQ(b + DetectorErrorModel(), b);
ASSERT_EQ(DetectorErrorModel() + b, b);
ASSERT_EQ(DetectorErrorModel() + DetectorErrorModel(), DetectorErrorModel());
}
TEST(detector_error_model, iadd) {
DetectorErrorModel a(R"MODEL(
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
)MODEL");
DetectorErrorModel b(R"MODEL(
error(0.125) D1
REPEAT 2 {
REPEAT 3 {
error(0.125) D1
}
}
)MODEL");
a += b;
ASSERT_EQ(a, DetectorErrorModel(R"MODEL(
error(0.25) D0
REPEAT 999 {
error(0.25) D1
}
error(0.125) D1
REPEAT 2 {
REPEAT 3 {
error(0.125) D1
}
}
)MODEL"));
DetectorErrorModel original = b;
b += DetectorErrorModel();
ASSERT_EQ(b, original);
b += a;
ASSERT_NE(b, original);
// Aliased.
a = original;
a += a;
a = DetectorErrorModel(a.str().data()); // Remove memory deduplication, because it affects equality.
ASSERT_EQ(a, original + original);
}
TEST(detector_error_model, iter_flatten_error_instructions) {
DetectorErrorModel d(R"MODEL(
error(0.25) D0
shift_detectors 1
error(0.375) D0 D1
repeat 5 {
error(0.125) D0 D1 D2 L0
shift_detectors 2
}
detector D5000
logical_observable L5000
)MODEL");
DetectorErrorModel dem;
d.iter_flatten_error_instructions([&](const DemInstruction &e) {
EXPECT_EQ(e.type, DEM_ERROR);
dem.append_error_instruction(e.arg_data[0], e.target_data);
});
ASSERT_EQ(dem, DetectorErrorModel(R"MODEL(
error(0.25) D0
error(0.375) D1 D2
error(0.125) D1 D2 D3 L0
error(0.125) D3 D4 D5 L0
error(0.125) D5 D6 D7 L0
error(0.125) D7 D8 D9 L0
error(0.125) D9 D10 D11 L0
)MODEL"));
}
TEST(detector_error_model, get_detector_coordinates_nested_loops) {
DetectorErrorModel dem(R"MODEL(
repeat 200 {
repeat 100 {
detector(0, 0, 0, 4) D1
shift_detectors(1, 0, 0) 10
}
detector(0, 0, 0, 3) D2
shift_detectors(0, 1, 0) 0
}
detector(0, 0, 0, 2) D3
)MODEL");
ASSERT_THROW({ dem.get_detector_coordinates({4000000000}); }, std::invalid_argument);
ASSERT_THROW({ dem.get_detector_coordinates({dem.count_detectors()}); }, std::invalid_argument);
auto result = dem.get_detector_coordinates({
0,
1,
11,
991,
1001,
1002,
1011,
1021,
});
ASSERT_EQ(
result,
(std::map<uint64_t, std::vector<double>>{
{0, {}},
{1, {0, 0, 0, 4}},
{11, {1, 0, 0, 4}},
{991, {99, 0, 0, 4}},
{1001, {100, 1, 0, 4}},
{1002, {100, 0, 0, 3}},
{1011, {101, 1, 0, 4}},
{1021, {102, 1, 0, 4}},
}));
}
TEST(detector_error_model, get_detector_coordinates_trivial) {
DetectorErrorModel dem;
dem = DetectorErrorModel(R"MODEL(
detector(1, 2) D1
)MODEL");
ASSERT_EQ(dem.get_detector_coordinates({0, 1}), (std::map<uint64_t, std::vector<double>>{
{0, {}},
{1, {1, 2}},
}));
ASSERT_THROW({
dem.get_detector_coordinates({2});
}, std::invalid_argument);
dem = DetectorErrorModel(R"MODEL(
error(0.25) D0 D1
)MODEL");
ASSERT_EQ(dem.get_detector_coordinates({0, 1}), (std::map<uint64_t, std::vector<double>>{
{0, {}},
{1, {}},
}));
ASSERT_THROW({
dem.get_detector_coordinates({2});
}, std::invalid_argument);
dem = DetectorErrorModel(R"MODEL(
error(0.25) D0 D1
detector(1, 2, 3) D1
shift_detectors(5) 1
detector(1, 2) D2
)MODEL");
ASSERT_EQ(dem.get_detector_coordinates({0, 1, 2, 3}), (std::map<uint64_t, std::vector<double>>{
{0, {}},
{1, {1, 2, 3}},
{2, {}},
{3, {6, 2}},
}));
ASSERT_THROW({
dem.get_detector_coordinates({4});
}, std::invalid_argument);
}
TEST(detector_error_model, final_detector_and_coord_shift) {
DetectorErrorModel dem(R"MODEL(
repeat 1000 {
repeat 2000 {
repeat 3000 {
shift_detectors(0, 0, 1) 0
}
shift_detectors(1) 2
}
shift_detectors(0, 1) 0
}
)MODEL");
ASSERT_EQ(
dem.final_detector_and_coord_shift(),
(std::pair<uint64_t, std::vector<double>>{4000000, {2000000, 1000, 6000000000}}));
}
| 23,336 | 9,374 |
#include <mainwindow.h>
#include <Player.h>
#include <BestInstallPath.h>
#include <HostMessageAdapter.h>
#include <Helper/CacheNetworkManagerFactory.h>
#include <Features/PlainFileCache.h>
#include <Features/Marketing/MarketingIntegrationMarker.h>
#include <viewmodel/UpdateViewModel.h>
#include <viewmodel/ApplicationStatisticViewModel.h>
#include <viewmodel/SettingsViewModel.h>
#include <viewmodel/GameSettingsViewModel.h>
#include <viewmodel/ServiceHandleViewModel.h>
#include <viewmodel/SettingsManagerViewModel.h>
#include <Host/Translation.h>
#include <Host/ClientConnection.h>
#include <Host/Dbus/DbusConnection.h>
#include <Host/Dbus/DownloaderBridgeProxy.h>
#include <Host/Dbus/DownloaderSettingsBridgeProxy.h>
#include <Host/Dbus/ServiceSettingsBridgeProxy.h>
#include <Host/Dbus/ExecutorBridgeProxy.h>
#include <Host/Dbus/ApplicationBridgeProxy.h>
#include <Host/Dbus/ApplicationStatisticBridgeProxy.h>
#include <Host/Dbus/LicenseManagerBridgeProxy.h>
#include <Core/UI/Message.h>
#include <Core/Marketing.h>
#include <Core/System/FileInfo.h>
#include <Core/System/HardwareId.h>
#include <GameExecutor/GameExecutorService.h>
#include <UpdateSystem/UpdateInfoGetterResultInterface.h>
#include <RestApi/Request/RequestFactory.h>
#include <Application/WindowHelper.h>
#include <Settings/settings.h>
#include <QtCore/QTranslator>
#include <QtCore/QSysInfo>
#include <QtCore/QFlags>
#include <QtCore/QStringList>
#include <QtCore/QSysInfo>
#include <QtWidgets/QBoxLayout>
#include <QtWidgets/QDesktopWidget>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQuickItem>
#include <QQmlError>
#include <QMetaType>
#define SIGNAL_CONNECT_CHECK(X) { bool result = X; Q_ASSERT_X(result, __FUNCTION__ , #X); }
using P1::Host::DBus::DBusConnection;
using P1::Host::ClientConnection;
using P1::RestApi::ProtocolOneCredential;
MainWindow::MainWindow(QWindow *parent)
: QQuickView(parent)
, _gameArea(P1::Core::Service::Live)
, _downloader(nullptr)
, _downloaderSettings(nullptr)
, _serviceSettings(nullptr)
, _executor(nullptr)
, _applicationProxy(nullptr)
, _applicationStatistic(nullptr)
, _clientConnection(nullptr)
, _bestInstallPath(nullptr)
{
this->hide();
QString path = QCoreApplication::applicationDirPath();
path += "/Config.yaml";
if (!this->_configManager.load(path))
qWarning() << "Cannot read application config file: " << path;
}
MainWindow::~MainWindow()
{
}
void MainWindow::initialize()
{
qRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>("P1::Host::Bridge::DownloadProgressArgs");
qDBusRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>();
// DBUS...
QDBusConnection &connection = DBusConnection::bus();
QString dbusService("com.protocolone.launcher.dbus");
this->_clientConnection = new ClientConnection("Launcher", this);
this->_clientConnection->init();
QObject::connect(this->_clientConnection, &ClientConnection::disconnected,
this, &MainWindow::onWindowClose);
QObject::connect(this->_clientConnection, &ClientConnection::authorizationError,
this, &MainWindow::authorizationError);
this->_applicationProxy = new ApplicationBridgeProxy(dbusService, "/application", connection, this);
this->_downloader = new DownloaderBridgeProxy(dbusService, "/downloader", connection, this);
this->_downloaderSettings = new DownloaderSettingsBridgeProxy(dbusService, "/downloader/settings", connection, this);
this->_serviceSettings = new ServiceSettingsBridgeProxy(dbusService, "/serviceSettings", connection, this);
this->_executor = new ExecutorBridgeProxy(dbusService, "/executor", connection, this);
this->_applicationStatistic = new ApplicationStatisticBridgeProxy(dbusService, "/applicationStatistic", connection, this);
this->_licenseManager = new LicenseManagerBridgeProxy(dbusService, "/licenseManager", connection, this);
QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::languageChanged,
this, &MainWindow::languageChanged);
this->_bestInstallPath = new BestInstallPath(this);
this->_bestInstallPath->setServiceSettings(this->_serviceSettings);
QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::initCompleted,
this, &MainWindow::initCompleted);
QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::restartUIRequest,
this, &MainWindow::restartUIRequest);
QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::shutdownUIRequest,
this, &MainWindow::shutdownUIRequest);
QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::uninstallServiceRequest,
this, &MainWindow::uninstallServiceRequest);
QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::additionalResourcesReady,
this, &MainWindow::additionalResourcesReady);
qRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>("P1::Host::Bridge::DownloadProgressArgs");
qDBusRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>();
new HostMessageAdapter(this);
this->initRestApi();
this->_commandLineArguments.parse(QCoreApplication::arguments());
if (this->_commandLineArguments.contains("gamepts"))
this->_gameArea = P1::Core::Service::Pts;
if (this->_commandLineArguments.contains("gametest"))
this->_gameArea = P1::Core::Service::Tst;
this->setFileVersion(P1::Core::System::FileInfo::version(QCoreApplication::applicationFilePath()));
this->setTitle("ProtocolOne " + this->_fileVersion);
this->setColor(QColor(0, 0, 0, 0));
this->setFlags(Qt::Window
| Qt::FramelessWindowHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowSystemMenuHint); //Этот код уберет все внешние элементы формы
P1::Host::Translation::load(this->translators, this);
this->selectLanguage(this->_applicationProxy->language());
this->checkDesktopDepth();
this->settingsViewModel = new SettingsViewModel(this);
this->settingsViewModel->setDownloaderSettings(this->_downloaderSettings);
this->settingsViewModel->setApplicationProxy(this->_applicationProxy);
qmlRegisterType<UpdateViewModel>("Launcher.Library", 1, 0, "UpdateViewModel");
qmlRegisterType<Player>("Launcher.Library", 1, 0, "Player");
qmlRegisterType<P1::Core::UI::Message>("Launcher.Library", 1, 0, "Message");
qmlRegisterType<ApplicationStatisticViewModel>("Launcher.Library", 1, 0, "ApplicationStatistic");
qmlRegisterType<ServiceHandleViewModel>("Launcher.Library", 1, 0, "ServiceHandle");
qmlRegisterType<SettingsManagerViewModel>("Launcher.Library", 1, 0, "SettingsManager");
qmlRegisterUncreatableType<P1::Downloader::DownloadResultsWrapper>("Launcher.Library", 1, 0, "DownloadResults", "");
qmlRegisterUncreatableType<P1::UpdateSystem::UpdateInfoGetterResultsWrapper>("Launcher.Library", 1, 0, "UpdateInfoGetterResults", "");
//this->initMarketing();
this->engine()->setNetworkAccessManagerFactory(new CacheNetworkManagerFactory(this));
this->engine()->addImportPath(":/");
this->engine()->addImportPath((QCoreApplication::applicationDirPath() + "/plugins5/"));
this->engine()->addPluginPath(QCoreApplication::applicationDirPath() + "/plugins5/");
QObject::connect(
&this->_restapiManager, &P1::RestApi::RestApiManager::authorizationError,
this, &MainWindow::onAuthorizationError);
messageAdapter = new QmlMessageAdapter(this);
this->_gameSettingsViewModel = new GameSettingsViewModel(this);
this->_gameSettingsViewModel->setDownloader(this->_downloader);
this->_gameSettingsViewModel->setServiceSettings(this->_serviceSettings);
this->rootContext()->setContextProperty("keyboardHook", &this->_keyboardLayoutHelper);
this->rootContext()->setContextProperty("mainWindow", this);
this->rootContext()->setContextProperty("installPath", "file:///" + QCoreApplication::applicationDirPath() + "/");
this->rootContext()->setContextProperty("settingsViewModel", settingsViewModel);
this->rootContext()->setContextProperty("messageBox", messageAdapter);
this->rootContext()->setContextProperty("gameSettingsModel", this->_gameSettingsViewModel);
this->setResizeMode(QQuickView::SizeRootObjectToView);
this->setSource(QUrl("qrc:/Main.qml"));
if (this->status() == QQuickView::Status::Error) {
Q_FOREACH(const QQmlError& error, this->errors()) {
DEBUG_LOG << error;
}
// UNDONE решить что делать в случаи фейла верстки
}
QObject::connect(this->engine(), &QQmlEngine::quit, this, &MainWindow::onWindowClose);
QObject::connect(this, &MainWindow::quit, this, &MainWindow::onWindowClose);
Message::setAdapter(messageAdapter);
if (this->_commandLineArguments.contains("minimized")) {
//this->showMinimized();
this->hide();
}
else {
DEBUG_LOG;
this->activateWindow();
}
this->sendStartingMarketing();
this->_keyboardLayoutHelper.update();
}
void MainWindow::hideToTaskBar()
{
this->showMinimized();
}
void MainWindow::sendStartingMarketing()
{
int dwMajorVersion = 6;
int dwMinorVersion = 1;
switch (QSysInfo::windowsVersion()) {
case QSysInfo::WV_5_1: dwMajorVersion = 5; dwMinorVersion = 1; break;
case QSysInfo::WV_6_0: dwMajorVersion = 6; dwMinorVersion = 0; break;
case QSysInfo::WV_6_1: dwMajorVersion = 6; dwMinorVersion = 1; break;
case QSysInfo::WV_6_2: dwMajorVersion = 6; dwMinorVersion = 2; break;
case QSysInfo::WV_6_3: dwMajorVersion = 6; dwMinorVersion = 3; break;
case QSysInfo::WV_10_0: dwMajorVersion = 10; dwMinorVersion = 0; break;
}
QVariantMap params;
params["windowsMajorVersion"] = dwMajorVersion;
params["windowsMinorVersion"] = dwMinorVersion;
params["windowsVersion"] = QSysInfo::productVersion();
params["updateArea"] = this->settingsViewModel->updateArea();
params["version"] = this->_fileVersion;
P1::Core::Marketing::send(P1::Core::Marketing::AnyStartLauncher, params);
P1::Core::Marketing::sendOnce(P1::Core::Marketing::FirstRunLauncher);
}
void MainWindow::restartUISlot(bool minimized)
{
this->_applicationProxy->restartApplication(minimized);
}
void MainWindow::shutdownUISlot()
{
this->_applicationProxy->shutdownUIResult();
this->onWindowClose();
}
void MainWindow::terminateGame(const QString& serviceId)
{
this->_executor->terminateGame(serviceId);
}
bool MainWindow::isInitCompleted()
{
return this->_applicationProxy->isInitCompleted();
}
void MainWindow::checkDesktopDepth() {
QDesktopWidget widget;
if (widget.depth() == 16) {
QString info = QObject::tr("SCREEN_DEPTH_LOVER_THAN_16_INFO");
QString caption = QObject::tr("SCREEN_DEPTH_LOVER_THAN_16_CAPTION");
MessageBoxW(0,
info.toStdWString().c_str(),
caption.toStdWString().c_str(),
MB_OK | MB_ICONINFORMATION);
}
}
bool MainWindow::nativeEvent(const QByteArray & eventType, void * message, long * result)
{
if (message != nullptr && reinterpret_cast<MSG*>(message)->message == WM_KEYUP)
this->_keyboardLayoutHelper.update();
return QQuickView::nativeEvent(eventType, message, result);
}
void MainWindow::activateWindow()
{
DEBUG_LOG << "activateWindow";
this->show();
// Это нам покажет окно
//this->setFocusPolicy(Qt::StrongFocus);
//this->setWindowState(Qt::WindowActive);
this->showNormal();
// Эта функция активирует окно и поднмиает его повех всех окон
P1::Application::WindowHelper::activate(reinterpret_cast<HWND>(this->winId()));
this->_taskBarHelper.restore();
//this->repaint();
}
bool MainWindow::isDownloading(QString serviceId)
{
return this->_downloader->isInProgress(serviceId);
}
QString MainWindow::language()
{
return this->_applicationProxy->language();
}
const QString& MainWindow::fileVersion() const
{
return _fileVersion;
}
void MainWindow::saveLanguage(const QString& language)
{
this->_applicationProxy->setLanguage(language);
}
void MainWindow::selectLanguage(const QString& language)
{
if (this->translators[language])
QApplication::installTranslator(this->translators[language]);
emit this->languageChanged();
}
void MainWindow::onWindowClose()
{
DEBUG_LOG << "Shutting down";
//this->repaint();
this->hide();
this->_clientConnection->close();
QCoreApplication::quit();
}
void MainWindow::authSuccessSlot(const QString& accessToken, const QString& acccessTokenExpiredTime)
{
this->_credential.setAcccessTokent(accessToken);
this->_credential.setAccessTokenExpiredTime(acccessTokenExpiredTime);
qDebug() << "Auth success with userId " << this->_credential.userId();
this->_restapiManager.setCridential(this->_credential);
this->_clientConnection->setCredential(this->_credential);
}
void MainWindow::updateAuthCredential(const QString& accessTokenOld, const QString& acccessTokenExpiredTimeOld
, const QString& accessTokenNew, const QString& acccessTokenExpiredTimeNew)
{
if (accessTokenOld == this->_credential.acccessTokent()) {
this->_credential.setAcccessTokent(accessTokenNew);
this->_credential.setAccessTokenExpiredTime(acccessTokenExpiredTimeNew);
this->_restapiManager.setCridential(this->_credential);
this->_clientConnection->setCredential(this->_credential);
}
ProtocolOneCredential oldValue(accessTokenOld, acccessTokenExpiredTimeOld);
ProtocolOneCredential newValue(accessTokenNew, acccessTokenExpiredTimeNew);
this->_restapiManager.updateCredential(oldValue, newValue);
this->_clientConnection->updateCredential(oldValue, newValue);
}
void MainWindow::restartApplication(bool shouldStartWithSameArguments)
{
this->_applicationProxy->restartApplication(shouldStartWithSameArguments);
}
void MainWindow::openExternalUrlWithAuth(const QString& url)
{
//QString authUrl;
//if(this->_credential.appKey().isEmpty()) {
// authUrl = url;
//} else {
// authUrl = "https://gnlogin.ru/?auth=";
// authUrl.append(this->_credential.cookie());
// authUrl.append("&rp=");
// authUrl.append(QUrl::toPercentEncoding(url));
//}
//authUrl.append('\0');
// UNDONE There are no shared auth between sites now.
this->openExternalUrl(url);
}
void MainWindow::openExternalUrl(const QString& url)
{
QDesktopServices::openUrl(url);
}
void MainWindow::logout()
{
this->_credential.clear();
this->_restapiManager.setCridential(this->_credential);
this->_clientConnection->setCredential(this->_credential);
}
void MainWindow::prepairGameDownloader()
{
using P1::GameDownloader::GameDownloadService;
QObject::connect(this->_downloader, &DownloaderBridgeProxy::totalProgress,
this, &MainWindow::downloadGameTotalProgressChanged);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::downloadProgress,
this, &MainWindow::downloadGameProgressChanged);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::started,
this, &MainWindow::gameDownloaderStarted);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::finished,
this, &MainWindow::gameDownloaderFinished);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::stopped,
this, &MainWindow::gameDownloaderStopped);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::stopping,
this, &MainWindow::gameDownloaderStopping);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::failed,
this, &MainWindow::gameDownloaderFailed);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::statusMessageChanged,
this, &MainWindow::gameDownloaderStatusMessageChanged);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::serviceInstalled,
this, &MainWindow::gameDownloaderServiceInstalled);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::serviceUpdated,
this, &MainWindow::gameDownloaderServiceUpdated);
QObject::connect(this->_downloader, &DownloaderBridgeProxy::accessRequired,
this, &MainWindow::gameDownloaderAccessRequired);
}
void MainWindow::downloadGameTotalProgressChanged(const QString& serviceId, int progress)
{
emit totalProgressChanged(serviceId, progress);
}
void MainWindow::downloadGameProgressChanged(
const QString& serviceId,
int progress,
P1::Host::Bridge::DownloadProgressArgs args)
{
if (args.status == static_cast<int>(P1::Libtorrent::EventArgs::ProgressEventArgs::CheckingFiles)) {
emit this->rehashProgressChanged(serviceId, progress, args.progress * 100);
return;
}
emit this->downloadProgressChanged(serviceId,
progress,
args.totalWantedDone,
args.totalWanted,
args.directTotalDownload,
args.peerTotalDownload,
args.payloadTotalDownload,
args.peerPayloadDownloadRate,
args.payloadDownloadRate,
args.directPayloadDownloadRate,
args.payloadUploadRate,
args.totalPayloadUpload);
}
void MainWindow::gameDownloaderStarted(const QString& serviceId, int startType)
{
emit this->downloaderStarted(serviceId, startType);
}
void MainWindow::gameDownloaderFinished(const QString& serviceId)
{
emit this->downloaderFinished(serviceId);
}
bool MainWindow::executeService(QString id)
{
if (this->_executor->isGameStarted(id))
return false;
if (!this->isWindowVisible()) {
emit this->selectService(id);
return false;
}
// UNDONE we shouldn't check here
//if (!this->_restapiManager.credential().isValid()) {
// emit this->authBeforeStartGameRequest(id);
// return false;
//}
if (!this->_serviceSettings->isDownloadable(id))
this->_licenseManager->acceptWebLicense();
P1::RestApi::ProtocolOneCredential baseCredential =
P1::RestApi::RestApiManager::commonInstance()->credential();
this->_executor->execute(
id,
baseCredential.acccessTokent(),
baseCredential.accessTokenExpiredTimeAsString());
this->startGame(id);
return true;
}
void MainWindow::gameDownloaderStopped(const QString& serviceId)
{
emit this->downloaderStopped(serviceId);
}
void MainWindow::gameDownloaderStopping(const QString& serviceId)
{
emit this->downloaderStopping(serviceId);
}
void MainWindow::updateFinishedSlot()
{
this->postUpdateInit();
}
void MainWindow::gameDownloaderFailed(const QString& serviceId)
{
emit this->downloaderFailed(serviceId);
}
void MainWindow::removeStartGame(QString serviceId)
{
int totalCount = this->_applicationStatistic->executeGameTotalCount(serviceId);
if (totalCount > 0) {
this->selectService(serviceId);
return;
}
this->downloadButtonStart(serviceId);
}
void MainWindow::downloadButtonStart(QString serviceId)
{
qDebug() << "downloadButtonStart " << serviceId;
emit this->downloadButtonStartSignal(serviceId);
if (!this->_serviceSettings->isDownloadable(serviceId)) {
int totalCount = this->_applicationStatistic->executeGameTotalCount(serviceId);
if (0 == totalCount) {
emit this->showWebLicense(serviceId);
return;
}
this->startGame(serviceId);
return;
}
if (this->isLicenseAccepted(serviceId)) {
this->startGame(serviceId);
return;
}
DEBUG_LOG;
this->activateWindow();
emit this->showLicense(serviceId);
}
void MainWindow::downloadButtonPause(QString serviceId)
{
if (this->_serviceSettings->isDownloadable(serviceId)) {
this->_downloader->stop(serviceId);
return;
}
P1::RestApi::ProtocolOneCredential baseCredential =
P1::RestApi::RestApiManager::commonInstance()->credential();
this->_executor->execute(serviceId
, baseCredential.acccessTokent()
, baseCredential.accessTokenExpiredTimeAsString());
}
void MainWindow::uninstallService(const QString serviceId)
{
this->_downloader->start(serviceId, P1::GameDownloader::Uninstall);
}
void MainWindow::cancelServiceUninstall(const QString serviceId)
{
this->_applicationProxy->cancelUninstallServiceRequest(serviceId);
}
bool MainWindow::isLicenseAccepted(const QString& serviceId)
{
return this->_licenseManager->hasAcceptedLicense(serviceId);
}
void MainWindow::startGame(const QString& serviceId)
{
if (this->_executor->isGameStarted(serviceId))
return;
if (this->_serviceSettings->isDownloadable(serviceId)) {
this->_downloader->start(serviceId, static_cast<int>(P1::GameDownloader::Normal));
return;
}
// UNDONE we shouldn't check here
//bool isAuthed = !this->_restapiManager.credential().isValid();
//if (!isAuthed) {
// emit this->authBeforeStartGameRequest(serviceId);
// return;
//}
P1::RestApi::ProtocolOneCredential baseCredential =
P1::RestApi::RestApiManager::commonInstance()->credential();
this->_executor->execute(
serviceId,
baseCredential.acccessTokent(),
baseCredential.accessTokenExpiredTimeAsString());
}
void MainWindow::commandRecieved(QString name, QStringList arguments)
{
DEBUG_LOG << name << arguments;
if (name == "quit") {
this->onWindowClose();
return;
}
if (name == "settings") {
emit this->navigate("ApplicationSettings");
return;
}
if (name == "activate") {
DEBUG_LOG;
this->activateWindow();
return;
}
if (name == "goprotocolonemoney") {
this->navigate("goprotocolonemoney");
return;
}
if (name == "uninstall" && arguments.size() > 0) {
QString serviceId = arguments.at(0);
emit this->uninstallServiceRequest(serviceId);
}
}
void MainWindow::onServiceStarted(const QString &serviceId)
{
emit this->serviceStarted(serviceId);
}
void MainWindow::onServiceFinished(const QString &serviceId, int state)
{
emit this->serviceFinished(serviceId, state);
}
void MainWindow::gameDownloaderStatusMessageChanged(const QString& serviceId, const QString& message)
{
emit this->downloaderServiceStatusMessageChanged(serviceId, message);
}
void MainWindow::onAuthorizationError(const P1::RestApi::ProtocolOneCredential &credential)
{
if (credential.userId() == this->_credential.userId()
&& this->_credential != credential
&& this->_credential.isValid()) {
this->_clientConnection->updateCredential(credential, this->_credential);
}
emit this->authorizationError(credential.acccessTokent(), credential.accessTokenExpiredTimeAsString());
}
void MainWindow::showEvent(QShowEvent* event)
{
this->_taskBarHelper.prepare(reinterpret_cast<HWND>(this->winId()));
emit this->taskBarButtonMsgRegistered(this->_taskBarHelper.getTaskbarCreatedMessageId());
QQuickView::showEvent(event);
}
bool MainWindow::isWindowVisible()
{
return this->isVisible() && this->windowState() != Qt::WindowMinimized;
}
void MainWindow::gameDownloaderServiceInstalled(const QString& serviceId)
{
emit this->serviceInstalled(serviceId);
}
void MainWindow::gameDownloaderServiceUpdated(const QString& serviceId)
{
DEBUG_LOG;
this->activateWindow();
emit this->selectService(serviceId);
}
void MainWindow::postUpdateInit()
{
this->prepairGameDownloader();
QObject::connect(this->_executor, &ExecutorBridgeProxy::serviceStarted,
this, &MainWindow::onServiceStarted);
QObject::connect(this->_executor, &ExecutorBridgeProxy::serviceFinished,
this, &MainWindow::onServiceFinished);
}
bool MainWindow::anyLicenseAccepted()
{
return this->_licenseManager->hasAcceptedLicense();
}
QString MainWindow::startingService()
{
if (!this->_commandLineArguments.contains("startservice"))
return "0";
QStringList arguments = this->_commandLineArguments.commandArguments("startservice");
if (arguments.count() > 0)
return arguments.at(0);
return "0";
}
QString MainWindow::getExpectedInstallPath(const QString& serviceId)
{
return this->_bestInstallPath->expectedPath(serviceId);
}
QString MainWindow::getBestInstallPath(const QString& serviceId)
{
return this->_bestInstallPath->bestInstallPath(serviceId);
}
void MainWindow::setServiceInstallPath(const QString& serviceId, const QString& path)
{
this->_serviceSettings->setInstallPath(serviceId, path);
if (!this->_serviceSettings->hasDownloadPath(serviceId)) {
this->_serviceSettings->setDownloadPath(serviceId, path);
return;
}
QString downloadPath = this->_serviceSettings->isDefaultDownloadPath(serviceId)
? QString("%1/dist").arg(path)
: this->_serviceSettings->downloadPath(serviceId);
this->_serviceSettings->setDownloadPath(serviceId, downloadPath);
}
void MainWindow::acceptFirstLicense(const QString& serviceId)
{
this->_licenseManager->acceptLicense(serviceId, "1");
}
void MainWindow::initFinished()
{
emit this->updateFinished();
}
void MainWindow::initRestApi()
{
QString apiUrl = this->_configManager.value<QString>("api\\url", "https://api.tst.protocol.one/");
qDebug() << "Using RestApi url " << apiUrl;
this->_restapiManager.setUri(apiUrl);
this->_restapiManager.setCache(new Features::PlainFileCache(&this->_restapiManager));
bool debugLogEnabled = this->_configManager.value<bool>("api\\debug", false);
this->_restapiManager.setDebugLogEnabled(debugLogEnabled);
P1::RestApi::RestApiManager::setCommonInstance(&this->_restapiManager);
}
bool MainWindow::event(QEvent* event)
{
switch(event->type()) {
case QEvent::Close:
this->hide();
event->ignore();
break;
}
return QQuickView::event(event);
}
//void MainWindow::initMarketing()
//{
// QSettings midSettings(
// QSettings::NativeFormat,
// QSettings::UserScope,
// QCoreApplication::organizationName(),
// QCoreApplication::applicationName());
//
// QString mid = midSettings.value("MID", "").toString();
// this->_marketingTargetFeatures.init("Launcher", mid);
//
// int installerKey = midSettings.value("InstKey").toInt();
// this->_marketingTargetFeatures.setInstallerKey(installerKey);
// this->_marketingTargetFeatures.setRequestInterval(1000);
//}
void MainWindow::mousePressEvent(QMouseEvent* event)
{
if (event->button() & Qt::LeftButton)
emit this->leftMousePress(event->x(), event->y());
QQuickView::mousePressEvent(event);
}
void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() & Qt::LeftButton)
emit this->leftMouseRelease(event->x(), event->y());
QQuickView::mouseReleaseEvent(event);
}
void MainWindow::onTaskbarButtonCreated()
{
this->_taskBarHelper.init();
}
void MainWindow::onProgressUpdated(int progressValue, const QString &status)
{
TaskBarHelper::Status newStatus = TaskBarHelper::StatusUnknown;
if (status == "Normal") {
newStatus = TaskBarHelper::StatusNormal;
}
else if (status == "Paused") {
newStatus = TaskBarHelper::StatusPaused;
}
else if (status == "Error") {
newStatus = TaskBarHelper::StatusError;
}
this->_taskBarHelper.setProgress(progressValue);
this->_taskBarHelper.setStatus(newStatus);
}
void MainWindow::setTaskbarIcon(const QString &iconSource)
{
this->_taskBarHelper.setIcon(iconSource);
}
void MainWindow::onLanguageChanged()
{
this->_keyboardLayoutHelper.update();
}
void MainWindow::switchClientVersion()
{
this->_applicationProxy->switchClientVersion();
}
| 26,785 | 8,484 |
// keyfeatures_example2.cpp -*-C++-*-
#include <ball_log.h>
#include <ball_loggermanager.h>
#include <ball_loggermanagerconfiguration.h>
#include <ball_fileobserver.h>
#include <ball_scopedattribute.h>
#include <bslma_allocator.h>
#include <bslma_default.h>
#include <bsl_iostream.h>
#include <bsl_memory.h>
using namespace BloombergLP;
///Key Example 2: Initialization
///- - - - - - - - - - - - - - -
// Clients that perform logging must first instantiate the singleton logger
// manager using the 'ball::LoggerManagerScopedGuard' class. This example
// shows how to create a logger manager with basic "default behavior".
// Subsequent examples will show more customized behavior.
//
// The following snippets of code illustrate the initialization sequence
// (typically performed near the top of 'main').
//
// First, we create a 'ball::LoggerManagerConfiguration' object,
// 'configuration', and set the logging "pass-through" level -- the level at
// which log records are published to registered observers -- to 'WARN' (see
// {'Categories, Severities, and Threshold Levels'}):
//..
// myApp.cpp
//
int main()
{
ball::LoggerManagerConfiguration configuration;
configuration.setDefaultThresholdLevelsIfValid(ball::Severity::e_WARN);
//..
// Next, create a 'ball::LoggerManagerScopedGuard' object whose constructor
// takes the configuration object just created. The guard will initialize the
// logger manager singleton on creation and destroy the singleton upon
// destruction. This guarantees that any resources used by the logger manager
// will be properly released when they are not needed:
//..
ball::LoggerManagerScopedGuard guard(configuration);
//..
// Note that the application is now prepared to log messages using the 'ball'
// logging subsystem, but until the application registers an observer, all log
// messages will be discarded.
//
// Finally, we create a 'ball::FileObserver' object 'observer' that will
// publish records to a file, and exceptional records to 'stdout'. We
// configure the log format to publish log attributes (see
// {Key Example 1: Write to a Log}, enable the logger to write to a log file,
// and then register 'observer' with the logger manager. Note that observers
// must be registered by name; this example simply uses "default" for a name:
//..
bslma::Allocator *alloc = bslma::Default::globalAllocator(0);
//
bsl::shared_ptr<ball::FileObserver> observer =
bsl::allocate_shared<ball::FileObserver>(alloc);
observer->setLogFormat(
ball::RecordStringFormatter::k_BASIC_ATTRIBUTE_FORMAT,
ball::RecordStringFormatter::k_BASIC_ATTRIBUTE_FORMAT);
if (0 != observer->enableFileLogging("myapplication.log.%T")) {
bsl::cout << "Failed to enable logging" << bsl::endl;
return -1;
}
ball::LoggerManager::singleton().registerObserver(observer, "default");
//..
// The application is now prepared to log messages using the 'ball' logging
// subsystem:
//..
// ...
//
BALL_LOG_SET_CATEGORY("MYLIBRARY.MYSUBSYSTEM");
BALL_LOG_ERROR << "Exiting the application (0)";
return 0;
}
//..
// Note that concrete observers that can be configured after their creation
// (e.g., as to whether log records are published in UTC or local time)
// generally can have their configuration adjusted at any time, either before
// or after being registered with a logger manager. For an example of such an
// observer, see 'ball_asyncfileobserver'.
| 3,624 | 991 |
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoBlueprintBase_VariableMovement_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.BlueprintPlayAnimationEvent
struct UDinoBlueprintBase_VariableMovement_C_BlueprintPlayAnimationEvent_Params
{
class UAnimMontage** AnimationMontage; // (Parm, ZeroConstructor, IsPlainOldData)
float* PlayRate; // (Parm, ZeroConstructor, IsPlainOldData)
float playedAnimLength; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5076
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5076_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3750
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3750_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5075
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5075_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_774
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_774_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3749
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3749_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3748
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3748_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3747
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3747_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3746
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3746_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5074
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5074_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5073
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5073_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3745
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3745_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3744
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3744_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5070
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5070_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_240
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_240_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5069
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5069_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3743
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3743_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3742
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3742_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5068
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5068_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5067
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5067_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3741
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3741_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3740
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3740_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3739
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3739_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_773
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_773_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3738
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3738_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3737
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3737_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3736
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3736_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_228
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_228_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_227
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_227_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_408
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_408_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3735
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3735_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_239
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_239_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3734
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3734_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_407
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_407_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5062
struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5062_Params
{
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.BlueprintUpdateAnimation
struct UDinoBlueprintBase_VariableMovement_C_BlueprintUpdateAnimation_Params
{
float* DeltaTimeX; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.ExecuteUbergraph_DinoBlueprintBase_VariableMovement
struct UDinoBlueprintBase_VariableMovement_C_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 14,355 | 4,746 |
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
*
* Copyright (c) 2020 fortiss GmbH, Stefan Profanter
* All rights reserved.
*/
#include "SimGripper.h"
bool SimGripper::startVaccum() {
return true;
}
bool SimGripper::stopVaccum() {
return true;
}
bool SimGripper::dropOff() {
return true;
}
| 397 | 137 |
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,x,res=0;
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
}
if(n==1){
res = 1;
cout<<res<<"\n";
}
else if(n==1){
res = 2;
cout<<res<<"\n";
}
else{
res = n/2;
cout<<res<<"\n";
}
return 0;
} | 341 | 150 |
#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <map>
#define EPS 0.001
using namespace std;
// day = 24 hours + 1/7 week
// = 24 (60 min) + 1/7(1/4 month)
// = 24( 60(60 sec)+ 1/7(1/4(1/12 year)
typedef struct{
string incUnit;
double inc = 0;
string decUnit;
double dec = 0;
}Ratio;
typedef map<string, Ratio> ratioMap; //map<unit,ratio>
namespace ariel{
// increase and decrease unitsMap
static ratioMap _ratioMap = ratioMap();
class NumberWithUnits
{
private:
map<string, map<string, double>> _unitsMap;
double _val;
string _unit;
double getRelation(string const &otherUnit) const;
double getRelationIncOrDec(string const &otherUnit, bool converUp) const;
public:
NumberWithUnits(double num, string const &unit);
~NumberWithUnits(){}
static void read_units(ifstream& file);
// unary operators
NumberWithUnits operator-() const;
NumberWithUnits operator+() const;
// arithmetics operators
friend NumberWithUnits operator*(const double mult, const NumberWithUnits& other);
NumberWithUnits operator*(const double mult) const;
NumberWithUnits operator+(const NumberWithUnits& other) const;
NumberWithUnits operator+=(const NumberWithUnits& other);
NumberWithUnits operator-(const NumberWithUnits& other) const;
NumberWithUnits operator-=(const NumberWithUnits& other) ;
// prefix ( operator++() ) and postfix ( operator++(int) )
NumberWithUnits& operator++();
NumberWithUnits operator++(int);
NumberWithUnits& operator--();
NumberWithUnits operator--(int);
// compering operators
bool operator<(const NumberWithUnits& other) const;
bool operator<=(const NumberWithUnits& other) const;
bool operator>(const NumberWithUnits& other) const;
bool operator>=(const NumberWithUnits& other) const;
bool operator==(const NumberWithUnits& other) const;
bool operator!=(const NumberWithUnits& other) const;
// ostream operators
friend ostream& operator<< (ostream& out, const NumberWithUnits& num);
friend istream& operator>> (istream& input, NumberWithUnits& num);
};
}
| 2,319 | 700 |
// Copyright Benoit Blanchon 2014-2016
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
// If you like this project, please add a star!
#pragma once
#include "../Polyfills/isInfinity.hpp"
#include "../Polyfills/isNaN.hpp"
#include "../Polyfills/normalize.hpp"
#include "../Print.hpp"
#include "Encoding.hpp"
#include "ForceInline.hpp"
#include "JsonFloat.hpp"
#include "JsonInteger.hpp"
namespace ArduinoJson {
namespace Internals {
// Writes the JSON tokens to a Print implementation
// This class is used by:
// - JsonArray::writeTo()
// - JsonObject::writeTo()
// - JsonVariant::writeTo()
// Its derived by PrettyJsonWriter that overrides some members to add
// indentation.
class JsonWriter {
public:
explicit JsonWriter(Print &sink) : _sink(sink), _length(0) {}
// Returns the number of bytes sent to the Print implementation.
// This is very handy for implementations of printTo() that must return the
// number of bytes written.
size_t bytesWritten() const { return _length; }
void beginArray() { writeRaw('['); }
void endArray() { writeRaw(']'); }
void beginObject() { writeRaw('{'); }
void endObject() { writeRaw('}'); }
void writeColon() { writeRaw(':'); }
void writeComma() { writeRaw(','); }
void writeBoolean(bool value) { writeRaw(value ? "true" : "false"); }
void writeString(const char *value) {
if (!value) {
writeRaw("null");
} else {
writeRaw('\"');
while (*value) writeChar(*value++);
writeRaw('\"');
}
}
void writeChar(char c) {
char specialChar = Encoding::escapeChar(c);
if (specialChar) {
writeRaw('\\');
writeRaw(specialChar);
} else {
writeRaw(c);
}
}
void writeFloat(JsonFloat value, int digits = 2) {
if (Polyfills::isNaN(value)) return writeRaw("NaN");
if (value < 0.0) {
writeRaw('-');
value = -value;
}
if (Polyfills::isInfinity(value)) return writeRaw("Infinity");
short powersOf10;
if (value > 1000 || value < 0.001) {
powersOf10 = Polyfills::normalize(value);
} else {
powersOf10 = 0;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
JsonFloat rounding = 0.5;
for (uint8_t i = 0; i < digits; ++i) rounding /= 10.0;
value += rounding;
// Extract the integer part of the value and print it
JsonUInt int_part = static_cast<JsonUInt>(value);
JsonFloat remainder = value - static_cast<JsonFloat>(int_part);
writeInteger(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0) {
writeRaw('.');
}
// Extract digits from the remainder one at a time
while (digits-- > 0) {
remainder *= 10.0;
JsonUInt toPrint = JsonUInt(remainder);
writeInteger(JsonUInt(remainder));
remainder -= static_cast<JsonFloat>(toPrint);
}
if (powersOf10 < 0) {
writeRaw("e-");
writeInteger(-powersOf10);
}
if (powersOf10 > 0) {
writeRaw('e');
writeInteger(powersOf10);
}
}
void writeInteger(JsonUInt value) {
char buffer[22];
uint8_t i = 0;
do {
buffer[i++] = static_cast<char>(value % 10 + '0');
value /= 10;
} while (value);
while (i > 0) {
writeRaw(buffer[--i]);
}
}
void writeRaw(const char *s) { _length += _sink.print(s); }
void writeRaw(char c) { _length += _sink.write(c); }
protected:
Print &_sink;
size_t _length;
private:
JsonWriter &operator=(const JsonWriter &); // cannot be assigned
};
}
}
| 3,567 | 1,257 |
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result= 0;
for(int i=0; i<32; i++)
result = (result<<1) + (n>>i &1);
return result;
}
}; | 209 | 83 |
/** @file
Code for class to manage configuration updates
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "tscore/ink_platform.h"
#include "tscore/ink_file.h"
#include "tscore/I_Layout.h"
#include "FileManager.h"
#include "Main.h"
#include "Rollback.h"
#include "WebMgmtUtils.h"
#include "MgmtUtils.h"
#include "ExpandingArray.h"
#include "MgmtSocket.h"
#include <vector>
#include <algorithm>
#define DIR_MODE S_IRWXU
#define FILE_MODE S_IRWXU
FileManager::FileManager()
{
bindings = ink_hash_table_create(InkHashTableKeyType_String);
ink_assert(bindings != nullptr);
ink_mutex_init(&accessLock);
ink_mutex_init(&cbListLock);
}
// FileManager::~FileManager
//
// There is only FileManager object in the process and it
// should never need to be destructed except at
// program exit
//
FileManager::~FileManager()
{
callbackListable *cb;
Rollback *rb;
InkHashTableEntry *entry;
InkHashTableIteratorState iterator_state;
// Let other operations finish and do not start any new ones
ink_mutex_acquire(&accessLock);
for (cb = cblist.pop(); cb != nullptr; cb = cblist.pop()) {
delete cb;
}
for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr;
entry = ink_hash_table_iterator_next(bindings, &iterator_state)) {
rb = (Rollback *)ink_hash_table_entry_value(bindings, entry);
delete rb;
}
ink_hash_table_destroy(bindings);
ink_mutex_release(&accessLock);
ink_mutex_destroy(&accessLock);
ink_mutex_destroy(&cbListLock);
}
// void FileManager::registerCallback(FileCallbackFunc func)
//
// Adds a new callback function
// callbacks are made whenever a configuration file has
// changed
//
// The callback function is responsible for free'ing
// the string the string it is passed
//
void
FileManager::registerCallback(FileCallbackFunc func)
{
callbackListable *newcb = new callbackListable();
ink_assert(newcb != nullptr);
newcb->func = func;
ink_mutex_acquire(&cbListLock);
cblist.push(newcb);
ink_mutex_release(&cbListLock);
}
// void FileManager::addFile(char* fileName, const configFileInfo* file_info,
// Rollback* parentRollback)
//
// for the baseFile, creates a Rollback object for it
//
// if file_info is not null, a WebFileEdit object is also created for
// the file
//
// Pointers to the new objects are stored in the bindings hashtable
//
void
FileManager::addFile(const char *fileName, bool root_access_needed, Rollback *parentRollback, unsigned flags)
{
ink_mutex_acquire(&accessLock);
addFileHelper(fileName, root_access_needed, parentRollback, flags);
ink_mutex_release(&accessLock);
}
// caller must hold the lock
void
FileManager::addFileHelper(const char *fileName, bool root_access_needed, Rollback *parentRollback, unsigned flags)
{
ink_assert(fileName != nullptr);
Rollback *rb = new Rollback(fileName, root_access_needed, parentRollback, flags);
rb->configFiles = this;
ink_hash_table_insert(bindings, fileName, rb);
}
// bool FileManager::getRollbackObj(char* fileName, Rollback** rbPtr)
//
// Sets rbPtr to the rollback object associated
// with the passed in fileName.
//
// If there is no binding, falseis returned
//
bool
FileManager::getRollbackObj(const char *fileName, Rollback **rbPtr)
{
InkHashTableValue lookup = nullptr;
int found;
ink_mutex_acquire(&accessLock);
found = ink_hash_table_lookup(bindings, fileName, &lookup);
ink_mutex_release(&accessLock);
*rbPtr = (Rollback *)lookup;
return (found == 0) ? false : true;
}
// bool FileManager::fileChanged(const char* fileName)
//
// Called by the Rollback class whenever a a config has changed
// Initiates callbacks
//
//
void
FileManager::fileChanged(const char *fileName, bool incVersion)
{
callbackListable *cb;
char *filenameCopy;
Debug("lm", "filename changed %s", fileName);
ink_mutex_acquire(&cbListLock);
for (cb = cblist.head; cb != nullptr; cb = cb->link.next) {
// Dup the string for each callback to be
// defensive incase it modified when it is not supposed to be
filenameCopy = ats_strdup(fileName);
(*cb->func)(filenameCopy, incVersion);
ats_free(filenameCopy);
}
ink_mutex_release(&cbListLock);
}
// void FileManger::rereadConfig()
//
// Interates through the list of managed files and
// calls Rollback::checkForUserUpdate on them
//
// although it is tempting, DO NOT CALL FROM SIGNAL HANDLERS
// This function is not Async-Signal Safe. It
// is thread safe
void
FileManager::rereadConfig()
{
Rollback *rb;
InkHashTableEntry *entry;
InkHashTableIteratorState iterator_state;
std::vector<Rollback *> changedFiles;
std::vector<Rollback *> parentFileNeedChange;
size_t n;
ink_mutex_acquire(&accessLock);
for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr;
entry = ink_hash_table_iterator_next(bindings, &iterator_state)) {
rb = (Rollback *)ink_hash_table_entry_value(bindings, entry);
if (rb->checkForUserUpdate(rb->isVersioned() ? ROLLBACK_CHECK_AND_UPDATE : ROLLBACK_CHECK_ONLY)) {
changedFiles.push_back(rb);
if (rb->isChildRollback()) {
if (std::find(parentFileNeedChange.begin(), parentFileNeedChange.end(), rb->getParentRollback()) ==
parentFileNeedChange.end()) {
parentFileNeedChange.push_back(rb->getParentRollback());
}
}
}
}
std::vector<Rollback *> childFileNeedDelete;
n = changedFiles.size();
for (size_t i = 0; i < n; i++) {
if (changedFiles[i]->isChildRollback()) {
continue;
}
// for each parent file, if it is changed, then delete all its children
for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr;
entry = ink_hash_table_iterator_next(bindings, &iterator_state)) {
rb = (Rollback *)ink_hash_table_entry_value(bindings, entry);
if (rb->getParentRollback() == changedFiles[i]) {
if (std::find(childFileNeedDelete.begin(), childFileNeedDelete.end(), rb) == childFileNeedDelete.end()) {
childFileNeedDelete.push_back(rb);
}
}
}
}
n = childFileNeedDelete.size();
for (size_t i = 0; i < n; i++) {
ink_hash_table_delete(bindings, childFileNeedDelete[i]->getFileName());
delete childFileNeedDelete[i];
}
ink_mutex_release(&accessLock);
n = parentFileNeedChange.size();
for (size_t i = 0; i < n; i++) {
if (std::find(changedFiles.begin(), changedFiles.end(), parentFileNeedChange[i]) == changedFiles.end()) {
fileChanged(parentFileNeedChange[i]->getFileName(), true);
}
}
// INKqa11910
// need to first check that enable_customizations is enabled
bool found;
int enabled = (int)REC_readInteger("proxy.config.body_factory.enable_customizations", &found);
if (found && enabled) {
fileChanged("proxy.config.body_factory.template_sets_dir", true);
}
fileChanged("proxy.config.ssl.server.ticket_key.filename", true);
}
bool
FileManager::isConfigStale()
{
Rollback *rb;
InkHashTableEntry *entry;
InkHashTableIteratorState iterator_state;
bool stale = false;
ink_mutex_acquire(&accessLock);
for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr;
entry = ink_hash_table_iterator_next(bindings, &iterator_state)) {
rb = (Rollback *)ink_hash_table_entry_value(bindings, entry);
if (rb->checkForUserUpdate(ROLLBACK_CHECK_ONLY)) {
stale = true;
break;
}
}
ink_mutex_release(&accessLock);
return stale;
}
// void configFileChild(const char *parent, const char *child)
//
// Add child to the bindings with parentRollback
void
FileManager::configFileChild(const char *parent, const char *child, unsigned flags)
{
InkHashTableValue lookup;
Rollback *parentRollback = nullptr;
ink_mutex_acquire(&accessLock);
int htfound = ink_hash_table_lookup(bindings, parent, &lookup);
if (htfound) {
parentRollback = (Rollback *)lookup;
addFileHelper(child, parentRollback->rootAccessNeeded(), parentRollback, flags);
}
ink_mutex_release(&accessLock);
}
| 8,873 | 2,956 |
#include <bits/stdc++.h>
using namespace std;
int main( void )
{
int n = 0, t = 0;
cin >> n >> t;
char pos[n];
cin >> pos;
while( t-- )
{
for(int i = 1; i < n; i++)
{
if( pos[i] == 'G' && pos[i - 1] == 'B')
{
pos[i] = 'B';
pos[i - 1] = 'G';
i++;
}
}
}
cout << pos << endl;
return 0;
}
| 438 | 177 |
#ifndef E2_I_NODE_INOUT_HPP
#define E2_I_NODE_INOUT_HPP
#include <thread>
#include <functional>
#include <type_traits>
#include <list>
namespace e2 { namespace interface {
template< class Impl >
class i_node_inout : public Impl {
public:
std::list< i_node_inout * > _in;
std::list< i_node_inout * > _out;
};
} }
#endif
| 332 | 141 |
/*
//@HEADER
// ************************************************************************
//
// nonlinear_solvers.hpp
// Pressio
// Copyright 2019
// National Technology & Engineering Solutions of Sandia, LLC (NTESS)
//
// Under the terms of Contract DE-NA0003525 with NTESS, the
// U.S. Government retains certain rights in this software.
//
// Pressio is licensed under BSD-3-Clause terms of use:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef PRESSIO4PY_PYBINDINGS_NONLINEAR_SOLVERS_HPP_
#define PRESSIO4PY_PYBINDINGS_NONLINEAR_SOLVERS_HPP_
namespace pressio4py{ namespace solvers{
void bindUpdatingEnums(pybind11::module & m)
{
pybind11::enum_<pressio::nonlinearsolvers::Update>(m, "update")
.value("Standard",
pressio::nonlinearsolvers::Update::Standard)
.value("Armijo",
pressio::nonlinearsolvers::Update::Armijo)
.value("LMSchedule1",
pressio::nonlinearsolvers::Update::LMSchedule1)
.value("LMSchedule2",
pressio::nonlinearsolvers::Update::LMSchedule2)
.export_values();
}
void bindStoppingEnums(pybind11::module & m)
{
pybind11::enum_<pressio::nonlinearsolvers::Stop>(m, "stop")
.value("WhenCorrectionAbsoluteNormBelowTolerance",
pressio::nonlinearsolvers::Stop::WhenCorrectionAbsoluteNormBelowTolerance)
.value("WhenCorrectionRelativeNormBelowTolerance",
pressio::nonlinearsolvers::Stop::WhenCorrectionRelativeNormBelowTolerance)
.value("WhenResidualAbsoluteNormBelowTolerance",
pressio::nonlinearsolvers::Stop::WhenResidualAbsoluteNormBelowTolerance)
.value("WhenResidualRelativeNormBelowTolerance",
pressio::nonlinearsolvers::Stop::WhenResidualRelativeNormBelowTolerance)
.value("WhenGradientAbsoluteNormBelowTolerance",
pressio::nonlinearsolvers::Stop::WhenGradientAbsoluteNormBelowTolerance)
.value("WhenGradientRelativeNormBelowTolerance",
pressio::nonlinearsolvers::Stop::WhenGradientRelativeNormBelowTolerance)
.value("AfterMaxIters",
pressio::nonlinearsolvers::Stop::AfterMaxIters)
.export_values();
}
template <typename nonlinear_solver_t>
void bindCommonSolverMethods(pybind11::class_<nonlinear_solver_t> & solverObj)
{
// methods to set and query num of iterations
solverObj.def("maxIterations",
&nonlinear_solver_t::maxIterations);
solverObj.def("setMaxIterations",
&nonlinear_solver_t::setMaxIterations);
// updating criterion
solverObj.def("setUpdatingCriterion",
&nonlinear_solver_t::setUpdatingCriterion);
solverObj.def("updatingCriterion",
&nonlinear_solver_t::updatingCriterion);
}
template <typename nonlinear_solver_t>
void bindTolerancesMethods(pybind11::class_<nonlinear_solver_t> & solverObj)
{
// tolerances
solverObj.def("setTolerance",
&nonlinear_solver_t::setTolerance);
solverObj.def("setCorrectionAbsoluteTolerance",
&nonlinear_solver_t::setCorrectionAbsoluteTolerance);
solverObj.def("setCorrectionRelativeTolerance",
&nonlinear_solver_t::setCorrectionRelativeTolerance);
solverObj.def("setResidualAbsoluteTolerance",
&nonlinear_solver_t::setResidualAbsoluteTolerance);
solverObj.def("setResidualRelativeTolerance",
&nonlinear_solver_t::setResidualRelativeTolerance);
solverObj.def("setGradientAbsoluteTolerance",
&nonlinear_solver_t::setGradientAbsoluteTolerance);
solverObj.def("setGradientRelativeTolerance",
&nonlinear_solver_t::setGradientRelativeTolerance);
solverObj.def("correctionAbsoluteTolerance",
&nonlinear_solver_t::correctionAbsoluteTolerance);
solverObj.def("correctionRelativeTolerance",
&nonlinear_solver_t::correctionRelativeTolerance);
solverObj.def("residualAbsoluteTolerance",
&nonlinear_solver_t::residualAbsoluteTolerance);
solverObj.def("residualRelativeTolerance",
&nonlinear_solver_t::residualRelativeTolerance);
solverObj.def("gradientAbsoluteTolerance",
&nonlinear_solver_t::gradientAbsoluteTolerance);
solverObj.def("gradientRelativeTolerance",
&nonlinear_solver_t::gradientRelativeTolerance);
}
template <typename nonlinear_solver_t>
void bindStoppingCriteria(pybind11::class_<nonlinear_solver_t> & solverObj)
{
// stopping criterion
solverObj.def("setStoppingCriterion",
&nonlinear_solver_t::setStoppingCriterion);
solverObj.def("stoppingCriterion",
&nonlinear_solver_t::stoppingCriterion);
};
//------------------------------------------------
// template <typename T, typename = void>
// struct has_system_typedef : std::false_type{};
// template <typename T>
// struct has_system_typedef<
// T, pressio::mpl::enable_if_t< !std::is_void<typename T::system_t >::value >
// > : std::true_type{};
// template <typename T, typename = void>
// struct has_stepper_typedef : std::false_type{};
// template <typename T>
// struct has_stepper_typedef<
// T, pressio::mpl::enable_if_t< !std::is_void<typename T::stepper_t >::value >
// > : std::true_type{};
// //-----------------------------------------------
// template<typename, typename = void>
// struct _have_rj_api;
// template<class T>
// struct _have_rj_api<
// T, pressio::mpl::enable_if_t< has_system_typedef<T>::value >
// >
// {
// static constexpr auto value =
// pressio::solvers::constraints::system_residual_jacobian<typename T::system_t>::value;
// };
// template<class T>
// struct _have_rj_api<
// T, pressio::mpl::enable_if_t< has_stepper_typedef<T>::value >
// >
// {
// static constexpr auto value =
// pressio::solvers::constraints::system_residual_jacobian<typename T::stepper_t>::value;
// };
// //------------------------------------------------
// template<class...>
// struct _have_rj_api_var;
// template<class head>
// struct _have_rj_api_var<head>
// {
// static constexpr auto value = _have_rj_api<head>::value;
// };
// template<class head, class... tail>
// struct _have_rj_api_var<head, tail...>
// {
// static constexpr auto value = _have_rj_api<head>::value
// and _have_rj_api_var<tail...>::value;
// };
// //------------------------------------------------
// template<class ...> struct bindCreateSolverVariadic;
// template<class SystemType>
// struct bindCreateSolverVariadic<SystemType>
// {
// template<class nonlinear_solver_t, class lin_s_t, typename tag>
// static void bind(pybind11::module & m, const std::string & createFuncName)
// {
// m.def(createFuncName.c_str(),
// &createSolver<nonlinear_solver_t, lin_s_t, SystemType, tag>,
// pybind11::return_value_policy::take_ownership);
// }
// };
// template<class head, class ... tail>
// struct bindCreateSolverVariadic<head, tail...>
// {
// template<class nonlinear_solver_t, class lin_s_t, class tag>
// static void bind(pybind11::module & m, const std::string & name)
// {
// bindCreateSolverVariadic<head>::template bind<nonlinear_solver_t, lin_s_t, tag>(m, name);
// bindCreateSolverVariadic<tail...>::template bind<nonlinear_solver_t, lin_s_t, tag>(m, name);
// }
// };
// template<class nonlinear_solver_t, class rom_problem_t, class tagT>
// pressio::mpl::enable_if_t<std::is_same<tagT, Unweighted>::value, nonlinear_solver_t>
// createSolver(rom_problem_t & romProb,
// const typename rom_problem_t::lspg_native_state_t & romState,
// pybind11::object pyobj) //linear or QR solver is a native python class
// {
// return nonlinear_solver_t(romProb, romState, pyobj);
// }
// template<class nonlinear_solver_t, class rom_problem_t, class tagT>
// pressio::mpl::enable_if_t<std::is_same<tagT, Weighted>::value, nonlinear_solver_t>
// createSolver(rom_problem_t & romProb,
// const typename rom_problem_t::lspg_native_state_t & romState,
// pybind11::object pyobj, // linear solver for norm eq is a native python class
// pybind11::object wO) // weighting operator is a native python class
// {
// return nonlinear_solver_t(romProb, romState, pyobj, wO);
// }
// template<class nonlinear_solver_t, class rom_problem_t, class tagT>
// pressio::mpl::enable_if_t<std::is_same<tagT, Irwls>::value, nonlinear_solver_t>
// createSolver(rom_problem_t & romProb,
// const typename rom_problem_t::lspg_native_state_t & romState,
// pybind11::object pyobj, // linear solver for norm eq is a native python class
// typename rom_problem_t::traits::scalar_t pNorm) // value of p-norm
// {
// return nonlinear_solver_t(romProb, romState, pyobj, pNorm);
// }
// template<class nonlinear_solver_t, class lin_s_t, class system_t, class tagT>
// pressio::mpl::enable_if_t<std::is_same<tagT, NewtonRaphson>::value, nonlinear_solver_t>
// createSolver(system_t & system,
// ::pressio4py::py_f_arr romState,
// pybind11::object pyobj)
// {
// std::cout << " create " << &system << " " << pyobj << "\n";
// return nonlinear_solver_t(system, romState, lin_s_t(pyobj));
// }
// helper tags
struct NewtonRaphson{};
struct LSUnweighted{};
struct LSWeighted{};
// struct Irwls{};
template<class nonlinear_solver_t, class lin_s_t, class system_t, class tagT>
pressio::mpl::enable_if_t<std::is_same<tagT, LSUnweighted>::value, nonlinear_solver_t>
createSolver(pybind11::object pysystem,
::pressio4py::py_f_arr romState,
pybind11::object pysol)
{
return nonlinear_solver_t(system_t(pysystem), romState, lin_s_t(pysol));
}
template<class nonlinear_solver_t, class lin_s_t, class system_t, class WeighWrapper, class tagT>
pressio::mpl::enable_if_t<std::is_same<tagT, LSWeighted>::value, nonlinear_solver_t>
createSolver(pybind11::object pysystem,
::pressio4py::py_f_arr romState,
pybind11::object pysol, // py solver
pybind11::object pywo) // py weighting operator
{
return nonlinear_solver_t(system_t(pysystem), romState, lin_s_t(pysol), WeighWrapper(pywo));
}
template<class nonlinear_solver_t, class lin_s_t, class system_t, class tagT>
pressio::mpl::enable_if_t<std::is_same<tagT, NewtonRaphson>::value, nonlinear_solver_t>
createSolver(pybind11::object pysystem,
::pressio4py::py_f_arr romState,
pybind11::object pysol)
{
return nonlinear_solver_t(system_t(pysystem), romState, lin_s_t(pysol));
}
//---------------------------------------------------
/* newton-raphson */
//---------------------------------------------------
template<class linear_solver_t, class ResJacSystemWrapper>
struct NewtonRaphsonBinder
{
using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::ComposeNewtonRaphson<
pressio4py::py_f_arr, ResJacSystemWrapper, linear_solver_t
>::type;
static void bindClassAndMethods(pybind11::module & m)
{
pybind11::class_<nonlinear_solver_t> solver(m, "NewtonRaphClass");
// Note we don't bind the constructor because from Python we use the create
// function (see below) to instantiate a solver object, we never
// use the class name directly.
m.def("create_newton_raphson",
&createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, NewtonRaphson>,
pybind11::return_value_policy::take_ownership);
bindTolerancesMethods(solver);
bindStoppingCriteria(solver);
bindCommonSolverMethods(solver);
solver.def("solve",
&nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>);
}
// static void bindCreate(pybind11::module & m){
// const std::string name = "create_newton_raphson";
// m.def(name.c_str(),
// &createSolverForPy<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, NewtonRaphson>,
// pybind11::return_value_policy::take_ownership);
// }
// template<class ...Systems>
// static void bindCreate(pybind11::module & m){
// const std::string name = "create_newton_raphson";
// bindCreateSolverVariadic<Systems...>::template bind<
// nonlinear_solver_t, linear_solver_t, NewtonRaphson>(m, name);
// }
};
//------------------------------------------------
/* GN: R/J API with normal equations */
//------------------------------------------------
template<class linear_solver_t, class ResJacSystemWrapper>
struct GNNormalEqResJacApiBinder{
using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose<
pressio4py::py_f_arr, ResJacSystemWrapper,
::pressio::nonlinearsolvers::GaussNewton, void, linear_solver_t
>::type;
static void bindClassAndMethods(pybind11::module & m)
{
pybind11::class_<nonlinear_solver_t> solver(m, "GaussNewton");
m.def("create_gauss_newton",
&createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, LSUnweighted>,
pybind11::return_value_policy::take_ownership);
bindTolerancesMethods(solver);
bindStoppingCriteria(solver);
bindCommonSolverMethods(solver);
solver.def("solve",
&nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>);
}
};
//------------------------------------------------
/* WEIGHTED GN: R/J API with normal equations */
//------------------------------------------------
template<class linear_solver_t, class ResJacSystemWrapper, class WeighWrapper>
struct WeighGNNormalEqResJacApiBinder{
using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose<
pressio4py::py_f_arr, ResJacSystemWrapper,
::pressio::nonlinearsolvers::GaussNewton, void, linear_solver_t, WeighWrapper
>::type;
static void bindClassAndMethods(pybind11::module & m)
{
pybind11::class_<nonlinear_solver_t> solver(m, "WeightedGaussNewton");
m.def("create_weighted_gauss_newton",
&createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, WeighWrapper, LSWeighted>,
pybind11::return_value_policy::take_ownership);
bindTolerancesMethods(solver);
bindStoppingCriteria(solver);
bindCommonSolverMethods(solver);
solver.def("solve",
&nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>);
}
};
//------------------------------------------------
/* GN: R/J API with QR */
//------------------------------------------------
template<class qr_solver_t, class ResJacSystemWrapper>
struct GNQRResJacApiBinder{
using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::ComposeGNQR<
pressio4py::py_f_arr, ResJacSystemWrapper, qr_solver_t
>::type;
static void bindClassAndMethods(pybind11::module & m)
{
pybind11::class_<nonlinear_solver_t> solver(m, "GaussNewtonQR");
m.def("create_gauss_newton_qr",
&createSolver<nonlinear_solver_t, qr_solver_t, ResJacSystemWrapper, LSUnweighted>,
pybind11::return_value_policy::take_ownership);
bindTolerancesMethods(solver);
bindStoppingCriteria(solver);
bindCommonSolverMethods(solver);
solver.def("solve",
&nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>);
}
};
//------------------------------------------------
/* LM: R/J API with normal equations */
//------------------------------------------------
template<class linear_solver_t, class ResJacSystemWrapper>
struct LMNormalEqResJacApiBinder
{
using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose<
pressio4py::py_f_arr, ResJacSystemWrapper,
::pressio::nonlinearsolvers::LM, void, linear_solver_t
>::type;
static void bindClassAndMethods(pybind11::module & m)
{
pybind11::class_<nonlinear_solver_t> solver(m, "LevenbergMarquardt");
m.def("create_levenberg_marquardt",
&createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, LSUnweighted>,
pybind11::return_value_policy::take_ownership);
bindTolerancesMethods(solver);
bindStoppingCriteria(solver);
bindCommonSolverMethods(solver);
solver.def("solve",
&nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>);
}
};
//------------------------------------------------
/* WEIGHTED LM: R/J API with normal equations */
//------------------------------------------------
template<class linear_solver_t, class ResJacSystemWrapper, class WeighWrapper>
struct WeighLMNormalEqResJacApiBinder
{
using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose<
pressio4py::py_f_arr, ResJacSystemWrapper,
::pressio::nonlinearsolvers::LM, void, linear_solver_t, WeighWrapper
>::type;
static void bindClassAndMethods(pybind11::module & m)
{
pybind11::class_<nonlinear_solver_t> solver(m, "WeightedLevenbergMarquardt");
m.def("create_weighted_levenberg_marquardt",
&createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, WeighWrapper, LSWeighted>,
pybind11::return_value_policy::take_ownership);
bindTolerancesMethods(solver);
bindStoppingCriteria(solver);
bindCommonSolverMethods(solver);
solver.def("solve",
&nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>);
}
};
}}//end namespace
#endif
// template<bool do_gn, typename ...>
// struct LeastSquaresNormalEqResJacApiBinder;
// template<bool do_gn, typename linear_solver_wrapper_t, typename ...Problems>
// struct LeastSquaresNormalEqResJacApiBinder<do_gn, linear_solver_wrapper_t, std::tuple<Problems...>>
// {
// static_assert(_have_rj_api_var<Problems...>::value, "");
// // it does not matter here if we use the steady system or stepper_t
// // as template arg to compose the solver type in the code below as long as it
// // meets the res-jac api. But since we are here, this condition is met
// // because it is asserted above. so just pick the first problem type in the
// // pack, which should be a steady lspg problem, and so it has a system_t typedef
// // that we can use for compose solver below
// using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type;
// using system_t = typename head_problem_t::system_t;
// // gauss-newton solver type
// using gn_type = pressio::nonlinearsolvers::impl::composeGaussNewton_t
// <system_t, linear_solver_wrapper_t>;
// // lm solver type
// using lm_type = pressio::nonlinearsolvers::impl::composeLevenbergMarquardt_t
// <system_t, linear_solver_wrapper_t>;
// // pick gn or lm conditioned on the bool argument
// using nonlinear_solver_t = typename std::conditional<do_gn, gn_type, lm_type>::type;
// static void bindClass(pybind11::module & m, const std::string & solverPythonName)
// {
// pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str());
// bindTolerancesMethods(nonLinSolver);
// bindStoppingCriteria(nonLinSolver);
// bindCommonSolverMethods(nonLinSolver);
// // Note we don't bind the constructor because from Python we use the create
// // function (see below) to instantiate a solver object, we never
// // use the class name directly. This is useful because it allows us
// // to overcome the problem of needing unique class names in python
// }
// static void bindCreate(pybind11::module & m)
// {
// const std::string name = do_gn ? "createGaussNewton" : "createLevenbergMarquardt";
// bindCreateSolverVariadic<Problems...>::template bind<
// nonlinear_solver_t, Unweighted>(m, name);
// }
// };
// //------------------------------------------------
// /* GN, R/H API solved with QR */
// //------------------------------------------------
// template<bool do_gn, class ...>
// struct LeastSquaresQRBinder;
// template<bool do_gn, class qr_solver_t, class ...Problems>
// struct LeastSquaresQRBinder<
// do_gn, qr_solver_t, std::tuple<Problems...>
// >
// {
// static_assert(do_gn, "QR-based solver only supported for GN");
// static_assert(_have_rj_api_var<Problems...>::value, "");
// // it does not matter here if we use the steady system or stepper_t
// // as template arg to compose the solver type in the code below as long as it
// // meets the res-jac api. But since we are here, this condition is met
// // because it is asserted above. so just pick the first problem type in the
// // pack, which should be a steady lspg problem, and so it has a system_t typedef
// // that we can use for compose solver below
// using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type;
// using system_t = typename head_problem_t::system_t;
// using nonlinear_solver_t =
// pressio::nonlinearsolvers::impl::composeGaussNewtonQR_t<system_t, qr_solver_t>;
// static void bindClass(pybind11::module & m, const std::string & solverPythonName)
// {
// pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str());
// bindTolerancesMethods(nonLinSolver);
// bindStoppingCriteria(nonLinSolver);
// bindCommonSolverMethods(nonLinSolver);
// // Note we don't bind the constructor because from Python we use the create
// // function (see below) to instantiate a solver object, we never
// // use the class name directly. This is useful because it allows us
// // to overcome the problem of needing unique class names in python
// }
// static void bindCreate(pybind11::module & m)
// {
// const std::string name = do_gn ? "createGaussNewtonQR" : "createLevenbergMarquardtQR";
// bindCreateSolverVariadic<Problems...>::template bind<
// nonlinear_solver_t, Unweighted>(m, name);
// }
// };
// //----------------------------------------------------
// /* weighted GN or LM, R/J API with normal equations */
// //----------------------------------------------------
// template<bool do_gn, class ...>
// struct WeightedLeastSquaresNormalEqBinder;
// template<
// bool do_gn,
// typename linear_solver_t,
// typename weigher_t,
// class ... Problems
// >
// struct WeightedLeastSquaresNormalEqBinder<
// do_gn, linear_solver_t, weigher_t, std::tuple<Problems...>
// >
// {
// static_assert(_have_rj_api_var<Problems...>::value, "");
// // it does not matter here if we use the steady system or stepper_t
// // as template arg to compose the solver type in the code below as long as it
// // meets the res-jac api. But since we are here, this condition is met
// // because it is asserted above. so just pick the first problem type in the
// // pack, which should be a steady lspg problem, and so it has a system_t typedef
// // that we can use for compose solver below
// using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type;
// using system_t = typename head_problem_t::system_t;
// // gauss-newton solver type
// using gn_type =
// pressio::nonlinearsolvers::impl::composeGaussNewton_t<system_t, linear_solver_t, weigher_t>;
// // lm solver type
// using lm_type =
// pressio::nonlinearsolvers::impl::composeLevenbergMarquardt_t<system_t, linear_solver_t, weigher_t>;
// // pick the final nonlin solver type is based on the do_gn
// using nonlinear_solver_t = typename std::conditional<do_gn, gn_type, lm_type>::type;
// static void bindClass(pybind11::module & m, const std::string & solverPythonName)
// {
// pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str());
// bindTolerancesMethods(nonLinSolver);
// bindStoppingCriteria(nonLinSolver);
// bindCommonSolverMethods(nonLinSolver);
// // Note we don't bind the constructor because from Python we use the create
// // function (see below) to instantiate a solver object, we never
// // use the class name directly. This is useful because it allows us
// // to overcome the problem of needing unique class names in python
// }
// static void bindCreate(pybind11::module & m)
// {
// const std::string name =
// do_gn ? "createWeightedGaussNewton" : "createWeightedLevenbergMarquardt";
// bindCreateSolverVariadic<Problems...>::template bind<
// nonlinear_solver_t, Weighted>(m, name);
// }
// };
// //----------------------------------------
// /* IRWGN normal equations */
// //----------------------------------------
// template<class ...>
// struct IrwLeastSquaresNormalEqBinder;
// template<class linear_solver_t, class ...Problems>
// struct IrwLeastSquaresNormalEqBinder<linear_solver_t, std::tuple<Problems...>>
// {
// static_assert(_have_rj_api_var<Problems...>::value, "");
// // it does not matter here if we use the steady system or stepper_t
// // as template arg to compose the solver type in the code below as long as it
// // meets the res-jac api. But since we are here, this condition is met
// // because it is asserted above. so just pick the first problem type in the
// // pack, which should be a steady lspg problem, and so it has a system_t typedef
// // that we can use for compose solver below
// using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type;
// using system_t = typename head_problem_t::system_t;
// using composer_t = pressio::nonlinearsolvers::impl::composeIrwGaussNewton<system_t, linear_solver_t>;
// using w_t = typename composer_t::weighting_t;
// using nonlinear_solver_t = typename composer_t::type;
// static void bindClass(pybind11::module & m, const std::string & solverPythonName)
// {
// pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str());
// bindTolerancesMethods(nonLinSolver);
// bindStoppingCriteria(nonLinSolver);
// bindCommonSolverMethods(nonLinSolver);
// // Note we don't bind the constructor because from Python we use the create
// // function (see below) to instantiate a solver object, we never
// // use the class name directly. This is useful because it allows us
// // to overcome the problem of needing unique class names in python
// }
// static void bindCreate(pybind11::module & m)
// {
// const std::string name = "createIrwGaussNewton";
// bindCreateSolverVariadic<Problems...>::template bind<
// nonlinear_solver_t, Irwls>(m, name);
// }
// };
// //-------------------------------------------------
// /* GN or LM with normal equations, hess-grad api */
// //-------------------------------------------------
// template<bool do_gn, typename ...>
// struct LeastSquaresNormalEqHessGrapApiBinder;
// template<bool do_gn, typename linear_solver_wrapper_t, typename ...Problems>
// struct LeastSquaresNormalEqHessGrapApiBinder<
// do_gn, linear_solver_wrapper_t, std::tuple<Problems...>
// >
// {
// using system_t = typename std::tuple_element<0, std::tuple<Problems...>>::type;
// // gauss-newton solver type
// using gn_type = pressio::nonlinearsolvers::impl::composeGaussNewton_t
// <system_t, linear_solver_wrapper_t>;
// // lm solver type
// using lm_type = pressio::nonlinearsolvers::impl::composeLevenbergMarquardt_t
// <system_t, linear_solver_wrapper_t>;
// // pick gn or lm conditioned on the bool argument
// using nonlinear_solver_t = typename std::conditional<do_gn, gn_type, lm_type>::type;
// static void bindClass(pybind11::module & m, const std::string & solverPythonName)
// {
// pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str());
// bindTolerancesMethods(nonLinSolver);
// bindStoppingCriteria(nonLinSolver);
// bindCommonSolverMethods(nonLinSolver);
// // Note we don't bind the constructor because from Python we use the create
// // function (see below) to instantiate a solver object, we never
// // use the class name directly. This is useful because it allows us
// // to overcome the problem of needing unique class names in python
// }
// static void bindCreate(pybind11::module & m)
// {
// const std::string name = "createGaussNewton";
// bindCreateSolverVariadic<Problems...>::template bind<
// nonlinear_solver_t, UnweightedWls>(m, name);
// }
// };
// //------------------------------------------------
// // helper metafunction for dealing with types in a tuple
// //------------------------------------------------
// template<template<bool, typename...> class T, bool, typename...>
// struct instantiate_from_tuple_pack { };
// template<
// template<bool, typename...> class T,
// bool b, class T1, typename... Ts
// >
// struct instantiate_from_tuple_pack<T, b, T1, std::tuple<Ts...>>
// {
// using type = T<b, T1, Ts...>;
// };
// template<
// template<bool, typename...> class T,
// bool b, class T1, class T2, typename... Ts
// >
// struct instantiate_from_tuple_pack<T, b, T1, T2, std::tuple<Ts...>>
// {
// using type = T<b, T1, T2, Ts...>;
// };
| 29,880 | 10,250 |
// ------------------------------------------------------------------------------------------------
#include "PocoLib/Register.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
extern void Register_POCO_Crypto(HSQUIRRELVM vm, Table & ns);
extern void Register_POCO_Data(HSQUIRRELVM vm, Table & ns);
extern void Register_POCO_Net(HSQUIRRELVM vm, Table & ns);
extern void Register_POCO_RegEx(HSQUIRRELVM vm, Table & ns);
extern void Register_POCO_Time(HSQUIRRELVM vm, Table & ns);
extern void Register_POCO_Util(HSQUIRRELVM vm, Table & ns);
// ================================================================================================
void Register_POCO(HSQUIRRELVM vm)
{
Table ns(vm);
Register_POCO_Crypto(vm, ns);
Register_POCO_Data(vm, ns);
Register_POCO_Net(vm, ns);
Register_POCO_RegEx(vm, ns);
Register_POCO_Time(vm, ns);
Register_POCO_Util(vm, ns);
RootTable(vm).Bind(_SC("Sq"), ns);
}
} // Namespace:: SqMod
| 1,113 | 344 |
/**
* @file sg_driver.cc
* @author Joseph Lee <development@jc-lab.net>
* @date 2020/07/23
* @copyright Copyright (C) 2020 jc-lab.\n
* This software may be modified and distributed under the terms
* of the Apache License 2.0. See the LICENSE file for details.
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <sys/ioctl.h>
#include "sg_driver.h"
#include "../../intl_utils.h"
#include "../sgio.h"
#include <jcu-dparm/ata_types.h>
#include <jcu-dparm/ata_utils.h>
namespace jcu {
namespace dparm {
namespace plat_linux {
namespace drivers {
class SgDriverHandle : public LinuxDriverHandle {
private:
scsi_sg_device dev_;
std::string path_;
public:
std::string getDriverName() const override {
return "LinuxSgDriver";
}
SgDriverHandle(const scsi_sg_device& dev, const std::string& path, ata::ata_identify_device_data_t *identify_device_data)
: dev_(dev), path_(path) {
const unsigned char *raw_identify_device_data = (const unsigned char *)identify_device_data;
driving_type_ = kDrivingAtapi;
ata_identify_device_buf_.insert(
ata_identify_device_buf_.end(),
&raw_identify_device_data[0],
&raw_identify_device_data[sizeof(ata::ata_identify_device_data_t)]
);
}
int getFD() const override {
return dev_.fd;
}
void close() override {
if (dev_.fd > 0) {
::close(dev_.fd);
dev_.fd = 0;
}
}
int reopenWritable() override {
int new_fd = ::open(path_.c_str(), O_RDWR | O_NONBLOCK);
if (new_fd < 0) {
return new_fd;
}
::close(dev_.fd);
dev_.fd = new_fd;
return 0;
}
bool driverIsAtaCmdSupported() const override {
return true;
}
DparmResult doAtaCmd(
int rw,
unsigned char* cdb,
unsigned int cdb_bytes,
void *data,
unsigned int data_bytes,
int pack_id,
unsigned int timeout_secs,
unsigned char *sense_buf,
unsigned int sense_buf_bytes
) override {
int rc = do_sg_ata(&dev_, rw, cdb, cdb_bytes, data, data_bytes, pack_id, timeout_secs, sense_buf, sense_buf_bytes);
if (rc > 0) {
return { DPARME_ATA_FAILED, rc };
}else if (rc < 0 ) {
return { DPARME_SYS, errno };
}
return { DPARME_OK, 0 };
}
bool driverIsTaskfileCmdSupported() const override {
return true;
}
DparmResult doTaskfileCmd(
int rw,
int dma,
ata::ata_tf_t *tf,
void *data,
unsigned int data_bytes,
unsigned int timeout_secs
) override {
unsigned char sense_data[32] = { 0 };
if (dma < 0) {
dma = ata::is_dma(tf->command);
}
int rc = sg16(&dev_, rw, dma, tf, data, data_bytes, timeout_secs, sense_data, sizeof(sense_data));
if (rc > 0) {
return { DPARME_ATA_FAILED, rc };
}else if (rc < 0 ) {
return { DPARME_SYS, errno };
}
return { DPARME_OK, 0 };
}
/**
* Reference: https://www.seagate.com/files/staticfiles/support/docs/manual/Interface%20manuals/100293068j.pdf
*/
DparmReturn<InquiryDeviceResult> inquiryDeviceInfo() override {
InquiryDeviceResult info = {};
for (int i=0; i < 2; i++) {
int result;
struct sg_io_hdr io_hdr;
unsigned char payload_buffer[192] = {0};
unsigned char sense[32] = {0};
// Standard INQUIRY
unsigned char inq_cmd[] = {
INQUIRY, 0, 0, 0, sizeof(payload_buffer), 0
};
if (i == 1) {
inq_cmd[1] = 1;
inq_cmd[2] = 0x80;
}
memset(&io_hdr, 0, sizeof(io_hdr));
io_hdr.interface_id = 'S';
io_hdr.cmdp = inq_cmd;
io_hdr.cmd_len = sizeof(inq_cmd);
io_hdr.dxferp = payload_buffer;
io_hdr.dxfer_len = sizeof(payload_buffer);
io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
io_hdr.sbp = sense;
io_hdr.mx_sb_len = sizeof(sense);
io_hdr.timeout = 5000;
result = ioctl(dev_.fd, SG_IO, &io_hdr);
if (result < 0) {
return {DPARME_IOCTL_FAILED, errno};
}
if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK) {
return {DPARME_IOCTL_FAILED, 0, (int32_t) io_hdr.info};
}
// fixed length... It may not be the full name.
if (i == 0) {
info.vendor_identification = intl::trimString(intl::readString(&payload_buffer[8], 8));
info.product_identification = intl::trimString(intl::readString(&payload_buffer[16], 16));
info.product_revision_level = intl::trimString(intl::readString(&payload_buffer[32], 4));
} else {
info.drive_serial_number = intl::trimString(intl::readString(&payload_buffer[4], payload_buffer[3]));
}
}
return { DPARME_OK, 0, 0, info };
}
};
DparmReturn<std::unique_ptr<LinuxDriverHandle>> SgDriver::open(const char *path) {
std::string strpath(path);
DparmResult result;
scsi_sg_device dev = {0};
unsigned char sense_data[32];
do {
dev.fd = ::open(path, O_RDONLY | O_NONBLOCK);
if (dev.fd == -1) {
result = { DPARME_SYS, errno };
break;
}
dev.debug_puts = options_.debug_puts;
dev.verbose = options_.verbose;
apt_detect(&dev);
ata::ata_tf_t tf = {0};
ata::ata_identify_device_data_t temp = {0};
tf.command = 0xec;
if (sg16(&dev, 0, 0, &tf, &temp, sizeof(temp), 3, sense_data, sizeof(sense_data)) == -1) {
result = { DPARME_SYS, dev.last_errno };
break;
}
std::unique_ptr<SgDriverHandle> driver_handle(new SgDriverHandle(dev, strpath, &temp));
return {DPARME_OK, 0, 0, std::move(driver_handle)};
} while (0);
if (dev.fd > 0) {
::close(dev.fd);
}
return { result.code, result.sys_error };
}
} // namespace dparm
} // namespace plat_linux
} // namespace dparm
} // namespace jcu
| 5,777 | 2,286 |
//
// Advent of Code 2017, day 22, part one
//
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
struct PairHash {
template<typename T1, typename T2>
std::size_t operator()(const std::pair<T1, T2> &p) const noexcept
{
std::size_t h1 = std::hash<T1>()(p.first);
std::size_t h2 = std::hash<T2>()(p.second);
return (17 * 37 + h1) * 37 + h2;
}
};
using Infected = std::unordered_set<std::pair<int, int>, PairHash>;
auto read_map()
{
std::vector<std::string> map;
for (std::string line; std::getline(std::cin, line) && !line.empty(); ) {
map.push_back(std::move(line));
}
return map;
}
auto get_infected_from_map(const auto &map)
{
Infected infected;
int mid_y = map.size() / 2;
int mid_x = map[0].size() / 2;
for (int y = 0; y < map.size(); ++y) {
for (int x = 0; x < map[y].size(); ++x) {
if (map[y][x] == '#') {
infected.insert({x - mid_x, mid_y - y});
}
}
}
return infected;
}
int main()
{
auto map = read_map();
auto infected = get_infected_from_map(map);
int x = 0;
int y = 0;
int dx = 0;
int dy = 1;
std::size_t num_became_infected = 0;
for (std::size_t bursts = 0; bursts != 10'000; ++bursts) {
if (auto [it, success] = infected.insert({x, y}); !success) {
dx = std::exchange(dy, -dx);
infected.erase(it);
}
else {
dy = std::exchange(dx, -dy);
++num_became_infected;
}
x += dx;
y += dy;
}
std::cout << num_became_infected << '\n';
}
| 1,496 | 712 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "spreadsheetdelegate.h"
#include <QtWidgets>
SpreadSheetDelegate::SpreadSheetDelegate(QObject *parent)
: QItemDelegate(parent) {}
QWidget *SpreadSheetDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &,
const QModelIndex &index) const
{
if (index.column() == 1) {
QDateTimeEdit *editor = new QDateTimeEdit(parent);
editor->setDisplayFormat("dd/M/yyyy");
editor->setCalendarPopup(true);
return editor;
}
QLineEdit *editor = new QLineEdit(parent);
// create a completer with the strings in the column as model
QStringList allStrings;
for (int i = 1; i<index.model()->rowCount(); i++) {
QString strItem(index.model()->data(index.sibling(i, index.column()),
Qt::EditRole).toString());
if (!allStrings.contains(strItem))
allStrings.append(strItem);
}
QCompleter *autoComplete = new QCompleter(allStrings);
editor->setCompleter(autoComplete);
connect(editor, &QLineEdit::editingFinished, this, &SpreadSheetDelegate::commitAndCloseEditor);
return editor;
}
void SpreadSheetDelegate::commitAndCloseEditor()
{
QLineEdit *editor = qobject_cast<QLineEdit *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}
void SpreadSheetDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
if (edit) {
edit->setText(index.model()->data(index, Qt::EditRole).toString());
return;
}
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
if (dateEditor) {
dateEditor->setDate(QDate::fromString(
index.model()->data(index, Qt::EditRole).toString(),
"d/M/yyyy"));
}
}
void SpreadSheetDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model, const QModelIndex &index) const
{
QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
if (edit) {
model->setData(index, edit->text());
return;
}
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
if (dateEditor)
model->setData(index, dateEditor->date().toString("dd/M/yyyy"));
}
| 3,934 | 1,120 |
// Copyright 2021 The Chromium 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 "third_party/blink/renderer/platform/testing/noop_web_url_loader.h"
#include "services/network/public/cpp/resource_request.h"
#include "third_party/blink/public/platform/resource_load_info_notifier_wrapper.h"
#include "third_party/blink/public/platform/web_url_request_extra_data.h"
namespace blink {
void NoopWebURLLoader::LoadSynchronously(
std::unique_ptr<network::ResourceRequest> request,
scoped_refptr<WebURLRequestExtraData> url_request_extra_data,
bool pass_response_pipe_to_client,
bool no_mime_sniffing,
base::TimeDelta timeout_interval,
WebURLLoaderClient*,
WebURLResponse&,
absl::optional<WebURLError>&,
WebData&,
int64_t& encoded_data_length,
int64_t& encoded_body_length,
WebBlobInfo& downloaded_blob,
std::unique_ptr<blink::ResourceLoadInfoNotifierWrapper>
resource_load_info_notifier_wrapper) {
NOTREACHED();
}
void NoopWebURLLoader::LoadAsynchronously(
std::unique_ptr<network::ResourceRequest> request,
scoped_refptr<WebURLRequestExtraData> url_request_extra_data,
bool no_mime_sniffing,
std::unique_ptr<blink::ResourceLoadInfoNotifierWrapper>
resource_load_info_notifier_wrapper,
WebURLLoaderClient*) {}
} // namespace blink
| 1,415 | 480 |
#include "gsVertex.hpp"
#include "gsEdge.hpp"
#include "gsTile.hpp"
#include <algorithm>
#include <iostream>
#include <limits>
using std::cerr;
using std::endl;
int gs::Vertex::idCounter = 0;
void gs::Vertex::AddLink(const gs::Link<gs::Vertex>& link)
{
links.push_back(link);
}
void gs::Vertex::AddTile(const shared_ptr<gs::Tile> tile)
{
tiles.push_back(tile);
}
void gs::Vertex::CalculateHeight()
{
double total = 0;
for (const auto& tile : tiles)
{
total += tile->GetHeight();
}
height = total / (double) tiles.size();
}
vector<shared_ptr<gs::Edge>> gs::Vertex::GetEdges() const
{
return edges;
}
shared_ptr<gs::Edge> gs::Vertex::GetEdgeWith(const shared_ptr<gs::Vertex> refVertex) const
{
for (auto link : links)
{
if (link.edge->HasVertex(refVertex))
{
return link.edge;
}
}
return nullptr;
}
double gs::Vertex::GetHeight() const
{
return height;
}
//gs::Vec3d gs::Vertex::GetPosition() const
//{
// return position;
//}
bool gs::Vertex::IsRiver() const
{
return (riverId != -1);
}
//
//void gs::Vertex::SetPosition(const gs::Vec3d& newPosition)
//{
// position = newPosition;
//}
bool gs::Vertex::SetRiver(const int newRiverId)
{
if (riverId == newRiverId)
{
//river converges with itself, which is impossible
return false;
}
else if (riverId != -1)
{
//two rivers converge
return true;
}
//else, the vertex is not already a river
//stop if vertex touches the sea
for (const auto& tile : tiles)
{
if (tile->GetSurface() == gs::Tile::Type::WATER)
{
return true;
}
}
riverId = newRiverId;
vector<int> visitedIds;
bool childSucceeded = false;
while (!childSucceeded)
{
gs::EdgePtr lowestEdge = nullptr;
gs::VertexPtr lowestVertex = nullptr;
double lowestHeight = GetHeight();
for (auto& link : links)
{
bool targetVisited = (std::find(visitedIds.begin(), visitedIds.end(), link.target->id) != visitedIds.end());
if (!targetVisited && link.target->GetHeight() < lowestHeight)
{
lowestEdge = link.edge;
lowestVertex = link.target;
lowestHeight = link.target->GetHeight();
}
}
if (lowestEdge == nullptr)
{
riverId = -1;
return false;
}
else
{
childSucceeded = lowestVertex->SetRiver(newRiverId);
if (childSucceeded)
{
lowestEdge->SetRiver();
}
else
{
visitedIds.push_back(lowestVertex->id);
}
}
}
return true;
}
gs::Vertex::Vertex(const gs::Vec3d& position)
: id(idCounter++),
position(position),
height(0.0),
riverId(-1)
{
}
| 3,095 | 1,011 |
class Solution {
private:
vector<vector<bool>> isPalindrome;
void helper(string& s, int start, vector<string>& ans, vector<vector<string>>& res)
{
if (start == s.size())
{
res.push_back(ans);
return;
}
for (auto i = start; i < s.size(); ++i)
{
if (isPalindrome[start][i])
{
ans.push_back(s.substr(start, i - start + 1));
helper(s, i + 1, ans, res);
ans.pop_back();
}
}
}
public:
vector<vector<string>> partition(string s) {
int size = s.size();
isPalindrome.resize(size, vector<bool>(size, false));
int i, j =0;
for (auto t = 0; t < size; ++t)
{
i = j = t;
while(i >= 0 && j < size && s[i] == s[j])
{
isPalindrome[i][j] = true;
i--;
j++;
}
i = t;
j = t + 1;
while(i >= 0 && j < size && s[i] == s[j])
{
isPalindrome[i][j] = true;
i--;
j++;
}
}
vector<string> ans;
vector<vector<string>> res;
helper(s, 0, ans, res);
return res;
}
}; | 1,349 | 425 |
#include "InitializedStructPortFieldProgram.hpp"
#include "Arp/System/Commons/Logging.h"
#include "Arp/System/Core/ByteConverter.hpp"
namespace InitializedStructPortField
{
void InitializedStructPortFieldProgram::Execute()
{
//implement program
}
} // end of namespace InitializedStructPortField
| 319 | 99 |
#include "UidGenerator.h"
UidGenerator::UidGenerator() :
next_(1)
{}
UidGenerator &UidGenerator::instance()
{
static UidGenerator uidGenerator;
return uidGenerator;
}
unsigned int UidGenerator::generate()
{
unsigned int uid = 0;
if (!released_.empty())
{
uid = released_.front();
released_.pop();
}
else
{
uid = next_++;
}
return uid;
}
void UidGenerator::release(unsigned int uid)
{
released_.push(uid);
} | 430 | 170 |
#include "simfem/timestepping.hpp"
// typedef double (*nlfct)(double u, double v);
//Hopf
// double global_Du = 0.0;
// double global_Dv = 0.0;
// double global_a = 1.0;
// double global_b = 2.1;
// double global_T = 50.0;
// double global_eps = 0.01;
//spatial pattern
// double global_Du = 0.001;
// double global_Dv = 0.01;
// double global_a = 1.0;
// double global_b = 2.0;
// double global_T = 30.0;
// double global_eps = 0.01;
//Turing
double global_Du = 0.0001;
double global_Dv = 0.01;
double global_a = 1.0;
double global_b = 1.5;
double global_T = 1.0;
double global_eps = 0.01;
/*---------------------------------------------------------------------------*/
int main(int argc, char** argv)
{
if (argc !=4)
{
printf("%s needs arguments <nx, nt, scheme>\n", argv[0]);
exit(1);
}
int nx = atoi(argv[1]);
int nt = atoi(argv[2]);
std::string scheme = argv[3];
TimeSteppingData timesteppingdata;
timesteppingdata.T = global_T;
timesteppingdata.nt = nt;
timesteppingdata.nx = nx;
timesteppingdata.scheme = scheme;
Nonlinearity nonlinearity("brusselator");
nonlinearity.set_Du(global_Du);
nonlinearity.set_Dv(global_Dv);
nonlinearity.set_eps(global_eps);
nonlinearity.set_a(global_a);
nonlinearity.set_b(global_b);
TimeStepping timestepping(timesteppingdata, nonlinearity);
timestepping.run();
return 0;
} | 1,370 | 566 |
#ifndef IMMUTABLE_STRING_HPP
#define IMMUTABLE_STRING_HPP
#include "basic_sys.hpp"
#include "hash.hpp"
class ImmutableStringCache {
public:
static ImmutableStringCache& getInstance() {
static ImmutableStringCache instance;
return instance;
}
private:
ImmutableStringCache(){};
ImmutableStringCache(ImmutableStringCache const&); // Don't Implement
void operator=(ImmutableStringCache const&); // Don't implement
std::set<std::string> strings;
// we special case this, as we need it often
std::string empty_string;
public:
const std::string* cachedString(const std::string& in) {
if(in == empty_string)
return &empty_string;
auto it = strings.find(in);
if(it != strings.end())
return &*it;
strings.insert(in);
it = strings.find(in);
if(it != strings.end())
return &*it;
abort();
}
const std::string* cachedEmptyString() {
return &empty_string;
}
};
class ImmutableString {
// In the long term, this could be made more efficient
const std::string* ptr;
public:
const std::string& getStdString() const {
return *ptr;
}
// The reason these are explicit is because constructing an 'ImmutableString'
// is fairly
// expensive, so we want to know when we do it.
explicit ImmutableString(const std::string& s)
: ptr(ImmutableStringCache::getInstance().cachedString(s)) {}
explicit ImmutableString(const char* s)
: ptr(ImmutableStringCache::getInstance().cachedString(s)) {}
ImmutableString() : ptr(ImmutableStringCache::getInstance().cachedEmptyString()) {}
char operator[](int i) const {
return (*ptr)[i];
}
auto begin() -> decltype(ptr->begin()) {
return ptr->begin();
}
auto end() -> decltype(ptr->end()) {
return ptr->end();
}
friend bool operator==(const ImmutableString& lhs, const ImmutableString& rhs) {
return lhs.ptr == rhs.ptr;
}
friend bool operator==(const ImmutableString& lhs, const char* c) {
return *(lhs.ptr) == c;
}
friend bool operator==(const char* c, const ImmutableString& rhs) {
return *(rhs.ptr) == c;
}
// this is the only operator where we really have to compare the true strings
friend bool operator<(const ImmutableString& lhs, const ImmutableString& rhs) {
return *(lhs.ptr) < *(rhs.ptr);
}
friend bool operator!=(const ImmutableString& lhs, const ImmutableString& rhs) {
return lhs.ptr != rhs.ptr;
}
friend std::ostream& operator<<(std::ostream& o, const ImmutableString& is) {
return o << *(is.ptr);
}
};
namespace std {
template <>
struct hash<ImmutableString> : minlib_hash_base<ImmutableString> {
public:
size_t operator()(const ImmutableString& p) const {
return getHash(p.getStdString());
}
};
}
#endif
| 2,764 | 898 |
#include "BandSplitter.hpp"
#include <cassert>
using byte_t = uint8_t;
BandSplitter::BandSplitter(const std::vector<byte_t>& data)
{
split(data);
}
BandSplitter::BandSplitter(const std::vector<float>& upper, const std::vector<float>& lower)
{
upper_band = upper;
lower_band = lower;
}
void BandSplitter::split(const std::vector<byte_t>& data)
{
if (data.size() == 0)
return;
lower_band.clear();
upper_band.clear();
for (size_t i = 1; i < data.size(); i += 2)
{
float lower = ((float)data[i] + (float)data[i - 1]) / 2.0f;
float upper = ((float)data[i] - (float)data[i - 1]) / 2.0f;
lower_band.push_back(lower);
upper_band.push_back(upper);
}
// If data is not even sized
if (data.size() % 2 != 0)
{
float lower = (float)data[data.size() - 1] / 2.0f;
float upper = -1 * (float)data[data.size() - 1] / 2.0f;
lower_band.push_back(lower);
upper_band.push_back(upper);
}
}
std::vector<byte_t> BandSplitter::mergeEven()
{
return merge(true);
}
std::vector<byte_t> BandSplitter::mergeUneven()
{
return merge(false);
}
std::vector<byte_t> BandSplitter::merge(bool even_result)
{
assert(lower_band.size() == upper_band.size());
const size_t BAND_SIZE = lower_band.size();
std::vector<byte_t> result;
if (even_result)
{
for (int i = 0; i < BAND_SIZE; i++)
{
float even = lower_band[i] - upper_band[i];
float uneven = lower_band[i] + upper_band[i];
even = even < 0 ? 0 : even;
even = even > 255 ? 255 : even;
uneven = uneven < 0 ? 0 : uneven;
uneven = uneven > 255 ? 255 : uneven;
result.push_back((byte_t)even);
result.push_back((byte_t)uneven);
}
}
else if (BAND_SIZE > 0)
{
for (int i = 0; i < BAND_SIZE - 1; i++)
{
float even = lower_band[i] - upper_band[i];
float uneven = lower_band[i] + upper_band[i];
result.push_back((byte_t)even);
result.push_back((byte_t)uneven);
}
float last_element = lower_band[BAND_SIZE - 1] - upper_band[BAND_SIZE - 1];
result.push_back((byte_t)last_element);
}
return result;
}
| 2,296 | 871 |
// FIFO_Send.cpp
// FIFO_Send.cpp,v 4.10 2000/10/07 08:03:47 brunsch Exp
#include "ace/FIFO_Send.h"
#include "ace/Log_Msg.h"
#if defined (ACE_LACKS_INLINE_FUNCTIONS)
#include "ace/FIFO_Send.i"
#endif
ACE_RCSID(ace, FIFO_Send, "FIFO_Send.cpp,v 4.10 2000/10/07 08:03:47 brunsch Exp")
ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Send)
void
ACE_FIFO_Send::dump (void) const
{
ACE_TRACE ("ACE_FIFO_Send::dump");
ACE_FIFO::dump ();
}
ACE_FIFO_Send::ACE_FIFO_Send (void)
{
// ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send");
}
int
ACE_FIFO_Send::open (const ACE_TCHAR *rendezvous_name,
int flags,
int perms,
LPSECURITY_ATTRIBUTES sa)
{
ACE_TRACE ("ACE_FIFO_Send::open");
return ACE_FIFO::open (rendezvous_name,
flags | O_WRONLY,
perms,
sa);
}
ACE_FIFO_Send::ACE_FIFO_Send (const ACE_TCHAR *fifo_name,
int flags,
int perms,
LPSECURITY_ATTRIBUTES sa)
{
ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send");
if (this->ACE_FIFO_Send::open (fifo_name,
flags,
perms,
sa) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("%p\n"),
ACE_LIB_TEXT ("ACE_FIFO_Send::ACE_FIFO_Send")));
}
| 1,470 | 583 |
#include "MessageReceiver.h"
#include "Arduino.h"
MessageReceiver::MessageReceiver() : currMessage(0u)
{
}
MessageBase* MessageReceiver::getNextMessage()
{
MessageBase* retVal = NULL;
if (messages.size() > currMessage)
{
retVal = messages.element_at(currMessage);
currMessage++;
}
else
{
messages.clear();
currMessage = 0u;
}
return retVal;
}
void MessageReceiver::storeMessage(MessageBase* msg)
{
messages.push_back(msg);
}
| 467 | 163 |
// Copyright (c) 2019 Michael Vilim
//
// This file is part of the bamboo library. It is currently hosted at
// https://github.com/mvilim/bamboo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <arrow.hpp>
namespace bamboo {
namespace arrow {
unique_ptr<Node> convert(const Array& array);
void update_nulls(const Array& array, Node& node) {
// it would be better to directly copy the null array values (or do it in a way that is more
// conducive to optimization)
for (size_t i = 0; i < array.length(); i++) {
if (array.IsNull(i)) {
node.add_null();
} else {
node.add_not_null();
}
}
}
template <class T> void add_primitives(const NumericArray<T>& array, PrimitiveNode& node) {
for (size_t i = 0; i < array.length(); i++) {
node.add(array.Value(i));
}
}
// we should share pieces of this (indexing) with the node visitor, but the templating is a bit
// tricky
class IndexArrayVisitor : public virtual ArrayVisitor {
private:
vector<size_t> indices;
PrimitiveNode& enum_node;
public:
IndexArrayVisitor(PrimitiveNode& enum_node) : enum_node(enum_node) {}
vector<size_t> take_result() {
return std::move(indices);
}
template <class T> Status handle_numeric(const NumericArray<T>& array) {
for (size_t i = 0; i < array.length(); i++) {
if (!array.IsNull(i)) {
indices.push_back(array.Value(i));
}
}
return Status::OK();
}
virtual Status Visit(const Int8Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const Int16Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const Int32Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const Int64Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt8Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt16Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt32Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt64Array& array) final override {
return handle_numeric(array);
}
};
struct ArrowDynamicEnum : public DynamicEnum {
ArrowDynamicEnum(unique_ptr<PrimitiveNode> enum_values_node)
: enum_values_node(std::move(enum_values_node)){};
virtual ~ArrowDynamicEnum() final override = default;
virtual PrimitiveVector& get_enums() final override {
return *enum_values_node->get_vector();
}
// assume that every arrow enum is consistently sourced
virtual const void* source() final override {
return 0;
}
private:
unique_ptr<PrimitiveNode> enum_values_node;
};
class NodeArrayVisitor : public virtual ArrayVisitor {
private:
unique_ptr<Node> node;
public:
unique_ptr<Node> take_result() {
return std::move(node);
}
template <class A, class P>
Status handle_generic(A array, std::function<P(A, size_t i)> const& extractor) {
node = make_unique<PrimitiveNode>();
PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node);
for (size_t i = 0; i < array.length(); i++) {
if (!array.IsNull(i)) {
pn.add(extractor(array, i));
}
}
return Status::OK();
}
// could we share more of this code with the generic version?
Status handle_float16(const HalfFloatArray& array) {
node = make_unique<PrimitiveNode>();
PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node);
for (size_t i = 0; i < array.length(); i++) {
if (!array.IsNull(i)) {
pn.add_by_type<PrimitiveType::FLOAT16>(array.Value(i));
}
}
return Status::OK();
}
template <class T> Status handle_numeric(const NumericArray<T>& array) {
return handle_generic<const NumericArray<T>&, typename T::c_type>(
array, [](const NumericArray<T>& a, size_t i) { return a.Value(i); });
}
virtual Status Visit(const NullArray& array) final override {
// how do we merge the nulls into the combined array?
return Status::NotImplemented("NullArray not implemented");
};
virtual Status Visit(const BooleanArray& array) final override {
return handle_generic<const BooleanArray&, bool>(
array, [](const BooleanArray& a, size_t i) { return a.Value(i); });
}
virtual Status Visit(const Int8Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const Int16Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const Int32Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const Int64Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt8Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt16Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt32Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const UInt64Array& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const HalfFloatArray& array) final override {
return handle_float16(array);
}
virtual Status Visit(const FloatArray& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const DoubleArray& array) final override {
return handle_numeric(array);
}
virtual Status Visit(const StringArray& array) final override {
node = make_unique<PrimitiveNode>();
PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node);
for (size_t i = 0; i < array.length(); i++) {
pn.add(array.GetString(i));
}
return Status::OK();
}
virtual Status Visit(const BinaryArray& array) final override {
return Status::NotImplemented("BinaryArray not implemented");
}
virtual Status Visit(const FixedSizeBinaryArray& array) final override {
return Status::NotImplemented("FixedSizeBinaryArray not implemented");
}
virtual Status Visit(const Date32Array& array) final override {
return Status::NotImplemented("Date32Array not implemented");
}
virtual Status Visit(const Date64Array& array) final override {
return Status::NotImplemented("Date64Array not implemented");
}
virtual Status Visit(const Time32Array& array) final override {
return Status::NotImplemented("Time32Array not implemented");
}
virtual Status Visit(const Time64Array& array) final override {
return Status::NotImplemented("Time64Array not implemented");
}
virtual Status Visit(const TimestampArray& array) final override {
return Status::NotImplemented("TimestampArray not implemented");
}
virtual Status Visit(const Decimal128Array& array) final override {
return Status::NotImplemented("Decimal128Array not implemented");
}
virtual Status Visit(const ListArray& array) final override {
node = make_unique<ListNode>();
// is there a cleaner way to do this without a raw pointer or cast?
ListNode& ln = static_cast<ListNode&>(*node);
for (size_t i = 0; i < array.length(); i++) {
if (!array.IsNull(i)) {
size_t length = array.value_offset(i + 1) - array.value_offset(i);
ln.add_list(length);
}
}
unique_ptr<Node>& sub_node = ln.get_list();
sub_node = convert(*array.values());
return Status::OK();
}
virtual Status Visit(const StructArray& array) final override {
node = make_unique<RecordNode>();
// is there a cleaner way to do this without a raw pointer or cast?
RecordNode& rn = static_cast<RecordNode&>(*node);
for (auto child : array.struct_type()->children()) {
unique_ptr<Node>& field_node = rn.get_field(child->name());
field_node = convert(*array.GetFieldByName(child->name()));
}
return Status::OK();
}
virtual Status Visit(const UnionArray& array) final override {
return Status::NotImplemented("UnionArray not implemented");
}
virtual Status Visit(const DictionaryArray& array) final override {
node = make_unique<PrimitiveNode>();
// is there a cleaner way to do this without a raw pointer or cast?
PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node);
NodeArrayVisitor enum_visitor;
Status status = array.dictionary()->Accept(&enum_visitor);
// can an enum have a non-primitive type?
// this is a bit ugly -- do we have a better way?
std::unique_ptr<PrimitiveNode> enum_values_node = std::unique_ptr<PrimitiveNode>(
dynamic_cast<PrimitiveNode*>(enum_visitor.take_result().release()));
shared_ptr<ArrowDynamicEnum> enum_value =
std::make_shared<ArrowDynamicEnum>(std::move(enum_values_node));
IndexArrayVisitor index_visitor(pn);
Status index_status = array.indices()->Accept(&index_visitor);
// would be better if we could move this
DynamicEnumVector enum_vector;
enum_vector.index = index_visitor.take_result();
enum_vector.values = enum_value;
pn.get_vector() = make_unique<PrimitiveEnumVector>(std::move(enum_vector));
return Status::OK();
}
};
unique_ptr<Node> convert(const Array& array) {
NodeArrayVisitor node_visitor;
Status status = array.Accept(&node_visitor);
if (status.ok()) {
unique_ptr<Node> node = node_visitor.take_result();
update_nulls(array, *node);
return node;
} else {
throw std::runtime_error(status.message());
}
}
unique_ptr<Node> convert(std::istream& is, const ColumnFilter* column_filter) {
std::shared_ptr<RecordBatchReader> output;
std::shared_ptr<ArrowInputStream> ais = std::make_shared<ArrowInputStream>(is);
std::shared_ptr<InputStream> ais_base = std::static_pointer_cast<InputStream>(ais);
Status status = ipc::RecordBatchStreamReader::Open(ais_base, &output);
std::shared_ptr<RecordBatch> batch;
// need to merge the nodes after these record batches
// or should the merge be done on the python side?
unique_ptr<ListNode> ln = make_unique<ListNode>();
ln->get_list() = make_unique<RecordNode>();
int64_t list_counter = 0;
while (true) {
Status batch_status = output->ReadNext(&batch);
if (!batch_status.ok()) {
throw std::runtime_error("Error while running Arrow batch reader");
}
if (batch) {
RecordNode& rn = static_cast<RecordNode&>(*ln->get_list().get());
for (size_t i = 0; i < batch->num_columns(); i++) {
std::shared_ptr<Array> column = batch->column(i);
unique_ptr<Node>& column_node = rn.get_field(batch->column_name(i));
column_node = convert(*column);
}
for (size_t i = 0; i < batch->num_rows(); i++) {
rn.add_not_null();
}
list_counter += batch->num_rows();
} else {
break;
}
}
ln->add_list(list_counter);
ln->add_not_null();
return std::move(ln);
}
} // namespace arrow
} // namespace bamboo
| 12,274 | 3,580 |
#ifndef TP_TALLER_DE_PROGRAMACION_FIUBA_CABEZAENEMIGO_HPP
#define TP_TALLER_DE_PROGRAMACION_FIUBA_CABEZAENEMIGO_HPP
#include "Terreno.hpp"
class CabezaEnemigo : public Terreno{
public:
CabezaEnemigo();
float aplicarCoeficienteDeRozamiento(float velocidadX) override;
float obtenerImpulsoHorizontal(float aceleracion) override;
float obtenerImpulsoVertical(float fuerza) override;
float amortiguarVelocidad(float velocidadY) override;
};
#endif //TP_TALLER_DE_PROGRAMACION_FIUBA_CABEZAENEMIGO_HPP
| 547 | 227 |
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "notificationhandler.h"
#include <numeric>
#include <QtDebug>
#include <interfaces/structures.h>
#include <interfaces/advancednotifications/inotificationrule.h>
#include <interfaces/advancednotifications/types.h>
#include "dockutil.h"
namespace LC
{
namespace AdvancedNotifications
{
namespace Dolle
{
NotificationMethod NotificationHandler::GetHandlerMethod () const
{
return NMTray;
}
void NotificationHandler::Handle (const Entity& e, const INotificationRule& rule)
{
const QString& cat = e.Additional_ ["org.LC.AdvNotifications.EventCategory"].toString ();
const QString& type = e.Additional_ ["org.LC.AdvNotifications.EventType"].toString ();
const QString& eventId = e.Additional_ ["org.LC.AdvNotifications.EventID"].toString ();
auto& data = Counts_ [type];
if (cat != "org.LC.AdvNotifications.Cancel")
{
if (const int delta = e.Additional_.value ("org.LC.AdvNotifications.DeltaCount", 0).toInt ())
data.Counts_ [eventId] += delta;
else
data.Counts_ [eventId] = e.Additional_.value ("org.LC.AdvNotifications.Count", 1).toInt ();
data.Color_ = rule.GetColor ();
data.Total_ = std::accumulate (data.Counts_.constBegin (), data.Counts_.constEnd (), 0);
}
else
{
QMutableMapIterator<QString, NotificationData> it { Counts_ };
bool removed = false;
while (it.hasNext () && !removed)
{
NotificationData& nd = it.next ().value ();
if (nd.Counts_.remove (eventId))
{
nd.Total_ = std::accumulate (data.Counts_.constBegin (), data.Counts_.constEnd (), 0);
removed = true;
}
}
if (!removed)
return;
}
DU::SetDockBadges (Counts_.values ());
}
}
}
}
| 2,061 | 744 |
/*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDesktopDeliveryClient.h"
#include "vtkDesktopDeliveryServer.h"
#include "vtkCallbackCommand.h"
#include "vtkCamera.h"
#include "vtkCubeSource.h"
#include "vtkDoubleArray.h"
#include "vtkLight.h"
#include "vtkLightCollection.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPolyDataMapper.h"
#include "vtkRendererCollection.h"
#include "vtkRenderWindow.h"
#include "vtkSquirtCompressor.h"
#include "vtkTimerLog.h"
#include "vtkUnsignedCharArray.h"
//-----------------------------------------------------------------------------
static void vtkDesktopDeliveryClientReceiveImageCallback(vtkObject *,
unsigned long,
void *clientdata,
void *)
{
vtkDesktopDeliveryClient *self
= reinterpret_cast<vtkDesktopDeliveryClient *>(clientdata);
self->ReceiveImageFromServer();
}
//-----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkDesktopDeliveryClient, "$Revision$");
vtkStandardNewMacro(vtkDesktopDeliveryClient);
//----------------------------------------------------------------------------
vtkDesktopDeliveryClient::vtkDesktopDeliveryClient()
{
this->ReplaceActors = 1;
this->Squirt = 0;
this->SquirtCompressionLevel = 5;
this->SquirtBuffer = vtkUnsignedCharArray::New();
this->UseCompositing = 0;
this->RemoteDisplay = 1;
this->ReceivedImageFromServer = 1;
vtkCallbackCommand *cbc = vtkCallbackCommand::New();
cbc->SetClientData(this);
cbc->SetCallback(vtkDesktopDeliveryClientReceiveImageCallback);
this->ReceiveImageCallback = cbc;
}
//----------------------------------------------------------------------------
vtkDesktopDeliveryClient::~vtkDesktopDeliveryClient()
{
this->SquirtBuffer->Delete();
this->ReceiveImageCallback->Delete();
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::SetUseCompositing(int v)
{
this->Superclass::SetUseCompositing(v);
if (this->RemoteDisplay)
{
this->SetParallelRendering(v);
}
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::SetController(vtkMultiProcessController *controller)
{
vtkDebugMacro("SetController");
if (controller && (controller->GetNumberOfProcesses() != 2))
{
vtkErrorMacro("vtkDesktopDelivery needs controller with 2 processes");
return;
}
this->Superclass::SetController(controller);
if (this->Controller)
{
this->RootProcessId = this->Controller->GetLocalProcessId();
this->ServerProcessId = 1 - this->RootProcessId;
}
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::SetRenderWindow(vtkRenderWindow *renWin)
{
//Make sure the renWin has at least one renderer
if (renWin)
{
vtkRendererCollection *rens = renWin->GetRenderers();
if (rens->GetNumberOfItems() < 1)
{
vtkRenderer *ren = vtkRenderer::New();
renWin->AddRenderer(ren);
ren->Delete();
}
}
this->Superclass::SetRenderWindow(renWin);
}
//----------------------------------------------------------------------------
// Called only on the client.
float vtkDesktopDeliveryClient::GetZBufferValue(int x, int y)
{
float z;
if (this->UseCompositing == 0)
{
// This could cause a problem between setting this ivar and rendering.
// We could always composite, and always consider client z.
float *pz;
pz = this->RenderWindow->GetZbufferData(x, y, x, y);
z = *pz;
delete [] pz;
return z;
}
// TODO:
// This first int is to check for byte swapping.
// int pArg[3];
// pArg[0] = 1;
// pArg[1] = x;
// pArg[2] = y;
// this->ClientController->TriggerRMI(1, (void*)pArg, sizeof(int)*3,
// vtkClientCompositeManager::GATHER_Z_RMI_TAG);
// this->ClientController->Receive(&z, 1, 1, vtkClientCompositeManager::CLIENT_Z_TAG);
z = 1.0;
return z;
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::CollectWindowInformation(vtkMultiProcessStream& stream)
{
this->Superclass::CollectWindowInformation(stream);
vtkDesktopDeliveryServer::SquirtOptions squirt_options;
squirt_options.Enabled = this->Squirt;
squirt_options.CompressLevel = this->SquirtCompressionLevel;
squirt_options.Save(stream);
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::PreRenderProcessing()
{
// Get remote display flag
this->Controller->Receive(&this->RemoteDisplay, 1, this->ServerProcessId,
vtkDesktopDeliveryServer::REMOTE_DISPLAY_TAG);
if (this->ImageReductionFactor > 1)
{
// Since we're not really doing parallel rendering, restore the renderer
// viewports.
vtkRendererCollection *rens = this->GetRenderers();
vtkRenderer *ren;
int i;
for (rens->InitTraversal(), i = 0; (ren = rens->GetNextItem()); i++)
{
ren->SetViewport(this->Viewports->GetTuple(i));
}
}
this->ReceivedImageFromServer = 0;
if (!this->SyncRenderWindowRenderers)
{
// Establish a callback so that the image from the server is retrieved
// before we draw renderers that we are not synced with. This will fail if
// a non-synced renderer is on a layer equal or less than a synced renderer.
vtkRendererCollection *allren = this->RenderWindow->GetRenderers();
vtkCollectionSimpleIterator cookie;
vtkRenderer *ren;
for (allren->InitTraversal(cookie);
(ren = allren->GetNextRenderer(cookie)) != NULL; )
{
if (!this->Renderers->IsItemPresent(ren))
{
ren->AddObserver(vtkCommand::StartEvent, this->ReceiveImageCallback);
}
}
}
// Turn swap buffers off before the render so the end render method has a
// chance to add to the back buffer.
if (this->UseBackBuffer)
{
this->RenderWindow->SwapBuffersOff();
}
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::PostRenderProcessing()
{
this->ReceiveImageFromServer();
this->Timer->StopTimer();
this->RenderTime += this->Timer->GetElapsedTime();
if (!this->SyncRenderWindowRenderers)
{
vtkRendererCollection *allren = this->RenderWindow->GetRenderers();
vtkCollectionSimpleIterator cookie;
vtkRenderer *ren;
for (allren->InitTraversal(cookie);
(ren = allren->GetNextRenderer(cookie)) != NULL; )
{
ren->RemoveObservers(vtkCommand::StartEvent, this->ReceiveImageCallback);
}
}
// Swap buffers here.
if (this->UseBackBuffer)
{
this->RenderWindow->SwapBuffersOn();
}
this->RenderWindow->Frame();
}
//-----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::ReceiveImageFromServer()
{
if (this->ReceivedImageFromServer) return;
this->ReceivedImageFromServer = 1;
vtkDesktopDeliveryServer::ImageParams ip;
int comm_success =
this->Controller->Receive((int *)(&ip),
vtkDesktopDeliveryServer::IMAGE_PARAMS_SIZE,
this->ServerProcessId,
vtkDesktopDeliveryServer::IMAGE_PARAMS_TAG);
// Adjust render time for actual render on server.
this->Timer->StopTimer();
this->RenderTime += this->Timer->GetElapsedTime();
if (comm_success && ip.RemoteDisplay)
{
// Receive image.
this->Timer->StartTimer();
this->ReducedImageSize[0] = ip.ImageSize[0];
this->ReducedImageSize[1] = ip.ImageSize[1];
this->ReducedImage->SetNumberOfComponents(ip.NumberOfComponents);
if ( this->FullImageSize[0] == this->ReducedImageSize[0]
&& this->FullImageSize[1] == this->ReducedImageSize[1] )
{
this->FullImage->SetNumberOfComponents(ip.NumberOfComponents);
this->FullImage->SetNumberOfTuples( this->FullImageSize[0]
* this->FullImageSize[1]);
this->FullImageUpToDate = true;
this->ReducedImage->SetArray(this->FullImage->GetPointer(0),
this->FullImage->GetSize(), 1);
}
this->ReducedImage->SetNumberOfTuples( this->ReducedImageSize[0]
* this->ReducedImageSize[1]);
if (ip.SquirtCompressed)
{
this->SquirtBuffer->SetNumberOfComponents(ip.NumberOfComponents);
this->SquirtBuffer->SetNumberOfTuples( ip.BufferSize
/ ip.NumberOfComponents);
this->Controller->Receive(this->SquirtBuffer->GetPointer(0),
ip.BufferSize, this->ServerProcessId,
vtkDesktopDeliveryServer::IMAGE_TAG);
this->SquirtDecompress(this->SquirtBuffer, this->ReducedImage);
}
else
{
this->Controller->Receive(this->ReducedImage->GetPointer(0),
ip.BufferSize, this->ServerProcessId,
vtkDesktopDeliveryServer::IMAGE_TAG);
}
this->ReducedImageUpToDate = true;
this->RenderWindowImageUpToDate = false;
this->Timer->StopTimer();
this->TransferTime = this->Timer->GetElapsedTime();
}
else
{
// No remote display means no transfer time.
this->TransferTime = 0.0;
// Leave the image in the window alone.
this->RenderWindowImageUpToDate = true;
}
vtkDesktopDeliveryServer::TimingMetrics tm;
this->Controller->Receive((double *)(&tm),
vtkDesktopDeliveryServer::TIMING_METRICS_SIZE,
this->ServerProcessId,
vtkDesktopDeliveryServer::TIMING_METRICS_TAG);
this->RemoteImageProcessingTime = tm.ImageProcessingTime;
this->WriteFullImage();
this->Timer->StartTimer();
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::ComputeVisiblePropBounds(vtkRenderer *ren,
double bounds[6])
{
this->Superclass::ComputeVisiblePropBounds(ren, bounds);
if (this->ReplaceActors)
{
vtkDebugMacro("Replacing actors.");
ren->GetActors()->RemoveAllItems();
vtkCubeSource* source = vtkCubeSource::New();
source->SetBounds(bounds);
vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
mapper->SetInput(source->GetOutput());
vtkActor* actor = vtkActor::New();
actor->SetMapper(mapper);
ren->AddActor(actor);
source->Delete();
mapper->Delete();
actor->Delete();
}
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::SetImageReductionFactorForUpdateRate(double desiredUpdateRate)
{
this->Superclass::SetImageReductionFactorForUpdateRate(desiredUpdateRate);
if (this->Squirt)
{
if (this->ImageReductionFactor == 1)
{
this->SetSquirtCompressionLevel(0);
}
else
{
this->SetSquirtCompressionLevel(5);
}
}
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::SquirtDecompress(vtkUnsignedCharArray *in,
vtkUnsignedCharArray *out)
{
vtkSquirtCompressor *compressor = vtkSquirtCompressor::New();
compressor->SetInput(in);
compressor->SetOutput(out);
compressor->Decompress();
compressor->Delete();
}
//----------------------------------------------------------------------------
void vtkDesktopDeliveryClient::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ServerProcessId: " << this->ServerProcessId << endl;
os << indent << "ReplaceActors: "
<< (this->ReplaceActors ? "On" : "Off") << endl;
os << indent << "RemoteDisplay: "
<< (this->RemoteDisplay ? "On" : "Off") << endl;
os << indent << "Squirt: "
<< (this->Squirt? "On" : "Off") << endl;
os << indent << "RemoteImageProcessingTime: "
<< this->RemoteImageProcessingTime << endl;
os << indent << "TransferTime: " << this->TransferTime << endl;
os << indent << "SquirtCompressionLevel: " << this->SquirtCompressionLevel << endl;
}
| 12,948 | 3,794 |
//
// Created by Mikel Matticoli on 2/14/18.
//
#include <iostream>
#include <math.h>
#include "Event.h"
#include "CustomerEvent.h"
#include "SortedEventQueue.h"
#include "TellerEvent.h"
// Function prototypes for non-class functions
int randTime(double min, double max);
int runSim(int customerCount, int tellerCount, double simDuration, double avgSvcTime, bool sharedQueue);
/**
* Parses command line arguments and runs simulation with and without shared queue
* @param argc number of args
* @param argv string array of args
* @return program exit code (==0 for success, !=0 for error)
*/
int main(int argc, char *argv[]) {
// If missing args, print usage
if(argc < 5) {
std::cout << "Usage:" << std::endl
<< "./qSim #customers #tellers simulationTime averageServiceTime <seed>" << std::endl;
return 1;
}
// Parse command line args
int customerCount = atoi(argv[1]);
int tellerCount = atoi(argv[2]);
double simDuration = atof(argv[3]);
double avgSvcTime = atof(argv[4]);
if(argc == 6) {
int seed = atoi(argv[5]);
srand(seed);
} else {
srand(time(NULL));
}
// If any args are invalid, print usage and >0 warning
if(!customerCount || !tellerCount || !simDuration || !avgSvcTime) {
std::cout << "Usage:" << std::endl
<< "./qSim #customers #tellers simulationTime averageServiceTime <seed>" << std::endl
<< "Note that all required parameters must be greater than 0" << std::endl;
return 1;
}
return runSim(customerCount, tellerCount, simDuration, avgSvcTime, true) +
runSim(customerCount, tellerCount, simDuration, avgSvcTime, false);
}
/**
* Run simulation with given parameters
* @param customerCount number of customers
* @param tellerCount number of tellers
* @param simDuration simulation duration (minutes)
* @param avgSvcTime average service time (minutes)
* @param sharedQueue whether or not to use one shared TellerQueue across all tellers
* @return 0 for success, 1 for error
*/
int runSim(int customerCount, int tellerCount, double simDuration, double avgSvcTime, bool sharedQueue) {
std::cout << "\nRunning simulation with " << (sharedQueue ? "shared queue" : "individual queues") << std::endl;
int simTime = 0; // Counter to track simulation time (minutes)
double avgWaitTime = 0; // Counter to track wait time
double customerWaitTimes[customerCount] = { }; // Array to track customer wait times for calculating statistics
int customerIndex = 0; // Current index in wait times array
SortedEventQueue *eventQueue = new SortedEventQueue();
// If using a shared queue, init a shared queue
TellerQueue *customerQueue;
if(sharedQueue) customerQueue = new TellerQueue();
// Create arrival events for customers and add them to the event queue
for(int i = 0; i < customerCount; i++) {
// Invariant: new CustomerEvent will be created and added to event queue
CustomerEvent *c = new CustomerEvent(randTime(0, simDuration), CEventType::ARRIVE);
eventQueue->add(c);
// Invariant: CustomerEvent c has been created and added to eventQueue
}
// Create teller events at time 0 (bank open) and add them to the event queue
for(int i = 0; i < tellerCount; i++) {
// Invariant: new TellerEvent will be created and added to event queue
// Init with shared queue or new unique queue
TellerEvent *t = new TellerEvent(0, (sharedQueue ? customerQueue : new TellerQueue()) );
eventQueue->add(t);
// Invariant: TellerEvent c has been created and added to eventQueue
}
while(simTime < simDuration) {
// Process events at head of queue that are timestamped at current time
// Invariant: simTime will be incremented by 1
while(eventQueue->peek()->startTime == simTime) {
// Invariant: First event in eventQueue will be processed and retasked/deleted
Event *e = eventQueue->pop();
if(e->getType() == "Teller") {
TellerEvent *t = static_cast<TellerEvent *>(e);
// If there's a customer waiting
if(t->queue->peek() != nullptr) {
// Serve the customer for a random amount of time
CustomerEvent *c = t->queue->pop();
int serveTime = randTime(1, avgSvcTime * 2);
c->retask(simTime + serveTime, CEventType::SERVED);
t->retask(simTime + serveTime);
eventQueue->add(t);
eventQueue->add(c);
} else {
//No customers, idle for random amount of time
int idleTime = randTime(1, avgSvcTime * 2);
t->retask(simTime + idleTime);
eventQueue->add(t);
}
} else if (e->getType() == "Customer") {
CustomerEvent *c = static_cast<CustomerEvent *>(e);
switch(c->eventType) {
case CEventType ::ARRIVE:
// Customer arrived, put them in the shortest customer queue
// If using shared queue, shortestTellerQueue will always point to the same queue
c->retask(simTime, CEventType::WAIT);
TellerQueue::shortestTellerQueue->add(c);
break;
default:
case CEventType ::SERVED:
// Customer is done being served and can now leave. Save necessary data for stats and delete
customerWaitTimes[customerIndex] = simTime - c->arrivalTime;
customerIndex++;
avgWaitTime += simTime - c->arrivalTime;
delete c;
break;
}
} else {
std::cerr << "Error, unrecognized event type" << std::endl;
return 1;
}
// Invariant: First event in eventQueue has been processed and retasked/deleted
}
simTime++;
// Invariant: simTime has been incremented by 1
}
// Calculate the average
avgWaitTime /= customerCount;
// Calculate the standard deviation:
double stdDv = 0.0;
// Calculate sum( (x-xbar)^2 )
for(int i = 0; i < customerCount; i++) {
// Invariant stdDv will be incremented by (x-xbar)^2 for x=ith element of customerWaitTimes
double dx = (customerWaitTimes[i] - avgWaitTime);
stdDv += dx*dx;
// Invariant stdDv has been incremented by (x-xbar)^2 for x=ith element of customerWaitTimes
}
// Divide by x-1 and take root to get s
stdDv /= customerCount - 1;
stdDv = sqrt(stdDv);
std::cout << "Average wait time with " << (sharedQueue ? "shared queue" : "individual queues") << " is "
<< round(avgWaitTime * 100) / 100 << " minutes" << std::endl;
std::cout << "Standard deviation of wait times with "
<< (sharedQueue ? "shared queue" : "individual queues") << " is "
<< round(stdDv * 100) / 100 << " minutes" << std::endl;
return 0;
}
/**
* Generate random time in minutes between min and max time
* @param min lower bound for rand time
* @param max upper bound for rand time (exclusive)
* @return random time between min and max
*/
int randTime(double min, double max) {
return (int)(rand() * (max - min) / float(RAND_MAX) + min);
} | 7,581 | 2,131 |
#include <Arduino.h>
#include <SPI.h>
#include <MFRC522.h>
#define LONGITUD_BYTES 18
#define LONGITUD_BYTES_ESCRITURA 16
/*
Pines para conectar el lector
*/
#define RST_PIN D3
#define SS_PIN D4
// Constantes para el ejemplo
#define MODO_LECTURA 1
#define MODO_ESCRITURA 2
#define MODO MODO_ESCRITURA
MFRC522 lector(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key clave;
bool leer(char mensaje[LONGITUD_BYTES])
{
if (!lector.PICC_IsNewCardPresent())
{
return false;
}
if (!lector.PICC_ReadCardSerial())
{
Serial.println("Error leyendo serial");
return false;
}
byte bloque = 1; // El bloque que leemos
byte longitud = LONGITUD_BYTES;
byte buferLectura[LONGITUD_BYTES];
MFRC522::StatusCode estado;
estado = lector.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, bloque, &clave, &(lector.uid));
if (estado != MFRC522::STATUS_OK)
{
Serial.println("Error autenticando");
Serial.println(lector.GetStatusCodeName(estado));
return false;
}
estado = lector.MIFARE_Read(bloque, buferLectura, &longitud);
if (estado != MFRC522::STATUS_OK)
{
Serial.println("Error leyendo bloque");
Serial.println(lector.GetStatusCodeName(estado));
return false;
}
for (uint8_t i = 0; i < LONGITUD_BYTES - 2; i++)
{
mensaje[i] = buferLectura[i];
}
// Ya pueden retirar la tarjeta
lector.PICC_HaltA();
lector.PCD_StopCrypto1();
return true;
}
bool escribir(char cadena[LONGITUD_BYTES_ESCRITURA])
{
if (!lector.PICC_IsNewCardPresent())
{
return false;
}
if (!lector.PICC_ReadCardSerial())
{
Serial.println("Error leyendo serial");
return false;
}
byte bloque = 1;
byte buferEscritura[LONGITUD_BYTES_ESCRITURA];
// Copiar cadena al búfer
for (uint8_t i = 0; i < LONGITUD_BYTES_ESCRITURA; i++)
{
buferEscritura[i] = cadena[i];
}
MFRC522::StatusCode estado;
estado = lector.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, bloque, &clave, &(lector.uid));
if (estado != MFRC522::STATUS_OK)
{
Serial.println("Error autenticando");
Serial.println(lector.GetStatusCodeName(estado));
return false;
}
estado = lector.MIFARE_Write(bloque, buferEscritura, LONGITUD_BYTES_ESCRITURA);
if (estado != MFRC522::STATUS_OK)
{
Serial.println("Error escribiendo bloque");
Serial.println(lector.GetStatusCodeName(estado));
return false;
}
// Ya pueden retirar la tarjeta
lector.PICC_HaltA();
lector.PCD_StopCrypto1();
return true;
}
void setup()
{
Serial.begin(9600);
while (!Serial)
{
// Esperar serial. Nota: la tarjeta NO HARÁ NADA hasta que haya comunicación Serial (es decir, que el monitor serial sea abierto)
// si tú no quieres esto, simplemente elimina todas las llamadas a Serial
}
// Iniciar lector
SPI.begin();
lector.PCD_Init();
// Preparar la clave para leer las tarjetas RFID
for (byte i = 0; i < 6; i++)
{
clave.keyByte[i] = 0xFF;
}
Serial.println("Iniciado correctamente");
}
void loop()
{
if (MODO == MODO_LECTURA)
{
char contenidoRfid[LONGITUD_BYTES] = "";
bool lecturaExitosa = leer(contenidoRfid);
if (lecturaExitosa)
{
Serial.println("Lo que hay escrito es:");
Serial.println(contenidoRfid);
}
else
{
Serial.println("Error leyendo. Tal vez no hay RFID presente");
}
}
else if (MODO == MODO_ESCRITURA)
{
char mensaje[] = "parzibyte";
bool escrituraExitosa = escribir(mensaje);
if (escrituraExitosa)
{
Serial.println("Escrito ok");
}
else
{
Serial.println("Error escribiendo. Tal vez no hay RFID presente");
}
}
delay(1000);
} | 3,620 | 1,515 |
/* Compile if this is MSVC 6. */
#if defined(_MSC_VER) && (_MSC_VER == 1200)
int main()
{
return 0;
}
#endif
| 112 | 56 |
/**
* Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
* Copyright (c) 2018 Terry Moore, MCCI
*
* Permission is hereby granted, free of charge, to anyone
* obtaining a copy of this document and accompanying files,
* to do whatever they want with them without any restriction,
* including, but not limited to, copying, modification and redistribution.
* NO WARRANTY OF ANY KIND IS PROVIDED.
*
* This example sends a valid LoRaWAN packet with payload "Hello,
* world!", using frequency and encryption settings matching those of
* the The Things Network.
*
* This uses ABP (Activation-by-personalisation), where a DevAddr and
* Session keys are preconfigured (unlike OTAA, where a DevEUI and
* application key is configured, while the DevAddr and session keys are
* assigned/generated in the over-the-air-activation procedure).
*
* Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in
* g1, 0.1% in g2), but not the TTN fair usage policy (which is probably
* violated by this sketch when left running for longer)!
*
* To use this sketch, first register your application and device with
* the things network, to set or generate a DevAddr, NwkSKey and
* AppSKey. Each device should have their own unique values for these
* fields.
*
* Do not forget to define the radio type correctly in
* arduino-lmic/project_config/lmic_project_config.h or from your BOARDS.txt.
*
*/
#include <Arduino.h>
// +++ LoRaWan TTN library
// the order of these includes has to stay like this
#include <lmic.h>
// keep it like this
#include <hal/hal.h>
// arrrrrrggggghhhhhh!
#include <SPI.h>
// our secrets
#include "env.h"
int measuringPeriod = 100;
int measuringIteration = 0;
unsigned long time_now = 0;
int valTwoIterationsAgo = 0;
int valPrevIteration = 0;
int valCurrentIteration = 0;
int sumAllHighPeakValues = 0;
int totalHighPeaksCount = 0;
int sumAllLowPeakValues = 0;
int totalLowPeaksCount = 0;
int maxPeak = 0;
int minPeak = 0;
float averageHighPeaks = 0;
float averageLowPeaks = 0;
float totalAverage = 0;
String requestString = "";
int SENSOR_PIN = 36;
void do_send(osjob_t *j);
// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in arduino-lmic/project_config/lmic_project_config.h,
// otherwise the linker will complain).
void os_getArtEui(u1_t *buf) {}
void os_getDevEui(u1_t *buf) {}
void os_getDevKey(u1_t *buf) {}
uint8_t tx_payload[8];
static osjob_t sendjob;
void updateValues()
{
valCurrentIteration = analogRead(SENSOR_PIN);
if (minPeak == 0)
{
minPeak = valCurrentIteration;
}
if (maxPeak == 0)
{
maxPeak = valCurrentIteration;
}
if (valCurrentIteration > maxPeak)
{
maxPeak = valCurrentIteration;
}
if (valCurrentIteration < minPeak)
{
minPeak = valCurrentIteration;
}
if (valPrevIteration > valTwoIterationsAgo && valPrevIteration > valCurrentIteration)
{
sumAllHighPeakValues += valPrevIteration;
totalHighPeaksCount += 1;
}
if (valPrevIteration < valTwoIterationsAgo && valPrevIteration < valCurrentIteration)
{
sumAllLowPeakValues += valPrevIteration;
totalLowPeaksCount += 1;
}
valTwoIterationsAgo = valPrevIteration;
valPrevIteration = valCurrentIteration;
}
void updateAverages()
{
if (totalHighPeaksCount > 0)
{
averageHighPeaks = sumAllHighPeakValues / totalHighPeaksCount;
}
if (totalLowPeaksCount > 0)
{
averageLowPeaks = sumAllLowPeakValues / totalLowPeaksCount;
}
if (totalHighPeaksCount > 0 && totalLowPeaksCount > 0)
{
totalAverage = averageLowPeaks + ((averageHighPeaks - averageLowPeaks) / 2);
}
}
void resetValues()
{
sumAllHighPeakValues = 0;
totalHighPeaksCount = 0;
sumAllLowPeakValues = 0;
totalLowPeaksCount = 0;
maxPeak = 0;
minPeak = 0;
averageHighPeaks = 0;
averageLowPeaks = 0;
}
// Schedule TX every this many seconds (might become longer due to duty cycle
// limitations).ssss
const unsigned TX_INTERVAL = 60 * 5; // 5 minutes
//
// PIN MAPPING FOR HELTEC ESP32 V2 --> do not change
//
const lmic_pinmap lmic_pins = {
.nss = 18,
.rxtx = LMIC_UNUSED_PIN,
.rst = 14, // reset pin
.dio = {26, 34, 35},
};
//
// PAYLOAD HELPER FUNCTION --> do not change
//
void printHex2(unsigned v) {
v &= 0xff;
if (v < 16)
Serial.print('0');
Serial.print(v, HEX);
}
// TTN DEBUGGING
// Messages can be checked withing your serial monitor. Do not
// change!
//
void onEvent(ev_t ev) {
Serial.print(os_getTime());
Serial.print(": ");
switch (ev) {
case EV_SCAN_TIMEOUT:
Serial.println(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Serial.println(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Serial.println(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Serial.println(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
Serial.println(F("EV_JOINED"));
break;
// This event is defined but not used in the code. No
// point in wasting codespace on it.
//
// case EV_RFU1:
// Serial.println(F("EV_RFU1"));
// break;
//
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
resetValues();
if (LMIC.txrxFlags & TXRX_ACK)
Serial.println(F("Received ack"));
if (LMIC.dataLen) {
Serial.println(F("Received "));
Serial.println(LMIC.dataLen);
Serial.println(F(" bytes of payload"));
}
// Schedule next transmission
os_setTimedCallback(&sendjob, os_getTime() + sec2osticks(TX_INTERVAL),
do_send);
break;
case EV_LOST_TSYNC:
Serial.println(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Serial.println(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Serial.println(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Serial.println(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Serial.println(F("EV_LINK_ALIVE"));
break;
//
// This event is defined but not used in the code. No
// point in wasting codespace on it.
//
// case EV_SCAN_FOUND:
// Serial.println(F("EV_SCAN_FOUND"));
// break;
case EV_TXSTART:
Serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
Serial.println(F("EV_TXCANCELED"));
break;
case EV_RXSTART:
// do not print anything -- it wrecks timing
break;
case EV_JOIN_TXCOMPLETE:
Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept"));
break;
default:
Serial.print(F("Unknown event: "));
Serial.println((unsigned)ev);
break;
}
}
//
// PAYLOAD CONFIG
// Bytes in Payload depend on (your) measurements -> change if
// needed
//
void generate_payload() {
int high = (int)(averageHighPeaks);
Serial.println("Average High Peaks: " + String(high));
int max = (int)(maxPeak);
Serial.println("Highest Peak: " + String(max));
int min = (int)(minPeak);
Serial.println("Lowest Peak: " + String(min));
int low = (int)(averageLowPeaks);
Serial.println("Average Low Peaks: " + String(low));
Serial.println("\n- - - - - - - - - - - - - - - -\n");
tx_payload[0] = high >> 8;
tx_payload[1] = high;
tx_payload[2] = max >> 8;
tx_payload[3] = max;
tx_payload[4] = min >> 8;
tx_payload[5] = min;
tx_payload[6] = low >> 8;
tx_payload[7] = low;
}
//
// TTN UPLINK
// Values which will be uploaded depend on (your) measurements
// --> change
//
void do_send(osjob_t *j) {
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println(F("OP_TXRXPEND, not sending"));
} else {
Serial.println("\n–––––––––––––––––––––––––––––––");
Serial.println("Sending playload now");
Serial.println("- - - - - - - - - - - - - - - -\n");
updateAverages();
generate_payload();
Serial.print("Payload: ");
int x = 0;
while (x < sizeof(tx_payload)) {
printHex2(tx_payload[x]);
Serial.print(" ");
x++;
}
Serial.println();
LMIC_setTxData2(1, tx_payload, sizeof(tx_payload), 0);
Serial.println(F("Packet queued"));
}
// Next TX is scheduled after TX_COMPLETE event.
}
void setup() {
// TTN
Serial.begin(115200);
SPI.begin(5, 19, 27, 18); //(MasterIN, SlaveOut,etc.)
while (!Serial)
; // wait for Serial to be initialized
delay(100); // per sample code on RF_95 test
Serial.println(F("Starting"));
// LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Set static session parameters. Instead of dynamically establishing a
// session by joining the network, precomputed session parameters are be
// provided.
#ifdef PROGMEM
// On AVR, these values are stored in flash and only copied to RAM
// once. Copy them to a temporary buffer here, LMIC_setSession will
// copy them into a buffer of its own again.
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession(0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession(0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif
#if defined(CFG_eu868)
// Set up the channels used by the Things Network, which corresponds
// to the defaults of most gateways. Without this, only three base
// channels from the LoRaWAN specification are used, which certainly
// works, so it is good for debugging, but can overload those
// frequencies, so be sure to configure the full frequency range of
// your network here (unless your network autoconfigures them).
// Setting up channels should happen after LMIC_setSession, as that
// configures the minimal channel set.
// NA-US channels 0-71 are configured automatically
LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B),
BAND_CENTI); // g-band
LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7),
BAND_CENTI); // g-band
LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK),
BAND_MILLI); // g2-band
// LMIC_disableChannel(0); //Send only at channel 0
LMIC_disableChannel(1);
LMIC_disableChannel(2);
LMIC_disableChannel(3);
LMIC_disableChannel(4);
LMIC_disableChannel(5);
LMIC_disableChannel(6);
LMIC_disableChannel(7);
LMIC_disableChannel(8);
// TTN defines an additional channel at 869.525Mhz using SF9 for class B
// devices' ping slots. LMIC does not have an easy way to define set this
// frequency and support for class B is spotty and untested, so this
// frequency is not configured here.
#elif defined(CFG_us915)
// NA-US channels 0-71 are configured automatically
// but only one group of 8 should (a subband) should be active
// TTN recommends the second sub band, 1 in a zero based count.
// https://github.com/TheThingsNetwork/gateway-conf/blob/master/US-global_conf.json
LMIC_selectSubBand(1);
#endif
// Disable link check validation
LMIC_setLinkCheckMode(0);
// TTN uses SF9 for its RX2 window.
LMIC.dn2Dr = DR_SF9;
// Set data rate and transmit power for uplink
// (note: txpow seems to be ignored by the library)
LMIC_setDrTxpow(DR_SF7, 14);
// TODO: More the code below to loop when you deploy
// Start job
do_send(&sendjob);
}
void loop()
{
os_runloop_once();
if (millis() >= measuringIteration * measuringPeriod)
{
updateValues();
measuringIteration += 1;
}
}
| 12,437 | 4,707 |
//~---------------------------------------------------------------------------//
// _______ _______ _______ _ _ //
// | _ || || || | _ | | //
// | |_| || || _ || || || | //
// | || || | | || | //
// | || _|| |_| || | //
// | _ || |_ | || _ | //
// |__| |__||_______||_______||__| |__| //
// www.amazingcow.com //
// File : main.cpp //
// Project : tocgen //
// Date : Jan 01, 2018 //
// License : GPLv3 //
// Author : n2omatt <n2omatt@amazingcow.com> //
// Copyright : AmazingCow - 2018 //
// //
// Description : //
// //
//---------------------------------------------------------------------------~//
// std
#include <iostream>
#include <regex>
// Amazing Cow Libs
#include "CoreFS/CoreFS.h"
#include "CoreLog/CoreLog.h"
#include "CoreFile/CoreFile.h"
#include "CoreString/CoreString.h"
//----------------------------------------------------------------------------//
// Constants //
//----------------------------------------------------------------------------//
#define COW_TOCGEN_VERSION_MAJOR "0"
#define COW_TOCGEN_VERSION_MINOR "1"
#define COW_TOCGEN_VERSION_REVISION "2"
#define COW_TOCGEN_VERSION \
COW_TOCGEN_VERSION_MAJOR "." \
COW_TOCGEN_VERSION_MINOR "." \
COW_TOCGEN_VERSION_REVISION
#define PROGRAM_NAME "tocgen"
#define COPYRIGHT_YEARS "2018"
#define TOCGEN_TEST 0
//----------------------------------------------------------------------------//
// Help / Version //
//----------------------------------------------------------------------------//
void show_help(int errorCode) noexcept
{
std::string str = R"(Usage:
%s [-h] [-v] [-V] <filename>
Options:
*-h --help : Show this screen.
*-v --version : Show app version and copyright.
-V --verbose : Turn debug logs on.
<filename> : The file's name that will be parsed.
Notes:
Options marked with * are exclusive, i.e. the %s will run that
and exit after the operation.
)";
printf("%s", CoreString::Format(str, PROGRAM_NAME, PROGRAM_NAME).c_str());
exit(errorCode);
}
void show_version() noexcept
{
std::string str = R"(%s - %s - N2OMatt <n2omatt@amazingcow.com>
Copyright (c) %s - Amazing Cow
This is a free software (GPLv3) - Share/Hack it
Check http://www.amazingcow.com for more :)
)";
printf("%s", CoreString::Format(
str,
PROGRAM_NAME,
COW_TOCGEN_VERSION,
COPYRIGHT_YEARS
).c_str());
exit(0);
}
std::string comment_string() noexcept
{
std::string str = R"(
%s v%s - Amazing Cow - GPLv3
n2omatt <n2omatt@amazingcow.com>
http://amazingcow.com
)";
return CoreString::Format(str, PROGRAM_NAME, COW_TOCGEN_VERSION);
}
//----------------------------------------------------------------------------//
// Data Structures //
//----------------------------------------------------------------------------//
struct Node
{
int value = 0;
std::string contents = "";
Node *pParent = nullptr;
std::vector<Node> children;
Node() = default;
Node(int value_, const std::string &contents_, Node *pParent_) :
value ( value_),
contents(contents_),
pParent ( pParent_)
{
// Empty...
}
};
//----------------------------------------------------------------------------//
// Functions //
//----------------------------------------------------------------------------//
void print_tree_html(const Node &node, int level = 0) noexcept
{
auto spaces = std::string(level * 2, ' ');
if(node.value == 0)
{
printf("<!-- %s --> \n", comment_string().c_str());
printf("<b>Table of Contents:</b>\n");
}
else
{
printf(
"%s<li>%s</li> <!-- <h%d> -->\n",
spaces.c_str(),
node.contents.c_str(),
node.value
);
}
if(!node.children.empty())
{
printf("%s<ul>\n", spaces.c_str());
for(const auto &child : node.children)
print_tree_html(child, level + 1);
printf("%s</ul>\n", spaces.c_str());
}
}
// This will remove all tags on the contents.
//
// Input:
// <a href="https://github.com/AmazingCow-Game-Framework/videos">olcConsoleGameEngine</a>
// Output:
// olcConsoleGameEngine
std::string remove_all_tags(const std::string &contents) noexcept
{
auto tag_re = std::regex ("<[^>]*>");
auto clean_contents = std::regex_replace(contents, tag_re, "");
return clean_contents;
}
//----------------------------------------------------------------------------//
// Entry Point //
//----------------------------------------------------------------------------//
#if (!TOCGEN_TEST)
int main(int argc, char *argv[])
{
if(argc < 2)
show_help(1);
auto filename = std::string();
auto verbose = false;
//--------------------------------------------------------------------------
// Parse the command line options.
// COWTODO(n2omatt): Would be nicer to user CMD later...
for(int i = 1; i < argc; ++i)
{
// Help.
if(CoreString::StartsWith(argv[i], "--help") ||
CoreString::StartsWith(argv[i], "-h"))
{
show_help(0);
}
// Version.
else if(CoreString::StartsWith(argv[i], "--version") ||
CoreString::StartsWith(argv[i], "-v"))
{
show_version();
}
// Verbose.
else if(CoreString::StartsWith(argv[i], "--verbose") ||
CoreString::StartsWith(argv[i], "-V"))
{
verbose = true;
}
// Filename.
else
{
filename = argv[i];
}
}
// Sanity Checks...
if(filename.empty())
show_help(1);
if(!CoreFS::IsFile(filename))
CoreLog::Fatal("Invalid filename: (%s)", filename);
// Configure Logger...
CoreLog::GetDefaultLogger().SetLevel(
(verbose)
? CoreLog::Logger::LOG_LEVEL_VERBOSE
: CoreLog::Logger::LOG_LEVEL_NONE
);
//--------------------------------------------------------------------------
// Create the regexes...
auto regex_tag_h = std::regex("<h[1-6]>.*<\\/h[1-6]>");
std::smatch sm;
//--------------------------------------------------------------------------
// Head is the main node of the TOC tree
// p_currNode is the current node that we're working on.
auto head = Node{};
auto p_currNode = &head;
//--------------------------------------------------------------------------
// Parse the file lines.
auto lines = CoreFile::ReadAllLines(filename);
auto lineno = 0; // Just to let us have a clue of where the string is.
for(const auto &line : lines)
{
++lineno;
if(CoreString::IsNullOrWhiteSpace(line))
continue;
// Check if we're on <H*> line.
auto clean_line = CoreString::Trim(line, " \n");
if(!std::regex_search(line, sm, regex_tag_h))
continue;
// Get the line's info.
auto value = int(clean_line[2]) - int('1') + 1;
auto contents = remove_all_tags(
CoreString::Trim(clean_line.substr(4, clean_line.size() -9))
);
// Log... ;D
CoreLog::Debug("(%d) %s", lineno, clean_line);
CoreLog::Debug("[Curr] Value: %d - Contents: %s", p_currNode->value, p_currNode->contents);
CoreLog::Debug("[New ] Value: %d - Contents: %s", value, contents);
//----------------------------------------------------------------------
// Adding children to current node.
if(p_currNode->value < value)
{
auto node = Node(value, contents, p_currNode);
p_currNode->children.push_back(node);
p_currNode = &p_currNode->children.back();
}
//----------------------------------------------------------------------
// Adding siblings to current node.
else if(p_currNode->value == value)
{
p_currNode = p_currNode->pParent;
auto node = Node(value, contents, p_currNode);
p_currNode->children.push_back(node);
p_currNode = &p_currNode->children.back();
}
//----------------------------------------------------------------------
// Adding siblings to the parent node.
else if(p_currNode->value > value)
{
while(p_currNode->value >= value)
p_currNode = p_currNode->pParent;
auto node = Node(value, contents, p_currNode);
p_currNode->children.push_back(node);
p_currNode = &p_currNode->children.back();
}
}
print_tree_html(head);
return 0;
}
#else
int main()
{
auto dirty_content = R"(<a href="https://github.com/AmazingCow-Game-Framework/videos">olcConsoleGameEngine</a>)";
auto clean_content = remove_all_tags(dirty_content);
CoreLog::I("Clean: %s", clean_content);
}
#endif
| 10,185 | 2,887 |